#require 'fileutils' module Eco module Data module Files class Directory attr_reader :dir_path def initialize(dir_path = Dir.pwd) dir_path = script_subfolder if dir_path == :script raise "Cannot initialize with directory: '#{dir_path.to_s}'" if !dir_path || dir_path.is_a?(Symbol) @dir_path = dir_path end def exists? Files.dir_exists(@dir_path) end def create succeed = Directory.create(File.expand_path(@dir_path)) unless self.exists? self.full_path if succeed end def full_path File.expand_path(@dir_path) end def dir_files(file: nil, pattern: dir_pattern) find = !!file ? file_pattern(file) : file_pattern(pattern) Dir.glob(find) end def newest_file(files_list = nil, file: nil) files_list = files_list || dir_files(file: file) return nil unless files_list && files_list.is_a?(Array) && (files_list.length > 0) # files available? files_list.max_by {|f| File.mtime(f) } end def file(filename, should_exist: false) return nil if !filename if File.expand_path(filename) == filename return filename if !should_exist || Files.file_exists?(filename) end file = FilePattern.new(filename).resolve(dir: @dir_path) return file if !should_exist || Files.file_exists?(file) file = File.expand_path(filename) return file if !should_exist || Files.file_exists?(file) nil end def join(*args) args.unshift(@dir_path) File.join(*args) end def self.create(path, includes_file: false) return true if Files.file_exists?(path) parts = Files.split(File.expand_path(path)) filename = parts.pop if includes_file return true if Files.dir_exists?(File.join(*parts)) subpath = nil begin parts.each do |curr| subpath = subpath ? File.join(subpath, curr) : curr Dir.mkdir(subpath) unless Files.dir_exists?(subpath) end rescue Exception => e pp e end false end private def file_pattern(value) case value when Files::FilePattern value else Files::FilePattern.new(value).pattern(@dir_path) end end def dir_pattern Files::FilePattern.new.pattern(@dir_path) end def script_subfolder Files.script_subfolder end end end end end