#!/usr/bin/ruby
# -*- mode: ruby; coding: utf-8; indent-tabs-mode: nil -*-
#
# Copyright(C) Youhei SASAKI <uwabami@gfd-dennou.org> All rights reserved.
# $Lastupdate: 2014-02-11 22:06:02$
# License: MIT/X11
#
# Code:
require 'nokogiri'
require 'date'
require 'pp'

#== Get Authors file
# File format
#
# account1:NAME FAMILY1 <e-mail address1>
# account2:NAME FAMILY2 <e-mail address2>
#
authors = Hash.new
File.open(ARGV[0], "r"){|lines|
  lines.each do |line|
    tmp = line.split(":",2)
    authors[tmp[0].strip] = tmp[1].strip
  end
}

#== Commit message formatting
#
def msg_shaping(line, indent, width)
  @l = line
  @indent = indent
  @w = width
  @r = @indent + @l.slice(0, @w) + "\n"
  if @l.length >= @w
    @r += msg_shaping(@l.slice(@w, @l.length), @indent, @w)
  end
  return @r
end

#== main loop
#
#
File.open(ARGV[1], "w").close()
src = Nokogiri::XML(open("|svn log --xml"))
logs = src.xpath('//logentry')
logs.each do |log|
  #
  #=== header part
  #
  # yyyy-mm-dd HH::MM::SS LAST First <mail address>
  #
  str = DateTime.parse(log.xpath('date').text).strftime("%F %H:%M:%S")
  str += "\s\s"
  str += authors[log.xpath('author').text] ||= "cvs2svn system commit"
  str += "\n\n"
  #
  #=== rivision and summary
  #
  # [rNNN]: commit message first line
  #
  revision ="[r"+log.values[0].to_s+"]: "
  str += "\t" + revision
  header_indent = "\s"*(8 + revision.length)
  msg = log.xpath('msg').text.split("\n")
  header = msg[0].gsub(/^\s*\*\s*/,'').gsub("\t",'')
  msg.delete_at(0)
  #
  #=== commit message
  #
  header = msg_shaping(header,header_indent,72-header_indent.length)
  header = header.split("\n")
  header[0].gsub!(/^\s*/,'')
  str += header.join("\n") + "\n"
  msg.each do |line|
    if line =~/^\n*$/
      str += "\n"
    else
      str += msg_shaping(line,"\t",64)
    end
  end
  str += "\n"
  str = str.gsub(/^\n\n/m,"\n")
  File.open(ARGV[1], "a"){|f|
    f.puts str
  }
end
