Module: Senv::Script::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/senv/script.rb

Instance Method Summary collapse

Instance Method Details

#async_reader_thread_for(io, accum) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/senv/script.rb', line 352

def async_reader_thread_for(io, accum)
  Thread.new(io, accum) do |i, a|
    Thread.current.abort_on_exception = true

    while true
      buf = i.read(8192)

      if buf
        a << buf
      else
        break
      end
    end
  end
end

#copy(object) ⇒ Object



262
263
264
# File 'lib/senv/script.rb', line 262

def copy(object)
  Marshal.load(Marshal.dump(object))
end

#debug(arg) ⇒ Object



274
275
276
# File 'lib/senv/script.rb', line 274

def debug(arg)
  debug!(arg) if debug?
end

#debug!(arg) ⇒ Object



266
267
268
269
270
271
272
# File 'lib/senv/script.rb', line 266

def debug!(arg)
  if arg.is_a?(String)
    warn "[DEBUG] #{ arg }"
  else
    warn "[DEBUG] >\n#{ arg.to_yaml rescue arg.pretty_inspect }"
  end
end

#debug?Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/senv/script.rb', line 278

def debug?
  ENV['SCRIPT_DEBUG'] || ENV['DEBUG']
end

#esc(*args) ⇒ Object



175
176
177
# File 'lib/senv/script.rb', line 175

def esc(*args)
  args.flatten.compact.map{|arg| Shellwords.escape(arg)}.join(' ')
end

#extract_options(args) ⇒ Object



234
235
236
237
238
239
240
# File 'lib/senv/script.rb', line 234

def extract_options(args)
  opts = extract_options!(args)

  args.push(opts)

  opts
end

#extract_options!(args) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
# File 'lib/senv/script.rb', line 222

def extract_options!(args)
  unless args.is_a?(Array)
    args = [args]
  end

  opts = args.last.is_a?(Hash) ? args.pop : {}

  symbolize_keys!(opts)

  return opts
end

#filelist(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/senv/script.rb', line 372

def filelist(*args, &block)
  accum = (block || proc{ Set.new }).call
  raise ArgumentError.new('accum.class != Set') unless accum.is_a?(Set)

  _ = args.last.is_a?(Hash) ? args.pop : {}

  entries = args.flatten.compact.map{|arg| realpath("#{ arg }")}.uniq.sort

  entries.each do |entry|
    case
      when test(?f, entry)
        file = realpath(entry)
        accum << file

      when test(?d, entry)
        glob = File.join(entry, '**/**')

        Dir.glob(glob) do |_entry|
          case
            when test(?f, _entry)
              filelist(_entry){ accum }
            when test(?d, entry)
              filelist(_entry){ accum }
          end
        end
    end
  end

  accum.to_a
end

#realpath(path) ⇒ Object



368
369
370
# File 'lib/senv/script.rb', line 368

def realpath(path)
  Pathname.new(path.to_s).expand_path.realpath.to_s
end

#slug_for(*args, &block) ⇒ Object



403
404
405
# File 'lib/senv/script.rb', line 403

def slug_for(*args, &block)
  Slug.for(*args, &block)
end

#symbolize_keys(hash) ⇒ Object



258
259
260
# File 'lib/senv/script.rb', line 258

def symbolize_keys(hash)
  symbolize_keys!(copy(hash))
end

#symbolize_keys!(hash) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/senv/script.rb', line 242

def symbolize_keys!(hash)
  hash.keys.each do |key|
    if key.is_a?(String)
      val = hash.delete(key)

      if val.is_a?(Hash)
        symbolize_keys!(val)
      end

      hash[key.to_s.gsub('-', '_').to_sym] = val
    end
  end

  return hash
end

#sys(*args, &block) ⇒ Object



344
345
346
347
348
349
350
# File 'lib/senv/script.rb', line 344

def sys(*args, &block)
  begin
    sys!(*args, &block)
  rescue Object
    false
  end
end

#sys!(*args, &block) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/senv/script.rb', line 282

def sys!(*args, &block)
  opts = extract_options!(args)

  cmd = args

  debug(:cmd => cmd)

  open3 = (
    block ||
    opts[:stdin] ||
    opts[:quiet] ||
    opts[:capture]
  )

  if(open3)
    stdin = opts[:stdin]
    stdout = ''
    stderr = ''
    status = nil

    Open3.popen3(*cmd) do |i, o, e, t|
      ot = async_reader_thread_for(o, stdout) 
      et = async_reader_thread_for(e, stderr) 

      i.write(stdin) if stdin
      i.close

      ot.join
      et.join

      status = t.value
    end

    if status.exitstatus == 0
      result = nil

      if opts[:capture]
        result = stdout.to_s.strip
      else
        if block
          result = block.call(status, stdout, stderr)
        else
          result = [status, stdout, stderr]
        end
      end

      return(result)
    else
      if opts[:capture]
        abort("#{ [cmd].join(' ') } #=> #{ status.exitstatus }")
      else
        false
      end
    end
  else
    env = opts[:env] || {}
    argv = [env, *cmd]
    system(*argv) || abort("#{ [cmd].join(' ') } #=> #{ $?.exitstatus }")
    return true
  end
end

#tmpfile(*args, &block) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/senv/script.rb', line 193

def tmpfile(*args, &block)
  opts = extract_options!(args)

  path = tmpname(opts)


  tmp = open(path, 'w+')
  tmp.binmode
  tmp.sync = true

  unless args.empty?
    src = args.join
    tmp.write(src)
    tmp.flush
    tmp.rewind
  end

  if block
    begin
      block.call(tmp)
    ensure
      FileUtils.rm_rf(path)
    end
  else
    at_exit{ Kernel.system("rm -rf #{ esc(path) }") }
    return tmp
  end
end

#tmpname(*args) ⇒ Object



183
184
185
186
187
188
189
190
191
# File 'lib/senv/script.rb', line 183

def tmpname(*args)
  opts = extract_options!(*args)

  base = opts.fetch(:base){ uuid }.to_s.strip
  ext = opts.fetch(:ext){ 'tmp' }.to_s.strip.sub(/^[.]+/, '')
  basename = opts.fetch(:basename){ "#{ base }.#{ ext }" }

  File.join(Dir.tmpdir, basename)
end

#unindent(arg) ⇒ Object



164
165
166
167
168
169
170
171
172
173
# File 'lib/senv/script.rb', line 164

def unindent(arg)
  string = arg.to_s.dup
  margin = nil
  string.each_line do |line|
    next if line =~ %r/^\s*$/
    margin = line[%r/^\s*/] and break
  end
  string.gsub!(%r/^#{ margin }/, "") if margin
  margin ? string : nil
end

#uuidObject



179
180
181
# File 'lib/senv/script.rb', line 179

def uuid
  SecureRandom.uuid
end