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