Coder Social home page Coder Social logo

piotrmurach / tty-command Goto Github PK

View Code? Open in Web Editor NEW
397.0 9.0 34.0 337 KB

Execute shell commands with pretty output logging and capture stdout, stderr and exit status.

Home Page: https://ttytoolkit.org

License: MIT License

Ruby 99.90% Shell 0.10%
ruby-gem cli tty tty-components stdout logging

tty-command's Introduction

TTY Toolkit logo

TTY::Command

Gem Version Actions CI Build status Code Climate Coverage Status

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.

TTY::Command provides independent command execution component for TTY toolkit.

Motivation

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.

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.

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.

Installation

Add this line to your application's Gemfile:

gem "tty-command"

And then execute:

$ bundle

Or install it yourself as:

$ gem install tty-command

Contents

1. Usage

Create a command instance and then run some commands:

require "tty-command"

cmd = TTY::Command.new
cmd.run("ls -la")
cmd.run("echo Hello!")

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.

You can use the return value to capture stdout and stderr:

out, err = cmd.run("cat ~/.bashrc | grep alias")

Instead of using a plain old string, you can break up the arguments and they'll get escaped if necessary:

path = "hello world"
FileUtils.touch(path)
cmd.run("sum #{path}")  # this will fail due to bad escaping
cmd.run("sum", path)    # this gets escaped automatically

2. Interface

2.1 Run

Run starts the specified command and waits for it to complete.

The argument signature of run is as follows:

run([env], command, [argv1, ...], [options])

The env, command and options arguments are described in the following sections.

For example, to display file contents:

cmd.run("cat file.txt")

If the command succeeds, a TTY::Command::Result is returned that records stdout and stderr:

out, err = cmd.run("date")
puts "The date is #{out}"
# => "The date is Tue 10 May 2016 22:30:15 BST\n"

You can also pass a block that gets invoked anytime stdout and/or stderr receive output:

cmd.run("long running script") do |out, err|
  output << out if out
  errors << err if err
end

If the command fails (with a non-zero exit code), a TTY::Command::ExitError is raised. The ExitError message will include:

  • the name of command executed
  • the exit status
  • stdout bytes
  • stderr bytes

If the error output is very long, the stderr may contain only a prefix, number of omitted bytes and suffix.

2.2 Run!

If you expect a command to fail occasionally, use run! instead. Then you can detect failures and respond appropriately. For example:

if cmd.run!("which xyzzy").failure?
  cmd.run("brew install xyzzy")
end

2.3 Logging

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:

  • :null - no output
  • :pretty - colorful output
  • :progress - minimal output with green dot for success and F for failure
  • :quiet - only output actual command stdout and stderr

like so:

cmd = TTY::Command.new(printer: :progress)

By default the printers log to stdout but this can be changed by passing an object that responds to << message:

logger = Logger.new("dev.log")
cmd = TTY::Command.new(output: logger)

You can force the printer to always in print in color by passing the :color option:

cmd = TTY::Command.new(color: true)

If the default printers don't meet your needs you can always create a custom printer

2.3.1 Color

When using printers you can switch off coloring by using :color option set to false.

2.3.2 UUID

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:

cmd = TTY::Command.new(uuid: false)
cmd.run("rm -R all_my_files")
# =>
#  Running rm -r all_my_files
#  ...
#  Finished in 6 seconds with exit status 0 (successful)

or individually per command run:

cmd = TTY::Command.new
cmd.run("echo hello", uuid: false)
# =>
#  Running echo hello
#      hello
#  Finished in 0.003 seconds with exit status 0 (successful)

2.3.3 Only output on error

When using a command that can fail, setting :only_output_on_error option to true hides the output if the command succeeds:

cmd = TTY::Command.new
cmd.run("non_failing_command", only_output_on_error: true)

This will only print the Running and Finished lines, while:

cmd.run("non_failing_command")

will also print any output that the non_failing_command might generate.

Running either:

cmd.run("failing_command", only_output_on_error: true)

either:

cmd.run("failing_command")

will also print the output.

Setting this option will cause the output to show at once, at the end of the command.

2.3.4 Verbose

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.

cmd.run("echo '\e[32mColors!\e[0m'", pty: true, verbose: false)

2.4 Dry run

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:

cmd = TTY::Command.new(dry_run: true)
cmd.run(:rm, "all_my_files")
# => [123abc] (dry run) rm all_my_files

To check what mode the command is in use the dry_run? query helper:

cmd.dry_run? # => true

2.5 Wait

If you need to wait for a long running script and stop it when a given pattern has been matched use wait like so:

cmd.wait "tail -f /var/log/production.log", /something happened/

2.6 Test

To simulate classic bash test command you case use test method with expression to check as a first argument:

if cmd.test "-e /etc/passwd"
  puts "Sweet..."
else
  puts "Ohh no! Where is it?"
  exit 1
end

2.7 Ruby interpreter

In order to run a command with Ruby interpreter do:

cmd.ruby %q{-e "puts 'Hello world'"}

3. Advanced Interface

3.1 Environment variables

The environment variables need to be provided as hash entries, that can be set directly as a first argument:

cmd.run({"RAILS_ENV" => "PRODUCTION"}, :rails, "server")

or as an option with :env key:

cmd.run(:rails, "server", env: {rails_env: :production})

When a value in env is nil, the variable is unset in the child process:

cmd.run(:echo, "hello", env: {foo: "bar", baz: nil})

3.2 Options

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.

3.2.1 Redirection

There are few ways you can redirect commands output.

You can directly use shell redirection like so:

out, err = cmd.run("ls 1&>2")
puts err
# =>
# CHANGELOG.md
# CODE_OF_CONDUCT.md
# Gemfile
# ...

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:

cmd.run(:ls, :err => :out)
cmd.run(:ls, :stderr => :stdout)
cmd.run(:ls, 2 => 1)
cmd.run(:ls, STDERR => :out)
cmd.run(:ls, STDERR => STDOUT)

The hash key and value specify a file descriptor in the child process (stderr & stdout in the examples).

You can also redirect to a file:

cmd.run(:cat, :in => "file")
cmd.run(:cat, :in => open("/etc/passwd"))
cmd.run(:ls, :out => "log")
cmd.run(:ls, :out => "/dev/null")
cmd.run(:ls, :out => "out.log", :err => "err.log")
cmd.run(:ls, [:out, :err] => "log")
cmd.run("ls 1>&2", :err => "log")

It is possible to specify flags and permissions of file creation explicitly by passing an array value:

cmd.run(:ls, :out => ["log", "w"]) # 0664 assumed
cmd.run(:ls, :out => ["log", "w", 0600])
cmd.run(:ls, :out => ["log", File::WRONLY|File::EXCL|File::CREAT, 0600])

You can, for example, read data from one source and output to another:

cmd.run("cat", :in => "Gemfile", :out => "gemfile.log")

3.2.2 Handling Input

You can provide input to stdin stream using the :input key. For instance, given the following executable called cli that expects name from stdin:

name = $stdin.gets
puts "Your name: #{name}"

In order to execute cli with name input do:

cmd.run("cli", input: "Piotr\n")
# => Your name: Piotr

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.

Assume you have run a program, that first asks for your email address and then for a password:

in_stream = StringIO.new
in_stream.puts "[email protected]"
in_stream.puts "password"
in_stream.rewind

cmd.run("my_cli_program", "login", in: in_stream).out

3.2.3 Timeout

You can timeout command execution by providing the :timeout option in seconds:

cmd.run("while test 1; sleep 1; done", timeout: 5)

And to set it for all commands do:

cmd = TTY::Command.new(timeout: 5)

Please run examples/timeout.rb to see timeout in action.

3.2.4 Binary mode

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:

cmd.run("echo 'hello'", binmode: true)

To set all commands to be run in binary mode do:

cmd = TTY::Command.new(binmode: true)

3.2.5 Signal

You can specify process termination signal other than the default SIGTERM:

cmd.run("whilte test1; sleep1; done", timeout: 5, signal: :KILL)

3.2.6 PTY(pseudo terminal)

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.

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.

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.

In order to run command in pseudo terminal, either set the flag globally for all commands:

cmd = TTY::Command.new(pty: true)

or individually for each executed command:

cmd.run("echo 'hello'", pty: true)

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:

cmd.run("git log") # => finishes and produces full output

However, in interactive mode with pty flag on:

cmd.run("git log", pty: true) # => uses pager and waits for user input (never returns)

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.

3.2.7 Current directory

To change directory in which the command is run pass the :chdir option:

cmd.run(:echo, "hello", chdir: "/var/tmp")

3.2.8 User

To run command as a given user do:

cmd.run(:echo, "hello", user: "piotr")

3.2.9 Group

To run command as part of group do:

cmd.run(:echo, "hello", group: "devs")

3.2.10 Umask

To run command with umask do:

cmd.run(:echo, "hello", umask: "007")

3.3 Result

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:

out, err = cmd.run(:echo, "Hello")

However, if you want to you can defer reading:

result = cmd.run(:echo, "Hello")
result.out
result.err

3.3.1 success?

To check if command exited successfully use success?:

result = cmd.run(:echo, "Hello")
result.success? # => true

3.3.2 failure?

To check if command exited unsuccessfully use failure? or failed?:

result = cmd.run(:echo, "Hello")
result.failure?  # => false
result.failed?   # => false

3.3.3 exited?

To check if command ran to completion use exited? or complete?:

result = cmd.run(:echo, "Hello")
result.exited?    # => true
result.complete?  # => true

3.3.4 each

The result itself is an enumerable and allows you to iterate over the stdout output:

result = cmd.run(:ls, "-1")
result.each { |line| puts line }
# =>
#  CHANGELOG.md
#  CODE_OF_CONDUCT.md
#  Gemfile
#  Gemfile.lock
#  ...
#  lib
#  pkg
#  spec
#  tasks

By default the linefeed character \n is used as a delimiter but this can be changed either globally by calling record_separator:

TTY::Command.record_separator = "\n\r"

or configured per each call by passing delimiter as an argument:

cmd.run(:ls, "-1").each("\t") { ... }

3.4 Custom printer

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.

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.

Please see lib/tty/command/printers/abstract.rb for a full set of methods that you can override.

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:

CustomPrinter < TTY::Command::Printers::Abstract
  def write(cmd, message)
    puts cmd.to_command + message
  end
end

cmd = TTY::Command.new(printer: CustomPrinter)

4. Example

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.

cmd = TTY::Command.new

# dependencies
cmd.run "apt-get -y install build-essential checkinstall"

# fetch ruby if necessary
if !File.exists?("ruby-2.3.0.tar.gz")
  puts "Downloading..."
  cmd.run "wget http://ftp.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.gz"
  cmd.run "tar xvzf ruby-2.3.0.tar.gz"
end

# now install
Dir.chdir("ruby-2.3.0") do
  puts "Building..."
  cmd.run "./configure --prefix=/usr/local"
  cmd.run "make"
end

Development

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.

Contributing

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 code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Copyright

Copyright (c) 2016 Piotr Murach. See LICENSE for further details.

tty-command's People

Contributors

abhinavs avatar brandoncc avatar dannyben avatar edmund avatar gurgeous avatar jeffmcfadden avatar ondra-m avatar piotrmurach avatar revolter avatar robotex82 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tty-command's Issues

Allow tty-logger to interop with tty-command

Are you in the right place?

  • For issues or feature requests file a GitHub issue in this repository
  • For general questions or discussion post in Gitter

Describe the problem

tty-command should allow tty-logger's Loggers to be used in Command.new.

Steps to reproduce the problem

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'tty-command'
require 'tty-logger'
require 'tty-option'

# rubocop disable Style/Documentation
class Demo
  include TTY::Option

  def initialize
    @logger = TTY::Logger.new do |config|
      config.metadata = %i[date time]
      config.level = :debug
    end
    @cmd = TTY::Command.new(printer: @logger)
  end

  def demo
    @logger.info "running demo"

    @cmd.run 'cat', '/etc/hosts'
  end

  def run!
    parse
    demo
  rescue StandardError => e
    @logger.fatal 'Error:', e
  end
end

Demo.new.run!

Actual behaviour

Traceback (most recent call last):
        7: from _scripts/demo-1.rb:46:in `<main>'
        6: from _scripts/demo-1.rb:46:in `new'
        5: from _scripts/demo-1.rb:22:in `initialize'
        4: from _scripts/demo-1.rb:22:in `new'
        3: from /home/amalia/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:60:in `initialize'
        2: from /home/amalia/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:197:in `use_printer'
        1: from /home/amalia/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:208:in `find_printer_class'
/home/amalia/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:208:in `const_defined?': wrong constant name #<tty::logger:0x0000560318e216b8> (NameError)

Expected behaviour

The command's output should go to the Logger.

Describe your environment

  • OS version: 5.4.34-1-MANJARO
  • Ruby version: ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
  • TTY version: tty-command (0.9.0), tty-logger (0.3.0)

Suggestion: Reading and writing streams simultaneously without threads

Hello Piotr ๐Ÿ‘‹

This is more of a feature request, as I haven't used tty-command yet and experienced an issue with it. However, I would like to suggest a reliability improvement for tty-command, which is to write to stdin and read from stdout/stderr simultaneously without threads, using the nonblocking APIs.

Let me explain. Some MiniMagick users have been experiencing deadlocks with the shell command execution. MiniMagick uses Open3.capture3, which spawns threads for reading stdout and stderr. The guess was that somewhere during thread context switching Ruby thinks it's in a deadlock, even though stdout and stderr pipes are being emptied.

The Basecamp team made pull request to use posix-spawn's simultaneous reading and writing from streams, which you can find in POSIX::Spawn::Child#read_and_write. That change fixed deadlocks for Basecamp, so I think it might fix potential deadlocks in tty-command. A bonus is that no additional threads need to be spawned, which is always nice.

What do you think?

Bad format string error if environment variable contains a %

Describe the problem

If you use a TTY::Command and have a % in one of your environment variables, you will get a malformed format string error.

Steps to reproduce the problem

require 'tty-command'
cmd = TTY::Command.new
cmd.run("true", env: { "foo": "%16" })

Actual behaviour

Traceback (most recent call last):
        7: from /tmp/test.rb:3:in `<main>'
        6: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:104:in `run'
        5: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:185:in `execute_command'
        4: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:41:in `run!'
        3: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command/printers/pretty.rb:20:in `print_command_start'
        2: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command/cmd.rb:121:in `to_command'
        1: from /Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command/cmd.rb:87:in `evars'
/Users/sam/.rbenv/versions/2.6.4/lib/ruby/gems/2.6.0/gems/tty-command-0.9.0/lib/tty/command/cmd.rb:87:in `%': malformed format string - %" (ArgumentError)

Expected behaviour

The command to return successfully with no error.

Describe your environment

  • OS version: Mac OSX Catalina
  • Ruby version: Ruby 2.6.4
  • TTY version: 0.9.0

Ability to turn off warning when no pseudo terminal is found

Hi,

I've noticed that the following message is printed when using the pty: true option on Windows:
Requested PTY device but the system doesn't support it. This makes sense and the graceful fallback mentioned in the readme happens.

However the message is

  • printed even if TTY::Command is used with no output
  • printed as a plain line and is therefore out of place if TTY::Command is used with pretty or custom output
  • sometimes simply expected and unwanted

Therefore it'd be great to have an option to turn off this message.

Deprecation notice under ruby 2.7.0

/Users/jrochkind/.gem/ruby/2.7.0/gems/tty-command-0.9.0/lib/tty/command.rb:177: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
/Users/jrochkind/.gem/ruby/2.7.0/gems/tty-command-0.9.0/lib/tty/command/cmd.rb:66: warning: The called method `update' is defined here

Timeout also displays traceback

Hi,

I noticed that in more recent versions of TTY-Command (0.8.0+), a timeout will output a traceback to the terminal. I have already rescued and display an error message of my own, what is the best way of suppressing the traceback?
Example included below.

#<Thread:0x00007ffca2a31820@/usr/local/lib/ruby/gems/2.5.0/gems/tty-command-0.8.1/lib/tty/command/process_runner.rb:159 run> terminated with exception (report_on_exception is true):
Traceback (most recent call last):
/usr/local/lib/ruby/gems/2.5.0/gems/tty-command-0.8.1/lib/tty/command/process_runner.rb:165:in `block in read_stream': TTY::Command::TimeoutExceeded (TTY::Command::TimeoutExceeded)

Thanks,

Quiet printer puts using print instead of <<

Hey everyone,

I'm not sure if this is an issue but the Quiet Printer uses output.print(message) instead of output << message as referenced in the readme.md file.

Running

#! /usr/bin/env ruby

require 'tty-command'

# Class prints and logs output of cmd
class Tee
  def initialize(file)
    @file = file
  end
  def <<(message)
   @file << message
   puts message
  end
end

# Command System
tee = Tee.new( File.open('foo.log', 'w') )
cmd = TTY::Command.new( output: tee, printer: :quiet )

cmd.run 'ping google.com -c 3'

results in an error of :

/Users/james/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/tty-command-0.4.0/lib/tty/command/printers/quiet.rb:20:in `write': private method `print' called for #<Tee:0x007f82db191558 @file=#<File:foo.log>> (NoMethodError)
        from /Users/james/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/tty-command-0.4.0/lib/tty/command/printers/abstract.rb:33:in `print_command_out_data'
        from /Users/james/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/tty-command-0.4.0/lib/tty/command/process_runner.rb:66:in `block in read_streams'

Put using the pretty printer instead works without issue. Changing << -> write or aliasing works as well.

Remove successful execution logging

I think you could probably ditch the with exit status 0 (successful) and only log failures. That will make them stand out more, I think. Or at least make successful use the same color as the rest of the line.

feature request: built-in printer for command-only?

The defualt printer prints command and stdout/stderr: "By default, when a command is run, the command and the output are printed to stdout using the :pretty printer."

:quiet will "only output actual command stdout and stderr", without the command.

:null and :progress will both print neither.

There is one thing missing from this matrix! I often want only the command printed out, without the stdout/stderr.

I could write my own custom printer, but is this common enough to justify including as a default? printer: :command maybe?

Or I might actually want the Running.. and Finished... lines, the Finished line too, just NOT the stdout/stderr! (Or actually, more advanced... I want to somehow capture stdout/stderr to ruby strings, but print out Running/Finished.... that is a more complicated usecase I'm not sure about how to do)

Add ability to stream binary data on stderr and stdout outputs

As suggested by @janko-m, this library would benefit from ability to stream binary data chunk by chunk to stdout/stderr when available from the running process.

I didn't want to first download the whole remote file onto disk, and then start streaming the downloaded file into the response, because then the user would have to wait for the whole file to get downloaded by the server before it can start downloading it from the server (which isn't ideal if these are videos that you want to play), also it would use unnecessary disk space, even if it will get deleted at the end.
I wanted to stream the remote file to the response as it is being downloaded. So I told wget to redirect to stdout. But I couldn't capture a simple string stdout here, because it would mean that the whole file would be loaded into memory. I knew that Open3.popen3 uses Ruby pipes for stdin/stdout/stderr, which are readable/writable IO objects, so after a lot of fiddling I managed to utilize it. It would be great that instead TTY::Command provides some wrapper for that.

Execute full command strings

Actually, that touches on a larger issue. I think it should be possible to just do:
cmd.execute("sudo apt-get install xyz > /tmp/output.txt")
instead of:
cmd.execute(:sudo, "apt-get", "install", ...)
This is the most common use case, in my opinion, and supporting this pattern will encourage people to stop using bash to write this stuff.

Inserts semicolon on line breaks

Test case:

require 'tty-command'

command = %{bash -c "echo 'a\nb' >/tmp/myfile"}

# This inserts the semicolon
puts "---1"
cmd = TTY::Command.new(printer: :pretty)
cmd.run(command)
puts File.read("/tmp/myfile")

# This works
puts "---2"
system(command)
puts File.read("/tmp/myfile")

This prints:

---1
[8c782eed] Running bash -c "echo 'a; b' >/tmp/myfile"
[8c782eed] Finished in 0.005 seconds with exit status 0 (successful)
a; b
---2
a
b

As you can see, the line break is replaced with ;, even though it's in the middle of a string argument.

Also tried escaping with $'\n', but it's still broken up.

I don't think tty-command should interfere with the contents of the command line like this.

While running bash like this is of little use, we use this occasionally to wrap the subshell in sudo, among other good reasons.

Is there a way to prevent it from doing it? I tried the vararg syntax, but that leads to fail (I don't know what kind of mangling it's doing here, some kind of attempt to escape the contents?):

cmd = TTY::Command.new(printer: :pretty)
cmd.run(:bash, "-c", "echo 'a\nb'")

Output:

[6caaddb3] Running bash -c 'echo 'a
b''a
b'''
[6caaddb3] 	a
[6caaddb3] 	sh: line 1: ba: command not found
[6caaddb3] 	sh: -c: line 2: unexpected EOF while looking for matching `''
[6caaddb3] 	sh: -c: line 3: syntax error: unexpected end of file
[6caaddb3] Finished in 0.007 seconds with exit status 2 (failed)
/Users/alex/.rbenv/versions/2.1.10/lib/ruby/gems/2.1.0/gems/tty-command-0.3.2/lib/tty/command.rb:91:in `run': Running `bash -c 'echo 'a (TTY::Command::ExitError)
b''a
b'''` failed with
  exit status: 2
  stdout: a
  stderr: sh: line 1: ba: command not found
sh: -c: line 2: unexpected EOF while looking for matching `''
sh: -c: line 3: syntax error: unexpected end of file
	from test.rb:16:in `<main>'

grab bag of feedback

This is neat! Some quick thoughts after a few minutes of poking around. I really like it, so please don't take any of this feedback as negative. It's much easier to list the stuff that stood out rather than comment on the overall package, which is excellent. Thanks for putting this together!

  • That output is awesome. Any reason to include the random # in the line prefix? I'd think the pid would be enough and it would be great to reduce noise.
  • Is this using a shell, or running the process directly? This makes a big difference when writing commands and can often result in unexpected behavior, especially when trying to use redirects or pipes. Which is quite common in my experience. :)
  • Actually, that touches on a larger issue. I think it should be possible to just do:
    cmd.execute("sudo apt-get install xyz > /tmp/output.txt")
    instead of:
    cmd.execute(:sudo, "apt-get", "install", ...)
    This is the most common use case, in my opinion, and supporting this pattern will encourage people to stop using bash to write this stuff.
  • Escaping can be a challenge with the current syntax. What should this do?
    cmd.execute(:ls, "hello world")
[71555-047a57b2] Running ls hello world
[71555-047a57b2]    ls: hello: No such file or directory
[71555-047a57b2]    ls: world: No such file or directory
[71555-047a57b2] Finished in 0.002 seconds with exit status 1 (failed)
  • Any reason to use symbols vs. strings for the command name? Sadly some commands have spaces in them...
  • I think that commands should throw exceptions if they fail by default. This is one of the biggest design flaws in bash, and I can't tell you the number of problems it's caused me (and people who work with me) over the past decade. When I write scripts I almost always want to halt on failure. I recognize that if we make this change we can't use execute!, sadly.
  • Timeout looks really handy. I've definitely wanted this a few times.
  • I think you could probably ditch the with exit status 0 (successful) and only log failures. That will make them stand out more, I think. Or at least make successful use the same color as the rest of the line.
  • Features I think you can safely ditch:
    -- env: (this can easily be handled with ENV)
    -- chdir (easily handled with Dir.chdir("x") { ... }
    -- redirection (typically in the command, not needed in ruby land)
    -- :user/:group/:umask (that's what sudo is for)
  • Can I convince you to change execute to run? I love brevity and there will never be a chance to change it after this! :)

Here's a typical example, one of hundreds that I have from my old startup. Think about this snippet - would it make sense to separate out every argument? Would it make sense for the script to continue after failure? Would it make sense to replace shell redirects/pipes with a custom syntax? Just some food for thought.

  # restore db
  def db
    if Util.mac?
      chmod, dst_dir = "#{user}:admin", "/usr/local/var/mongodb"
    else
      chmod, dst_dir = "mongodb", "/var/lib/mongodb"
    end

    Util.rm_and_mkdir(TMP)
    Dir.chdir(TMP) do
      # untar
      banner "Untarring #{db_src}..."
      run("tar xvfz #{db_src} --exclude 'prealloc*'")

      # atomically move the files into place
      with_db_stopped do
        Dir.chdir("mongodb") do
          Dir["startup*"].sort.each do |src|
            next if src == "lost+found"
            next if src =~ /\.old$/

            dst = "#{dst_dir}/#{src}"
            old = "#{dst}.old"
            run "sudo rm -rf #{old}"
            run "sudo mv #{dst} #{old}" if File.exist?(dst)
            run "sudo chown #{chmod} #{src}"
            run "sudo mv #{src} #{dst}"
            run "sudo restore > /tmp/restore.txt"
          end
        end
      end
    end
  end

Happy to help implement any/all changes... Thanks again!

binary streamed :in ?

ruby: 3.2.2
TTY::Command: 0.10.1

I am trying to stream a Down::ChunkedIO object from down to a TTY::Command.

Where the content could be arbitrary binary content. But binary content streamed in: raises a Encoding::UndefinedConversionError

A simple reproduction:

require 'down'
require 'tty/command'

down_io = Down.open("https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg")

runner = TTY::Command.new

runner.run("cat > out.jpg", in: down_io)

But this raises Encoding::UndefinedConversionError

/Users/jrochkind/.rubies/ruby-3.2.2/lib/ruby/3.2.0/delegate.rb:349:in `write': "\xFF" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)
	from /Users/jrochkind/.rubies/ruby-3.2.2/lib/ruby/3.2.0/delegate.rb:349:in `block in delegating_block'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:200:in `convert_to_fd'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:136:in `convert'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:115:in `block in normalize_redirect_options'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:113:in `each'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:113:in `reduce'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:113:in `normalize_redirect_options'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/child_process.rb:24:in `spawn'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command/process_runner.rb:44:in `run!'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command.rb:185:in `execute_command'
	from /Users/jrochkind/.gem/ruby/3.2.2/gems/tty-command-0.10.1/lib/tty/command.rb:104:in `run'

I expect this to instead properly stream to process, in this case (for reproduction purposes only) resulting in writing output to out.jpg.

I think I can fix the problem by changing this line:

tmp = ::Tempfile.new(::SecureRandom.uuid.split("-")[0])

To:

tmp = ::Tempfile.new(::SecureRandom.uuid.split("-")[0], :encoding => 'ascii-8bit')

If I make that change, the reproduction script no longer raises, and has the outcome I expect -- writing the bytes to local out.jpg.

I'm not sure if that change might break anything else, or if this is simply a bug that can be fixed?

But wait, streaming in: writes a a tempfile?

However, looking at that code and seeing it's writing the stream to a tempfile on disk.... may defeat the purpose of what I'm trying to do anyway. I was trying to improve performance by avoiding the write to disk, and streaming the bytes from network directly to the process. (Which is not cat in my real use case of course, that was just a simple reproduction).

But if TTY::Command is going to write whatever in: stream I give it to disk in a temporary file anyway, I'm not going to get the performance increase I was hoping for. So this may still be a bug that should be fixed, but maybe won't actually help me out.

Is is not feasible to stream the bytes directly to the process without creating the intermediate temp file? In my real use case, these are very large files from the network, and I was hoping to stream them directly to a spawned process stdin without first buffering them all on disk and taking the performance hit of the write-to-disk then read-from-disk.

Is it possible to 'watch' for changes?

I don't quite know the exact terminology, but is it possible to detect changes when long running commands change the output on the screen?

For example when you run ffmpeg it replaces the existing output (rather than appending lines to the output) each frame it renders. I want to detect every time it changes the output if possible.

I thought it might be stored as the result but when I do output.to_s I just get "0". I am thinking maybe this is because the terminal command things the warnings generated by ffmpeg are errors maybe? Can I ignore the errors, or somehow access the output even when theres errors? Thanks

Escaping command

Escaping can be a challenge with the current syntax. What should this do?
cmd.execute(:ls, "hello world")

[71555-047a57b2] Running ls hello world
[71555-047a57b2]    ls: hello: No such file or directory
[71555-047a57b2]    ls: world: No such file or directory
[71555-047a57b2] Finished in 0.002 seconds with exit status 1 (failed)

Print output only on error

Is it possible to only print the command output only if it failed?

So it would print:

[hash] Running command

when it succeeds, and:

[hash] Running command
[hash] ** BUILD FAILED **
[hash] Finished in 2.788 seconds with exit status 65 (failed)

when it fails.

Modified command ran when it contains special characters

Hi,

I ran into the issue that I cannot execute the following command when passing the parameters one by one:
git for-each-ref --format='%(refname)' refs/heads/

Because it tries to run this command instead: git for-each-ref '--format='%(refname)''%(refname)''' refs/heads/

See:

require 'tty-command'
cmd = TTY::Command.new
cmd.run(*['git', 'for-each-ref', "--format='%(refname)'", 'refs/heads/'])

A possible workaround is to do this:
cmd.run("git for-each-ref --format='%(refname)' refs/heads/")

How to watch a command and then on stop return back?

Hi,

All of the tty stuff is amazing and before i start i would like to thank you for the effort you put into it.

I have a question about a specific usage of tty command for the cli i am trying to build.

I bootstrapped my cli with teletype and I am also using thor_repl to make my cli interactive. I don't really need to run one time scripts but rather have it run in a repl kind of fasion and that is working fine. But now i am stuck on trying to get something work with tty-command. I have a command (docker-compose ps) that i want to get refreshed once in a while to see the output of it and want to stop it when i do a certain key combo.

I tried with using the 'watch' command which calls the given command in certain intervals and that works kind of ok but problematic part is that i cannot exit out of it anymore unless i hit CTRL+C but that triggers the interrupted signal which stops everything.

command(printer: :quiet).run('watch docker-compose ps', pty: true)

Now is there a way that you can think of (also maybe using other tty tools like https://github.com/piotrmurach/tty-reader) to somehow trap a key combo while that command is running and have a way to stop it and return to the cli? Or is this just impossible todo cause that command would be a subprocess that is running? Or is there a way to catch the interrupt in some way to restart the cli again? Or are there other means to run a command in a loop and stop that loop on key combo?

Would be happy to have your thought or opinions since you are more familiar with the possibilities of the tool.

Thnx in advance.

Retaining color of STDOUT

Hi there,

First of all, great gem!

I was happy when I read colorful output, however it seems that it only applies to your gem's output and not the original command's.

Do you have any plans to make it possible to retain the color of the original output, or do you know whether that's even possible? According to my limited understanding you should somehow pretend to be a tty.

Are you supposed to always use `rescue TTY::Command::ExitError`?

Is there a case in which a command doesn't succeeds, but also doesn't throw TTY::Command::ExitError?
If not, does this mean that you're supposed to always enclose the run() in begin ... recue TTY::Command::ExitError?
If yes, should this be mentioned in the README?

Typo in README

3.2.1 Current directory

To change directory in which the command is run pass the :chidir option:

A slip. chidir -> chdir

Nice gem!

Pastel strict dependency prevents upgrading tty-markdown

Describe the problem

After the release of new tty-markdown (with the kramdown vulnerability fix), I am trying to update the bundle of my Jobly gem, which includes both tty-markdown and tty-command, but upgrade is blocked by bundler.

This line:

spec.add_dependency "pastel", "~> 0.8"

which seems to have been updated only recently, is not yet available in the released version.

So, when trying to update a bundle that includes both tty gems, there is a bundler conflict error.

Steps to reproduce the problem

Use this Gemfile, and run bundle

source "https://rubygems.org"
gem "tty-command", '~> 0.9'
gem "tty-markdown", '~> 0.7'

Actual behaviour

Error:

Bundler could not find compatible versions for gem "pastel":
  In Gemfile:
    tty-command (~> 0.9) was resolved to 0.9.0, which depends on
      pastel (~> 0.7.0)

    tty-markdown (~> 0.7) was resolved to 0.7.0, which depends on
      pastel (~> 0.8)

Expected behaviour

It is expected to work.

Describe your environment

  • OS version: Ubuntu 18
  • Ruby version: 2.7.0
  • TTY::Command version: NA

Redirection example in the README raises an error

2.4.0 (main):0 > cmd = TTY::Command.new
#<TTY::Command:0x007fe751c0cca0 @output=#<IO:<STDOUT>>, @color=true, @uuid=true, @printer_name=:pretty, @dry_run=false, @printer=#<TTY::Command::Printers::Pretty:0x007fe751c0f2c0 @output=#<IO:<STDOUT>>, @options={:color=>true, :uuid=>true}, @enabled=true, @color=#<Pastel @styles=[]>>>
2.4.0 (main):0 > cmd.run('echo foo', stderr: :stdout)
[b0c321ca] Running echo foo
TypeError: no implicit conversion from nil to integer
from /Users/benjamin/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/tty-command-0.5.0/lib/tty/command/process_runner.rb:65:in `kill'

Documentation on how to handle STDIN?

Hi,

I have a question regarding the input stream. Assume I have a cli program, that first asks for an email address and then asks for a password via STDIN. How can I handle this situation?

I tried something like this, but I am not able to split the input, so it inputs the email address first, and then the password.

TTY::Command.new.run("my_cli_program", "login", in: StringIO.new("[email protected]\r\npassword")).out

Any clues?

Many thanks!

Best regards,
Roberto

Can't run shells in interactive mode

Describe the problem

Shells cannot be run with TTY::Command. Keyboard input is not read by the shell.

Steps to reproduce the problem

require 'tty-command'

cmd = TTY::Command.new(pty: true, printer: :quiet)

cmd.run(*ARGV)

Actual behaviour

(slightly edited to remove identifying information)

% bundle exec ruby ./test.rb dash
$ ls
oh no input is going nowhere
^C
$ ^C
$ but ctrl-c is handled?

^C
$ ctrl-d does nothing
^C
$ ^C
$ ^C
$ i have to kill this from another shell
zsh: terminated  bundle exec ruby ./test.rb

% bundle exec ruby ./test.rb bash
bash: cannot set terminal process group (84144): Inappropriate ioctl for device
bash: no job control in this shell
$ input does not go to the shell


ctrl c kills the process
^CTraceback (most recent call last):
	5: from ./test.rb:6:in `<main>'
	4: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:104:in `run'
	3: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:185:in `execute_command'
	2: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:48:in `run!'
	1: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `read_streams'
./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `join': Interrupt

 bundle exec ruby ./test.rb zsh
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
zsh: substitution failed
ls
I can't even get a prompt on zsh
^CTraceback (most recent call last):
	5: from ./test.rb:6:in `<main>'
	4: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:104:in `run'
	3: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:185:in `execute_command'
	2: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:48:in `run!'
	1: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `read_streams'
./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `join': Interrupt

% bundle exec ruby ./test.rb ssh $some_host
<snip MOTD banner>
$ ls
^CTraceback (most recent call last):
	5: from ./test.rb:6:in `<main>'
	4: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:104:in `run'
	3: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command.rb:185:in `execute_command'
	2: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:48:in `run!'
	1: from ./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `read_streams'
./.bundle/gems/ruby/2.6.0/gems/tty-command-0.9.0/lib/tty/command/process_runner.rb:146:in `join': Interrupt

Expected behaviour

A working interactive shell.

Describe your environment

  • OS version: Debian linux sid
  • Ruby version: 2.6.6 and 2.7.1
  • TTY::Command version: 0.9.0

TTY::Command::Result labeling command outputs incorrectly?

I'm running a command like this:
git clone [email protected]:some_organization/some_repo.git /tmp/d20161007-16174-ldlovj/frontend

with this code:

cmd = TTY::Command.new(printer: :quiet)
command = "git clone #{repositories[repository.to_sym]} #{clone_dir}"
result = cmd.run(command)

The command succeeds and I see the output from the command, but either the output is being mapped incorrectly or I'm misunderstanding something, because result looks like this:

pry(main)> result.as_json
{
    "status" => 0,
       "out" => "",
       "err" => "Cloning into '/tmp/d20161007-16174-ldlovj/frontend'...\n"
}

Shouldn't it look like this:

{
    "status" => 0,
       "out" => "Cloning into '/tmp/d20161007-16174-ldlovj/frontend'...\n",
       "err" => ""
}

โ“ ๐Ÿ˜•

Feature request: until / line parser

Following functions I am missing at the most. They can be implemented in pure bash, but they would fit very nicely in this libraries scope.

Until - Stdout evaluation until (bash like)

Raw implementation (bash):

cmd.run 'until [ $(kubectl get pods -n kube-system -l app=helm,name=tiller -o jsonpath="{.items[0].status.containerStatuses[0].ready}") = "true" ]; do
   sleep 2
done'

Better:

cmd.until 'kubectl get pods -n kube-system -l app=helm,name=tiller -o jsonpath="{.items[0].status.containerStatuses[0].ready}', 'Ready'

So this waits until the output of the command is Ready. The stdout which get compared should be striped.

Wait - Log running script line match

Similar but not the same. Long running bash process which output log style lines - it should be possible to wait until a specific pattern match to a line. Example:

cmd.wait 'tail -f /var/log/php.log', /something happened/

Ignore errors (no detailed concept now)

Sometimes shell executions could output some errors which should not cause a raise. A regexp pattern could help here.

Throwing exceptions if command fails by default

I think that commands should throw exceptions if they fail by default. This is one of the biggest design flaws in bash, and I can't tell you the number of problems it's caused me (and people who work with me) over the past decade. When I write scripts I almost always want to halt on failure. I recognize that if we make this change we can't use execute!, sadly.

overhaul README prior to release

Here are some suggestions off the top of my head:

  • add "Motivation" section
  • add "Escaping" section, talk about cmd.execute("echo", "hello world")
  • buff up "Logging" (out/err and printers)
  • add "Errors" and discuss execute!
  • add "Advanced Options" to include chdir, redirects, etc.
  • document dryrun (if implemented) and Printers::Quiet

?

Remove command execution shell features

Features I think you can safely ditch:
-- env: (this can easily be handled with ENV)
-- chdir (easily handled with Dir.chdir("x") { ... }
-- redirection (typically in the command, not needed in ruby land)
-- :user/:group/:umask (that's what sudo is for)

Timeout isn't working as expected if both stdout and stderr are redirected

Describe the problem

Timeout isn't working as expected if both stdout and stderr are redirected.

Steps to reproduce the problem

TTY::Command.new(printer: :quiet).run!('sleep 5', timeout: 1, [:out, :err] => '/dev/null')

Actual behaviour

The code above doesn't fail. It takes 5 seconds to run and ignores the timeout option set to 1 second.

Expected behaviour

The code above should raise an exception.

Describe your environment

  • OS version: macOS Ventura 13.5 / Debian 12
  • Ruby version: 3.2.2
  • TTY::Command version: 0.10.1

Timeout when there isn't any output

The timeout is currently handled each time a line is printed out by the system command.
I have a problem with a command not outputting anything and not exiting either, and tty-command is not catching that.

I think it would be nice to keep checking the time while waiting for the next line.

High memory usage for long running commands with lots of output

Describe the problem

Long running commands with lots of output consume too much memory.

All stdout and stderr data is aggregated for the duration of the command, but that is a problem for commands that should run as long as possible.

Even if I run tty-command as following:

TTY::Command.new(uuid: true, printer: :null, :out => "/dev/null", :err => "/dev/null").run(cmd) { |out, err| } 

the output data is still aggregated.

And I believe the problematic code is in this method:

   def read_streams(stdout, stderr)
        stdout_data = [] 
        stderr_data = Truncator.new

        out_handler = ->(data) {
          stdout_data << data
          @printer.print_command_out_data(cmd, data)
          @block.(data, nil) if @block
        }

        err_handler = ->(data) {
          stderr_data << data
          @printer.print_command_err_data(cmd, data)
          @block.(nil, data) if @block
        }

        stdout_thread = read_stream(stdout, out_handler)
        stderr_thread = read_stream(stderr, err_handler)

        stdout_thread.join
        stderr_thread.join

        encoding = @binmode ? Encoding::BINARY : Encoding::UTF_8

        [
          stdout_data.join.force_encoding(encoding),
          stderr_data.read.dup.force_encoding(encoding)
        ]
      end

stdout_data and stderr_data is appended without regard of using too much memory.

Actual behaviour

After few days of running a command that prints lots of data to stdout, the command is terminated by the system because it uses to much memory.

Expected behaviour

One of following:

  • create an option to collect max N bytes of stdout/stderr data
  • do not collect data if block is given with .run command
  • aggregate the data in a fixed buffer size, so that only the last N bytes are stored in memory

Describe your environment

Docker container in kubernetes

  • OS version: Debian bullseye
  • Ruby version: 2.7.6
  • TTY::Command version: 0.10.1

Streamed output printed on new lines with `pty` option since v0.8.0

Hey, it's me again! :D

I noticed this behaviour with v0.8.0:

irb
require "tty-command"
cmd = TTY::Command.new(pty: true)
cmd.run('rubocop')

=>

8908f6bb] Running rubocop
[8908f6bb]      .rubocop.yml: Lint/EndAlignment has the wrong namespace - should be Layout
[8908f6bb]      Inspecting 28 files
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]      .
[8908f6bb]

[8908f6bb]      28 files inspected, no offenses detected
[8908f6bb] Finished in 1.704 seconds with exit status 0 (successful)

Without the pty option it works fine, in v0.7.0 both with or without works fine.

fatal: No live threads left. Deadlock?

Does TTY::Command use threads in some way? It looks like it does, and as odd as it seems, I think it may be responsible for some very strange and hard to reproduce fatal: No live threads left. Deadlock? exceptions I've started getting in my app since introducing TTY::Command.

Could it be causing a deadlock somehow? Any ideas?

The backtrace looks like:

[GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command/process_runner.rb:128 :in `join`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command/process_runner.rb:128 :in `block in read_streams`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command/process_runner.rb:127 :in `each`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command/process_runner.rb:127 :in `read_streams`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command/process_runner.rb:45 :in `run!`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command.rb:174 :in `block in execute_command`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command.rb:174 :in `synchronize`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command.rb:174 :in `execute_command`
 [GEM_ROOT]/gems/tty-command-0.6.0/lib/tty/command.rb:94 :in `run`
[PROJECT_ROOT]/app/services/chf/create_dzi_service.rb:123 :in `block in create_dzi!`

Environment variables are persisted in Ruby 3.0

Describe the problem

The environment variables options (in its two forms) behave differently, where one form seems to persist the variables even for subsequent commands.

Steps to reproduce the problem

require 'tty/command'

shell = TTY::Command.new

env1 = { a: "a", b: "b" }
env2 = { c: "d", d: "d" }

# PASS
shell.run :echo, env: env1
# => Running ( export A="a" B="b" ; echo )

# FAIL - env is expected not to be used here
shell.run :echo
# => Running ( export A="a" B="b" ; echo )

# FAIL - env1 was merged with env2 here, unexpectedly
shell.run env2, :echo
# => Running ( export C="d" D="d" A="a" B="b" ; echo )

# 1 x PASS: env2 was NOT persisted from the previous call
# 1 x FAIL: env1 is still here
shell.run :echo
# => Running ( export A="a" B="b" ; echo )

Actual behaviour

Environment variables were sometimes persisted and used in subsequent commands, even if they did not have env setting.

Expected behaviour

Expected env vars to only influence the running command, and not contaminate subsequent commands.

Side note: In case there is a desire to set a global environment, I expected it to be defined in the form of TTY::Command.new env: { ... }

Additional notes

I was also wondering why the environment is prepended to the command in this form:

export VAR="val" VAR2="val" ; command

instead of this form (no export, no semicolon):

VAR="val" VAR2="val" command

which, to my understanding, it the common way of setting environment variables for a single command.

Describe your environment

  • OS version: Ubuntu 18
  • Ruby version: ruby 3.0.0p0
  • TTY::Command version: 0.10.0

Permission error with IP tables

I am running the following command in my controller, doing an IP lookup to get ASN and other details to determine whether to add to IPTABLES as a DROP. The goal is to dynamically populate the IP address. Here's my code so far testing with a statically defined IP

cmd = TTY::Command.new
cmd.run('iptables -A INPUT -s 77.111.246.10 -j DROP', user: 'root')

I am getting the following error. It appears IPTABLES want the controller to be set as root. Is there a way to define root user with password to get around this?

TTY::Command::ExitError (Running sudo -u root -- sh -c 'iptables -A INPUT -s 77.111.246.10 -j DROP' failed with
exit status: 1
stdout: Nothing written

Without user defined in the command I get an exit status: 3

Perhaps the rails 5 app is using a different user and therein lies the rub.

Would appreciate any help as we are trying to automate bans of certain IPs vs dealing with it manually.

Thank you for any feedback.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.