From c001971bb3360904c96f5f6b640dd3a9756b5e18 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 13 May 2021 14:42:00 -0700 Subject: [PATCH] Fix Reline::Unicode.calculate_width when input is not a TTY This fixes an error when output is redirected: ``` $ run_ruby -rreline -e '$stderr.puts Reline::Unicode.calculate_width("\u221a").inspect' /dev/null /home/jeremy/tmp/ruby/lib/reline/ansi.rb:189:in `raw': Operation not supported by device (Errno::ENODEV) ``` The @@encoding -> defined?(@@encoding) changes is necessary because without that part of the commit, the following error would be raised by the above command: ``` /home/jeremy/tmp/reline/lib/reline/general_io.rb:10:in `encoding': uninitialized class variable @@encoding in Reline::GeneralIO (NameError) ``` Problem reported and initial patch for Windows provided by Richard Sharman. I tested this only on OpenBSD, but hopefully it works for other operating systems. Fixes [Bug #17493] --- lib/reline.rb | 18 +++++++++++++----- lib/reline/general_io.rb | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/reline.rb b/lib/reline.rb index 6fc27caecd..26cf9119ee 100644 --- a/lib/reline.rb +++ b/lib/reline.rb @@ -453,17 +453,25 @@ def self.line_editor end end +require 'reline/general_io' if RbConfig::CONFIG['host_os'] =~ /mswin|msys|mingw|cygwin|bccwin|wince|emc/ require 'reline/windows' if Reline::Windows.msys_tty? - require 'reline/ansi' - Reline::IOGate = Reline::ANSI + Reline::IOGate = if ENV['TERM'] == 'dumb' + Reline::GeneralIO + else + require 'reline/ansi' + Reline::ANSI + end else Reline::IOGate = Reline::Windows end else - require 'reline/ansi' - Reline::IOGate = Reline::ANSI + Reline::IOGate = if $stdout.isatty + require 'reline/ansi' + Reline::ANSI + else + Reline::GeneralIO + end end Reline::HISTORY = Reline::History.new(Reline.core.config) -require 'reline/general_io' diff --git a/lib/reline/general_io.rb b/lib/reline/general_io.rb index 4f605628a3..2f87d718c6 100644 --- a/lib/reline/general_io.rb +++ b/lib/reline/general_io.rb @@ -7,7 +7,7 @@ def self.reset(encoding: nil) end def self.encoding - if @@encoding + if defined?(@@encoding) @@encoding elsif RUBY_PLATFORM =~ /mswin|mingw/ Encoding::UTF_8