#!/usr/bin/env python
# Copyright (C) 2013 Igalia S.L.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

import difflib
import optparse
import shutil
import sys

def check_api(options, from_file, to_file):
    from_lines = open(from_file, 'r').readlines()
    from_lines.sort()
    to_lines = open(to_file, 'r').readlines()
    to_lines.sort()

    diff = difflib.unified_diff(from_lines, to_lines)

    diff_out = ""
    failed = False
    for line in diff:
        # Ignore initial lines since we don't use from/file filenames.
        if line.startswith('+++') or line.startswith('---'):
            continue

        diff_out += line
        if line[0] == '-':
            failed = True

    if diff_out:
        if failed:
            sys.stderr.write("API incompatibility detected in GObject DOM bindings\n")
            sys.stderr.write(diff_out)
            # This test can give false positives because the GObject
            # DOM bindings API varies depending on the compilation options.
            # So this shouldn't be made fatal until we figure out a way to handle it.
            # See https://bugs.webkit.org/show_bug.cgi?id=121481
            return 0

        if options.reset_results:
            sys.stdout.write("Reset results: %s\n" % from_file)
            shutil.copyfile(to_file, from_file)
        else:
            sys.stdout.write("API compatible changes found in GObject DOM bindings\n")
            sys.stdout.write("To update the symbols file, execute %s --reset-results %s DerivedSources/webkitdom/webkitdom.symbols\n" % (sys.argv[0], from_file))
            sys.stdout.write(diff_out)

    return 0


option_parser = optparse.OptionParser(usage='usage: %prog [options] FROM_FILE TO_FILE')
option_parser.add_option('--reset-results', action='store_true', dest='reset_results')
options, args = option_parser.parse_args()
sys.exit(check_api(options, args[0], args[1]))

