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