Skip to content

Commit

Permalink
use an Array for wrapped help instead of fighting with StringIO
Browse files Browse the repository at this point in the history
  • Loading branch information
toy committed Jul 10, 2023
1 parent 6a9ab39 commit 9926ed4
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions lib/image_optim/runner/option_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,32 +43,35 @@ def help
# don't try to wrap if there is too little space for description
return text if wrapped_width < 20

wrapped = StringIO.new('')
wrapped_text(text, wrapped_width, wrapped_indent, columns)
end

private

def terminal_columns
stty_columns = `stty size 2> /dev/null`[/^\d+ (\d+)$/, 1]
stty_columns ? stty_columns.to_i : `tput cols`.to_i
end

def wrapped_text(text, wrapped_width, wrapped_indent, columns)
wrapped = []
text.split("\n").each do |line|
if line.length <= columns
wrapped.puts line
wrapped << line << "\n"
else
wrapped.puts line.slice!(wrap_regex(columns)).rstrip
wrapped << line.slice!(wrap_regex(columns)).rstrip << "\n"
if line =~ /^\s/
line.scan(wrap_regex(wrapped_width)) do |part|
wrapped << wrapped_indent
wrapped.puts part.rstrip
wrapped << wrapped_indent << part.rstrip << "\n"
end
else
line.scan(wrap_regex(columns)) do |part|
wrapped.puts part.rstrip
wrapped << part.rstrip << "\n"
end
end
end
end
wrapped.string
end

private

def terminal_columns
stty_columns = `stty size 2> /dev/null`[/^\d+ (\d+)$/, 1]
stty_columns ? stty_columns.to_i : `tput cols`.to_i
wrapped.join(nil)
end

def wrap_regex(width)
Expand Down

0 comments on commit 9926ed4

Please sign in to comment.