Module: Hem::Helper

Extended by:
Helper
Included in:
Helper, Lib::Seed::Project
Defined in:
lib/hem/helper/shell.rb,
lib/hem/helper/github.rb,
lib/hem/helper/command.rb,
lib/hem/helper/vm_command.rb,
lib/hem/helper/file_locator.rb,
lib/hem/helper/http_download.rb,
lib/hem/helper/argument_parser.rb

Instance Method Summary collapse

Instance Method Details

#bundle_shell(*args, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/hem/helper/shell.rb', line 4

def bundle_shell *args, &block
  has_bundle = begin
    shell "bundle", "exec", "ruby -v"
    true
  rescue ::Hem::ExternalCommandError
    false
  end

  if has_bundle
    args = [ 'bundle', 'exec' ] + args
  end

  shell *args, &block
end

#chunk_line_iterator(stream) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hem/helper/shell.rb', line 23

def chunk_line_iterator stream
  begin
    until (chunk = stream.readpartial(1024)).nil? do
      chunk.each_line do |outer_line|
        outer_line.each_line("\r") do |line|
          yield line
        end
      end
    end
  rescue EOFError
    # NOP
  end
end

#convert_args(task_name, args, arg_list) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/hem/helper/argument_parser.rb', line 3

def convert_args task_name, args, arg_list
  original_args = args.dup
  task_args = []
  arg_list.each do |_, options|
    if args.empty?
      if !options[:optional]
        raise ::Hem::MissingArgumentsError.new(task_name, original_args)
      else
        task_args << options[:default]
      end
    elsif options[:as] == Array
      task_args << args.dup
      args.clear
    else
      task_args << args.shift
    end
  end

  unless args.empty?
    raise ::Hem::InvalidCommandOrOpt.new(args.join(' '))
  end

  task_args
end

#create_command(command = nil, opts = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/hem/helper/command.rb', line 35

def create_command command = nil, opts = {}
  run_env = opts[:run_environment] || get_run_environment
  case run_env
  when 'vm'
    ::Hem::Lib::Vm::Command.new command, opts
  when 'local'
    ::Hem::Lib::Local::Command.new command, opts
  else
    raise Hem::InvalidCommandOrOpt.new "run_environment #{run_env}"
  end
end

#create_mysql_command(opts = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/hem/helper/command.rb', line 19

def create_mysql_command opts = {}
  opts = {
    :auto_echo => true,
    :db => "",
    :user => maybe(Hem.project_config.mysql.username) || "",
    :pass => maybe(Hem.project_config.mysql.password) || "",
    :mysql => 'mysql'
  }.merge(opts)

  opts[:user] = "-u#{opts[:user].shellescape}" unless opts[:user].empty?
  opts[:pass] = "-p#{opts[:pass].shellescape}" unless opts[:pass].empty?
  opts[:db] = opts[:db].shellescape unless opts[:db].empty?

  create_command "#{opts[:mysql]} #{opts[:user]} #{opts[:pass]} #{opts[:db]}".strip, opts
end

#get_run_environmentObject



3
4
5
6
7
8
9
10
11
12
# File 'lib/hem/helper/command.rb', line 3

def get_run_environment
  [
    ENV['HEM_RUN_ENV'],
    Hem.project_config.run_environment,
    Hem.user_config.run_environment,
    'vm'
  ].each do |env|
    return env unless env.nil?
  end
end

#http_download(url, target_file, opts = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hem/helper/http_download.rb', line 3

def http_download url, target_file, opts = {}
  require 'net/http'
  require 'openssl'
  require 'uri'
  opts = { :progress => Hem.method(:progress) }.merge(opts)
  uri = URI.parse(url)
  size = 0
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'

  # TODO: May want to verify SSL validity...
  # http://notetoself.vrensk.com/2008/09/verified-https-in-ruby/#comment-22252
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  http.start do
    begin
      file = open(target_file, 'wb+')
      http.request_get(uri.path) do |response|
        size = response.content_length
        response.read_body do |chunk|
          file.write(chunk)
          opts[:progress].call(
            target_file,
            chunk.length,
            size,
            :update
          ) if opts[:progress]
        end
      end
    ensure
      opts[:progress].call(target_file, 0, size, :finsh) if opts[:progress]
      file.close
    end
  end
end

#locate(name, patterns = nil, opts = {}, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/hem/helper/file_locator.rb', line 5

def locate(name, patterns = nil, opts = {}, &block)
  opts = {
    type: 'git',
    patterns: patterns || [name, "**/#{name}"],
    path: Hem.project_path,
  }.merge(opts)

  match = nil

  unless Hem.project_config[:locate].nil? || Hem.project_config[:locate][name].nil?
    opts = opts.merge(Hem.project_config[:locate][name].to_hash_sym)
  end

  Dir.chdir opts[:path] do
    case opts[:type]
    when 'git'
      match = locate_git(opts[:patterns], &block)
    when 'files'
      match = locate_files(opts[:patterns], &block)
    end
  end

  return match unless block_given?
  return true if match

  Hem.ui.warning opts[:missing] if opts[:missing]
  return false
end

#parse_github_url(url) ⇒ Object



3
4
5
6
# File 'lib/hem/helper/github.rb', line 3

def parse_github_url(url)
  matches = /github\.com[\/:]+(?<owner>.*)\/(?<repo>((?!\.git).)*)/.match(url)
  {:owner => matches[:owner], :repo => matches[:repo]}
end

#run(command, opts = {}) ⇒ Object Also known as: run_command



14
15
16
# File 'lib/hem/helper/command.rb', line 14

def run command, opts = {}
  create_command(command, opts).run
end

#shell(*args, &block) ⇒ Object



19
20
21
22
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
50
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/hem/helper/shell.rb', line 19

def shell *args, &block
  require 'open3'
  require 'tempfile'

  def chunk_line_iterator stream
    begin
      until (chunk = stream.readpartial(1024)).nil? do
        chunk.each_line do |outer_line|
          outer_line.each_line("\r") do |line|
            yield line
          end
        end
      end
    rescue EOFError
      # NOP
    end
  end

  opts = (args.size > 1 && args.last.is_a?(Hash)) ? args.pop : {}
  opts = {
    :capture => false,
    :strip => true,
    :indent => 0,
    :realtime => false,
    :env => {},
    :ignore_errors => false,
    :exit_status => false
  }.merge! opts

  Hem::Logging.logger.debug("helper.shell: Invoking '#{args.join(" ")}' with #{opts.to_s}")

  require 'bundler'
  ::Bundler.with_clean_env do
    indent = " " * opts[:indent]
    ::Open3.popen3 opts[:env], *args do |stdin, out, err, external|
      buffer = ::Tempfile.new 'hem_run_buf'
      buffer.sync = true
      threads = [external]
      last_buf = ""

      ## Create a thread to read from each stream
      { :out => out, :err => err }.each do |key, stream|
        threads.push(::Thread.new do
          chunk_line_iterator stream do |line|
            line = ::Hem.ui.color(line, :error) if key == :err
            line_formatted = if opts[:strip]
              line.strip
            else
              line
            end
            buffer.write("#{line_formatted}\n")
            Hem::Logging.logger.debug("helper.shell: #{line_formatted}")
            line = yield line if block
            print indent + line if opts[:realtime] && !line.nil?
          end
        end)
      end

      threads.each do |t|
        t.join
      end

      buffer.fsync
      buffer.rewind

      return external.value.exitstatus if opts[:exit_status]

      raise ::Hem::ExternalCommandError.new(args.join(" "), external.value.exitstatus, buffer) if external.value.exitstatus != 0 && !opts[:ignore_errors]

      if opts[:capture]
        return buffer.read unless opts[:strip]
        return buffer.read.strip
      else
        return nil
      end
    end
  end
end

#vm_command(command = nil, opts = {}) ⇒ Object



15
16
17
18
19
# File 'lib/hem/helper/vm_command.rb', line 15

def vm_command command = nil, opts = {}
  Hem.ui.warning "Using vm_command is deprecated and will be removed in a future release. Please use create_command instead"
  opts['run_environment'] = 'vm'
  create_command command, opts
end

#vm_mysql(opts = {}) ⇒ Object



9
10
11
12
13
# File 'lib/hem/helper/vm_command.rb', line 9

def vm_mysql opts = {}
  Hem.ui.warning "Using vm_mysql is deprecated and will be removed in a future release. Please use create_mysql_command instead"
  opts['run_environment'] = 'vm'
  create_mysql_command opts
end

#vm_shell(command, opts = {}) ⇒ Object



3
4
5
6
7
# File 'lib/hem/helper/vm_command.rb', line 3

def vm_shell command, opts = {}
  Hem.ui.warning "Using vm_shell is deprecated and will be removed in a future release. Please use run instead"
  opts['run_environment'] = 'vm'
  run command, opts
end