#!/usr/bin/python3
# Copyright (c) TurnKey GNU/Linux - http://www.turnkeylinux.org
#
# This file is part of AutoVersion
#
# AutoVersion is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.

import os
import re
import sys
import argparse

import autoversion_lib as autoversion

examples = """Example usage:
    autoversion HEAD                    # print latest version
    autoversion -r v1.0                 # print commit of version v1.0
    autoversion $(git-rev-list --all)   # print all versions
"""


def fatal(s):
    print("error: " + str(s), file=sys.stderr)
    sys.exit(1)


def resolve_committish(git, committish):
    # skip expensive git-rev-parse if given a full commit id
    if re.match('[0-9a-f]{40}$', committish):
        return committish

    commit = git.rev_parse(committish)
    if commit is None:
        fatal("invalid committish `%s'" % committish)
    return commit


def main():
    parser = argparse.ArgumentParser(description='Map git commits to auto'
                                                 '-versions and vice versa',
                                     epilog=examples)
    parser.add_argument('-r', '--reverse', action='store_true', default=False,
                        help='map version to git commit')
    parser.add_argument('commit', help='any revision supported by git (e.g.,'
                                       'commit ids, tags, refs, etc.)')
    args = parser.parse_args()

    opt_reverse = reverse

    av = autoversion.Autoversion(os.getcwd(), precache=len(args) > 1)
    if args.reverse:
        print(av.version2commit(arg))
    else:
        print(av.commit2version(resolve_committish(av.git, arg)))


if __name__ == "__main__":
    main()
