Module: ALib::Util

Extended by:
Exporter
Includes:
Casting
Defined in:
lib/alib-0.5.1/util.rb

Overview

the utility module is a namespace for things which otherwise wouldn’t have a home. the methods of Util can be used as module methods or included into a class and then used as instance OR class methods

Defined Under Namespace

Modules: Casting, Exporter

Constant Summary collapse

LSPAWN_CMDNO =
[0]
LSPAWN_LOG =
Hash.new{|h,k| h[k] = alib.logging.default_logger}
LSPAWN_IO =
Class.new do
  def initialize log, prefix, io
    @log, @prefix, @io = log, prefix, io
  end
  def << buf
    @log << " #{ @prefix }__ #{ buf.chomp }\n"
    #@log << "#{ buf.chomp }\n"
    @io << buf if @io
  end
end

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Exporter

export

Methods included from Casting

#bool_cast, #float_cast, #float_list, #int_cast, #int_list, #pathname_cast, #re_cast, #string_cast, #string_list

Class Method Details

.append_features(c) ⇒ Object Also known as: included



30
31
32
33
34
35
# File 'lib/alib-0.5.1/util.rb', line 30

def append_features c
#--{{{
  super
  c.extend self 
#--}}}  
end

.castingObject



1573
# File 'lib/alib-0.5.1/util.rb', line 1573

def self.casting() Casting end

Instance Method Details

#__atomic_op(op, src, dst, opts = {}) ⇒ Object



1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/alib-0.5.1/util.rb', line 1132

def __atomic_op op, src, dst, opts = {}
#--{{{
  f, fu = File, FileUtils
  src_dirname, src_basename = f.split src
  src_stat = File.stat src

  dst = f.join dst, src_basename if test ?d, dst
  dst_dirname, dst_basename = f.split dst

  pid = Process.pid
  tmp = f.join dst_dirname, ".#{ dst_basename }.#{ hostname }.#{ pid }.#{ rand(4242) }.alib.tmp"

  timeout = getopt 'timeout', opts, 42
  utime = getopt 'utime', opts
  mtime = getopt 'mtime', opts
  atime = getopt 'atime', opts

  safe_cp = lambda do |a, b|
    4.times do
      begin
        break(fu.cp_r(a, b, :preserve => true))
      rescue => e
        STDERR.puts(errmsg(e))
        uncache a rescue nil
        uncache b rescue nil
        sleep timeout 
      end
    end
  end

  safe_mv = lambda do |a, b|
    4.times do
      begin
        break(fu.mv(a, b))
      rescue => e
        STDERR.puts(errmsg(e))
        uncache a rescue nil
        uncache b rescue nil
        sleep timeout 
      end
    end
  end

  safe_rm = lambda do |a|
    4.times do
      begin
        break(fu.rm_rf(a))
      rescue => e
        STDERR.puts(errmsg(e))
        uncache a rescue nil
        sleep timeout 
      end
    end
  end

  begin
    case op
      when 'cp'
        safe_cp[src, tmp]
        safe_mv[tmp, dst]
      when 'mv'
        safe_cp[src, tmp]
        safe_mv[tmp, dst]
        safe_rm[src]
      else
        raise ArgumentError, op.to_s
    end
  ensure
    safe_rm[tmp]
  end

  if utime or mtime or atime
    a = (atime or utime or src_stat.atime) 
    m = (mtime or utime or src_stat.mtime) 
    a = src_stat.atime unless Time === a 
    m = src_stat.mtime unless Time === m 
    ALib::Util::find(dst){|e| File.utime a, m, e} 
  end

  dst
#--}}}
end

#alive(pid) ⇒ Object Also known as: alive?

returns true if pid is running, false otherwise



203
204
205
206
207
208
209
210
211
212
213
# File 'lib/alib-0.5.1/util.rb', line 203

def alive pid
#--{{{
  pid = Integer("#{ pid }")
  begin
    Process::kill 0, pid
    true
  rescue Errno::ESRCH
    false
  end
#--}}}
end

#argv_split(argv) ⇒ Object

pop of options from an arglist



784
785
786
787
788
789
790
# File 'lib/alib-0.5.1/util.rb', line 784

def argv_split(argv)
#--{{{
  args = argv
  opts = Hash === args.last ? args.pop : {}
  [args, opts]
#--}}}
end

#atoi(s, opts = {}) ⇒ Object

convert a string to an integer



922
923
924
925
926
# File 'lib/alib-0.5.1/util.rb', line 922

def atoi(s, opts = {})
#--{{{
  strtod("#{ s }".gsub(%r/^0+/,''), 'base' => 10)
#--}}}
end

#atomic_copy(src, dst, opts = {}) ⇒ Object Also known as: atomic_cp



1216
1217
1218
# File 'lib/alib-0.5.1/util.rb', line 1216

def atomic_copy src, dst, opts = {}
  __atomic_op 'cp', src, dst, opts
end

#atomic_move(src, dst, opts = {}) ⇒ Object Also known as: atomic_mv



1223
1224
1225
# File 'lib/alib-0.5.1/util.rb', line 1223

def atomic_move src, dst, opts = {}
  __atomic_op 'mv', src, dst, opts
end

#attempt(label = 'attempt') ⇒ Object

is aborted. calls to attempt may be nested.



687
688
689
690
691
692
693
694
# File 'lib/alib-0.5.1/util.rb', line 687

def attempt label = 'attempt'
#--{{{
  ret = nil
  n_attempts = 0
  loop{ break unless catch("#{ label }"){ ret = yield(n_attempts += 1) } == 'try_again' }
  ret
#--}}}
end

#bcall(b, argv) ⇒ Object



1497
1498
1499
1500
1501
1502
# File 'lib/alib-0.5.1/util.rb', line 1497

def bcall b, argv
#--{{{
  a = block_argv b, argv
  b[*a]
#--}}}
end

#block_argv(b, argv) ⇒ Object



1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
# File 'lib/alib-0.5.1/util.rb', line 1480

def block_argv b, argv
#--{{{
  arity = b.arity
  if arity >= 0
    argv[0,arity]
  else
    head = []
    tail = []
    n = arity.abs - 1
    head = argv[0...n]
    tail = argv[n..-1]
    [*(head + tail)]
  end
#--}}}
end

#btrace(e) ⇒ Object

format exception backtrace as string



464
465
466
467
468
# File 'lib/alib-0.5.1/util.rb', line 464

def btrace e
#--{{{
  (e.backtrace or []).join("\n")
#--}}}
end

#camel_case(string) ⇒ Object



1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/alib-0.5.1/util.rb', line 1122

def camel_case string
#--{{{
  return string if string =~ %r/[A-Z]/ and string !~ %r/_/
  words = string.strip.split %r/\s*_+\s*/
  words.map!{|w| w.downcase.sub(%r/^./){|c| c.upcase}}
  words.join
#--}}}
end

#child_objectObject



1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
# File 'lib/alib-0.5.1/util.rb', line 1230

def child_object
#--{{{
  r, w = IO.pipe
  IO.popen('-') do |pipe|
    if pipe
      w.close
      buf = pipe.read
      Process.wait
      unless $? == 0
        loaded = Marshal.load r.read
        case loaded
          when Exception
            raise loaded
          else
            klass, message, backtrace = loaded
            e = klass.new message
            e.set_backtrace backtrace
            raise e
        end
      end
      Marshal.load(buf)
    else
      r.close
      begin
        print(Marshal.dump(yield))
      rescue Exception => e
        dumped =
          begin
            Marshal.dump e # we can't do this in ruby 1.8.1
          rescue
            Marshal.dump [e.class, e.message, e.backtrace]
          end
        w.write dumped
        exit! 42
      end
    end
  end
ensure
  r.close rescue nil
#--}}}
end

#columnize(buf, opts = {}) ⇒ Object

option (default 0)



638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'lib/alib-0.5.1/util.rb', line 638

def columnize buf, opts = {}
#--{{{
  width = getopt 'width', opts, 80
  indent = getopt 'indent', opts
  indent = Fixnum === indent ? (' ' * indent) : "#{ indent }"
  column = []
  words = buf.split %r/\s+/o
  row = "#{ indent }"
  while((word = words.shift))
    if((row.size + word.size) < (width - 1))
      row << word
    else
      column << row
      row = "#{ indent }"
      row << word
    end
    row << ' ' unless row.size == (width - 1)
  end
  column << row unless row.strip.empty?
  column.join "\n"
#--}}}
end

#constant_get(hierachy) ⇒ Object

a better const_get



721
722
723
724
725
726
727
728
729
730
731
# File 'lib/alib-0.5.1/util.rb', line 721

def constant_get(hierachy)
#--{{{
  ancestors = hierachy.split(%r/::/)
  parent = Object
  while((child = ancestors.shift))
    klass = parent.const_get child
    parent = klass
  end
  klass
#--}}}
end

#curl(uri, opts = {}) ⇒ Object



1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
# File 'lib/alib-0.5.1/util.rb', line 1273

def curl uri, opts = {}
#--{{{
  retries = begin;(getopt 'retries', opts, 42).to_i;rescue NoMethodError;0;end
  wait = Float(getopt('wait', opts, 2))
  begin
    uri = URI === uri ? uri : URI::parse(uri.to_s)
    req = Net::HTTP::Get.new(uri.path || 'index.html')
    res = Net::HTTP::start(uri.host, uri.port){|http| http.request(req)}
    res.body
  rescue Timeout::Error, Errno::ECONNREFUSED => e
    if retries > 0 
      retries -= 1
      #Kernel::warn(errmsg(e))
      sleep wait 
      retry
    else
      raise
    end
  end
#--}}}
end

#defval(var, opts = {}) ⇒ Object

returning the option default, or nil



667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/alib-0.5.1/util.rb', line 667

def defval var, opts = {} 
#--{{{  
  default = getopt 'default', opts, nil
  c = getopt 'class', opts, klass

  d0, d1 = "default_#{ var }".intern, "#{ var }".intern
  c0, c1 = "DEFAULT_#{ var }".upcase.intern, "#{ var }".upcase.intern

  [d0, d1].each{|x| return(c.send(x)) if c.respond_to?(x)}
  [c0, c1].each{|x| return(c.const_get(x)) if c.const_defined?(x)}

  return default
#--}}}
end

#delopt(opt, hash, default = nil) ⇒ Object Also known as: delete_opt, extract_opt, extractopt, xopt

returning the value or, if key is not found, nil or default



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/alib-0.5.1/util.rb', line 176

def delopt opt, hash, default = nil
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return hash.delete(key) if hash.has_key? key
    key = "#{ key }"
    return hash.delete(key) if hash.has_key? key
    key = key.intern
    return hash.delete(key) if hash.has_key? key
  end

  return default
#--}}}
end

#dhms(s) ⇒ Object



979
980
981
982
983
984
985
986
987
# File 'lib/alib-0.5.1/util.rb', line 979

def dhms s
#--{{{
  s = s.to_i if Time === s
  d, s = s.divmod 86400 
  h, s = s.divmod 3600
  m, s = s.divmod 60
  [d.to_i, h.to_i, m.to_i, s]
#--}}}
end

#emsg(e) ⇒ Object

format exception as Logger class does - no backtrace



455
456
457
458
459
# File 'lib/alib-0.5.1/util.rb', line 455

def emsg e
#--{{{
  "#{ e.message } - (#{ e.class })"
#--}}}
end

#erreq(a, b) ⇒ Object

determine equality of two exceptions



482
483
484
485
486
487
488
# File 'lib/alib-0.5.1/util.rb', line 482

def erreq a, b
#--{{{
  a.class == b.class and
  a.message == b.message and
  a.backtrace == b.backtrace
#--}}}
end

#errmsg(e) ⇒ Object

format exception as Logger class does - with backtrace



473
474
475
476
477
# File 'lib/alib-0.5.1/util.rb', line 473

def errmsg e
#--{{{
  emsg(e) << "\n" << btrace(e)
#--}}}
end

#escape(s, char, esc) ⇒ Object

new copy of s with any occurances of char escaped with esc



383
384
385
386
387
# File 'lib/alib-0.5.1/util.rb', line 383

def escape s, char, esc
#--{{{
  escape! "#{ s }", char, esc
#--}}}
end

#escape!(s, char, esc) ⇒ Object

escapes any occurances of char in s with esc modifying s inplace



370
371
372
373
374
375
376
377
378
# File 'lib/alib-0.5.1/util.rb', line 370

def escape! s, char, esc
#--{{{
  # re = %r/([#{ 0x5c.chr << esc }]*)#{ char }/
  re = %r/([#{ Regexp::quote esc }]*)#{ Regexp::quote char }/
  s.gsub!(re) do
    (($1.size % 2 == 0) ? ($1 << esc) : $1) + char 
  end
#--}}}
end

#exec(*args, &block) ⇒ Object

an quiet exec



407
408
409
410
411
412
413
414
415
416
417
# File 'lib/alib-0.5.1/util.rb', line 407

def exec(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Kernel::exec(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#expand(string, opts = {}) ⇒ Object



1014
1015
1016
1017
1018
# File 'lib/alib-0.5.1/util.rb', line 1014

def expand string, opts = {}
#--{{{
  expand! string.dup, opts
#--}}}
end

#expand!(string, vars = {}) ⇒ Object

expand variables in a string destructively (to the string)



992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
# File 'lib/alib-0.5.1/util.rb', line 992

def expand! string, vars = {} 
#--{{{
  loop do
    changed = false
    vars.each do |var, value|
      var = var.to_s
      var.gsub! %r/[^a-zA-Z0-9_]/, ''
      [ 
        %r/\$#{ var }\b/, 
        %r/\@#{ var }\b/, 
        %r/\$\{\s*#{ var }\s*\}/, 
        %r/\@\{\s*#{ var }\s*\}/ 
      ].each do |pat|
        changed = string.gsub! pat, "#{ value }"
      end
    end
    break unless changed
  end
  string
#--}}}
end

#find(*a, &b) ⇒ Object

shortcut to Find2



745
746
747
748
749
750
# File 'lib/alib-0.5.1/util.rb', line 745

def find(*a, &b)
#--{{{
  a << '.' if a.empty?
  ALib::Find2::find(*a, &b)
#--}}}
end

#find2(*a, &b) ⇒ Object

shortcut to Find2



755
756
757
758
759
760
# File 'lib/alib-0.5.1/util.rb', line 755

def find2(*a, &b)
#--{{{
  a << '.' if a.empty?
  ALib::Find2::find2(*a, &b)
#--}}}
end

#fork(*args, &block) ⇒ Object

a quiet fork



392
393
394
395
396
397
398
399
400
401
402
# File 'lib/alib-0.5.1/util.rb', line 392

def fork(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Process::fork(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#getopt(opt, hash, default = nil) ⇒ Object Also known as: get_opt

returning the value or, if key is not found, nil or default



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/alib-0.5.1/util.rb', line 128

def getopt opt, hash, default = nil
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return hash[key] if hash.has_key? key
    key = "#{ key }"
    return hash[key] if hash.has_key? key
    key = key.intern
    return hash[key] if hash.has_key? key
  end

  return default
#--}}}
end

#give_up!(label = 'attempt') ⇒ Object Also known as: giveup!, give_up

see attempt



710
711
712
713
714
# File 'lib/alib-0.5.1/util.rb', line 710

def give_up! label = 'attempt'
#--{{{
  throw "#{ label }", 'give_up'
#--}}}
end

#hashify(*hashes) ⇒ Object

collect n hashed into one hash - later keys overried earlier keys



118
119
120
121
122
# File 'lib/alib-0.5.1/util.rb', line 118

def hashify(*hashes)
#--{{{
  hashes.inject(accum={}){|accum,hash| accum.update hash}
#--}}}
end

#hasopt(opt, hash, default = false) ⇒ Object Also known as: has_opt, hasopt?, has_opt?

see getopt



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/alib-0.5.1/util.rb', line 150

def hasopt opt, hash, default = false 
#--{{{
  keys = opt.respond_to?('each') ? opt : [opt]

  keys.each do |key|
    return key if hash.has_key? key
    key = "#{ key }"
    return key if hash.has_key? key
    key = key.intern
    return key if hash.has_key? key
  end

  return default
#--}}}
end

#hms(s) ⇒ Object

explode a



971
972
973
974
975
976
977
# File 'lib/alib-0.5.1/util.rb', line 971

def hms s
#--{{{
  h, s = s.divmod 3600
  m, s = s.divmod 60
  [h.to_i, m.to_i, s]
#--}}}
end

#hostObject

lookup, and cache, the host (first bit of hostname quad)



446
447
448
449
450
# File 'lib/alib-0.5.1/util.rb', line 446

def host
#--{{{
  @__host__ ||= hostname.gsub(%r/\..*$/o,'')
#--}}}
end

#hostnameObject

lookup, and cache, the hostname



437
438
439
440
441
# File 'lib/alib-0.5.1/util.rb', line 437

def hostname
#--{{{
  @__hostname__ ||= Socket::gethostname
#--}}}
end

#klassObject

self.class



85
86
87
88
89
# File 'lib/alib-0.5.1/util.rb', line 85

def klass
#--{{{
  Module === self ? self : self.class
#--}}}
end

#klass_stamp(hierachy, *a, &b) ⇒ Object

creates a class by class name



736
737
738
739
740
# File 'lib/alib-0.5.1/util.rb', line 736

def klass_stamp(hierachy, *a, &b)
#--{{{
  constant_get(hierachy)::new(*a, &b)
#--}}}
end

#lspawn(cmd, opts = {}) ⇒ Object

–}}}



1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
# File 'lib/alib-0.5.1/util.rb', line 1377

def lspawn cmd, opts = {}
#--{{{
  begin
    Thread.critical = true

    stdin = ALib::Util::getopt ['stdin', 'i', 'in', '0', 0], opts 
    stdout = ALib::Util::getopt ['stdout', 'o', 'out', '1', 1], opts
    stderr = ALib::Util::getopt ['stderr', 'e', 'err', '2', 2], opts
    expect = ALib::Util::getopt ['expect', 'status', 'success'], opts, 0
    log = Alib::Util::getopt ['logger', 'log'], opts 

    log ||= (self.logger rescue (defined?(@logger) ? @logger : LSPAWN_LOG[0]))

    stdout = LSPAWN_IO.new log, :o, stdout
    stderr = LSPAWN_IO.new log, :e, stderr

    cmdno = LSPAWN_CMDNO[0]

    log.info{ "cmd[#{ cmdno }] <#{ cmd }>" }

    status = Alib::Util::spawn(cmd, 'quiet'=>true, 'raise'=>false, 'stdin'=>stdin, 'stdout'=>stdout, 'stderr'=>stderr)

    exitstatus = ( (status ? (status.exitstatus || 127) : 127) rescue 127 )

    log.send(exitstatus == 0 ? 'info' : 'warn'){ "status[#{ cmdno }] <#{ exitstatus }>" }

    if expect
      codes = [*expect].flatten.compact.map{|code| Integer code}
      success = codes.detect{|code| exitstatus == code}
      unless success
        log.fatal{ "cmd[#{ cmdno }] failure" }
        exit exitstatus
      end
    end

    if status and status.signaled?
      if status.termsig
        log.warn{ "termsig[#{ cmdno }] <#{ status.termsig }>" }
      end
      if status.stopsig
        log.warn{ "stopsig[#{ cmdno }] <#{ status.stopsig }>" }
      end
    end

    exitstatus
  ensure
    LSPAWN_CMDNO[0] = LSPAWN_CMDNO[0] + 1
    Thread.critical = false
  end
#--}}}
end

#maim(pid, opts = {}) ⇒ Object

and 4 respectively



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/alib-0.5.1/util.rb', line 223

def maim(pid, opts = {})
#--{{{
  sigs = getopt 'signals', opts, %w(SIGTERM SIGQUIT SIGKILL)
  suspend = getopt 'suspend', opts, 4
  pid = Integer("#{ pid }")
  existed = false
  sigs.each do |sig|
    begin
      Process::kill(sig, pid)
      existed = true 
    rescue Errno::ESRCH
      unless existed
        return nil 
      else
        return true 
      end
    end
    return true unless alive?(pid)
    sleep suspend
    return true unless alive?(pid)
  end
  return(not alive?(pid)) 
#--}}}
end

#mcp(obj) ⇒ Object

marshal’d ‘deep’ copy of obj



76
77
78
79
80
# File 'lib/alib-0.5.1/util.rb', line 76

def mcp obj
#--{{{
  Marshal.load(Marshal.dump(obj))
#--}}}
end

#mdObject

declare multi-dimensional arrays as in md



1033
1034
1035
1036
1037
1038
# File 'lib/alib-0.5.1/util.rb', line 1033

def md
#--{{{
  @__md__ ||=
    lambda{|*ds| Array::new(ds.shift||0).map{md[*ds] unless ds.empty?}}
#--}}}
end

#optfilter(*list) ⇒ Object

pull out options from arglist



774
775
776
777
778
779
# File 'lib/alib-0.5.1/util.rb', line 774

def optfilter(*list)
#--{{{
  args, opts = [ list ].flatten.partition{|item| not Hash === item}
  [args, hashify(*opts)]
#--}}}
end

#parse_timespec(spec) ⇒ Object



1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
# File 'lib/alib-0.5.1/util.rb', line 1065

def parse_timespec spec
#--{{{
ret = nil
if((m = %r/^ (\d+(?:\.\d+)?) : (\d+(?:\.\d+)?) : (\d+(?:\.\d+)?) $/iox.match(spec.to_s)))
  m, h, m, s, ignored = m.to_a
  h, m, s = Float(h), Float(m), Float(s)
  #ret = h.hours + m.minutes + s.seconds
  ret = (h * 60 * 60) + (m * 60) + (s) 
else
  pat = %r/(\d+(?:\.\d+)?)\s*([sSmMhHdDwWyY][^\d]*)?/
  begin
    "#{ spec }".scan(pat) do |m|
      n = Float m[0]
      unit = m[1]
      if unit
        factor =
          case unit
            when %r/^m/i
              case unit
                when %r/^mo/i
                  7 * (60 * 60 * 24)
                else
                  60
              end
            when %r/^h/i
              60 * 60
            when %r/^d/i
              60 * 60 * 24
            when %r/^w/i
              7 * (60 * 60 * 24)
            when %r/^y/i
              365 * 7 * (60 * 60 * 24)
            else
              1
          end
        n *= factor
      end
      ret ||= 0.0
      ret += n
    end
  rescue
    raise "bad time spec <#{ spec }>"
  end
end
ret
#--}}}
end

#prognamObject

the basename of $0



67
68
69
70
71
# File 'lib/alib-0.5.1/util.rb', line 67

def prognam
#--{{{
  File::basename $0
#--}}}
end

#pruneObject

shortcut to Find2.prune



765
766
767
768
769
# File 'lib/alib-0.5.1/util.rb', line 765

def prune
#--{{{
  ALib::Find2.prune
#--}}}
end

#rangemod(n, ir) ⇒ Object

bin a integer into a int range using modulo logic



931
932
933
934
935
936
937
938
939
940
941
942
# File 'lib/alib-0.5.1/util.rb', line 931

def rangemod n, ir
#--{{{
  a, b = Integer(ir.first), Integer(ir.last)
  a, b = b, a if a >= b
  exclusive = ir.exclude_end?
  size = b - a 
  size += 1 unless exclusive
  offset = a - 0
  x = (n + offset).modulo size
  x += offset
#--}}}
end

#realpath(path) ⇒ Object

File::expand_path + link resolution



104
105
106
107
108
109
110
111
112
113
# File 'lib/alib-0.5.1/util.rb', line 104

def realpath path
#--{{{
  path = File::expand_path "#{ path }"
  begin
    Pathname.new(path).realpath.to_s
  rescue Errno::ENOENT, Errno::ENOTDIR
    path
  end
#--}}}
end

#require_version(version) ⇒ Object

require_version ‘1.8.0’



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/alib-0.5.1/util.rb', line 43

def require_version version
#--{{{
  major, minor, teeny = "#{ version }".split(%r/\./o).map{|n| Integer(n)}
  required = "#{ major }.#{ minor }.#{ teeny }"
  _major, _minor, _teeny = 
    %w( MAJOR MINOR TEENY ).map{|k| Integer(::Config::CONFIG[k])}
  actual = "#{ _major }.#{ _minor }.#{ _teeny }"
  unless _major > major  or _major == major and _minor >= minor 
    STDERR.puts("=" * 79)
    STDERR.puts "this program requires a ruby version >= <#{ required }>"
    STDERR.puts 
    STDERR.puts "you are currenlty running ruby version <#{ actual }>"
    STDERR.puts 
    STDERR.puts "possible problems which could cause this are:"
    STDERR.puts "  - improper PATH environment variable setting"
    STDERR.puts "  - ruby > <#{ required }> has not been installed"
    STDERR.puts("=" * 79)
    exit 1
  end
#--}}}
end

#singleton_class(&b) ⇒ Object

evaluates block in singleton scope or simply returns singleton_class



94
95
96
97
98
99
100
# File 'lib/alib-0.5.1/util.rb', line 94

def singleton_class &b
#--{{{
  sc = 
    class << self; self; end
  b ? sc.module_eval(&b) : sc
#--}}}
end

#snake_case(string) ⇒ Object



1114
1115
1116
1117
1118
1119
# File 'lib/alib-0.5.1/util.rb', line 1114

def snake_case string
#--{{{
  return string unless string =~ %r/[A-Z]/
  string.reverse.scan(%r/[A-Z]+|[^A-Z]*[A-Z]+?/).reverse.map{|word| word.reverse.downcase}.join '_'
#--}}}
end

#splitpath(path) ⇒ Object

split a path into dirname, basename, extension



795
796
797
798
799
800
801
# File 'lib/alib-0.5.1/util.rb', line 795

def splitpath path
#--{{{
  path = path.to_s 
  dirname, basename = File::split path
  [ dirname, (%r/^([^\.]*)(.*)$/).match(basename)[1,2] ].flatten
#--}}}
end

#stamptime(string, opts = {}) ⇒ Object

TODO - 1.8.4 parses usec but 1.8.2 does not. handle differently.



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/alib-0.5.1/util.rb', line 296

def stamptime string, opts = {} 
#--{{{
  tz = string[ %r/-\d\d:\d\d\s*$/ ]
  time = nil
  if opts.empty? or tz
    u = string[%r/\.\d+/]
    string[%r/\.\d+/] = '' if u 
    time = Time::parse string
    time += u.to_f if u
  else
    local = getopt 'local', opts, false 
    string = "#{ string }"
    pat = %r/^\s*(\d\d\d\d)-(\d\d)-(\d\d)[\s_tT]+(\d\d):(\d\d):(\d\d)(?:.(\d+))?\s*$/o
    match = pat.match string
    raise ArgumentError, "<#{ string.inspect }>" unless match
    yyyy,mm,dd,h,m,s,u = match.to_a[1..-1].map{|m| (m || 0).to_i}
    if local
      time = Time::local yyyy,mm,dd,h,m,s,u
    else
      time = Time::gm yyyy,mm,dd,h,m,s,u
    end
  end
  return time
#--}}}
end

#strtod(s, opts = {}) ⇒ Object

convert a string to an integer of any base



904
905
906
907
908
909
910
911
912
913
914
915
916
917
# File 'lib/alib-0.5.1/util.rb', line 904

def strtod(s, opts = {})
#--{{{
  base = getopt 'base', opts, 10
  case base
    when 2
      s = "0b#{ s }" unless s =~ %r/^0b\d/
    when 8
      s = "0#{ s }" unless s =~ %r/^0\d/
    when 16 
      s = "0x#{ s }" unless s =~ %r/^0x\d/
  end
  Integer s
#--}}}
end

#sweep(hash) ⇒ Object



1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
# File 'lib/alib-0.5.1/util.rb', line 1430

def sweep hash
#--{{{
  srcdir, dstdir, ignored = hash.to_a.first
  Dir.glob(File.join(srcdir, '*')) do |src|
    dirname, basename = File.split src
    dst = File.join dstdir, basename
    FileUtils.mv src, dst
  end
#--}}}
end

#system(*args, &block) ⇒ Object

a quiet system



422
423
424
425
426
427
428
429
430
431
432
# File 'lib/alib-0.5.1/util.rb', line 422

def system(*args, &block)
#--{{{
  begin
    verbose = $VERBOSE
    $VERBOSE = nil
    Kernel::system(*args, &block)
  ensure
    $VERBOSE = verbose
  end
#--}}}
end

#threadify(list, n = 4, &b) ⇒ Object



1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/alib-0.5.1/util.rb', line 1443

def threadify list, n = 4, &b
#--{{{
  n = Integer n
  done = Object.new.freeze
  jobs = Queue.new

  list.each_with_index{|elem, i| jobs.push [elem, i]}
  n.times{ jobs.push done} # mark the end

  consumers = Array.new n

  n.times do |i|
    consumers[i] = Thread.new do
      this = Thread.current
      this.abort_on_exception = true

      loop{
        job = jobs.pop
        this.exit if job == done
        jobs << (job << bcall(b, job))
      }
    end
  end

  consumers.map{|t| t.join}
  jobs.push done

  ret = []
  while((job = jobs.pop) != done)
    elem, i, value = job
    ret[i] = value
  end
  ret
#--}}}
end

#timestamp(arg = Time::now) ⇒ Object

nospace option - useful for constructing filenames



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/alib-0.5.1/util.rb', line 253

def timestamp arg = Time::now
#--{{{
  if Time === arg 
    arg.iso8601 2
  else
    opts =
      case arg
        when Hash
          opts = arg
        when Time
          {'time' => arg}
        else
          raise ArgumentError, "#{ arg.inspect } (#{ arg.class })"
      end
    time = getopt 'time', opts, Time::now
    local = getopt 'local', opts, false 
    nospace = getopt('nospace', opts, getopt('no_space', opts, false))
    dateonly = getopt('dateonly', opts, getopt('date_only', opts, false))
    time = time.utc unless local
    usec = "#{ time.usec }"
    usec << ('0' * (6 - usec.size)) if usec.size < 6 
    stamp =
    unless dateonly
      time.strftime('%Y-%m-%d %H:%M:%S.') << usec
    else
      time.strftime('%Y-%m-%d')
    end
    if nospace
      spc = TrueClass === nospace ? 'T' : "#{ nospace }"
      stamp.gsub! %r/\s+/, spc
    end
    stamp
  end
#--}}}
end

#tmpdir(*argv) ⇒ Object

generate a temporary directory



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# File 'lib/alib-0.5.1/util.rb', line 571

def tmpdir(*argv)
#--{{{
  args, opts = argv_split argv
  retries = getopt 'retries', opts, 42
  turd = getopt 'turd', opts
  dir =  args.first || getopt(%w(dir base prefix), opts)
  dir ||= ENV['ALIB_TMP'] || ENV['ALIB_TEMP']
  dir ||= '.' 
  opts['dir'] = dir
  d = nil
  retries.times do
    td = tmpnam(opts)
    break if ((d = FileUtils::mkdir_p td rescue nil))
  end
  raise "surpassed max retries <#{ retries }>" unless d
  d = File::expand_path d

  delete = lambda do
    Dir::glob(File::join(d, "**")).each{|e| FileUtils::rm_rf e}
    FileUtils::rm_rf d
  end

  if block_given?
    cwd = Dir::pwd
    begin
      Dir::chdir d
      yield [cwd,d]
    ensure
      Dir::chdir cwd if cwd
      delete.call unless turd
    end
  else
    at_exit &delete unless turd
    return d
  end

#--}}}
end

#tmpnam(*argv) ⇒ Object

basename



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'lib/alib-0.5.1/util.rb', line 494

def tmpnam(*argv)
#--{{{
  args, opts = argv_split argv
  dirname = (argv.shift || getopt(%w(dir base prefix), opts, '.')).to_s
  seed = getopt 'seed', opts, prognam
  reap = getopt 'reap', opts, true
  dot = getopt 'dot', opts, true 
  nodot = getopt 'nodot', opts, false 

  dot = false if nodot

#p 'nodot' => nodot
#p 'dot' => dot
#p dirname

  dirname = File.expand_path dirname

  seed = seed.gsub(%r/[^0-9a-zA-Z]/,'_').gsub(%r/\s+/, '')
  host = hostname.gsub(%r/\./, '_')

  if reap
    begin
      baseglob =
        if nodot
          "%s__*__*__*__%s" % [ host, seed ] 
        else
          ".%s__*__*__*__%s" % [ host, seed ] 
        end
      host_re = 
        if nodot
          %r/^#{ host }$/
        else
          %r/^\.#{ host }$/
        end
      g = File.join dirname, baseglob
      Dir.glob(g).each do |candidate|
        basename = File.basename candidate
        parts = basename.split %r/__/, 5
        if parts[0] =~ host_re
          pid = Integer parts[1]
          unless alive? pid
#STDERR.puts "FileUtils.rm_rf #{ candidate }"
            FileUtils.rm_rf candidate
          end
        end
      end
    rescue => e
      warn(errmsg(e)) rescue nil
    end
  end

  basename = 
    if nodot
      "%s__%s__%s__%s__%s" % [
        host, 
        Process::pid, 
        timestamp('nospace' => true),
        rand,
        seed,
      ] 
    else
      ".%s__%s__%s__%s__%s" % [
        host, 
        Process::pid, 
        timestamp('nospace' => true),
        rand,
        seed,
      ] 
    end

  File.join(dirname, basename)
#--}}}
end

#try_again!(label = 'attempt') ⇒ Object Also known as: try_again, again!

see attempt



699
700
701
702
703
# File 'lib/alib-0.5.1/util.rb', line 699

def try_again! label = 'attempt'
#--{{{
  throw "#{ label }", 'try_again'
#--}}}
end

#uncache(file) ⇒ Object

make best effort to invalidate any inode caching done by nfs clients



613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/alib-0.5.1/util.rb', line 613

def uncache file 
#--{{{
  refresh = nil
  begin
    is_a_file = File === file
    path = (is_a_file ? file.path : file.to_s) 
    stat = (is_a_file ? file.stat : File::stat(file.to_s)) 
    refresh = tmpnam(File::dirname(path))
    File::link path, refresh rescue File::symlink path, refresh
    File::chmod stat.mode, path
    File::utime stat.atime, stat.mtime, path
    open(File::dirname(path)){|d| d.fsync rescue nil}
  ensure 
    begin
      File::unlink refresh if refresh
    rescue Errno::ENOENT
    end
  end
#--}}}
end

#unindent(s) ⇒ Object



1056
1057
1058
1059
1060
1061
1062
# File 'lib/alib-0.5.1/util.rb', line 1056

def unindent s
#--{{{
  s = "#{ s }"
  unindent! s
  s
#--}}}
end

#unindent!(s) ⇒ Object

find natural left margin of a here-doc and un-indent it



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
# File 'lib/alib-0.5.1/util.rb', line 1043

def unindent! s
#--{{{
  indent = nil
  s.each do |line|
    next if line =~ %r/^\s*$/
    indent = line[%r/^\s*/] and break
  end
  s.gsub! %r/^#{ indent }/, "" if indent
  indent ? s : nil
#--}}}
end

#unzip(path, z_pat = nil) ⇒ Object Also known as: gunzip

unzip a file - return unzipped name



859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/alib-0.5.1/util.rb', line 859

def unzip path, z_pat = nil 
#--{{{
  path = path.to_s 
  z_pat ||= %r/\.(?:z|gz)$/io
  spawn "gzip --force --decompress #{ path }" if zipped?(path, z_pat)
  #spawn "gzip --force --decompress #{ path }"
  uzn = unzipped_name path, z_pat 
  if block_given?
    yield uzn
  else
    uzn
  end
#--}}}
end

#unzipped(path, z_pat = %r/\.(?:z|gz)$/io) ⇒ Object

handle a pathname after unzipping (iff needed)



806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/alib-0.5.1/util.rb', line 806

def unzipped path, z_pat = %r/\.(?:z|gz)$/io
#--{{{
  path = path.to_s 
  zipped = zipped?(path, z_pat)
  unless zipped
    yield path
  else
    unzipped = unzip path
    begin
      yield unzipped
    ensure
      zip unzipped
    end
  end
#--}}}
end

#unzipped_name(path, z_pat = nil) ⇒ Object

return the unzipped name of a path



879
880
881
882
883
884
885
# File 'lib/alib-0.5.1/util.rb', line 879

def unzipped_name path, z_pat = nil 
#--{{{
  path = path.to_s 
  z_pat ||= %r/\.(?:z|gz)$/io
  path.gsub z_pat, ''
#--}}}
end

#version_cmp(a, b) ⇒ Object



322
323
324
325
326
327
# File 'lib/alib-0.5.1/util.rb', line 322

def version_cmp a, b
#--{{{
  to_v = lambda{|v| v.to_s.scan(%r/\d+/).map{|c| Integer c}}
  to_v[a] <=> to_v[b]
#--}}}
end

#which_rubyObject

determine path of current ruby interpreter (argv in c)



1023
1024
1025
1026
1027
1028
# File 'lib/alib-0.5.1/util.rb', line 1023

def which_ruby
#--{{{
  c = ::Config::CONFIG
  File::join(c['bindir'], c['ruby_install_name']) << c['EXEEXT']
#--}}}
end

#zip(path, z_ext = nil) ⇒ Object Also known as: gzip

zip a file - return zipped name



826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/alib-0.5.1/util.rb', line 826

def zip path, z_ext = nil 
#--{{{
  path = path.to_s 
  z_ext ||= '.gz'
  z_ext.gsub! %r/^\s*\.+/, '.'
  spawn "gzip --suffix #{ z_ext } --force #{ path }"
  zipped = "#{ path }#{ z_ext }"
  raise "could not create <#{ zipped }>" unless test ?e, zipped
  if block_given?
    yield zipped
  else
    zipped
  end
#--}}}
end

#zipped?(path, z_pat = %r/\.(?:z|gz)$/io) ⇒ Boolean Also known as: gzipped?, zipped

guess if a file is zipped based on pathname

Returns:

  • (Boolean)


890
891
892
893
894
895
# File 'lib/alib-0.5.1/util.rb', line 890

def zipped? path, z_pat = %r/\.(?:z|gz)$/io
#--{{{
  path = path.to_s 
  path =~ z_pat
#--}}}
end

#zipped_name(path, z_ext = nil) ⇒ Object

return the zipped name of a path



847
848
849
850
851
852
853
854
# File 'lib/alib-0.5.1/util.rb', line 847

def zipped_name path, z_ext = nil 
#--{{{
  path = path.to_s 
  z_ext ||= '.gz'
  z_ext.gsub! %r/^\s*\.+/, '.'
  "#{ path }#{ z_ext }"
#--}}}
end