1#!/usr/bin/env python3
2#
3# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
4#
5# SPDX-License-Identifier: BSD-2-Clause
6#
7
8import subprocess
9import datetime
10import sys
11
12output = []
13
14# Check arguments.
15if len(sys.argv) != 2:
16    print("Usage: gen_env.py <output file>")
17    sys.exit(1)
18output_filename = sys.argv[1]
19
20# Fetch details about the current repo revision.
21p = subprocess.Popen(["git", "log", "-r", "HEAD", "-n", "1", "--pretty=format:%ci"],
22                     stdout=subprocess.PIPE)
23commit_date_string = p.communicate()[0]
24
25# in python3, this is a bytes, so convert it to a str
26if isinstance(commit_date_string, bytes):
27    commit_date_string = commit_date_string.decode("utf-8")
28
29commit_date = datetime.datetime.strptime(commit_date_string.split()[0], "%Y-%m-%d")
30
31# Output in a format that LaTeX can read.
32output.append('\\newcommand{\\commitdate}{%s}' % (
33    commit_date.strftime("%-d %B %Y")))
34output.append('\\newcommand{\\commityear}{%s}' % (
35    commit_date.strftime("%Y")))
36
37# Output file, if it has changed.
38new_data = "\n".join(output) + "\n"
39old_data = None
40try:
41    with open(sys.argv[1], "r") as f:
42        old_data = f.read()
43except:
44    pass
45if new_data != old_data:
46    with open(sys.argv[1], "w") as f:
47        f.write(new_data)
48
49# Done!
50sys.exit(0)
51