#!/usr/bin/env ruby
#
#  git-contrib
#  Author: William Woodruff
#  ------------------------
#  Generates CONTRIBUTORS files for a git repositories
#  Capable of Markdown, CSV, and plain-text.
#  ------------------------
#  This program is licensed by William Woodruff under the MIT License.
#  https://opensource.org/license/MIT

require 'optparse'

system('git rev-parse 2>/dev/null') or abort('No git repository found. Exiting.')

options = {}

optparse = OptionParser.new do |opts|
  opts.banner = 'Usage: git-contrib.rb [-m, --markdown | -c, --csv]'

  options[:markdown] = false
  opts.on('-m', '--markdown', 'Use markdown formatting') do
    options[:markdown] = true
  end

  options[:csv] = false
  opts.on('-c', '--csv', 'Use csv formatting') do
    options[:csv] = true
  end

  opts.on('-h', '--help', 'Display this screen') do
    puts opts
    exit
  end
end

begin
  optparse.parse!
rescue OptionParser::InvalidOption
  puts 'Invalid option.'
  puts 'Usage: git-contrib.rb [-m, --markdown | -c, --csv]'
  exit
end

if options[:markdown]
  File.open('CONTRIBUTORS.md', 'w') do |contribFile|
    contribFile.write("CONTRIBUTORS\n")
    contribFile.write("=============\n")
    contribFile.write("### Generated by git-contrib on #{`date +"%H:%M:%S %Y/%m/%d"`}")
    contribFile.write("-------------------------------------------------\n\n")
    contribFile.write("Commits | Author | Email\n")
    contribFile.write("--- | --- | ---\n")

    log = `git shortlog -sne`.gsub(/^[' \t]*/, '')
    log.each_line do |line|
      elements = line.split(' ')
      if elements.length == 4
        contribFile.write("#{elements[0]} | #{elements[1]} #{elements[2]} | #{elements[3]}\n")
      else
        contribFile.write("#{elements[0]} | #{elements[1]} | #{elements[2]}\n")
      end
    end
  end
elsif options[:csv]
  File.open('CONTRIBUTORS.csv', 'w') do |contribFile|
    contribFile.write("Commits, Author, Email\n")
    log = `git shortlog -sne`.gsub(/^[' \t]*/, '')
    log.each_line do |line|
      elements = line.split(' ')
      if elements.length == 4
        contribFile.write("#{elements[0]},#{elements[1]} #{elements[2]},#{elements[3]}\n")
      else
        contribFile.write("#{elements[0]},#{elements[1]},#{elements[2]}\n")
      end
    end
  end
else
  File.open('CONTRIBUTORS', 'w') do |contribFile|
    contribFile.write("CONTRIBUTORS\n")
    contribFile.write("Generated by git-contrib on #{`date +"%H:%M:%S %Y/%m/%d"`}")
    contribFile.write("-------------------------------------------------\n\n")
    contribFile.write("Commits\tAuthor\tEmail\n")

    contribFile.write(`git shortlog -sne`)

    contribFile.write("\n")
  end
end
