outstand-tty-command 0.10.0.pre

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 670b236f6c356ffce5f7129c216ee5152059fc5f530130cff724dc6dff56bf7a
4
+ data.tar.gz: ebc3e2ad3c4fbb69e12eee0de437ce7fa82cbc01f34d6db1deb854b0c44ebc6c
5
+ SHA512:
6
+ metadata.gz: fdab824404e9d9c49fca6d50eb2ec875518c3f574761c02feb10e7476a6fd56897bc13f0ce1aeaad88781b4aaa69561f54f2f365eab54ca08ec41a6116160e6d
7
+ data.tar.gz: 5a55d5e0703adcd6fa376c41c7593c9134400d0ed5b2909d2343698557bdaf992c1936b47172c7222fafa871139659e1b7f3c2197b692fa802f78203bfd9a344
@@ -0,0 +1,156 @@
1
+ # Change log
2
+
3
+ ## [v0.10.0] - unreleased
4
+
5
+ ### Changed
6
+ * Change :chdir option to escape directory location path
7
+ * Change gemspec to add metadata and remove test artefacts
8
+ * Change to update pastel dependency and restrict version to minor only
9
+
10
+ ### Fixed
11
+ * Fix Ruby 2.7 keyword conversion errors
12
+ * Fix error when environment variable contains % character
13
+
14
+ ## [v0.9.0] - 2019-09-28
15
+
16
+ ### Changed
17
+ * Change gemspec to require Ruby >= 2.0.0
18
+
19
+ ## [v0.8.2] - 2018-08-07
20
+
21
+ ### Changed
22
+ * Change gemspec to load only required files
23
+
24
+ ### Fixed
25
+ * Fix issue with Ruby greater than 2.5.0 displaying thread error traceback by default
26
+
27
+ ## [v0.8.1] - 2018-05-20
28
+
29
+ ### Changed
30
+ * Change ProcessRunner#write_stream to handle all writing logic
31
+
32
+ ## [v0.8.0] - 2018-04-22
33
+
34
+ ### Added
35
+ * Add :output_only_on_error option by Iulian Onofrei(@revolter)
36
+ * Add :verbose flag to toggle warnings
37
+
38
+ ### Changed
39
+ * Change ProcessRunner to use waitpid2 api for direct status
40
+ * Change ProcessRunner stdout & stderr reading to use IO.select and be non-blocking
41
+
42
+ ### Fixed
43
+ * Fix :timeout to raise when long running without input or output
44
+ * Fix ProcessRunner to ensure no zombie processes on timeouts
45
+
46
+ ## [v0.7.0] - 2017-11-19
47
+
48
+ ### Added
49
+ * Add :binmode option to allow configuring input & ouput as binary
50
+ * Add :pty option to allow runnig commands in PTY(pseudo terminal)
51
+
52
+ ### Changed
53
+ * Change Command to remove threads synchronization to leave it up to client to handle
54
+ * Change Cmd to allow updating options
55
+ * Change Command to accept options for all commands such as :timeout, :binmode etc...
56
+ * Change Execute to ChildProcess module
57
+ * Change ChildProcess to skip spawn redirect close options on Windows platform
58
+ * Change to enforce UTF-8 encoding for process pipes to be cross platform
59
+ * Change ProcessRunner to stop rescuing runtime failures
60
+ * Change to stop mutating String instances
61
+
62
+ ### Fixed
63
+ * Fix ProcessRunner threads deadlocking on exclusive mutex
64
+ * Fix :timeout option to raise TimeoutExceeded error
65
+ * Fix test suite to work on Windows
66
+ * Fix Cmd arguments escaping
67
+
68
+ ## [v0.6.0] - 2017-07-22
69
+
70
+ ### Added
71
+ * Add runtime property to command result
72
+ * Add ability to merge multiple redirects
73
+
74
+ ### Changed
75
+ * Change to make all strings immutable
76
+ * Change waiting for pid to recover when already dead
77
+
78
+ ### Fix
79
+ * Fix redirection to instead of redirecting to parent process, redirect to child process. And hence allow for :out => :err redirection to work with output logging.
80
+
81
+ ## [v0.5.0] - 2017-07-16
82
+
83
+ ### Added
84
+ * Add :signal option for timeout
85
+ * Add :input option for handling stdin input
86
+ * Add ability for Command#run to specify a callback that is invoked whenever stdout or stderr receive output
87
+ * Add Command#wait for polling a long running script for matching output
88
+
89
+ ### Changed
90
+ * Change ProcessRunner to immediately sync write pipe
91
+ * Change ProcessRunner to write to stdin stream when writable
92
+
93
+ ### Fixed
94
+ * Fix quiet printer write call by @jamesepatrick
95
+ * Fix to correctly close all pipe ends between parent and child process
96
+ * Fix timeout behaviour for writable and readable streams
97
+
98
+ ## [v0.4.0] - 2017-02-22
99
+
100
+ ### Changed
101
+ * Remove automatic insertion of semicolons on line breaks and fix issue #27
102
+
103
+ ## [v0.3.3] - 2017-02-10
104
+
105
+ ### Changed
106
+ * Update deprecated Fixnum class to Integer for Ruby 2.4 compatability by Edmund Larden(@admund)
107
+ * Remove self extension from Execute
108
+
109
+ ## [v0.3.2] - 2017-02-06
110
+
111
+ ### Fixed
112
+ * Fix File namespacing
113
+
114
+ ## [v0.3.1] - 2017-01-22
115
+
116
+ ### Fixed
117
+ * Fix top level File constant
118
+
119
+ ## [v0.3.0] - 2017-01-13
120
+
121
+ ### Added
122
+ * Add ability to enumerate Result output
123
+ * Add #record_saparator for specifying delimiter for enumeration
124
+
125
+ ### Changed
126
+ * Change Abstract printer to separate arguments out
127
+ * Change Cmd to prevent modifications
128
+ * Change pastel dependency version
129
+
130
+ ## [v0.2.0] - 2016-07-03
131
+
132
+ ### Added
133
+ * Add ruby interperter helper
134
+
135
+ ### Fixed
136
+ * Fix multibyte content truncation for streams by Ondrej Moravcik(@ondra-m)
137
+
138
+ ## [v0.1.0] - 2016-05-29
139
+
140
+ * Initial implementation and release
141
+
142
+ [v0.10.0]: https://github.com/piotrmurach/tty-command/compare/v0.9.0...v0.10.0
143
+ [v0.9.0]: https://github.com/piotrmurach/tty-command/compare/v0.8.2...v0.9.0
144
+ [v0.8.2]: https://github.com/piotrmurach/tty-command/compare/v0.8.1...v0.8.2
145
+ [v0.8.1]: https://github.com/piotrmurach/tty-command/compare/v0.8.0...v0.8.1
146
+ [v0.8.0]: https://github.com/piotrmurach/tty-command/compare/v0.7.0...v0.8.0
147
+ [v0.7.0]: https://github.com/piotrmurach/tty-command/compare/v0.6.0...v0.7.0
148
+ [v0.6.0]: https://github.com/piotrmurach/tty-command/compare/v0.5.0...v0.6.0
149
+ [v0.5.0]: https://github.com/piotrmurach/tty-command/compare/v0.4.0...v0.5.0
150
+ [v0.4.0]: https://github.com/piotrmurach/tty-command/compare/v0.3.3...v0.4.0
151
+ [v0.3.3]: https://github.com/piotrmurach/tty-command/compare/v0.3.2...v0.3.3
152
+ [v0.3.2]: https://github.com/piotrmurach/tty-command/compare/v0.3.1...v0.3.2
153
+ [v0.3.1]: https://github.com/piotrmurach/tty-command/compare/v0.3.0...v0.3.1
154
+ [v0.3.0]: https://github.com/piotrmurach/tty-command/compare/v0.2.0...v0.3.0
155
+ [v0.2.0]: https://github.com/piotrmurach/tty-command/compare/v0.1.0...v0.2.0
156
+ [v0.1.0]: https://github.com/piotrmurach/tty-command/compare/v0.1.0
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Piotr Murach
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,661 @@
1
+ <div align="center">
2
+ <a href="https://piotrmurach.github.io/tty" target="_blank"><img width="130" src="https://cdn.rawgit.com/piotrmurach/tty/master/images/tty.png" alt="tty logo" /></a>
3
+ </div>
4
+
5
+ # TTY::Command [![Gitter](https://badges.gitter.im/Join%20Chat.svg)][gitter]
6
+
7
+ [![Gem Version](https://badge.fury.io/rb/tty-command.svg)][gem]
8
+ [![Build Status](https://secure.travis-ci.org/piotrmurach/tty-command.svg?branch=master)][travis]
9
+ [![Build status](https://ci.appveyor.com/api/projects/status/0150ync7bdkfhmsv?svg=true)][appveyor]
10
+ [![Code Climate](https://codeclimate.com/github/piotrmurach/tty-command/badges/gpa.svg)][codeclimate]
11
+ [![Coverage Status](https://coveralls.io/repos/github/piotrmurach/tty-command/badge.svg)][coverage]
12
+ [![Inline docs](http://inch-ci.org/github/piotrmurach/tty-command.svg?branch=master)][inchpages]
13
+
14
+ [gitter]: https://gitter.im/piotrmurach/tty
15
+ [gem]: http://badge.fury.io/rb/tty-command
16
+ [travis]: http://travis-ci.org/piotrmurach/tty-command
17
+ [appveyor]: https://ci.appveyor.com/project/piotrmurach/tty-command
18
+ [codeclimate]: https://codeclimate.com/github/piotrmurach/tty-command
19
+ [coverage]: https://coveralls.io/github/piotrmurach/tty-command
20
+ [inchpages]: http://inch-ci.org/github/piotrmurach/tty-command
21
+
22
+ > Run external commands with pretty output logging and capture stdout, stderr and exit status. Redirect stdin, stdout and stderr of each command to a file or a string.
23
+
24
+ **TTY::Command** provides independent command execution component for [TTY](https://github.com/piotrmurach/tty) toolkit.
25
+
26
+ ## Motivation
27
+
28
+ Complex software projects aren't just a single app. These projects usually spawn dozens or hundreds of supplementary standalone scripts which are just as important as the app itself. Examples include - data validation, deployment, monitoring, database maintenance, backup & restore, configuration management, crawling, ETL, analytics, log file processing, custom reports, etc. One of the contributors to **TTY::Command** counted 222 scripts in the `bin` directory for his startup.
29
+
30
+ Why should we be handcuffed to `sh` or `bash` for these scripts when we could be using Ruby? Ruby is easier to write and more fun, and we gain a lot by using a better language. It's nice for everyone to just use Ruby everywhere.
31
+
32
+ **TTY::Command** tries to add value in other ways. It'll halt automatically if a command fails. It's easy to get verbose or quiet output as appropriate, or even capture output and parse it with Ruby. Escaping arguments is a breeze. These are all areas where traditional shell scripts tend to fall flat.
33
+
34
+ ## Installation
35
+
36
+ Add this line to your application's Gemfile:
37
+
38
+ ```ruby
39
+ gem 'tty-command'
40
+ ```
41
+
42
+ And then execute:
43
+
44
+ $ bundle
45
+
46
+ Or install it yourself as:
47
+
48
+ $ gem install tty-command
49
+
50
+ ## Contents
51
+
52
+ * [1. Usage](#1-usage)
53
+ * [2. Interface](#2-interface)
54
+ * [2.1. Run](#21-run)
55
+ * [2.2. Run!](#22-run)
56
+ * [2.3. Logging](#23-logging)
57
+ * [2.3.1. Color](#231-color)
58
+ * [2.3.2. UUID](#232-uuid)
59
+ * [2.3.3. Only output on error](#233-only-output-on-error)
60
+ * [2.3.4. Verbose](#234-verbose)
61
+ * [2.4. Dry run](#24-dry-run)
62
+ * [2.5. Wait](#25-wait)
63
+ * [2.6. Test](#26-test)
64
+ * [2.7. Ruby interpreter](#27-ruby-interpreter)
65
+ * [3. Advanced Interface](#3-advanced-interface)
66
+ * [3.1. Environment variables](#31-environment-variables)
67
+ * [3.2. Options](#32-options)
68
+ * [3.2.1. Redirection](#321-redirection)
69
+ * [3.2.2. Handling input](#322-handling-input)
70
+ * [3.2.3. Timeout](#323-timeout)
71
+ * [3.2.4. Binary mode](#324-binary-mode)
72
+ * [3.2.5. Signal](#325-signal)
73
+ * [3.2.6. PTY(pseudo-terminal)](#326-ptypseudo-terminal)
74
+ * [3.2.7. Current directory](#327-current-directory)
75
+ * [3.2.8. User](#328-user)
76
+ * [3.2.9. Group](#329-group)
77
+ * [3.2.10. Umask](#3210-umask)
78
+ * [3.3. Result](#33-result)
79
+ * [3.3.1. success?](#331-success)
80
+ * [3.3.2. failure?](#332-failure)
81
+ * [3.3.3. exited?](#333-exited)
82
+ * [3.3.4. each](#334-each)
83
+ * [3.4. Custom printer](#34-custom-printer)
84
+ * [4. Example](#4-example)
85
+
86
+ ## 1. Usage
87
+
88
+ Create a command instance and then run some commands:
89
+
90
+ ```ruby
91
+ require 'tty-command'
92
+
93
+ cmd = TTY::Command.new
94
+ cmd.run('ls -la')
95
+ cmd.run('echo Hello!')
96
+ ```
97
+
98
+ Note that `run` will throw an exception if the command fails. This is already an improvement over ordinary shell scripts, which just keep on going when things go bad. That usually makes things worse.
99
+
100
+ You can use the return value to capture stdout and stderr:
101
+
102
+ ```ruby
103
+ out, err = cmd.run('cat ~/.bashrc | grep alias')
104
+ ```
105
+
106
+ Instead of using a plain old string, you can break up the arguments and they'll get escaped if necessary:
107
+
108
+ ```ruby
109
+ path = "hello world"
110
+ FileUtils.touch(path)
111
+ cmd.run("sum #{path}") # this will fail due to bad escaping
112
+ cmd.run("sum", path) # this gets escaped automatically
113
+ ```
114
+
115
+ ## 2. Interface
116
+
117
+ ### 2.1 Run
118
+
119
+ Run starts the specified command and waits for it to complete.
120
+
121
+ The argument signature of `run` is as follows:
122
+
123
+ `run([env], command, [argv1, ...], [options])`
124
+
125
+ The `env`, `command` and `options` arguments are described in the following sections.
126
+
127
+ For example, to display file contents:
128
+
129
+ ```ruby
130
+ cmd.run('cat file.txt')
131
+ ```
132
+
133
+ If the command succeeds, a `TTY::Command::Result` is returned that records stdout and stderr:
134
+
135
+ ```ruby
136
+ out, err = cmd.run('date')
137
+ puts "The date is #{out}"
138
+ # => "The date is Tue 10 May 2016 22:30:15 BST\n"
139
+ ```
140
+
141
+ You can also pass a block that gets invoked anytime stdout and/or stderr receive output:
142
+
143
+ ```ruby
144
+ cmd.run('long running script') do |out, err|
145
+ output << out if out
146
+ errors << err if err
147
+ end
148
+ ```
149
+
150
+ If the command fails (with a non-zero exit code), a `TTY::Command::ExitError` is raised. The `ExitError` message will include:
151
+
152
+ * the name of command executed
153
+ * the exit status
154
+ * stdout bytes
155
+ * stderr bytes
156
+
157
+ If the error output is very long, the stderr may contain only a prefix, number of omitted bytes and suffix.
158
+
159
+ ### 2.2 Run!
160
+
161
+ If you expect a command to fail occasionally, use `run!` instead. Then you can detect failures and respond appropriately. For example:
162
+
163
+ ```ruby
164
+ if cmd.run!('which xyzzy').failure?
165
+ cmd.run('brew install xyzzy')
166
+ end
167
+ ```
168
+
169
+ ### 2.3 Logging
170
+
171
+ By default, when a command is run, the command and the output are printed to `stdout` using the `:pretty` printer. If you wish to change printer you can do so by passing a `:printer` option:
172
+
173
+ * `:null` - no output
174
+ * `:pretty` - colorful output
175
+ * `:progress` - minimal output with green dot for success and F for failure
176
+ * `:quiet` - only output actual command stdout and stderr
177
+
178
+ like so:
179
+
180
+ ```ruby
181
+ cmd = TTY::Command.new(printer: :progress)
182
+ ```
183
+
184
+ By default the printers log to `stdout` but this can be changed by passing an object that responds to `<<` message:
185
+
186
+ ```ruby
187
+ logger = Logger.new('dev.log')
188
+ cmd = TTY::Command.new(output: logger)
189
+ ```
190
+
191
+ You can force the printer to always in print in color by passing the `:color` option:
192
+
193
+ ```ruby
194
+ cmd = TTY::Command.new(color: true)
195
+ ```
196
+
197
+ If the default printers don't meet your needs you can always create [a custom printer](#34-custom-printer)
198
+
199
+ #### 2.3.1 Color
200
+
201
+ When using printers you can switch off coloring by using `:color` option set to `false`.
202
+
203
+ #### 2.3.2 UUID
204
+
205
+ By default, when logging is enabled and `pretty` printer is used, each log entry is prefixed by specific command run uuid number. This number can be switched off using the `:uuid` option at initialization:
206
+
207
+ ```ruby
208
+ cmd = TTY::Command.new(uuid: false)
209
+ cmd.run('rm -R all_my_files')
210
+ # =>
211
+ # Running rm -r all_my_files
212
+ # ...
213
+ # Finished in 6 seconds with exit status 0 (successful)
214
+ ```
215
+
216
+ or individually per command run:
217
+
218
+ ```rub
219
+ cmd = TTY::Command.new
220
+ cmd.run("echo hello", uuid: false)
221
+ # =>
222
+ # Running echo hello
223
+ # hello
224
+ # Finished in 0.003 seconds with exit status 0 (successful)
225
+ ```
226
+
227
+ #### 2.3.3 Only output on error
228
+
229
+ When using a command that can fail, setting `:only_output_on_error` option to `true` hides the output if the command succeeds:
230
+
231
+ ```ruby
232
+ cmd = TTY::Command.new
233
+ cmd.run('non_failing_command', only_output_on_error: true)
234
+ ```
235
+
236
+ This will only print the `Running` and `Finished` lines, while:
237
+
238
+ ```ruby
239
+ cmd.run('non_failing_command')
240
+ ```
241
+
242
+ will also print any output that the `non_failing_command` might generate.
243
+
244
+ Running either:
245
+
246
+ ```ruby
247
+ cmd.run('failing_command', only_output_on_error: true)
248
+ ```
249
+
250
+ either:
251
+
252
+ ```ruby
253
+ cmd.run('failing_command')
254
+ ```
255
+
256
+ will also print the output.
257
+
258
+ *Setting this option will cause the output to show at once, at the end of the command.*
259
+
260
+ #### 2.3.4 Verbose
261
+
262
+ By default commands will produce warnings when, for example `pty` option is not supported on a given platform. You can switch off such warnings with `:verbose` option set to `false`.
263
+
264
+ ```ruby
265
+ cmd.run("echo '\e[32mColors!\e[0m'", pty: true, verbose: false)
266
+ ```
267
+
268
+ ### 2.4 Dry run
269
+
270
+ Sometimes it can be useful to put your script into a "dry run" mode that prints commands without actually running them. To simulate execution of the command use the `:dry_run` option:
271
+
272
+ ```ruby
273
+ cmd = TTY::Command.new(dry_run: true)
274
+ cmd.run(:rm, 'all_my_files')
275
+ # => [123abc] (dry run) rm all_my_files
276
+ ```
277
+
278
+ To check what mode the command is in use the `dry_run?` query helper:
279
+
280
+ ```ruby
281
+ cmd.dry_run? # => true
282
+ ```
283
+
284
+ ### 2.5 Wait
285
+
286
+ If you need to wait for a long running script and stop it when a given pattern has been matched use `wait` like so:
287
+
288
+ ```ruby
289
+ cmd.wait 'tail -f /var/log/production.log', /something happened/
290
+ ```
291
+
292
+ ### 2.6 Test
293
+
294
+ To simulate classic bash test command you case use `test` method with expression to check as a first argument:
295
+
296
+ ```ruby
297
+ if cmd.test '-e /etc/passwd'
298
+ puts "Sweet..."
299
+ else
300
+ puts "Ohh no! Where is it?"
301
+ exit 1
302
+ end
303
+ ```
304
+
305
+ ### 2.7 Ruby interpreter
306
+
307
+ In order to run a command with Ruby interpreter do:
308
+
309
+ ```ruby
310
+ cmd.ruby %q{-e "puts 'Hello world'"}
311
+ ```
312
+
313
+ ## 3. Advanced Interface
314
+
315
+ ### 3.1 Environment variables
316
+
317
+ The environment variables need to be provided as hash entries, that can be set directly as a first argument:
318
+
319
+ ```ruby
320
+ cmd.run({'RAILS_ENV' => 'PRODUCTION'}, :rails, 'server')
321
+ ```
322
+
323
+ or as an option with `:env` key:
324
+
325
+ ```ruby
326
+ cmd.run(:rails, 'server', env: {rails_env: :production})
327
+ ```
328
+
329
+ When a value in env is nil, the variable is unset in the child process:
330
+
331
+ ```ruby
332
+ cmd.run(:echo, 'hello', env: {foo: 'bar', baz: nil})
333
+ ```
334
+
335
+ ### 3.2 Options
336
+
337
+ When a hash is given in the last argument (options), it allows to specify a current directory, umask, user, group and zero or more fd redirects for the child process.
338
+
339
+ #### 3.2.1 Redirection
340
+
341
+ There are few ways you can redirect commands output.
342
+
343
+ You can directly use shell redirection like so:
344
+
345
+ ```ruby
346
+ out, err = cmd.run("ls 1&>2")
347
+ puts err
348
+ # =>
349
+ # CHANGELOG.md
350
+ # CODE_OF_CONDUCT.md
351
+ # Gemfile
352
+ # ...
353
+ ```
354
+
355
+ You can provide redirection as additional hash options where the key is one of `:in`, `:out`, `:err`, an integer (a file descriptor for the child process), an IO or array. For example, `stderr` can be merged into stdout as follows:
356
+
357
+ ```ruby
358
+ cmd.run(:ls, :err => :out)
359
+ cmd.run(:ls, :stderr => :stdout)
360
+ cmd.run(:ls, 2 => 1)
361
+ cmd.run(:ls, STDERR => :out)
362
+ cmd.run(:ls, STDERR => STDOUT)
363
+ ```
364
+
365
+ The hash key and value specify a file descriptor in the child process (stderr & stdout in the examples).
366
+
367
+ You can also redirect to a file:
368
+
369
+ ```ruby
370
+ cmd.run(:cat, :in => 'file')
371
+ cmd.run(:cat, :in => open('/etc/passwd'))
372
+ cmd.run(:ls, :out => 'log')
373
+ cmd.run(:ls, :out => "/dev/null")
374
+ cmd.run(:ls, :out => 'out.log', :err => "err.log")
375
+ cmd.run(:ls, [:out, :err] => "log")
376
+ cmd.run("ls 1>&2", :err => 'log')
377
+ ```
378
+
379
+ It is possible to specify flags and permissions of file creation explicitly by passing an array value:
380
+
381
+ ```ruby
382
+ cmd.run(:ls, :out => ['log', 'w']) # 0664 assumed
383
+ cmd.run(:ls, :out => ['log', 'w', 0600])
384
+ cmd.run(:ls, :out => ['log', File::WRONLY|File::EXCL|File::CREAT, 0600])
385
+ ```
386
+
387
+ You can, for example, read data from one source and output to another:
388
+
389
+ ```ruby
390
+ cmd.run("cat", :in => "Gemfile", :out => 'gemfile.log')
391
+ ```
392
+
393
+ #### 3.2.2 Handling Input
394
+
395
+ You can provide input to stdin stream using the `:input` key. For instance, given the following executable called `cli` that expects name from `stdin`:
396
+
397
+ ```ruby
398
+ name = $stdin.gets
399
+ puts "Your name: #{name}"
400
+ ```
401
+
402
+ In order to execute `cli` with name input do:
403
+
404
+ ```ruby
405
+ cmd.run('cli', input: "Piotr\n")
406
+ # => Your name: Piotr
407
+ ```
408
+
409
+ Alternatively, you can pass input via the :in option, by passing a `StringIO` Object. This object might have more than one line, if the executed command reads more than once from STDIN.
410
+
411
+ Assume you have run a program, that first asks for your email address and then for a password:
412
+
413
+ ```ruby
414
+ in_stream = StringIO.new
415
+ in_stream.puts "username@example.com"
416
+ in_stream.puts "password"
417
+ in_stream.rewind
418
+
419
+ cmd.run("my_cli_program", "login", in: in_stream).out
420
+ ```
421
+
422
+ #### 3.2.3 Timeout
423
+
424
+ You can timeout command execution by providing the `:timeout` option in seconds:
425
+
426
+ ```ruby
427
+ cmd.run("while test 1; sleep 1; done", timeout: 5)
428
+ ```
429
+
430
+ And to set it for all commands do:
431
+
432
+ ```ruby
433
+ cmd = TTY::Command.new(timeout: 5)
434
+ ```
435
+
436
+ Please run `examples/timeout.rb` to see timeout in action.
437
+
438
+ #### 3.2.4 Binary mode
439
+
440
+ By default the standard input, output and error are non-binary. However, you can change to read and write in binary mode by using the `:binmode` option like so:
441
+
442
+ ```ruby
443
+ cmd.run("echo 'hello'", binmode: true)
444
+ ```
445
+
446
+ To set all commands to be run in binary mode do:
447
+
448
+ ```ruby
449
+ cmd = TTY::Command.new(binmode: true)
450
+ ```
451
+
452
+ #### 3.2.5 Signal
453
+
454
+ You can specify process termination signal other than the default `SIGTERM`:
455
+
456
+ ```ruby
457
+ cmd.run("whilte test1; sleep1; done", timeout: 5, signal: :KILL)
458
+ ```
459
+
460
+ #### 3.2.6 PTY(pseudo terminal)
461
+
462
+ The `:pty` configuration option causes the command to be executed in subprocess where each stream is a `pseudo terminal`. By default this options is set to `false`.
463
+
464
+ If you require to interface with interactive subprocess then setting this option to `true` will enable a `pty` terminal device. For example, a command may emit colored output only if it is running via terminal device. You may also wish to run a program that waits for user input, and simulates typing in commands and reading responses.
465
+
466
+ This option will only work on systems that support BSD pty devices such as Linux or OS X, and it will gracefully fallback to non-pty device on all the other.
467
+
468
+ In order to run command in `pseudo terminal`, either set the flag globally for all commands:
469
+
470
+ ```ruby
471
+ cmd = TTY::Command.new(pty: true)
472
+ ```
473
+
474
+ or individually for each executed command:
475
+
476
+ ```ruby
477
+ cmd.run("echo 'hello'", pty: true)
478
+ ```
479
+
480
+ Please note that setting `:pty` to `true` may change how the command behaves. It's important to understand the difference between `interactive` and `non-interactive` modes. For example, executing `git log` to view the commit history in default `non-interactive` mode:
481
+
482
+ ```ruby
483
+ cmd.run("git log") # => finishes and produces full output
484
+ ```
485
+
486
+ However, in `interactive` mode with `pty` flag on:
487
+
488
+ ```ruby
489
+ cmd.run("git log", pty: true) # => uses pager and waits for user input (never returns)
490
+ ```
491
+
492
+ In addition, when pty device is used, any input to command may be echoed to the standard output, as well as some redirects may not work.
493
+
494
+ #### 3.2.7 Current directory
495
+
496
+ To change directory in which the command is run pass the `:chdir` option:
497
+
498
+ ```ruby
499
+ cmd.run(:echo, 'hello', chdir: '/var/tmp')
500
+ ```
501
+
502
+ #### 3.2.8 User
503
+
504
+ To run command as a given user do:
505
+
506
+ ```ruby
507
+ cmd.run(:echo, 'hello', user: 'piotr')
508
+ ```
509
+
510
+ #### 3.2.9 Group
511
+
512
+ To run command as part of group do:
513
+
514
+ ```ruby
515
+ cmd.run(:echo, 'hello', group: 'devs')
516
+ ```
517
+
518
+ #### 3.2.10 Umask
519
+
520
+ To run command with umask do:
521
+
522
+ ```ruby
523
+ cmd.run(:echo, 'hello', umask: '007')
524
+ ```
525
+
526
+ ### 3.3 Result
527
+
528
+ Each time you run command the stdout and stderr are captured and return as result. The result can be examined directly by casting it to tuple:
529
+
530
+ ```ruby
531
+ out, err = cmd.run(:echo, 'Hello')
532
+ ```
533
+
534
+ However, if you want to you can defer reading:
535
+
536
+ ```ruby
537
+ result = cmd.run(:echo, 'Hello')
538
+ result.out
539
+ result.err
540
+ ```
541
+
542
+ #### 3.3.1 success?
543
+
544
+ To check if command exited successfully use `success?`:
545
+
546
+ ```ruby
547
+ result = cmd.run(:echo, 'Hello')
548
+ result.success? # => true
549
+ ```
550
+
551
+ #### 3.3.2 failure?
552
+
553
+ To check if command exited unsuccessfully use `failure?` or `failed?`:
554
+
555
+ ```ruby
556
+ result = cmd.run(:echo, 'Hello')
557
+ result.failure? # => false
558
+ result.failed? # => false
559
+ ```
560
+
561
+ #### 3.3.3 exited?
562
+
563
+ To check if command ran to completion use `exited?` or `complete?`:
564
+
565
+ ```ruby
566
+ result = cmd.run(:echo, 'Hello')
567
+ result.exited? # => true
568
+ result.complete? # => true
569
+ ```
570
+
571
+ #### 3.3.4 each
572
+
573
+ The result itself is an enumerable and allows you to iterate over the stdout output:
574
+
575
+ ```ruby
576
+ result = cmd.run(:ls, '-1')
577
+ result.each { |line| puts line }
578
+ # =>
579
+ # CHANGELOG.md
580
+ # CODE_OF_CONDUCT.md
581
+ # Gemfile
582
+ # Gemfile.lock
583
+ # ...
584
+ # lib
585
+ # pkg
586
+ # spec
587
+ # tasks
588
+ ```
589
+
590
+ By default the linefeed character `\n` is used as a delimiter but this can be changed either globally by calling `record_separator`:
591
+
592
+ ```ruby
593
+ TTY::Command.record_separator = "\n\r"
594
+ ```
595
+
596
+ or configured per `each` call by passing delimiter as an argument:
597
+
598
+ ```ruby
599
+ cmd.run(:ls, '-1').each("\t") { ... }
600
+ ```
601
+
602
+ ### 3.4 Custom printer
603
+
604
+ If the built-in printers do not meet your requirements you can create your own. A printer is a regular Ruby class that can be registered through `:printer` option to receive notifications about received command data.
605
+
606
+ As the command runs the custom printer will be notified when the command starts, when data is printed to stdout, when data is printed to stderr and when the command exits.
607
+
608
+ Please see [lib/tty/command/printers/abstract.rb](https://github.com/piotrmurach/tty-command/blob/master/lib/tty/command/printers/abstract.rb) for a full set of methods that you can override.
609
+
610
+ At the very minimum you need to specify the `write` method that will be called during the lifecycle of command execution. The `write` accepts two arguments, first the currently run command instance and second the message to be printed:
611
+
612
+ ```ruby
613
+ CustomPrinter < TTY::Command::Printers::Abstract
614
+ def write(cmd, message)
615
+ puts cmd.to_command + message
616
+ end
617
+ end
618
+
619
+ cmd = TTY::Command.new(printer: CustomPrinter)
620
+ ```
621
+
622
+ ## 4. Example
623
+
624
+ Here's a slightly more elaborate example to illustrate how tty-command can improve on plain old shell scripts. This example installs a new version of Ruby on an Ubuntu machine.
625
+
626
+ ```ruby
627
+ cmd = TTY::Command.new
628
+
629
+ # dependencies
630
+ cmd.run "apt-get -y install build-essential checkinstall"
631
+
632
+ # fetch ruby if necessary
633
+ if !File.exists?("ruby-2.3.0.tar.gz")
634
+ puts "Downloading..."
635
+ cmd.run "wget http://ftp.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.gz"
636
+ cmd.run "tar xvzf ruby-2.3.0.tar.gz"
637
+ end
638
+
639
+ # now install
640
+ Dir.chdir("ruby-2.3.0") do
641
+ puts "Building..."
642
+ cmd.run "./configure --prefix=/usr/local"
643
+ cmd.run "make"
644
+ end
645
+ ```
646
+
647
+ ## Development
648
+
649
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
650
+
651
+ ## Contributing
652
+
653
+ Bug reports and pull requests are welcome on GitHub at https://github.com/piotrmurach/tty-command. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
654
+
655
+ ## License
656
+
657
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
658
+
659
+ ## Copyright
660
+
661
+ Copyright (c) 2016 Piotr Murach. See LICENSE for further details.