require 'prettypatch/PrettyPatch'
require 'mail'

module PurdyPatch
  class CLI
    def self.start(*args)
      mail = Mail.read(args.first)
      parts = mail.parts.dup
      parts.each_with_index do |part, i|
        if (part.content_type =~ %r(text/x-patch))
          purdy = Mail::Part.new do
            content_type 'text/html; charset=UTF-8'
            body PrettyPatch.prettify(part.body.decoded)
          end
          mail.parts.insert(i, purdy)
        end
      end
      puts mail.to_s
    end
  end
end

require 'mail'
require 'pathname'
require 'purdypatch/version'
require 'prettypatch/PrettyPatch'

module PurdyPatch
  class CLI
    def self.start(*args)
      if args.empty?
        puts "purdypatch expects one or more files created via `git format-patch --attach [ <since> | <revision range> ]`."
        exit
      end

      args.each do |arg|
        patch_mail_path = Pathname.new(arg)
        next unless patch_mail_path.exist?

        mail = Mail.read(patch_mail_path)
        parts = mail.parts.dup
        purdified = false
        parts.each_with_index do |part, i|
          next unless part.attachment? && part.content_type =~ %r(text/x-patch)

          purdy_part = Mail::Part.new do
            content_type 'text/html; charset=UTF-8'
            body PrettyPatch.prettify(part.body.decoded)
          end
          mail.parts.insert(i, purdy_part)
          mail.header['X-Formatter'] = "PurdyPatch-#{PurdyPatch::VERSION}"
          purdified = true
        end

        if purdified
          purdy_patch_mail_path = patch_mail_path.sub_ext('.purdypatch')
          File.open(purdy_patch_mail_path, File::CREAT | File::TRUNC | File::RDWR) do |f|
            f.write mail.to_s
          end
          puts %Q(Purdified patch email saved to "#{purdy_patch_mail_path}".)
        end

      end
    end
  end
end

Support for >1 patch files & writing to disk.
Support for >1 patch files & writing to disk.

The `purdypatch` CLI tool now accepts multiple patch email files, and will
write a purdified copy of the patch email alongside the original file with
the file extension changed to '.purdypatch'.

This allows for the following workflow:

    $ git format-patch --attach HEAD~1
    $ purdypatch *.patch
    $ git send-email *.purdypatch
