Class: CommandButler::Mediator

Inherits:
Object
  • Object
show all
Defined in:
lib/command_butler/mediator.rb

Instance Method Summary collapse

Instance Method Details

#execute(file_name, options) ⇒ Object



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
46
47
48
49
50
51
52
53
# File 'lib/command_butler/mediator.rb', line 12

def execute(file_name, options)
  # resultクラスも作る
  histories = []
  @commands = CommandParser.parse(file_name:file_name)

  @vals = {}
  if options[:val_file]
    @vals = ValParser.parse(file_name:options[:val_file])
    @vals.each_pair do |k,v|
      @commands.each {|c| c.replace_command(val:{k=>v})}
    end
  end
  jump_index = -1 # jump制御

  contents = (0 < @vals.size)? ValDecorator.decoration(vals:@vals) : ""
  puts TitleDecorator.decoration(file_name:file_name, contents:contents)

  @commands.each_with_index do |command, index|

    # jumpが設定されていたらskipしたことにする
    if (index < jump_index)
      histories[index] = {input: Input.skip_instance}
      next
    end

    # show all comamnds
    show_commands(current_index: index, histories: histories) # 1件実行ごとにコマンドを表示する
    # execute
    input = command.need_confirm?? Input.start : Input.execute_instance
    exit 1 if input.abort?
    jump_index = (input.input_value - 1) if input.jump?
    histories[index] = {input: input}

    Dir.chdir(command.chdir) if command.chdir

    if input.execute? && command.command
      stdout, stderr, status = execute_command(command:command, index:index) 
      histories[index][:result] = {stdout:stdout, stderr: stderr, status: status}
      @commands.each {|c| c.replace_command(val:{command.set_val => stdout})} if command.set_val_command?
    end
  end
end

#execute_command(command: command, index: index) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/command_butler/mediator.rb', line 55

def execute_command(command:command, index:index)
  return unless command.command

  # set_valコマンドの時は標準出力を取りたいのでopen3で実行
  stdout, stderr, status = "", "", nil
  ResultDecorator.decoration_frame(command: command, index: index) do
    stdout, stderr, status = command.execute
    if status.success?
      ResultDecorator.decoration_stdout  stdout: stdout, status:status
    else
      ResultDecorator.decoration_stderr stderr: stderr, status:status
    end
  end

  sleep 0.5 # 表示がいっきに流れて見失しなうのでsleep
  [stdout, stderr, status]
end

#show_commands(current_index: current_index, histories: histories) ⇒ Object



73
74
75
76
77
78
79
# File 'lib/command_butler/mediator.rb', line 73

def show_commands(current_index:current_index, histories:histories)
  @commands.each_with_index do |command, index|
    puts LineDecorator.decoration command: command, index: index, current_index: current_index, history: histories[index]
    detail = LineDetailDecorator.decoration  command: command
    puts detail if 0 < detail.size
  end
end