class EcoRake module Lib module Files class Purge < EcoRake::Lib::BaseTask options_with_defaults true option '-e', '--enviro ENVIRO', String, desc: 'Target environment to run against (i.e. org, live)', required: true option '-d', '--folder NAME', desc: 'Source local folder' option '-l', '--list', TrueClass, desc: 'Lists files that will be deleted' option '-o', '--older-than [DAYS]', Integer, desc: 'Number of days files to archive should be older than' option '-r', '--remove', TrueClass, desc: "It deletes those files" def task(*_args) if target_files.empty? puts "There were no files in folder '#{source_folder}' to be #{str_op}" elsif options[:list] msg = "#{target_files.count} target log files (from '#{source_folder}') will be #{str_op}" msg << " to '#{dest_folder}':" unless remove? puts msg target_files.each {|file| puts " • #{File.basename(file)}"} elsif options[:remove] delete_file(*target_files, message: "Removing the following #{target_files.count} files from '#{source_folder}':") else ensure_dest_folder! msg = "Moving #{target_files.count} log files from '#{source_folder}' to the '#{dest_folder}' folder:" move_file(*target_files, folder: dest_folder, message: msg) end end private # Based on `older-than` option # @return [Array] def target_files @target_files ||= folder_files(source_folder, older_than: older_than) end # Folder where the files will be moved (when applicable) def dest_folder @dest_folder ||= File.join(source_folder, 'archive').tap do |folder| directory folder end end # It declares the folder as a task and creates it if it doesn't exist def ensure_dest_folder! directory dest_folder Rake::Task[dest_folder].invoke end # @return [String] def source_folder @source_folder ||= File.expand_path(options[:folder]) end # @return [Integer] number of days the files are older than. def older_than options[:older_than] || (remove?? 15 : 3) end # @return [String] def str_op remove?? 'deleted' : 'moved' end # @return [Boolean] whether the files should be moved or removed/deleted. def remove? options[:remove] end end end end end