Skip to content

Instantly share code, notes, and snippets.

@nanki
Created September 8, 2015 06:38
Show Gist options
  • Save nanki/a58cf2ecf52b0f737e65 to your computer and use it in GitHub Desktop.
Save nanki/a58cf2ecf52b0f737e65 to your computer and use it in GitHub Desktop.
file finder
#!/usr/bin/env ruby
# -*- coding: UTF-8 -*-;
require 'open3'
require 'shellwords'
EDITOR = ENV['EDITOR'] || 'vim -b'
EXCLUDE_EXTENTSONS = %w(psd gif jpg png DS_Store tmp JPG PNG swp swf o bundle dylib so)
class Args
attr_reader :subdirs, :patterns, :open_with_editor
def initialize()
@subdirs = Dir.glob("*")
@patterns = []
@open_with_editor = false
end
def process(argv)
__, argv = argv.partition{|v| "--" == v}
@open_with_editor = true unless __.empty?
subdirs, patterns = argv.partition{|v| /^[-+]?@/ === v}
@patterns += patterns
subdirs.each do |dir|
case dir
when /^@(.*)/
@subdirs = [$1]
when /^-@(.*)/
@subdirs -= [$1]
when /^\+@(.*)/
@subdirs += [$1]
end
end
end
end
def find(args, path=nil)
ext = EXCLUDE_EXTENTSONS.map{|ext| "! -name '*.#{ext}' "}.join
patterns = args.patterns.map{|v| "#{/^-/ === v ? '!' : ''} -path '*#{v.sub(/^-/, '')}*' "}.join
cmd = "find #{args.subdirs.map{|v| Shellwords.escape v}.join(' ')} -type f #{ext} ! -path '*/.git/*' ! -path '*/.hg/*' ! -path '*/.svn/*' #{patterns}"
_, stdout, _ = *Open3.popen3(cmd)
stdout.set_encoding("binary")
files = []
stdout.each_line do |file|
file.strip!
file = File.join(path, file) if path
files << file
puts file unless args.open_with_editor
end
files
end
def args()
args = Args.new
['~/.ffrc', '.ffrc'].each do |path|
rcpath = File.expand_path path
args.process(open(rcpath).read.split) if File.exist? rcpath
end
args.process(ARGV)
args
end
files = []
if $stdin.tty?
files.concat find(args)
else
$stdin.each do |path|
path.strip!
begin
Dir.chdir path do
files.concat find(args, path)
end
rescue
end
end
end
if files.empty?
$stderr.puts "Not found."
exit 1
else
if args.open_with_editor
system("</dev/tty #{EDITOR} #{files.map{|v| '"'+v+'"'}.join(' ')}")
puts files
end
$stderr.puts "#{files.size} files found."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment