Skip to content

Instantly share code, notes, and snippets.

@kch
Created August 3, 2010 13:34
Show Gist options
  • Save kch/506382 to your computer and use it in GitHub Desktop.
Save kch/506382 to your computer and use it in GitHub Desktop.
mac: watch home dir via fsevents and set encoding attr and reveal extension for txt and rb files
#!/usr/bin/ruby
# encoding: UTF-8
require 'rubygems'
require 'fsevent'
require 'shellwords'
class Time
def age_in_seconds(now = Time.now)
now - self
end
end
class FTFFEvents < FSEvent
WATCH_PATH = ENV['HOME']
WATCH_EXTENSIONS = %w[ txt rb ]
ACTIONS = %w[ set_enconding_xattr reveal_extension ]
LATENCY = 1.0
CHANGE_HISTORY = []
def self.start
new.start
end
def start
self.latency = LATENCY
self.watch_directories WATCH_PATH
super
end
def on_change(directories)
now = Time.now
candidate_paths = directories.map { |d| Dir[File.join(d, "*.{#{WATCH_EXTENSIONS.join(',')}}")] }.flatten\
.select { |path| File.file?(path) }\
.select { |path| File.mtime(path).age_in_seconds(now) <= LATENCY * 2 }
CHANGE_HISTORY.reject! { |path, time_of_change| time_of_change.age_in_seconds(now) > LATENCY * 2 }
candidate_paths -= CHANGE_HISTORY.map(&:first)
CHANGE_HISTORY.concat(candidate_paths.map { |path| [path, now] })
return if candidate_paths.empty?
ACTIONS.each { |m| send(m, candidate_paths) }
end
private
def set_enconding_xattr(candidate_paths)
target_paths = candidate_paths\
.select { |path| `file -b --mime-encoding #{escape_args(path)}` =~ /ascii|utf-8/i }\
.reject { |path| system("xattr -p com.apple.TextEncoding #{escape_args(path)} >/dev/null 2>&1") }
system("xattr -w com.apple.TextEncoding 'UTF-8;134217984' #{escape_args(target_paths)}")
end
def reveal_extension(target_paths)
system("/Developer/usr/bin/SetFile -a e #{escape_args(target_paths)}")
end
def escape_args(*a)
a.flatten.map(&:shellescape).join(" ")
end
end
FTFFEvents.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment