Komenda
Komenda is a convenience wrapper to run shell commands in Ruby.
Usage
Run a command:
Komenda.run('date')The run() method will block until the subprocess finishes.
It will expose the output and exit status as a Komenda::Result value:
result = Komenda.run('date')
result.stdout # => "Tue Nov 26 14:45:03 EST 2013\n"
result.stderr # => ""
result.output # => "Tue Nov 26 14:45:03 EST 2013\n" (combined stdout + stderr)
result.status # => 0
result.success? # => true
result.error? # => false
result.pid # => 32157The program and its arguments can be passed as an array:
result = Komenda.run(['echo', '-n', 'hello'])
result.output # => "hello"Run options
The run() method has a second options argument.
result = Komenda.run('date', fail_on_fail: true)The following options can be configured:
-
env(Hash): Additional environment variables to set. -
use_bundler_env(Boolean): Use the environment of the current bundle. Defaults tofalse. -
cwd(String): Directory to change to before running the process. -
fail_on_fail(Boolean): Whether to raise an error when the exit code is not "0". Defaults tofalse.
Asynchronous running
The create() method creates a Process which can be run() (or start()ed as a Thread).
process = Komenda.create('date')
result = process.runEvent callbacks can be registered with Process.on(), for example for when output is written.
process = Komenda.create('date')
process.on(:stdout) { |output| puts "STDOUT: #{output}" }
result = process.runThe following events are emitted:
-
.on(:stdout) { |output| }: When data is available on STDOUT. -
.on(:stderr) { |output| }: When data is available on STDERR. -
.on(:output) { |output| }: When data is available on STDOUT or STDERR. -
.on(:exit) { |result| }: When the process finishes. -
.on(:error) { |exception| }: When process execution fails (e.g. executable file cannot be found).
Development
Install dependencies:
$ bundle install
Run the tests:
$ bundle exec rake spec
Release a new version:
- Bump the version in
komenda.gemspec, merge to master. - Push a new tag to master.
- Release to RubyGems with
bundle exec rake release.
Copyright and License
Copyright © 2015-2019 by Cargo Media.
This is free software; you can redistribute it and/or modify it under the terms of the MIT License.