summaryrefslogtreecommitdiff
path: root/lib/jive/shell.rb
blob: 7663f72649b30615b1e2a0205c8c54872d7f66d8 (plain)
1
2
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
38
39
40
41
42
43
44
45
# frozen_string_literal: true

module Jive
  class Shell
    COMMAND_MAP = {
      cd: "/usr/bin/cd",
      echo: "/usr/bin/echo",
      git: "/usr/bin/git",
      mkdir: "/bin/mkdir"
    }.freeze

    def run_each(tasks)
      tasks.each do |task|
        break unless execute(task)
      end
    end

    def execute(command, env: {})
      system(env, expand(command))
    end

    def after_run(tasks)
      finalizer_fd = 42
      pipe = IO.new(finalizer_fd)
      pipe.puts(tasks.map { |x| x.join(":") }.join("\n"))
    rescue Errno::EBADF => e
      puts e
      exit 1
    end

    def expand(command)
      Array(command)
        .flatten
        .map { |x| COMMAND_MAP.fetch(x, x).to_s }
        .join(" ")
    end

    def run_safely
      yield
    rescue StandardError => e
      puts e
      after_run([%w[noop noop]])
    end
  end
end