aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/chouette/command_line_support.rb
blob: 99c61fa5bffaded725d0ef9fb92f202780692e7c (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
module Chouette::CommandLineSupport

  class ExecutionError < StandardError; end

  def available_loggers
    [].tap do |logger|
      logger << Chouette::ActiveRecord.logger  
      logger << Rails.logger if defined?(Rails)
      logger << Logger.new($stdout)
    end.compact
  end

  def logger
    @logger ||= available_loggers.first
  end

  def max_output_length
    2000
  end

  def execute!(command)
    logger.debug "execute '#{command}'"

    output = `#{command} 2>&1`
    output = "[...] #{output[-max_output_length,max_output_length]}" if output.length > max_output_length
    logger.info output unless output.empty?

    if $? != 0
      raise ExecutionError.new("Command failed: #{command} (error code #{$?})")
    end

    true
  end

end