#!/usr/bin/env python
"""
Fixes a bogus git patch.

Sometimes a patch that people submit to sympy contains the UTF-8 byte-order
mark (BOM), which are 3 characters at the beginning, that cause "git am" to
fail when applying it. The solution is to remove them, which is the purpose of
this script. See this link for more info:

http://en.wikipedia.org/wiki/Byte-order_mark

Usage:

  git-fix-patch some.patch > some_fixed.patch

you can also rewrite the original file with the fix (inplace) by:

  git-fix-patch -s some.patch

"""

from textwrap import fill
import os
import re
from optparse import OptionParser

def main():
    parser = OptionParser(usage="[options] args")
    parser.add_option("-s", "--save", dest="save", action="store_true",
            default=False,
            help="Rewrite the original file with the fixed patch")
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.print_help()
        return

    filename = args[0]
    s = open(filename).read()
    start = s.find("From")
    if start > 10:
        raise Exception("Uknown format of the git patch")

    # strip the bogus characters at the beginning of the file
    s = s[start:]

    # either save to a file or dump to stdout:
    if options.save:
        outfile = filename
        open(outfile, "w").write(s)
    else:
        print s

if __name__ == '__main__':
    main()
