diff --git a/lib/puppet/util/terminal.rb b/lib/puppet/util/terminal.rb new file mode 100644 index 000000000..8674a4956 --- /dev/null +++ b/lib/puppet/util/terminal.rb @@ -0,0 +1,15 @@ +module Puppet::Util::Terminal + class << self + # Borrowed shamelessly from Thor, who borrowed this from Rake. + def width + if Puppet.features.posix? + result = %x{stty size 2>/dev/null}.split[1] || + %x{tput cols 2>/dev/null}.split[0] || + '80' + end + return result.to_i + rescue + return 80 + end + end +end diff --git a/spec/unit/util/terminal_spec.rb b/spec/unit/util/terminal_spec.rb new file mode 100644 index 000000000..d01754914 --- /dev/null +++ b/spec/unit/util/terminal_spec.rb @@ -0,0 +1,34 @@ +#!/usr/bin/env rspec +require 'spec_helper' +require 'puppet/util/terminal' + +describe Puppet::Util::Terminal do + describe '.width' do + it 'should invoke `stty` and return the width' do + height, width = 100, 200 + subject.expects(:`).with('stty size 2>/dev/null').returns("#{height} #{width}\n") + subject.width.should == width + end + + it 'should use `tput` if `stty` is unavailable' do + width = 200 + subject.expects(:`).with('stty size 2>/dev/null').returns("\n") + subject.expects(:`).with('tput cols 2>/dev/null').returns("#{width}\n") + subject.width.should == width + end + + it 'should default to 80 columns if `tput` and `stty` are unavailable' do + width = 80 + subject.expects(:`).with('stty size 2>/dev/null').returns("\n") + subject.expects(:`).with('tput cols 2>/dev/null').returns("\n") + subject.width.should == width + end + + it 'should default to 80 columns if `tput` or `stty` raise exceptions' do + width = 80 + subject.expects(:`).with('stty size 2>/dev/null').raises() + subject.stubs(:`).with('tput cols 2>/dev/null').returns("#{width + 1000}\n") + subject.width.should == width + end + end +end