#!/usr/bin/env python3

# This script runs through this git project's git commit history and forcefully
# tags each commit whose commit message starts with "Tutorial #" or
# "Tutorial #.#"
#
# NOTE: This is an abuse of the git tag system in most codebases, so don't copy
# this logic in normal circumstances! In this case, this codebase is a
# tutorial, with a commit history reflecting chapters in the tutorial; this
# requires a lot of "push --force" commands and ensuring I'm the only person
# working on it.

from subprocess import call
from commit_history import *

seen_tags = set()
commit_tags = set()

# Last line is "Initial commit" so slice it out
for commit in CommitHistory.from_git_logs():
    if commit.version is None:
        raise Exception(
            'Expected message "Tutorial #(.#)", instead got "{0}"'.format(
                commit.message))

    tag = "tutorial{0}.{1}".format(commit.version.major, commit.version.minor)

    if tag in seen_tags:
        raise Exception('Tried to create duplicate tag [{0}]'.format(tag))
    seen_tags.add(tag)
    commit_tags.add((commit.git_hash, tag))

for commit_tag in commit_tags:
    git_hash = commit_tag[0]
    tag = commit_tag[1]
    message = 'Tag [{0}] autogenerated by scripts/update_tutorial_tags.py'.format(
        tag)
    call(['git', 'tag', '-f', '-a', tag, git_hash, '-m', message])

print()
print('After updating, current tags are:')
call(['git', 'tag', '-l'])
print()
