]> 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 end
409
410 class Time
411   def to_indexable_s
412     sprintf "%012d", self
413   end
414
415   def nearest_hour
416     if min < 30
417       self
418     else
419       self + (60 - min) * 60
420     end
421   end
422
423   def midnight # within a second
424     self - (hour * 60 * 60) - (min * 60) - sec
425   end
426
427   def is_the_same_day? other
428     (midnight - other.midnight).abs < 1
429   end
430
431   def is_the_day_before? other
432     other.midnight - midnight <=  24 * 60 * 60 + 1
433   end
434
435   def to_nice_distance_s from=Time.now
436     later_than = (self < from)
437     diff = (self.to_i - from.to_i).abs.to_f
438     text = 
439       [ ["second", 60],
440         ["minute", 60],
441         ["hour", 24],
442         ["day", 7],
443         ["week", 4.345], # heh heh
444         ["month", 12],
445         ["year", nil],
446       ].argfind do |unit, size|
447         if diff.round <= 1
448           "one #{unit}"
449         elsif size.nil? || diff.round < size
450           "#{diff.round} #{unit}s"
451         else
452           diff /= size.to_f
453           false
454         end
455       end
456     if later_than
457       text + " ago"
458     else
459       "in " + text
460     end  
461   end
462
463   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
464   def to_nice_s from=Time.now
465     if year != from.year
466       strftime "%b %Y"
467     elsif month != from.month
468       strftime "%b %e"
469     else
470       if is_the_same_day? from
471         strftime("%l:%M%P")
472       elsif is_the_day_before? from
473         "Yest."  + nearest_hour.strftime("%l%P")
474       else
475         strftime "%b %e"
476       end
477     end
478   end
479 end
480
481 ## simple singleton module. far less complete and insane than the ruby
482 ## standard library one, but automatically forwards methods calls and
483 ## allows for constructors that take arguments.
484 ##
485 ## You must have #initialize call "self.class.i_am_the_instance self"
486 ## at some point or everything will fail horribly.
487 module Singleton
488   module ClassMethods
489     def instance; @instance; end
490     def instantiated?; defined?(@instance) && !@instance.nil?; end
491     def deinstantiate!; @instance = nil; end
492     def method_missing meth, *a, &b
493       raise "no instance defined!" unless defined? @instance
494
495       ## if we've been deinstantiated, just drop all calls. this is
496       ## useful because threads that might be active during the
497       ## cleanup process (e.g. polling) would otherwise have to
498       ## special-case every call to a Singleton object
499       return nil if @instance.nil?
500
501       @instance.send meth, *a, &b
502     end
503     def i_am_the_instance o
504       raise "there can be only one! (instance)" if defined? @instance
505       @instance = o
506     end
507   end
508
509   def self.included klass
510     klass.extend ClassMethods
511   end
512 end
513
514 ## wraps an object. if it throws an exception, keeps a copy.
515 class Recoverable
516   def initialize o
517     @o = o
518     @error = nil
519     @mutex = Mutex.new
520   end
521
522   attr_accessor :error
523
524   def clear_error!; @error = nil; end
525   def has_errors?; !@error.nil?; end
526
527   def method_missing m, *a, &b; __pass m, *a, &b end
528   
529   def id; __pass :id; end
530   def to_s; __pass :to_s; end
531   def to_yaml x; __pass :to_yaml, x; end
532   def is_a? c; @o.is_a? c; end
533
534   def respond_to?(m, include_private=false)
535     @o.respond_to?(m, include_private)
536   end
537
538   def __pass m, *a, &b
539     begin
540       @o.send(m, *a, &b)
541     rescue Exception => e
542       @error ||= e
543       raise
544     end
545   end
546 end
547
548 ## acts like a hash with an initialization block, but saves any
549 ## newly-created value even upon lookup.
550 ##
551 ## for example:
552 ##
553 ## class C
554 ##   attr_accessor :val
555 ##   def initialize; @val = 0 end
556 ## end
557 ## 
558 ## h = Hash.new { C.new }
559 ## h[:a].val # => 0
560 ## h[:a].val = 1
561 ## h[:a].val # => 0
562 ##
563 ## h2 = SavingHash.new { C.new }
564 ## h2[:a].val # => 0
565 ## h2[:a].val = 1
566 ## h2[:a].val # => 1
567 ##
568 ## important note: you REALLY want to use #member? to test existence,
569 ## because just checking h[anything] will always evaluate to true
570 ## (except for degenerate constructor blocks that return nil or false)
571 class SavingHash
572   def initialize &b
573     @constructor = b
574     @hash = Hash.new
575   end
576
577   def [] k
578     @hash[k] ||= @constructor.call(k)
579   end
580
581   defer_all_other_method_calls_to :hash
582 end
583
584 class OrderedHash < Hash
585   alias_method :store, :[]=
586   alias_method :each_pair, :each
587   attr_reader :keys
588
589   def initialize *a
590     @keys = []
591     a.each { |k, v| self[k] = v }
592   end
593
594   def []= key, val
595     @keys << key unless member?(key)
596     super
597   end
598
599   def values; keys.map { |k| self[k] } end
600   def index key; @keys.index key end
601
602   def delete key
603     @keys.delete key
604     super
605   end
606
607   def each; @keys.each { |k| yield k, self[k] } end
608 end
609
610 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
611 ## first person to hit the finish line
612 class FinishLine
613   def initialize
614     @m = Mutex.new
615     @over = false
616   end
617
618   def winner?
619     @m.synchronize { !@over && @over = true }
620   end
621 end
622
623 class Iconv
624   def self.easy_decode target, charset, text
625     return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
626     charset = case charset
627                 when /UTF[-_ ]?8/i: "utf-8"
628                 when /(iso[-_ ])?latin[-_ ]?1$/i: "ISO-8859-1"
629                 when /iso[-_ ]?8859[-_ ]?15/i: 'ISO-8859-15'
630                 when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i: "utf-7"
631                 else charset
632               end
633
634     # Convert:
635     #
636     # Remember - Iconv.open(to, from)!
637     Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
638   end
639 end