]> git.cworth.org Git - sup/blob - lib/sup/util.rb
Merge branch 'master' into next
[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 display_length; scan(/./u).size end
176
177   def camel_to_hyphy
178     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
179   end
180
181   def find_all_positions x
182     ret = []
183     start = 0
184     while start < length
185       pos = index x, start
186       break if pos.nil?
187       ret << pos
188       start = pos + 1
189     end
190     ret
191   end
192
193   ## a very complicated regex found on teh internets to split on
194   ## commas, unless they occurr within double quotes.
195   def split_on_commas
196     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
197   end
198
199   ## ok, here we do it the hard way. got to have a remainder for purposes of
200   ## tab-completing full email addresses
201   def split_on_commas_with_remainder
202     ret = []
203     state = :outstring
204     pos = 0
205     region_start = 0
206     while pos <= length
207       newpos = case state
208         when :escaped_instring, :escaped_outstring: pos
209         else index(/[,"\\]/, pos)
210       end 
211       
212       if newpos
213         char = self[newpos]
214       else
215         char = nil
216         newpos = length
217       end
218
219       case char
220       when ?"
221         state = case state
222           when :outstring: :instring
223           when :instring: :outstring
224           when :escaped_instring: :instring
225           when :escaped_outstring: :outstring
226         end
227       when ?,, nil
228         state = case state
229           when :outstring, :escaped_outstring:
230             ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
231             region_start = newpos + 1
232             :outstring
233           when :instring: :instring
234           when :escaped_instring: :instring
235         end
236       when ?\\
237         state = case state
238           when :instring: :escaped_instring
239           when :outstring: :escaped_outstring
240           when :escaped_instring: :instring
241           when :escaped_outstring: :outstring
242         end
243       end
244       pos = newpos + 1
245     end
246
247     remainder = case state
248       when :instring
249         self[region_start .. -1].gsub(/^\s+/, "")
250       else
251         nil
252       end
253
254     [ret, remainder]
255   end
256
257   def wrap len
258     ret = []
259     s = self
260     while s.length > len
261       cut = s[0 ... len].rindex(/\s/)
262       if cut
263         ret << s[0 ... cut]
264         s = s[(cut + 1) .. -1]
265       else
266         ret << s[0 ... len]
267         s = s[len .. -1]
268       end
269     end
270     ret << s
271   end
272
273   def normalize_whitespace
274     gsub(/\t/, "    ").gsub(/\r/, "")
275   end
276
277   ## takes a space-separated list of words, and returns an array of symbols.
278   ## typically used in Sup for translating Ferret's representation of a list
279   ## of labels (a string) to an array of label symbols.
280   def symbolistize; split.map { |x| x.intern } end
281 end
282
283 class Numeric
284   def clamp min, max
285     if self < min
286       min
287     elsif self > max
288       max
289     else
290       self
291     end
292   end
293
294   def in? range; range.member? self; end
295
296   def to_human_size
297     if self < 1024
298       to_s + "b"
299     elsif self < (1024 * 1024)
300       (self / 1024).to_s + "k"
301     elsif self < (1024 * 1024 * 1024)
302       (self / 1024 / 1024).to_s + "m"
303     else
304       (self / 1024 / 1024 / 1024).to_s + "g"
305     end
306   end
307 end
308
309 class Fixnum
310   def to_character
311     if self < 128 && self >= 0
312       chr
313     else
314       "<#{self}>"
315     end
316   end
317
318   ## hacking the english language
319   def pluralize s
320     to_s + " " +
321       if self == 1
322         s
323       else
324         if s =~ /(.*)y$/
325           $1 + "ies"
326         else
327           s + "s"
328         end
329       end
330   end
331 end
332
333 class Hash
334   def - o
335     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
336   end
337
338   def select_by_value v=true
339     select { |k, vv| vv == v }.map { |x| x.first }
340   end
341 end
342
343 module Enumerable
344   def map_with_index
345     ret = []
346     each_with_index { |x, i| ret << yield(x, i) }
347     ret
348   end
349
350   def sum; inject(0) { |x, y| x + y }; end
351   
352   def map_to_hash
353     ret = {}
354     each { |x| ret[x] = yield(x) }
355     ret
356   end
357
358   # like find, except returns the value of the block rather than the
359   # element itself.
360   def argfind
361     ret = nil
362     find { |e| ret ||= yield(e) }
363     ret || nil # force
364   end
365
366   def argmin
367     best, bestval = nil, nil
368     each do |e|
369       val = yield e
370       if bestval.nil? || val < bestval
371         best, bestval = e, val
372       end
373     end
374     best
375   end
376
377   ## returns the maximum shared prefix of an array of strings
378   ## optinally excluding a prefix
379   def shared_prefix caseless=false, exclude=""
380     return "" if empty?
381     prefix = ""
382     (0 ... first.length).each do |i|
383       c = (caseless ? first.downcase : first)[i]
384       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
385       next if exclude[i] == c
386       prefix += first[i].chr
387     end
388     prefix
389   end
390
391   def max_of
392     map { |e| yield e }.max
393   end
394 end
395
396 class Array
397   def flatten_one_level
398     inject([]) { |a, e| a + e }
399   end
400
401   def to_h; Hash[*flatten]; end
402   def rest; self[1..-1]; end
403
404   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
405
406   def last= e; self[-1] = e end
407   def nonempty?; !empty? end
408
409   def to_set_of_symbols
410     map { |x| x.is_a?(Symbol) ? x : x.intern }.uniq
411   end
412 end
413
414 class Time
415   def to_indexable_s
416     sprintf "%012d", self
417   end
418
419   def nearest_hour
420     if min < 30
421       self
422     else
423       self + (60 - min) * 60
424     end
425   end
426
427   def midnight # within a second
428     self - (hour * 60 * 60) - (min * 60) - sec
429   end
430
431   def is_the_same_day? other
432     (midnight - other.midnight).abs < 1
433   end
434
435   def is_the_day_before? other
436     other.midnight - midnight <=  24 * 60 * 60 + 1
437   end
438
439   def to_nice_distance_s from=Time.now
440     later_than = (self < from)
441     diff = (self.to_i - from.to_i).abs.to_f
442     text = 
443       [ ["second", 60],
444         ["minute", 60],
445         ["hour", 24],
446         ["day", 7],
447         ["week", 4.345], # heh heh
448         ["month", 12],
449         ["year", nil],
450       ].argfind do |unit, size|
451         if diff.round <= 1
452           "one #{unit}"
453         elsif size.nil? || diff.round < size
454           "#{diff.round} #{unit}s"
455         else
456           diff /= size.to_f
457           false
458         end
459       end
460     if later_than
461       text + " ago"
462     else
463       "in " + text
464     end  
465   end
466
467   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
468   def to_nice_s from=Time.now
469     if year != from.year
470       strftime "%b %Y"
471     elsif month != from.month
472       strftime "%b %e"
473     else
474       if is_the_same_day? from
475         strftime("%l:%M%P")
476       elsif is_the_day_before? from
477         "Yest."  + nearest_hour.strftime("%l%P")
478       else
479         strftime "%b %e"
480       end
481     end
482   end
483 end
484
485 ## simple singleton module. far less complete and insane than the ruby
486 ## standard library one, but automatically forwards methods calls and
487 ## allows for constructors that take arguments.
488 ##
489 ## You must have #initialize call "self.class.i_am_the_instance self"
490 ## at some point or everything will fail horribly.
491 module Singleton
492   module ClassMethods
493     def instance; @instance; end
494     def instantiated?; defined?(@instance) && !@instance.nil?; end
495     def deinstantiate!; @instance = nil; end
496     def method_missing meth, *a, &b
497       raise "no instance defined!" unless defined? @instance
498
499       ## if we've been deinstantiated, just drop all calls. this is
500       ## useful because threads that might be active during the
501       ## cleanup process (e.g. polling) would otherwise have to
502       ## special-case every call to a Singleton object
503       return nil if @instance.nil?
504
505       @instance.send meth, *a, &b
506     end
507     def i_am_the_instance o
508       raise "there can be only one! (instance)" if defined? @instance
509       @instance = o
510     end
511   end
512
513   def self.included klass
514     klass.extend ClassMethods
515   end
516 end
517
518 ## wraps an object. if it throws an exception, keeps a copy.
519 class Recoverable
520   def initialize o
521     @o = o
522     @error = nil
523     @mutex = Mutex.new
524   end
525
526   attr_accessor :error
527
528   def clear_error!; @error = nil; end
529   def has_errors?; !@error.nil?; end
530
531   def method_missing m, *a, &b; __pass m, *a, &b end
532   
533   def id; __pass :id; end
534   def to_s; __pass :to_s; end
535   def to_yaml x; __pass :to_yaml, x; end
536   def is_a? c; @o.is_a? c; end
537
538   def respond_to?(m, include_private=false)
539     @o.respond_to?(m, include_private)
540   end
541
542   def __pass m, *a, &b
543     begin
544       @o.send(m, *a, &b)
545     rescue Exception => e
546       @error ||= e
547       raise
548     end
549   end
550 end
551
552 ## acts like a hash with an initialization block, but saves any
553 ## newly-created value even upon lookup.
554 ##
555 ## for example:
556 ##
557 ## class C
558 ##   attr_accessor :val
559 ##   def initialize; @val = 0 end
560 ## end
561 ## 
562 ## h = Hash.new { C.new }
563 ## h[:a].val # => 0
564 ## h[:a].val = 1
565 ## h[:a].val # => 0
566 ##
567 ## h2 = SavingHash.new { C.new }
568 ## h2[:a].val # => 0
569 ## h2[:a].val = 1
570 ## h2[:a].val # => 1
571 ##
572 ## important note: you REALLY want to use #member? to test existence,
573 ## because just checking h[anything] will always evaluate to true
574 ## (except for degenerate constructor blocks that return nil or false)
575 class SavingHash
576   def initialize &b
577     @constructor = b
578     @hash = Hash.new
579   end
580
581   def [] k
582     @hash[k] ||= @constructor.call(k)
583   end
584
585   defer_all_other_method_calls_to :hash
586 end
587
588 class OrderedHash < Hash
589   alias_method :store, :[]=
590   alias_method :each_pair, :each
591   attr_reader :keys
592
593   def initialize *a
594     @keys = []
595     a.each { |k, v| self[k] = v }
596   end
597
598   def []= key, val
599     @keys << key unless member?(key)
600     super
601   end
602
603   def values; keys.map { |k| self[k] } end
604   def index key; @keys.index key end
605
606   def delete key
607     @keys.delete key
608     super
609   end
610
611   def each; @keys.each { |k| yield k, self[k] } end
612 end
613
614 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
615 ## first person to hit the finish line
616 class FinishLine
617   def initialize
618     @m = Mutex.new
619     @over = false
620   end
621
622   def winner?
623     @m.synchronize { !@over && @over = true }
624   end
625 end
626
627 class Iconv
628   def self.easy_decode target, charset, text
629     return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
630     charset = case charset
631                 when /UTF[-_ ]?8/i: "utf-8"
632                 when /(iso[-_ ])?latin[-_ ]?1$/i: "ISO-8859-1"
633                 when /iso[-_ ]?8859[-_ ]?15/i: 'ISO-8859-15'
634                 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i: "utf-7"
635                 else charset
636               end
637
638     # Convert:
639     #
640     # Remember - Iconv.open(to, from)!
641     Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
642   end
643 end