Last active
February 24, 2023 15:49
-
-
Save roryhardy/47fd826aca658001705c7e44d93aecf4 to your computer and use it in GitHub Desktop.
Copy files from a nested structure to a flat structure while preserving naming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'fileutils' | |
def create_filename(item, source, separator) | |
parents = File.dirname(item).split('/').last(2) | |
root = source.split('/').last | |
name = parents.first == root ? parents.last : parents.join(separator) | |
name += separator + File.basename(item) | |
end | |
def create_pattern(file_type) | |
file_type == '' ? '*.{jpg,png}' : "*.{#{file_type}}" | |
end | |
def empty_destination(destination) | |
FileUtils.rm_rf(Dir["#{destination}/*"]) | |
end | |
def get_input(msg) | |
puts msg | |
STDIN.gets.strip | |
end | |
def help_prompt(args) | |
if (args.first == '--help' || args.count != 2) | |
puts "Usage: #{__FILE__} [source] [destination]\n" | |
exit | |
end | |
end | |
help_prompt(ARGV) | |
VALID_INPUT = %w(y yes) | |
# Getting source and destination from the shell so that I get | |
# auto completion and path expansion | |
# e.g. ~/Desktop -> /Users/me/Desktop | |
SOURCE = ARGV[0] | |
DESTINATION = ARGV[1] | |
# For all other input prompt to make it easier to use | |
empty = get_input "Do you want to empty '#{DESTINATION}'? (n)" | |
file_type = get_input("\nWhat kind of files do you want? (jpg png)").gsub(/\s+/, ',') | |
separator = get_input "\nHow would you like to separate words? ()" | |
glob_pattern = create_pattern(file_type) | |
empty_destination DESTINATION if VALID_INPUT.include? empty.downcase | |
Dir.glob("#{SOURCE}/**/#{glob_pattern}").each do |item| | |
name = create_filename(item, SOURCE, separator) | |
FileUtils.cp(item, "#{DESTINATION}/#{name}") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment