]> git.cworth.org Git - sup/blob - lib/sup/util.rb
Merge branch 'xapian-updates' into next
[sup] / lib / sup / util.rb
1 require 'thread'
2 require 'lockfile'
3 require 'mime/types'
4 require 'pathname'
5 require 'set'
6
7 ## time for some monkeypatching!
8 class Lockfile
9   def gen_lock_id
10     Hash[
11          'host' => "#{ Socket.gethostname }",
12          'pid' => "#{ Process.pid }",
13          'ppid' => "#{ Process.ppid }",
14          'time' => timestamp,
15          'pname' => $0,
16          'user' => ENV["USER"]
17         ]
18   end
19
20   def dump_lock_id lock_id = @lock_id
21       "host: %s\npid: %s\nppid: %s\ntime: %s\nuser: %s\npname: %s\n" %
22         lock_id.values_at('host','pid','ppid','time','user', 'pname')
23     end
24
25   def lockinfo_on_disk
26     h = load_lock_id IO.read(path)
27     h['mtime'] = File.mtime path
28     h['path'] = path
29     h
30   end
31
32   def touch_yourself; touch path end
33 end
34
35 class Pathname
36   def human_size
37     s =
38       begin
39         size
40       rescue SystemCallError
41         return "?"
42       end
43     s.to_human_size
44   end
45
46   def human_time
47     begin
48       ctime.strftime("%Y-%m-%d %H:%M")
49     rescue SystemCallError
50       "?"
51     end
52   end
53 end
54
55 ## more monkeypatching!
56 module RMail
57   class EncodingUnsupportedError < StandardError; end
58
59   class Message
60     def self.make_file_attachment fn
61       bfn = File.basename fn
62       t = MIME::Types.type_for(bfn).first || MIME::Types.type_for("exe").first
63       make_attachment IO.read(fn), t.content_type, t.encoding, bfn.to_s
64     end
65
66     def charset
67       if header.field?("content-type") && header.fetch("content-type") =~ /charset="?(.*?)"?(;|$)/i
68         $1
69       end
70     end
71
72     def self.make_attachment payload, mime_type, encoding, filename
73       a = Message.new
74       a.header.add "Content-Disposition", "attachment; filename=#{filename.inspect}"
75       a.header.add "Content-Type", "#{mime_type}; name=#{filename.inspect}"
76       a.header.add "Content-Transfer-Encoding", encoding if encoding
77       a.body =
78         case encoding
79         when "base64"
80           [payload].pack "m"
81         when "quoted-printable"
82           [payload].pack "M"
83         when "7bit", "8bit", nil
84           payload
85         else
86           raise EncodingUnsupportedError, encoding.inspect
87         end
88       a
89     end
90   end
91 end
92
93 class Range
94   ## only valid for integer ranges (unless I guess it's exclusive)
95   def size
96     last - first + (exclude_end? ? 0 : 1)
97   end
98 end
99
100 class Module
101   def bool_reader *args
102     args.each { |sym| class_eval %{ def #{sym}?; @#{sym}; end } }
103   end
104   def bool_writer *args; attr_writer(*args); end
105   def bool_accessor *args
106     bool_reader(*args)
107     bool_writer(*args)
108   end
109
110   def defer_all_other_method_calls_to obj
111     class_eval %{
112       def method_missing meth, *a, &b; @#{obj}.send meth, *a, &b; end
113       def respond_to?(m, include_private = false)
114         @#{obj}.respond_to?(m, include_private)
115       end
116     }
117   end
118 end
119
120 class Object
121   def ancestors
122     ret = []
123     klass = self.class
124
125     until klass == Object
126       ret << klass
127       klass = klass.superclass
128     end
129     ret
130   end
131
132   ## "k combinator"
133   def returning x; yield x; x; end
134
135   ## clone of java-style whole-method synchronization
136   ## assumes a @mutex variable
137   ## TODO: clean up, try harder to avoid namespace collisions
138   def synchronized *methods
139     methods.each do |meth|
140       class_eval <<-EOF
141         alias unsynchronized_#{meth} #{meth}
142         def #{meth}(*a, &b)
143           @mutex.synchronize { unsynchronized_#{meth}(*a, &b) }
144         end
145       EOF
146     end
147   end
148
149   def ignore_concurrent_calls *methods
150     methods.each do |meth|
151       mutex = "@__concurrent_protector_#{meth}"
152       flag = "@__concurrent_flag_#{meth}"
153       oldmeth = "__unprotected_#{meth}"
154       class_eval <<-EOF
155         alias #{oldmeth} #{meth}
156         def #{meth}(*a, &b)
157           #{mutex} = Mutex.new unless defined? #{mutex}
158           #{flag} = true unless defined? #{flag}
159           run = #{mutex}.synchronize do
160             if #{flag}
161               #{flag} = false
162               true
163             end
164           end
165           if run
166             ret = #{oldmeth}(*a, &b)
167             #{mutex}.synchronize { #{flag} = true }
168             ret
169           end
170         end
171       EOF
172     end
173   end
174 end
175
176 class String
177   ## nasty multibyte hack for ruby 1.8. if it's utf-8, split into chars using
178   ## the utf8 regex and count those. otherwise, use the byte length.
179   def display_length
180     if $encoding == "UTF-8"
181       scan(/./u).size
182     else
183       size
184     end
185   end
186
187   def camel_to_hyphy
188     self.gsub(/([a-z])([A-Z0-9])/, '\1-\2').downcase
189   end
190
191   def find_all_positions x
192     ret = []
193     start = 0
194     while start < length
195       pos = index x, start
196       break if pos.nil?
197       ret << pos
198       start = pos + 1
199     end
200     ret
201   end
202
203   ## a very complicated regex found on teh internets to split on
204   ## commas, unless they occurr within double quotes.
205   def split_on_commas
206     split(/,\s*(?=(?:[^"]*"[^"]*")*(?![^"]*"))/)
207   end
208
209   ## ok, here we do it the hard way. got to have a remainder for purposes of
210   ## tab-completing full email addresses
211   def split_on_commas_with_remainder
212     ret = []
213     state = :outstring
214     pos = 0
215     region_start = 0
216     while pos <= length
217       newpos = case state
218         when :escaped_instring, :escaped_outstring then pos
219         else index(/[,"\\]/, pos)
220       end
221
222       if newpos
223         char = self[newpos]
224       else
225         char = nil
226         newpos = length
227       end
228
229       case char
230       when ?"
231         state = case state
232           when :outstring then :instring
233           when :instring then :outstring
234           when :escaped_instring then :instring
235           when :escaped_outstring then :outstring
236         end
237       when ?,, nil
238         state = case state
239           when :outstring, :escaped_outstring then
240             ret << self[region_start ... newpos].gsub(/^\s+|\s+$/, "")
241             region_start = newpos + 1
242             :outstring
243           when :instring then :instring
244           when :escaped_instring then :instring
245         end
246       when ?\\
247         state = case state
248           when :instring then :escaped_instring
249           when :outstring then :escaped_outstring
250           when :escaped_instring then :instring
251           when :escaped_outstring then :outstring
252         end
253       end
254       pos = newpos + 1
255     end
256
257     remainder = case state
258       when :instring
259         self[region_start .. -1].gsub(/^\s+/, "")
260       else
261         nil
262       end
263
264     [ret, remainder]
265   end
266
267   def wrap len
268     ret = []
269     s = self
270     while s.length > len
271       cut = s[0 ... len].rindex(/\s/)
272       if cut
273         ret << s[0 ... cut]
274         s = s[(cut + 1) .. -1]
275       else
276         ret << s[0 ... len]
277         s = s[len .. -1]
278       end
279     end
280     ret << s
281   end
282
283   def normalize_whitespace
284     gsub(/\t/, "    ").gsub(/\r/, "")
285   end
286
287   unless method_defined? :ord
288     def ord
289       self[0]
290     end
291   end
292
293   ## takes a list of words, and returns an array of symbols.  typically used in
294   ## Sup for translating Ferret's representation of a list of labels (a string)
295   ## to an array of label symbols.
296   ##
297   ## split_on will be passed to String#split, so you can leave this nil for space.
298   def to_set_of_symbols split_on=nil; Set.new split(split_on).map { |x| x.strip.intern } end
299 end
300
301 class Numeric
302   def clamp min, max
303     if self < min
304       min
305     elsif self > max
306       max
307     else
308       self
309     end
310   end
311
312   def in? range; range.member? self; end
313
314   def to_human_size
315     if self < 1024
316       to_s + "b"
317     elsif self < (1024 * 1024)
318       (self / 1024).to_s + "k"
319     elsif self < (1024 * 1024 * 1024)
320       (self / 1024 / 1024).to_s + "m"
321     else
322       (self / 1024 / 1024 / 1024).to_s + "g"
323     end
324   end
325 end
326
327 class Fixnum
328   def to_character
329     if self < 128 && self >= 0
330       chr
331     else
332       "<#{self}>"
333     end
334   end
335
336   ## hacking the english language
337   def pluralize s
338     to_s + " " +
339       if self == 1
340         s
341       else
342         if s =~ /(.*)y$/
343           $1 + "ies"
344         else
345           s + "s"
346         end
347       end
348   end
349 end
350
351 class Hash
352   def - o
353     Hash[*self.map { |k, v| [k, v] unless o.include? k }.compact.flatten_one_level]
354   end
355
356   def select_by_value v=true
357     select { |k, vv| vv == v }.map { |x| x.first }
358   end
359 end
360
361 module Enumerable
362   def map_with_index
363     ret = []
364     each_with_index { |x, i| ret << yield(x, i) }
365     ret
366   end
367
368   def sum; inject(0) { |x, y| x + y }; end
369   
370   def map_to_hash
371     ret = {}
372     each { |x| ret[x] = yield(x) }
373     ret
374   end
375
376   # like find, except returns the value of the block rather than the
377   # element itself.
378   def argfind
379     ret = nil
380     find { |e| ret ||= yield(e) }
381     ret || nil # force
382   end
383
384   def argmin
385     best, bestval = nil, nil
386     each do |e|
387       val = yield e
388       if bestval.nil? || val < bestval
389         best, bestval = e, val
390       end
391     end
392     best
393   end
394
395   ## returns the maximum shared prefix of an array of strings
396   ## optinally excluding a prefix
397   def shared_prefix caseless=false, exclude=""
398     return "" if empty?
399     prefix = ""
400     (0 ... first.length).each do |i|
401       c = (caseless ? first.downcase : first)[i]
402       break unless all? { |s| (caseless ? s.downcase : s)[i] == c }
403       next if exclude[i] == c
404       prefix += first[i].chr
405     end
406     prefix
407   end
408
409   def max_of
410     map { |e| yield e }.max
411   end
412 end
413
414 class Array
415   def flatten_one_level
416     inject([]) { |a, e| a + e }
417   end
418
419   def to_h; Hash[*flatten]; end
420   def rest; self[1..-1]; end
421
422   def to_boolean_h; Hash[*map { |x| [x, true] }.flatten]; end
423
424   def last= e; self[-1] = e end
425   def nonempty?; !empty? end
426 end
427
428 class Time
429   def to_indexable_s
430     sprintf "%012d", self
431   end
432
433   def nearest_hour
434     if min < 30
435       self
436     else
437       self + (60 - min) * 60
438     end
439   end
440
441   def midnight # within a second
442     self - (hour * 60 * 60) - (min * 60) - sec
443   end
444
445   def is_the_same_day? other
446     (midnight - other.midnight).abs < 1
447   end
448
449   def is_the_day_before? other
450     other.midnight - midnight <=  24 * 60 * 60 + 1
451   end
452
453   def to_nice_distance_s from=Time.now
454     later_than = (self < from)
455     diff = (self.to_i - from.to_i).abs.to_f
456     text = 
457       [ ["second", 60],
458         ["minute", 60],
459         ["hour", 24],
460         ["day", 7],
461         ["week", 4.345], # heh heh
462         ["month", 12],
463         ["year", nil],
464       ].argfind do |unit, size|
465         if diff.round <= 1
466           "one #{unit}"
467         elsif size.nil? || diff.round < size
468           "#{diff.round} #{unit}s"
469         else
470           diff /= size.to_f
471           false
472         end
473       end
474     if later_than
475       text + " ago"
476     else
477       "in " + text
478     end  
479   end
480
481   TO_NICE_S_MAX_LEN = 9 # e.g. "Yest.10am"
482   def to_nice_s from=Time.now
483     if year != from.year
484       strftime "%b %Y"
485     elsif month != from.month
486       strftime "%b %e"
487     else
488       if is_the_same_day? from
489         strftime("%l:%M%P")
490       elsif is_the_day_before? from
491         "Yest."  + nearest_hour.strftime("%l%P")
492       else
493         strftime "%b %e"
494       end
495     end
496   end
497 end
498
499 ## simple singleton module. far less complete and insane than the ruby standard
500 ## library one, but it automatically forwards methods calls and allows for
501 ## constructors that take arguments.
502 ##
503 ## classes that inherit this can define initialize. however, you cannot call
504 ## .new on the class. To get the instance of the class, call .instance;
505 ## to create the instance, call init.
506 module Singleton
507   module ClassMethods
508     def instance; @instance; end
509     def instantiated?; defined?(@instance) && !@instance.nil?; end
510     def deinstantiate!; @instance = nil; end
511     def method_missing meth, *a, &b
512       raise "no #{name} instance defined in method call to #{meth}!" unless defined? @instance
513
514       ## if we've been deinstantiated, just drop all calls. this is
515       ## useful because threads that might be active during the
516       ## cleanup process (e.g. polling) would otherwise have to
517       ## special-case every call to a Singleton object
518       return nil if @instance.nil?
519
520       @instance.send meth, *a, &b
521     end
522     def init *args
523       raise "there can be only one! (instance)" if defined? @instance
524       @instance = new(*args)
525     end
526   end
527
528   def self.included klass
529     klass.private_class_method :allocate, :new
530     klass.extend ClassMethods
531   end
532 end
533
534 ## wraps an object. if it throws an exception, keeps a copy.
535 class Recoverable
536   def initialize o
537     @o = o
538     @error = nil
539     @mutex = Mutex.new
540   end
541
542   attr_accessor :error
543
544   def clear_error!; @error = nil; end
545   def has_errors?; !@error.nil?; end
546
547   def method_missing m, *a, &b; __pass m, *a, &b end
548
549   def id; __pass :id; end
550   def to_s; __pass :to_s; end
551   def to_yaml x; __pass :to_yaml, x; end
552   def is_a? c; @o.is_a? c; end
553
554   def respond_to?(m, include_private=false)
555     @o.respond_to?(m, include_private)
556   end
557
558   def __pass m, *a, &b
559     begin
560       @o.send(m, *a, &b)
561     rescue Exception => e
562       @error ||= e
563       raise
564     end
565   end
566 end
567
568 ## acts like a hash with an initialization block, but saves any
569 ## newly-created value even upon lookup.
570 ##
571 ## for example:
572 ##
573 ## class C
574 ##   attr_accessor :val
575 ##   def initialize; @val = 0 end
576 ## end
577 ## 
578 ## h = Hash.new { C.new }
579 ## h[:a].val # => 0
580 ## h[:a].val = 1
581 ## h[:a].val # => 0
582 ##
583 ## h2 = SavingHash.new { C.new }
584 ## h2[:a].val # => 0
585 ## h2[:a].val = 1
586 ## h2[:a].val # => 1
587 ##
588 ## important note: you REALLY want to use #member? to test existence,
589 ## because just checking h[anything] will always evaluate to true
590 ## (except for degenerate constructor blocks that return nil or false)
591 class SavingHash
592   def initialize &b
593     @constructor = b
594     @hash = Hash.new
595   end
596
597   def [] k
598     @hash[k] ||= @constructor.call(k)
599   end
600
601   defer_all_other_method_calls_to :hash
602 end
603
604 class OrderedHash < Hash
605   alias_method :store, :[]=
606   alias_method :each_pair, :each
607   attr_reader :keys
608
609   def initialize *a
610     @keys = []
611     a.each { |k, v| self[k] = v }
612   end
613
614   def []= key, val
615     @keys << key unless member?(key)
616     super
617   end
618
619   def values; keys.map { |k| self[k] } end
620   def index key; @keys.index key end
621
622   def delete key
623     @keys.delete key
624     super
625   end
626
627   def each; @keys.each { |k| yield k, self[k] } end
628 end
629
630 ## easy thread-safe class for determining who's the "winner" in a race (i.e.
631 ## first person to hit the finish line
632 class FinishLine
633   def initialize
634     @m = Mutex.new
635     @over = false
636   end
637
638   def winner?
639     @m.synchronize { !@over && @over = true }
640   end
641 end
642
643 class Iconv
644   def self.easy_decode target, charset, text
645     return text if charset =~ /^(x-unknown|unknown[-_ ]?8bit|ascii[-_ ]?7[-_ ]?bit)$/i
646     charset = case charset
647       when /UTF[-_ ]?8/i then "utf-8"
648       when /(iso[-_ ])?latin[-_ ]?1$/i then "ISO-8859-1"
649       when /iso[-_ ]?8859[-_ ]?15/i then 'ISO-8859-15'
650       when /unicode[-_ ]1[-_ ]1[-_ ]utf[-_]7/i then "utf-7"
651       else charset
652     end
653
654     begin
655       Iconv.iconv(target + "//IGNORE", charset, text + " ").join[0 .. -2]
656     rescue Errno::EINVAL, Iconv::InvalidEncoding, Iconv::InvalidCharacter, Iconv::IllegalSequence => e
657       info "couldn't transcode text from #{charset} to #{target} (\"#{text[0 ... 20]}\"...)"
658       text
659     end
660   end
661 end