Module: Squared::Common::System

Defined in:
lib/squared/common/system.rb

Class Method Summary collapse

Class Method Details

.confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 15) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/squared/common/system.rb', line 23

def confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 15)
  require 'readline'
  require 'timeout'
  agree = /^#{agree}$/i if agree.is_a?(::String)
  cancel = /^#{cancel}$/i if cancel.is_a?(::String)
  Timeout.timeout(timeout) do
    begin
      while (ch = Readline.readline(msg, true))
        ch = ch.chomp
        ch = default if ch.empty?
        case ch
        when agree
          return true
        when cancel
          return false
        end
        attempts -= 1
        exit 1 unless attempts >= 0
      end
    rescue Interrupt
      puts
      exit 0
    else
      false
    end
  end
end

.copy_d(src, dest, glob: ['**/*'], create: false, verbose: true) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/squared/common/system.rb', line 51

def copy_d(src, dest, glob: ['**/*'], create: false, verbose: true)
  src = Pathname.new(src)
  dest = Pathname.new(dest)
  raise "#{dest} (not found)" if !create && !dest.exist?

  subdir = []
  files = 0
  dest.mkpath if create
  glob = [glob] unless glob.is_a?(::Array)
  glob.each do |val|
    Dir.glob(src.join(val)) do |path|
      ent = Pathname.new(path)
      next if ent.directory?

      target = dest.join(ent.relative_path_from(src))
      dir = target.dirname
      unless subdir.include?(dir.to_s)
        dir.mkpath
        subdir << dir.to_s
      end
      copy_f ent, target
      files += 1
    end
  end
  puts [dest.realpath, subdir.size.to_s, files.to_s].join(' => ') if verbose
end

.copy_f(src, dest, overwrite: true, verbose: false) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/squared/common/system.rb', line 78

def copy_f(src, dest, overwrite: true, verbose: false)
  unless overwrite
    path = Pathname.new(dest)
    if path.directory?
      src = [src] unless src.is_a?(::Array)
      src = src.reject { |val| path.join(File.basename(val)).exist? }
    elsif path.exist?
      return
    end
  end
  FileUtils.cp(src, dest, verbose: verbose)
end

.shell(*cmd, **kwargs) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/squared/common/system.rb', line 11

def shell(*cmd, **kwargs)
  if RUBY_VERSION =~ /^2\.[0-5]\./
    exception = kwargs.delete(:exception)
    ret = system(*cmd, **kwargs)
    raise $?.to_s if !ret && exception

    ret
  else
    system(*cmd, **kwargs)
  end
end