]> git.cworth.org Git - sup/blob - lib/sup/util.rb
Merge commit 'origin/undo-manager'
[sup] / lib / sup / util.rb
1 require 'thread'
2 require 'lockfile'
3 require 'mime/types'
4 require 'pathname'
5
6 ## time for some monkeypatching!
7 class Lockfile
8   def gen_lock_id
9     Hash[
10          'host' => "#{ Socket.gethostname }",
11          'pid' => "#{ Process.pid }",
12          'ppid' => "#{ Process.ppid }",
13          'time' => timestamp,
14          'pname' => $0,
15          'user' => ENV["USER"]
16         ]
17   end
18
19   def dump_lock_id lock_id = @lock_id
20       "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
21         lock_id.values_at('host','pid','ppid','time','user', 'pname')
22     end
23
24   def lockinfo_on_disk
25     h = load_lock_id IO.read(path)
26     h['mtime'] = File.mtime path
27     h
28   end
29
30   def touch_yourself; touch path end
31 end
32
33 class Pathname
34   def human_size
35     s =
36       begin
37         size
38       rescue SystemCallError
39         return "?"
40       end
41     s.to_human_size
42   end
43
44   def human_time
45     begin
46       ctime.strftime("%Y-%m-%d %H:%M")
47     rescue SystemCallError
48       "?"
49     end
50   end
51 end
52
53 ## more monkeypatching!
54 module RMail
55   class EncodingUnsupportedError < StandardError; end
56
57   class Message
58     def self.make_file_attachment fn
59       bfn = File.basename fn
60       t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
61       make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
62     end
63
64     def charset
65       if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
66         $1
67       end
68     end
69
70     def self.make_attachment payload, mime_type, encoding, filename
71       a = Message.new
72       a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
73       a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
74       a.header.add "Content-Transfer-Encoding", encoding if encoding
75       a.body =
76         case encoding
77         when "base64"
78           [payload].pack "m"
79         when "quoted-printable"
80           [payload].pack "M"
81         when "7bit", "8bit", nil
82           payload
83         else
84           raise EncodingUnsupportedError, encoding.inspect
85         end
86       a
87     end
88   end
89 end
90
91 class Range
92   ## only valid for integer ranges (unless I guess it's exclusive)
93   def size 
94     last - first + (exclude_end? ? 0 : 1)
95   end
96 end
97
98 class Module
99   def bool_reader *args
100     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
101   end
102   def bool_writer *args; attr_writer(*args); end
103   def bool_accessor *args
104     bool_reader(*args)
105     bool_writer(*args)
106   end
107
108   def defer_all_other_method_calls_to obj
109     class_eval %{
110       def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
111       def respond_to?(m, include_private = false)
112         @#{obj}.respond_to?(m, include_private)
113       end
114     }
115   end
116 end
117
118 class Object
119   def ancestors
120     ret = []
121     klass = self.class
122
123     until klass == Object
124       ret << klass
125       klass = klass.superclass
126     end
127     ret
128   end
129
130   ## "k combinator"
131   def returning x; yield x; x; end
132
133   ## clone of java-style whole-method synchronization
134   ## assumes a @mutex variable
135   ## TODO: clean up, try harder to avoid namespace collisions
136   def synchronized *meth
137     meth.each do
138       class_eval <<-EOF
139         alias unsynchronized_#{meth} #{meth}
140         def #{meth}(*a, &b)
141           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
142         end
143       EOF
144     end
145   end
146
147   def ignore_concurrent_calls *meth
148     meth.each do
149       mutex = "@__concurrent_protector_#{meth}"
150       flag = "@__concurrent_flag_#{meth}"
151       oldmeth = "__unprotected_#{meth}"
152       class_eval <<-EOF
153         alias #{oldmeth} #{meth}
154         def #{meth}(*a, &b)
155           #{mutex} = Mutex.new unless defined? #{mutex}
156           #{flag} = true unless defined? #{flag}
157           run = #{mutex}.synchronize do
158             if #{flag}
159               #{flag} = false
160               true
161             end
162           end
163           if run
164             ret = #{oldmeth}(*a, &b)
165             #{mutex}.synchronize { #{flag} = true }
166             ret
167           end
168         end
169       EOF
170     end
171   end
172 end
173
174 class String
175   def camel_to_hyphy
176     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
177   end
178
179   def find_all_positions x
180     ret = []
181     start = 0
182     while start < length
183       pos = index x, start
184       break if pos.nil?
185       ret << pos
186       start = pos + 1
187     end
188     ret
189   end
190
191   ## a very complicated regex found on teh internets to split on
192   ## commas, unless they occurr within double quotes.
193   def split_on_commas
194     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
195   end
196
197   ## ok, here we do it the hard way. got to have a remainder for purposes of
198   ## tab-completing full email addresses
199   def split_on_commas_with_remainder
200     ret = []
201     state = :outstring
202     pos = 0
203     region_start = 0
204     while pos <= length
205       newpos = case state
206         when :escaped_instring, :escaped_outstring: pos
207         else index(/[,"\\]/, pos)
208       end 
209       
210       if newpos
211         char = self[newpos]
212       else
213         char = nil
214         newpos = length
215       end
216
217       case char
218       when ?"
219         state = case state
220           when :outstring: :instring
221           when :instring: :outstring
222           when :escaped_instring: :instring
223           when :escaped_outstring: :outstring
224         end
225       when ?,, nil
226         state = case state
227           when :outstring, :escaped_outstring:
228             ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
229             region_start = newpos + 1
230             :outstring
231           when :instring: :instring
232           when :escaped_instring: :instring
233         end
234       when ?\\
235         state = case state
236           when :instring: :escaped_instring
237           when :outstring: :escaped_outstring
238           when :escaped_instring: :instring
239           when :escaped_outstring: :outstring
240         end
241       end
242       pos = newpos + 1
243     end
244
245     remainder = case state
246       when :instring
247         self[region_start .. -1].gsub(/^\s+/, "")
248       else
249         nil
250       end
251
252     [ret, remainder]
253   end
254
255   def wrap len
256     ret = []
257     s = self
258     while s.length > len
259       cut = s[0 ... len].rindex(/\s/)
260       if cut
261         ret << s[0 ... cut]
262         s = s[(cut + 1) .. -1]
263       else
264         ret << s[0 ... len]
265         s = s[len .. -1]
266       end
267     end
268     ret << s
269   end
270
271   def normalize_whitespace
272     gsub(/\t/, "    ").gsub(/\r/, "")
273   end
274
275   ## takes a space-separated list of words, and returns an array of symbols.
276   ## typically used in Sup for translating Ferret's representation of a list
277   ## of labels (a string) to an array of label symbols.
278   def symbolistize; split.map { |x| x.intern } end
279 end
280
281 class Numeric
282   def clamp min, max
283     if self < min
284       min
285     elsif self > max
286       max
287     else
288       self
289     end
290   end
291
292   def in? range; range.member? self; end
293
294   def to_human_size
295     if self < 1024
296       to_s + "b"
297     elsif self < (1024 * 1024)
298       (self / 1024).to_s + "k"
299     elsif self < (1024 * 1024 * 1024)
300       (self / 1024 / 1024).to_s + "m"
301     else
302       (self / 1024 / 1024 / 1024).to_s + "g"
303     end
304   end
305 end
306
307 class Fixnum
308   def to_character
309     if self < 128 && self >= 0
310       chr
311     else
312       "<#{self}>"
313     end
314   end
315
316   ## hacking the english language
317   def pluralize s
318     to_s + " " +
319       if self == 1
320         s
321       else
322         if s =~ /(.*)y$/
323           $1 + "ies"
324         else
325           s + "s"
326         end
327       end
328   end
329 end
330
331 class Hash
332   def - o
333     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
334   end
335
336   def select_by_value v=true
337     select { |k, vv| vv == v }.map { |x| x.first }
338   end
339 end
340
341 module Enumerable
342   def map_with_index
343     ret = []
344     each_with_index { |x, i| ret << yield(x, i) }
345     ret
346   end
347
348   def sum; inject(0) { |x, y| x + y }; end
349   
350   def map_to_hash
351     ret = {}
352     each { |x| ret[x] = yield(x) }
353     ret
354   end
355
356   # like find, except returns the value of the block rather than the
357   # element itself.
358   def argfind
359     ret = nil
360     find { |e| ret ||= yield(e) }
361     ret || nil # force
362   end
363
364   def argmin
365     best, bestval = nil, nil
366     each do |e|
367       val = yield e
368       if bestval.nil? || val < bestval
369         best, bestval = e, val
370       end
371     end
372     best
373   end
374
375   ## returns the maximum shared prefix of an array of strings
376   ## optinally excluding a prefix
377   def shared_prefix caseless=false, exclude=""
378     return "" if empty?
379     prefix = ""
380     (0 ... first.length).each do |i|
381       c = (caseless ? first.downcase : first)[i]
382       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
383       next if exclude[i] == c
384       prefix += first[i].chr
385     end
386     prefix
387   end
388
389   def max_of
390     map { |e| yield e }.max
391   end
392 end
393
394 class Array
395   def flatten_one_level
396     inject([]) { |a, e| a + e }
397   end
398
399   def to_h; Hash[*flatten]; end
400   def rest; self[1..-1]; end
401
402   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
403
404   def last= e; self[-1] = e end
405   def nonempty?; !empty? end
406
407   def to_set_of_symbols
408     map { |x| x.is_a?(Symbol) ? x : x.intern }.uniq
409   end
410 end
411
412 class Time
413   def to_indexable_s
414     sprintf "%012d", self
415   end
416
417   def nearest_hour
418     if min < 30
419       self
420     else
421       self + (60 - min) * 60
422     end
423   end
424
425   def midnight # within a second
426     self - (hour * 60 * 60) - (min * 60) - sec
427   end
428
429   def is_the_same_day? other
430     (midnight - other.midnight).abs < 1
431   end
432
433   def is_the_day_before? other
434     other.midnight - midnight <=  24 * 60 * 60 + 1
435   end
436
437   def to_nice_distance_s from=Time.now
438     later_than = (self < from)
439     diff = (self.to_i - from.to_i).abs.to_f
440     text = 
441       [ ["second", 60],
442         ["minute", 60],
443         ["hour", 24],
444         ["day", 7],
445         ["week", 4.345], # heh heh
446         ["month", 12],
447         ["year", nil],
448       ].argfind do |unit, size|
449         if diff.round <= 1
450           "one #{unit}"
451         elsif size.nil? || diff.round < size
452           "#{diff.round} #{unit}s"
453         else
454           diff /= size.to_f
455           false
456         end
457       end
458     if later_than
459       text + " ago"
460     else
461       "in " + text
462     end  
463   end
464
465   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
466   def to_nice_s from=Time.now
467     if year != from.year
468       strftime "%b %Y"
469     elsif month != from.month
470       strftime "%b %e"
471     else
472       if is_the_same_day? from
473         strftime("%l:%M%P")
474       elsif is_the_day_before? from
475         "Yest."  + nearest_hour.strftime("%l%P")
476       else
477         strftime "%b %e"
478       end
479     end
480   end
481 end
482
483 ## simple singleton module. far less complete and insane than the ruby
484 ## standard library one, but automatically forwards methods calls and
485 ## allows for constructors that take arguments.
486 ##
487 ## You must have #initialize call "self.class.i_am_the_instance self"
488 ## at some point or everything will fail horribly.
489 module Singleton
490   module ClassMethods
491     def instance; @instance; end
492     def instantiated?; defined?(@instance) && !@instance.nil?; end
493     def deinstantiate!; @instance = nil; end
494     def method_missing meth, *a, &b
495       raise "no instance defined!" unless defined? @instance
496
497       ## if we've been deinstantiated, just drop all calls. this is
498       ## useful because threads that might be active during the
499       ## cleanup process (e.g. polling) would otherwise have to
500       ## special-case every call to a Singleton object
501       return nil if @instance.nil?
502
503       @instance.send meth, *a, &b
504     end
505     def i_am_the_instance o
506       raise "there can be only one! (instance)" if defined? @instance
507       @instance = o
508     end
509   end
510
511   def self.included klass
512     klass.extend ClassMethods
513   end
514 end
515
516 ## wraps an object. if it throws an exception, keeps a copy.
517 class Recoverable
518   def initialize o
519     @o = o
520     @error = nil
521     @mutex = Mutex.new
522   end
523
524   attr_accessor :error
525
526   def clear_error!; @error = nil; end
527   def has_errors?; !@error.nil?; end
528
529   def method_missing m, *a, &b; __pass m, *a, &b end
530   
531   def id; __pass :id; end
532   def to_s; __pass :to_s; end
533   def to_yaml x; __pass :to_yaml, x; end
534   def is_a? c; @o.is_a? c; end
535
536   def respond_to?(m, include_private=false)
537     @o.respond_to?(m, include_private)
538   end
539
540   def __pass m, *a, &b
541     begin
542       @o.send(m, *a, &b)
543     rescue Exception => e
544       @error ||= e
545       raise
546     end
547   end
548 end
549
550 ## acts like a hash with an initialization block, but saves any
551 ## newly-created value even upon lookup.
552 ##
553 ## for example:
554 ##
555 ## class C
556 ##   attr_accessor :val
557 ##   def initialize; @val = 0 end
558 ## end
559 ## 
560 ## h = Hash.new { C.new }
561 ## h[:a].val # => 0
562 ## h[:a].val = 1
563 ## h[:a].val # => 0
564 ##
565 ## h2 = SavingHash.new { C.new }
566 ## h2[:a].val # => 0
567 ## h2[:a].val = 1
568 ## h2[:a].val # => 1
569 ##
570 ## important note: you REALLY want to use #member? to test existence,
571 ## because just checking h[anything] will always evaluate to true
572 ## (except for degenerate constructor blocks that return nil or false)
573 class SavingHash
574   def initialize &b
575     @constructor = b
576     @hash = Hash.new
577   end
578
579   def [] k
580     @hash[k] ||= @constructor.call(k)
581   end
582
583   defer_all_other_method_calls_to :hash
584 end
585
586 class OrderedHash < Hash
587   alias_method :store, :[]=
588   alias_method :each_pair, :each
589   attr_reader :keys
590
591   def initialize *a
592     @keys = []
593     a.each { |k, v| self[k] = v }
594   end
595
596   def []= key, val
597     @keys << key unless member?(key)
598     super
599   end
600
601   def values; keys.map { |k| self[k] } end
602   def index key; @keys.index key end
603
604   def delete key
605     @keys.delete key
606     super
607   end
608
609   def each; @keys.each { |k| yield k, self[k] } end
610 end
611
612 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
613 ## first person to hit the finish line
614 class FinishLine
615   def initialize
616     @m = Mutex.new
617     @over = false
618   end
619
620   def winner?
621     @m.synchronize { !@over && @over = true }
622   end
623 end
624
625 class Iconv
626   def self.easy_decode target, charset, text
627     return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
628     charset = case charset
629                 when /UTF[-_ ]?8/i: "utf-8"
630                 when /(iso[-_ ])?latin[-_ ]?1$/i: "ISO-8859-1"
631                 when /iso[-_ ]?8859[-_ ]?15/i: 'ISO-8859-15'
632                 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i: "utf-7"
633                 else charset
634               end
635
636     # Convert:
637     #
638     # Remember - Iconv.open(to, from)!
639     Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
640   end
641 end