]> git.cworth.org Git - sup/blob - lib/sup/util.rb
hook system
[sup] / lib / sup / util.rb
1 require 'lockfile'
2 require 'mime/types'
3 require 'pathname'
4
5 ## time for some monkeypatching!
6 class Lockfile
7   def gen_lock_id
8     Hash[
9          'host' => "#{ Socket.gethostname }",
10          'pid' => "#{ Process.pid }",
11          'ppid' => "#{ Process.ppid }",
12          'time' => timestamp,
13          'pname' => $0,
14          'user' => ENV["USER"]
15         ]
16   end
17
18   def dump_lock_id lock_id = @lock_id
19       "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
20         lock_id.values_at('host','pid','ppid','time','user', 'pname')
21     end
22
23   def lockinfo_on_disk
24     h = load_lock_id IO.read(path)
25     h['mtime'] = File.mtime path
26     h
27   end
28
29   def touch_yourself; touch path end
30 end
31
32 class Pathname
33   def human_size
34     s =
35       begin
36         size
37       rescue SystemCallError
38         return "?"
39       end
40
41     if s < 1024
42       s.to_s + "b"
43     elsif s < (1024 * 1024)
44       (s / 1024).to_s + "k"
45     elsif s < (1024 * 1024 * 1024)
46       (s / 1024 / 1024).to_s + "m"
47     else
48       (s / 1024 / 1024 / 1024).to_s + "g"
49     end
50   end
51
52   def human_time
53     begin
54       ctime.strftime("%Y-%m-%d %H:%M")
55     rescue SystemCallError
56       "?"
57     end
58   end
59 end
60
61 ## more monkeypatching!
62 module RMail
63   class EncodingUnsupportedError < StandardError; end
64
65   class Message
66     def add_attachment fn
67       bfn = File.basename fn
68       a = Message.new
69       t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
70
71       a.header.add "Content-Disposition", "attachment; filename=#{bfn}"
72       a.header.add "Content-Type", "#{t.content_type}; name=#{bfn}"
73       a.header.add "Content-Transfer-Encoding", t.encoding
74       a.body =
75         case t.encoding
76         when "base64"
77           [IO.read(fn)].pack "m"
78         when "quoted-printable"
79           [IO.read(fn)].pack "M"
80         else
81           raise EncodingUnsupportedError, t.encoding
82         end
83
84       add_part a
85     end
86   end
87 end
88
89 class Range
90   ## only valid for integer ranges (unless I guess it's exclusive)
91   def size 
92     last - first + (exclude_end? ? 0 : 1)
93   end
94 end
95
96 class Module
97   def bool_reader *args
98     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
99   end
100   def bool_writer *args; attr_writer(*args); end
101   def bool_accessor *args
102     bool_reader(*args)
103     bool_writer(*args)
104   end
105
106   def defer_all_other_method_calls_to obj
107     class_eval %{
108       def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
109       def respond_to? meth; @#{obj}.respond_to?(meth); end
110     }
111   end
112 end
113
114 class Object
115   def ancestors
116     ret = []
117     klass = self.class
118
119     until klass == Object
120       ret << klass
121       klass = klass.superclass
122     end
123     ret
124   end
125
126   ## "k combinator"
127   def returning x; yield x; x; end
128
129   ## clone of java-style whole-method synchronization
130   ## assumes a @mutex variable
131   def synchronized *meth
132     meth.each do
133       class_eval <<-EOF
134         alias unsynchronized_#{meth} #{meth}
135         def #{meth}(*a, &b)
136           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
137         end
138       EOF
139     end
140   end
141 end
142
143 class String
144   def camel_to_hyphy
145     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
146   end
147
148   def find_all_positions x
149     ret = []
150     start = 0
151     while start < length
152       pos = index x, start
153       break if pos.nil?
154       ret << pos
155       start = pos + 1
156     end
157     ret
158   end
159
160   def ucfirst
161     self[0 .. 0].upcase + self[1 .. -1]
162   end
163
164   ## a very complicated regex found on teh internets to split on
165   ## commas, unless they occurr within double quotes.
166   def split_on_commas
167     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
168   end
169
170   def wrap len
171     ret = []
172     s = self
173     while s.length > len
174       cut = s[0 ... len].rindex(/\s/)
175       if cut
176         ret << s[0 ... cut]
177         s = s[(cut + 1) .. -1]
178       else
179         ret << s[0 ... len]
180         s = s[len .. -1]
181       end
182     end
183     ret << s
184   end
185
186   def normalize_whitespace
187     gsub(/\t/, "    ").gsub(/\r/, "")
188   end
189 end
190
191 class Numeric
192   def clamp min, max
193     if self < min
194       min
195     elsif self > max
196       max
197     else
198       self
199     end
200   end
201
202   def in? range; range.member? self; end
203 end
204
205 class Fixnum
206   def num_digits base=10
207     return 1 if self == 0
208     1 + (Math.log(self) / Math.log(10)).floor
209   end
210   
211   def to_character
212     if self < 128 && self >= 0
213       chr
214     else
215       "<#{self}>"
216     end
217   end
218 end
219
220 class Hash
221   def - o
222     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
223   end
224
225   def select_by_value v=true
226     select { |k, vv| vv == v }.map { |x| x.first }
227   end
228 end
229
230 module Enumerable
231   def map_with_index
232     ret = []
233     each_with_index { |x, i| ret << yield(x, i) }
234     ret
235   end
236
237   def sum; inject(0) { |x, y| x + y }; end
238   
239   def map_to_hash
240     ret = {}
241     each { |x| ret[x] = yield(x) }
242     ret
243   end
244
245   # like find, except returns the value of the block rather than the
246   # element itself.
247   def argfind
248     ret = nil
249     find { |e| ret ||= yield(e) }
250     ret || nil # force
251   end
252
253   def argmin
254     best, bestval = nil, nil
255     each do |e|
256       val = yield e
257       if bestval.nil? || val < bestval
258         best, bestval = e, val
259       end
260     end
261     best
262   end
263
264   ## returns the maximum shared prefix of an array of strings
265   ## optinally excluding a prefix
266   def shared_prefix caseless=false, exclude=""
267     return "" if empty?
268     prefix = ""
269     (0 ... first.length).each do |i|
270       c = (caseless ? first.downcase : first)[i]
271       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
272       next if exclude[i] == c
273       prefix += first[i].chr
274     end
275     prefix
276   end
277
278   def max_of
279     map { |e| yield e }.max
280   end
281 end
282
283 class Array
284   def flatten_one_level
285     inject([]) { |a, e| a + e }
286   end
287
288   def to_h; Hash[*flatten]; end
289   def rest; self[1..-1]; end
290
291   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
292
293   def last= e; self[-1] = e end
294 end
295
296 class Time
297   def to_indexable_s
298     sprintf "%012d", self
299   end
300
301   def nearest_hour
302     if min < 30
303       self
304     else
305       self + (60 - min) * 60
306     end
307   end
308
309   def midnight # within a second
310     self - (hour * 60 * 60) - (min * 60) - sec
311   end
312
313   def is_the_same_day? other
314     (midnight - other.midnight).abs < 1
315   end
316
317   def is_the_day_before? other
318     other.midnight - midnight <=  24 * 60 * 60 + 1
319   end
320
321   def to_nice_distance_s from=Time.now
322     later_than = (self < from)
323     diff = (self.to_i - from.to_i).abs.to_f
324     text = 
325       [ ["second", 60],
326         ["minute", 60],
327         ["hour", 24],
328         ["day", 7],
329         ["week", 4.345], # heh heh
330         ["month", 12],
331         ["year", nil],
332       ].argfind do |unit, size|
333         if diff.round <= 1
334           "one #{unit}"
335         elsif size.nil? || diff.round < size
336           "#{diff.round} #{unit}s"
337         else
338           diff /= size.to_f
339           false
340         end
341       end
342     if later_than
343       text + " ago"
344     else
345       "in " + text
346     end  
347   end
348
349   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
350   def to_nice_s from=Time.now
351     if year != from.year
352       strftime "%b %Y"
353     elsif month != from.month
354       strftime "%b %e"
355     else
356       if is_the_same_day? from
357         strftime("%l:%M%P")
358       elsif is_the_day_before? from
359         "Yest."  + nearest_hour.strftime("%l%P")
360       else
361         strftime "%b %e"
362       end
363     end
364   end
365 end
366
367 ## simple singleton module. far less complete and insane than the ruby
368 ## standard library one, but automatically forwards methods calls and
369 ## allows for constructors that take arguments.
370 ##
371 ## You must have #initialize call "self.class.i_am_the_instance self"
372 ## at some point or everything will fail horribly.
373 module Singleton
374   module ClassMethods
375     def instance; @instance; end
376     def instantiated?; defined?(@instance) && !@instance.nil?; end
377     def deinstantiate!; @instance = nil; end
378     def method_missing meth, *a, &b
379       raise "no instance defined!" unless defined? @instance
380
381       ## if we've been deinstantiated, just drop all calls. this is
382       ## useful because threads that might be active during the
383       ## cleanup process (e.g. polling) would otherwise have to
384       ## special-case every call to a Singleton object
385       return nil if @instance.nil?
386
387       @instance.send meth, *a, &b
388     end
389     def i_am_the_instance o
390       raise "there can be only one! (instance)" if defined? @instance
391       @instance = o
392     end
393   end
394
395   def self.included klass
396     klass.extend ClassMethods
397   end
398 end
399
400 ## wraps an object. if it throws an exception, keeps a copy, and
401 ## rethrows it for any further method calls.
402 class Recoverable
403   def initialize o
404     @o = o
405     @e = nil
406   end
407
408   def clear_error!; @e = nil; end
409   def has_errors?; !@e.nil?; end
410   def error; @e; end
411
412   def method_missing m, *a, &b; __pass m, *a, &b; end
413   
414   def id; __pass :id; end
415   def to_s; __pass :to_s; end
416   def to_yaml x; __pass :to_yaml, x; end
417   def is_a? c; @o.is_a? c; end
418
419   def respond_to? m; @o.respond_to? m end
420
421   def __pass m, *a, &b
422     begin
423       @o.send(m, *a, &b)
424     rescue Exception => e
425       @e = e
426       raise e
427     end
428   end
429 end
430
431 ## acts like a hash with an initialization block, but saves any
432 ## newly-created value even upon lookup.
433 ##
434 ## for example:
435 ##
436 ## class C
437 ##   attr_accessor :val
438 ##   def initialize; @val = 0 end
439 ## end
440 ## 
441 ## h = Hash.new { C.new }
442 ## h[:a].val # => 0
443 ## h[:a].val = 1
444 ## h[:a].val # => 0
445 ##
446 ## h2 = SavingHash.new { C.new }
447 ## h2[:a].val # => 0
448 ## h2[:a].val = 1
449 ## h2[:a].val # => 1
450 ##
451 ## important note: you REALLY want to use #member? to test existence,
452 ## because just checking h[anything] will always evaluate to true
453 ## (except for degenerate constructor blocks that return nil or false)
454 class SavingHash
455   def initialize &b
456     @constructor = b
457     @hash = Hash.new
458   end
459
460   def [] k
461     @hash[k] ||= @constructor.call(k)
462   end
463
464   defer_all_other_method_calls_to :hash
465 end