class EcoRake module Shell module Files include Rake::DSL DAY_SECONDS = (60 * 60 * 24) # It creates directory `path` constructively. # @note if any parent directory does not exist, it creates it as well. def upsert_local_dir(path) return if path.to_s.strip.empty? return if File.directory?(path) require 'fileutils' puts "Creating directory '#{path}'" FileUtils.mkdir_p(path) end # TODO: check delete status def delete_file(*files, message: 'Deleting files:') files = files.select {|file| File.exist?(file)} return if files.empty? puts message if message files.each do |file| File.delete(file) puts " • #{file}" if message end end def move_file(*files, folder:, message: 'Moving files:') puts message if message files.each do |file| new_name = File.join(folder, File.basename(file)) File.name(file, new_name) puts " • #{File.basename(file)}" if message end end # It identifies files in a folder by using different criteria. # @return [Array] files that match the criteria **sorted** by name ascendant (i.e. abc) def folder_files(folder = ".", pattern = "*", regexp: nil, older_than: nil) target = File.join(File.expand_path(folder), pattern) Dir[target].tap do |dir_files| dir_files.select! {|f| File.file?(f)} dir_files.select! {|f| file_older_than?(f, days: older_than)} if older_than dir_files.select! {|f| File.basename(f).match(regexp)} if regexp.is_a?(Regexp) end.sort end # @see #folder_files . Same but fixed to `*.csv` **pattern** def csv_files(folder = ".", regexp: nil, older_than: nil) folder_files(folder, "*.csv", regexp: regexp, older_than: older_than) end # @see #folder_files . Same but fixed to `*.csv.gpg` **pattern** def gpg_files(folder = ".", regexp: nil, older_than: nil) gpg = folder_files(folder, "*.gpg", regexp: regexp, older_than: older_than) pgp = folder_files(folder, "*.pgp", regexp: regexp, older_than: older_than) gpg.concat(pgp) end # Preserves the folder and the base name of `gpg_file` name # and changes its extension to `csv`. # @return [String] def gpg_to_csv_filename(gpg_file) return nil unless gpg_file ext = gpg_file.split('.')[1..-1].join('.') base = File.basename(gpg_file, ".#{ext}") folder = File.dirname(gpg_file) File.join(folder, "#{base}.csv") end private def file_older_than?(file, days:) File.mtime(file) < Time.now - days_to_seconds(days) end def days_to_seconds(days) return nil unless days days * DAY_SECONDS end end end end