Imran
Imran

Reputation: 146

include revision number from mercurial into python file template pycharm

I have a python file template defined as follows in pycharm 2016.3

__author__ = ${USER}
__date__ = ${DATE}
__copyright__ = ""
__credits__ = [""]
__license__ = ""
__revision__ = ""
__maintainer__ = ${USER}
__status__ = "Development"

for the revision number I want to use the output of the command "hg id -n" which gives me the current revision number pulled from mercurial.

what would be the best way to do this?

Upvotes: 1

Views: 276

Answers (1)

planetmaker
planetmaker

Reputation: 6044

Spawn a child process and call hg in order to collect the output. I use something like this. A bit shortened, in essence (I hope I didn't introduce errors by the shortening to the basics, it's py3, though):

def get_child_output(cmd):
    """
    Run a child process, and collect the generated output.

    @param cmd: Command to execute.
    @type  cmd: C{list} of C{str}

    @return: Generated output of the command, split on whitespace.
    @rtype:  C{list} of C{str}
    """
    return subprocess.check_output(cmd, universal_newlines = True).split()


def get_hg_version():
    path =     os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    version = ''
    version_list = get_child_output(['hg', '-R', path, 'id', '-n', '-i'])

    hash = version_list[0].rstrip('+')

    # Get the date of the commit of the current NML version in days since January 1st 2000
    ctimes = get_child_output(["hg", "-R", path, "parent", "--template='{date|hgdate} {date|shortdate}\n'"])
    ctime = (int((ctimes[0].split("'"))[1]) - 946684800) // (60 * 60 * 24)
    cversion = str(ctime)

    # Combine the version string
    version = "v{}:{} from {}".format(cversion, hash, ctimes[2].split("'", 1)[0])
    return version

# Save the revision in the proper variable
__revision__ = get_hg_version()

Lastly: Consider to NOT use (only) the output of hg id -n as your version number: it is a value which is local to that specific instance of the repo only and may and will vary wildely between different clones of the same repo. Use the hash and/or the commit time as version (as well).

Upvotes: 2

Related Questions