#!/usr/bin/env ruby
#
# align-columns - vertically align columns, which are delimited by user-defined
# regular expression, that are present in the input given on STDIN.
#
# For example, the following input:
#
#   short text    =            foo
#   really long text = bar
#   wide operator   <=>  moz
#
# yields the following output:
#
#   short text        =  foo
#   really long text  =  bar
#   wide operator    <=> moz
#
# ---
# source: https://github.com/sunaku/home

class Column < Struct.new(:left, :delim, :right)
  def to_s
    mid = delim.empty? ? ' ' : " #{delim} "
    left + mid + right
  end
end

def align_columns(lines, delimiter, selector, rejector)
  # determine columns widths
  left_width = 0
  delim_width = 0

  cols = lines.map do |line|
    if line =~ selector &&
       line !~ rejector &&
       line =~ /^(.*?)(#{delimiter})(.*?)$/
    then
      left = $1.to_s.rstrip
      delim = $2.to_s.strip
      right = $3.to_s.lstrip

      left_width = [left_width, left.length].max
      delim_width = [delim_width, delim.length].max

      Column.new(left, delim, right)
    else
      line.chomp
    end
  end

  # equalize column widths
  cols.each do |col|
    if col.is_a? Column
      col.left = col.left.ljust(left_width)
      col.delim = col.delim.center(delim_width)
    end
  end

  cols.join("\n")
end

if $PROGRAM_NAME == __FILE__
  require 'optparse'
  parser = OptionParser.new

  parser.on '-h', '--help', 'show this help message' do
    puts File.read(__FILE__).split(/^$/).first, nil, parser
    exit
  end

  parser.on '-d', '--delimiter REGEXP', 'column delimiter',
            "(default: #{(delimiter = /[[:punct:]]*=[[:punct:]]*/).inspect})\n",
            String do |arg|
    delimiter = arg
  end

  parser.on '-m', '--select REGEXP', 'only wrap lines that match REGEXP',
            "(default: #{(selector = //).inspect})",
            Regexp do |arg|
    selector = arg
  end

  parser.on '-M', '--reject REGEXP', 'do not wrap lines that match REGEXP',
            "(default: #{(rejector = nil).inspect})",
            Regexp do |arg|
    rejector = arg
  end

  parser.parse ARGV

  puts align_columns($stdin.readlines, delimiter, selector, rejector)
end
