aboutsummaryrefslogtreecommitdiffstats
path: root/lib/alaveteli_external_command.rb
blob: 7d32be9040e04655fabc336ab41a862e9374f2db (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
25pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlig
require 'external_command'

module AlaveteliExternalCommand
    class << self
        def run(program_name, *args)
            # Run an external program, and return its output.
            # Standard error is suppressed unless the program
            # fails (i.e. returns a non-zero exit status).
            opts = {}
            if !args.empty? && args[-1].is_a?(Hash)
                opts = args.pop
            end
            
            if program_name =~ %r(^/)
                program_path = program_name
            else
                utility_search_path = MySociety::Config.get("UTILITY_SEARCH_PATH", ["/usr/bin", "/usr/local/bin"])
                found = false
                utility_search_path.each do |d|
                    program_path = File.join(d, program_name)
                    if File.file? program_path and File.executable? program_path
                        found = true
                        break
                    end
                end
                 raise "Could not find #{program_name} in any of #{utility_search_path.join(', ')}" if !found
            end
            
            xc = ExternalCommand.new(program_path, *args)
            if opts.has_key? :append_to
                xc.out = opts[:append_to]
            end
            xc.run(opts[:stdin_string] || "", opts[:env] || {})
            if xc.status != 0
                # Error
                $stderr.puts("Error from #{program_name} #{args.join(' ')}:")
                $stderr.print(xc.err)
                return nil
            else
                if opts.has_key? :append_to
                    opts[:append_to] << "\n\n"
                else
                    return xc.out
                end
            end
        end
    end
end