Last active
August 29, 2015 14:08
-
-
Save akouryy/05e2fc4ef9f5aba1ab72 to your computer and use it in GitHub Desktop.
filter by tag
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
# encoding utf-8 | |
# example: | |
# ruby ぴょんぴょん.rb -e png -e jpg -e gif -t シャロ -t チノ | |
# : .png or .jpg or .gif, シャロ or チノ | |
# ruby ぴょんぴょん.rb -o リゼシャロ --tag シャロ リゼ -千夜 | |
# : シャロ and リゼ but 千夜, ./リゼシャロ/ will contain symlinks | |
require 'fileutils' | |
raise "No command-line arguments found" if ARGV.empty? | |
option = nil | |
options = { | |
ext: [], | |
in_dir: ?., | |
out_dir: nil, | |
cond: [], | |
} | |
cond = nil | |
ARGV.each{|arg| | |
if arg =~ /^-t(ag)?$/ | |
options[:cond] << cond = {tag: [], tag_not: []} | |
next | |
end | |
if cond | |
if arg[0] == ?- | |
cond[:tag_not] << arg | |
else | |
cond[:tag] << arg | |
end | |
else | |
case option | |
when :input | |
option[:in_dir] = arg | |
option = nil | |
when :output | |
option[:out_dir] = arg | |
option = nil | |
when :ext | |
options[:ext] << arg | |
option = nil | |
else | |
raise "Invalid argument #{arg}. maybe you meant '-t #{arg}'" unless arg[0] == ?- | |
case arg[1..-1] | |
when ?i, '-in' | |
option = :input | |
when ?o, '-out' | |
option = :output | |
when ?e, '-ext' | |
option = :ext | |
when ?t, '-tag' | |
options[:cond] << cond = {tag: [], tag_not: []} | |
option = nil | |
else | |
raise "Invalid option #{arg}" | |
end | |
end | |
end | |
} | |
files = options[:cond].flat_map do |cond| | |
files = Dir.new(options[:in_dir]).to_a | |
unless options[:ext].empty? | |
files.select! do |f| | |
ext.any?{|e| f.end_with? ?. + e} | |
end | |
end | |
cond[:tag].each do |t| | |
files &= File.read(options[:in_dir] + "/#{t}.list").lines.map &:strip | |
end | |
cond[:tag_not].each do |t| | |
files -= File.read(options[:in_dir] + "/#{t[1..-1]}.list").lines.map &:strip | |
end | |
files | |
end | |
unless options[:out_dir] | |
options[:out_dir] = options[:cond].map{|c| | |
(c[:tag] + c[:tag_not]).join ' & ' | |
}.join ', ' | |
puts "output directory: " + options[:out_dir] | |
end | |
FileUtils.remove_dir options[:out_dir], force: true | |
FileUtils.mkdir options[:out_dir] | |
begin | |
FileUtils.symlink files, options[:out_dir] | |
rescue NotImplementedError | |
raise "Cannot make directory " + options[:out_dir] if options[:out_dir] =~ /"/ | |
files.each do |f| | |
system "cmd /c mklink \"#{options[:out_dir]}\\#{f}\" \"..\\#{f}\"" | |
end | |
end | |
puts "succeed." | |
puts "linked #{files.size} files." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment