]> git.cworth.org Git - sup/blob - lib/sup/util.rb
encoding bugfix thanks to jeff covey
[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         when "7bit", "8bit"
81           IO.read(fn)
82         else
83           raise EncodingUnsupportedError, t.encoding
84         end
85
86       add_part 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   def synchronized *meth
134     meth.each do
135       class_eval <<-EOF
136         alias unsynchronized_#{meth} #{meth}
137         def #{meth}(*a, &b)
138           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
139         end
140       EOF
141     end
142   end
143 end
144
145 class String
146   def camel_to_hyphy
147     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
148   end
149
150   def find_all_positions x
151     ret = []
152     start = 0
153     while start < length
154       pos = index x, start
155       break if pos.nil?
156       ret << pos
157       start = pos + 1
158     end
159     ret
160   end
161
162   def ucfirst
163     self[0 .. 0].upcase + self[1 .. -1]
164   end
165
166   ## a very complicated regex found on teh internets to split on
167   ## commas, unless they occurr within double quotes.
168   def split_on_commas
169     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
170   end
171
172   def wrap len
173     ret = []
174     s = self
175     while s.length > len
176       cut = s[0 ... len].rindex(/\s/)
177       if cut
178         ret << s[0 ... cut]
179         s = s[(cut + 1) .. -1]
180       else
181         ret << s[0 ... len]
182         s = s[len .. -1]
183       end
184     end
185     ret << s
186   end
187
188   def normalize_whitespace
189     gsub(/\t/, "    ").gsub(/\r/, "")
190   end
191 end
192
193 class Numeric
194   def clamp min, max
195     if self < min
196       min
197     elsif self > max
198       max
199     else
200       self
201     end
202   end
203
204   def in? range; range.member? self; end
205 end
206
207 class Fixnum
208   def num_digits base=10
209     return 1 if self == 0
210     1 + (Math.log(self) / Math.log(10)).floor
211   end
212   
213   def to_character
214     if self < 128 && self >= 0
215       chr
216     else
217       "<#{self}>"
218     end
219   end
220 end
221
222 class Hash
223   def - o
224     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
225   end
226
227   def select_by_value v=true
228     select { |k, vv| vv == v }.map { |x| x.first }
229   end
230 end
231
232 module Enumerable
233   def map_with_index
234     ret = []
235     each_with_index { |x, i| ret << yield(x, i) }
236     ret
237   end
238
239   def sum; inject(0) { |x, y| x + y }; end
240   
241   def map_to_hash
242     ret = {}
243     each { |x| ret[x] = yield(x) }
244     ret
245   end
246
247   # like find, except returns the value of the block rather than the
248   # element itself.
249   def argfind
250     ret = nil
251     find { |e| ret ||= yield(e) }
252     ret || nil # force
253   end
254
255   def argmin
256     best, bestval = nil, nil
257     each do |e|
258       val = yield e
259       if bestval.nil? || val < bestval
260         best, bestval = e, val
261       end
262     end
263     best
264   end
265
266   ## returns the maximum shared prefix of an array of strings
267   ## optinally excluding a prefix
268   def shared_prefix caseless=false, exclude=""
269     return "" if empty?
270     prefix = ""
271     (0 ... first.length).each do |i|
272       c = (caseless ? first.downcase : first)[i]
273       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
274       next if exclude[i] == c
275       prefix += first[i].chr
276     end
277     prefix
278   end
279
280   def max_of
281     map { |e| yield e }.max
282   end
283 end
284
285 class Array
286   def flatten_one_level
287     inject([]) { |a, e| a + e }
288   end
289
290   def to_h; Hash[*flatten]; end
291   def rest; self[1..-1]; end
292
293   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
294
295   def last= e; self[-1] = e end
296 end
297
298 class Time
299   def to_indexable_s
300     sprintf "%012d", self
301   end
302
303   def nearest_hour
304     if min < 30
305       self
306     else
307       self + (60 - min) * 60
308     end
309   end
310
311   def midnight # within a second
312     self - (hour * 60 * 60) - (min * 60) - sec
313   end
314
315   def is_the_same_day? other
316     (midnight - other.midnight).abs < 1
317   end
318
319   def is_the_day_before? other
320     other.midnight - midnight <=  24 * 60 * 60 + 1
321   end
322
323   def to_nice_distance_s from=Time.now
324     later_than = (self < from)
325     diff = (self.to_i - from.to_i).abs.to_f
326     text = 
327       [ ["second", 60],
328         ["minute", 60],
329         ["hour", 24],
330         ["day", 7],
331         ["week", 4.345], # heh heh
332         ["month", 12],
333         ["year", nil],
334       ].argfind do |unit, size|
335         if diff.round <= 1
336           "one #{unit}"
337         elsif size.nil? || diff.round < size
338           "#{diff.round} #{unit}s"
339         else
340           diff /= size.to_f
341           false
342         end
343       end
344     if later_than
345       text + " ago"
346     else
347       "in " + text
348     end  
349   end
350
351   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
352   def to_nice_s from=Time.now
353     if year != from.year
354       strftime "%b %Y"
355     elsif month != from.month
356       strftime "%b %e"
357     else
358       if is_the_same_day? from
359         strftime("%l:%M%P")
360       elsif is_the_day_before? from
361         "Yest."  + nearest_hour.strftime("%l%P")
362       else
363         strftime "%b %e"
364       end
365     end
366   end
367 end
368
369 ## simple singleton module. far less complete and insane than the ruby
370 ## standard library one, but automatically forwards methods calls and
371 ## allows for constructors that take arguments.
372 ##
373 ## You must have #initialize call "self.class.i_am_the_instance self"
374 ## at some point or everything will fail horribly.
375 module Singleton
376   module ClassMethods
377     def instance; @instance; end
378     def instantiated?; defined?(@instance) && !@instance.nil?; end
379     def deinstantiate!; @instance = nil; end
380     def method_missing meth, *a, &b
381       raise "no instance defined!" unless defined? @instance
382
383       ## if we've been deinstantiated, just drop all calls. this is
384       ## useful because threads that might be active during the
385       ## cleanup process (e.g. polling) would otherwise have to
386       ## special-case every call to a Singleton object
387       return nil if @instance.nil?
388
389       @instance.send meth, *a, &b
390     end
391     def i_am_the_instance o
392       raise "there can be only one! (instance)" if defined? @instance
393       @instance = o
394     end
395   end
396
397   def self.included klass
398     klass.extend ClassMethods
399   end
400 end
401
402 ## wraps an object. if it throws an exception, keeps a copy, and
403 ## rethrows it for any further method calls.
404 class Recoverable
405   def initialize o
406     @o = o
407     @e = nil
408   end
409
410   def clear_error!; @e = nil; end
411   def has_errors?; !@e.nil?; end
412   def error; @e; end
413
414   def method_missing m, *a, &b; __pass m, *a, &b; end
415   
416   def id; __pass :id; end
417   def to_s; __pass :to_s; end
418   def to_yaml x; __pass :to_yaml, x; end
419   def is_a? c; @o.is_a? c; end
420
421   def respond_to? m; @o.respond_to? m end
422
423   def __pass m, *a, &b
424     begin
425       @o.send(m, *a, &b)
426     rescue Exception => e
427       @e = e
428       raise e
429     end
430   end
431 end
432
433 ## acts like a hash with an initialization block, but saves any
434 ## newly-created value even upon lookup.
435 ##
436 ## for example:
437 ##
438 ## class C
439 ##   attr_accessor :val
440 ##   def initialize; @val = 0 end
441 ## end
442 ## 
443 ## h = Hash.new { C.new }
444 ## h[:a].val # => 0
445 ## h[:a].val = 1
446 ## h[:a].val # => 0
447 ##
448 ## h2 = SavingHash.new { C.new }
449 ## h2[:a].val # => 0
450 ## h2[:a].val = 1
451 ## h2[:a].val # => 1
452 ##
453 ## important note: you REALLY want to use #member? to test existence,
454 ## because just checking h[anything] will always evaluate to true
455 ## (except for degenerate constructor blocks that return nil or false)
456 class SavingHash
457   def initialize &b
458     @constructor = b
459     @hash = Hash.new
460   end
461
462   def [] k
463     @hash[k] ||= @constructor.call(k)
464   end
465
466   defer_all_other_method_calls_to :hash
467 end