Updated Mercurial Batch Pull/Update Python Script#

It has been awhile since I last posted. Here is an update to the mercurial push, pull & update scripts I had posted earlier. The code is much better then the original scripts. All of the functionality is wrapped into one script instead of across a few. It should run on Windows without alteration (I’ll get a chance to test it out on Tuesday).

Some interesting things about the code:

  • It is licensed under the MIT License.

  • It uses the Python subprocess module to run the hg commands.

  • Given a root folder containing a number of mercurial repositories it searches for all of them and then performs the required action(s) in a batch mode.

  • It uses the Python optparse module to provide the command line option functionality - this is a really slick method!

  • It is all contained within a single script file making it a little more portable then the original code.

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-

    """
    This script is designed to work with mercurial. Its main purpose is to initiate
    hg pull, push or update on a group of repositories stored in a root directory.

    License:
    The MIT License
    Copyright (c) 2010 Troy Williams

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    """

    import sys
    import os
    import subprocess
    import ConfigParser

    __uuid__ = '2fa2a3dd-f271-4aef-a602-76ec29e32619'
    __version__ = '0.1'
    __author__ = 'Troy Williams'
    __email__ = 'troy.williams@bluebill.net'
    __copyright__ = 'Copyright (c) 2010, Troy Williams'
    __date__ = '2010-04-05'
    __license__ = 'MIT'
    __maintainer__ = 'Troy Williams'
    __status__ = 'Development'

    def run_command(command, useshell=False):
        """
        Takes the list and attempts to run it in the command shell.
        """
        if not command:
            raise Exception, 'Valid command required - fill the list please!'

        p = subprocess.Popen(command, shell=useshell)
        retval = p.wait()
        return retval

    def find_directories(root, dir_to_find):
        """
        Walks through the directory structure from the root and finds the
        directory names that match dir_to_find

        returns a list of paths matching the folder
        """
        foundDirs = []
        for root, dirs, files in os.walk(root):
            for d in dirs:
                if d.upper() == dir_to_find.upper():
                    foundDirs.append(os.path.join(root, d))
        return foundDirs

    def find_repositories(root):
        """
        Searches for mercurial repositories from along the root path.

        Returns a list of repository folders.
        """
        #Find all .hg folders. These indicate repositories
        dirs = find_directories(root, '.hg')

        #return the list of parent folder names
        return [os.path.dirname(item) for item in dirs]

    def pull(dirs):
        """
        Issues the hg pull command on all valid repositories that were discovered on
        the root folder path
        """

        if not dirs:
            print "Mercurial repositories not found..."
            return

        for repo in dirs:
            print 'Pulling changes for repository: ', repo
            cmd = ['hg', 'pull', '-R', repo]
            run_command(cmd)

    def push(dirs):
        """
        Issues the hg push command on all valid repositories
        """

        if not dirs:
            print "Mercurial repositories not found..."
            return
        for repo in dirs:
            print 'Pushing changes for repository: ', repo
            cmd = ['hg', 'push', '-R', repo]
            run_command(cmd)

    def update(dirs):
        """
        Issues the hg update command on all valid repositories
        """

        if not dirs:
            print "Mercurial repositories not found..."
            return

        for repo in dirs:
            print 'Updating repository to tip: ', repo
            cmd = ['hg', 'update', '-R', repo]
            run_command(cmd)

    def main():
        """
        Parse the command line and issue the appropriate mercurial command.
        """

        from optparse import OptionParser

        usage = "usage: %prog [options]"
        parser = OptionParser(usage=usage, version="%prog v" + __version__)
        parser.add_option("-p", "--pull", action="store_true",
                                          dest="pull",
                                          help="Pull remote changes to local \
                                          repository")
        parser.add_option("", "--pullupdate", action="store_true",
                                              dest="pullupdate",
                                              help="Pull remote changes to local \
                                                    repository and update to \
                                                    tip.")
        parser.add_option("-u", "--update", action="store_true",
                                             dest="update",
                                             help="Update local repositories to \
                                                   tip.")
        parser.add_option("-s", "--push", action="store_true",
                                          dest="push",
                                          help="Push local changes to remote \
                                                repository.")
        parser.add_option("-r", "--root", dest="searchpath",
                                          help="Root folder containing all \
                                          repositories to search. Defaults to the \
                                          the same folder as the script.",
                                          default=sys.path[0],
                                          metavar="PATH")


        options, args = parser.parse_args(args=None, values=None)

        print "Searching ", options.searchpath
        dirs = find_repositories(options.searchpath)

        if options.pullupdate:
            pull(dirs)
            update(dirs)
        elif options.pull:
            pull(dirs)
        elif options.push:
            push(dirs)
        elif options.update:
            update(dirs)
        else:
            print parser.print_help()
            return -1

        return 0 # success

    if __name__ == '__main__':
        status = main()
        sys.exit(status)

Update - 2010-04-20 - There were a couple of errors in the original code namely the cmd list in each of the push, pull and update methods would append ‘-R’ and the repository name to the list for every repository that the script found.

The script can be called from a shell script. I use the script with the –pullupdate flag which pulls all the changes from the remote repository and updates it. This process is applied to each of the discovered repositories under the root folder (pull is performed first as a batch operation, then update is performed next as a batch operation).

Here are the available command line switches:

$./hg_util.py -h

Usage: hg_util.py [options]

Options:
  --version       Show program's version number and exit
  -h, --help      Show this help message and exit
  -p, --pull       Pull remote changes to local repository
  --pullupdate   Pull remote changes to local repository and update to tip.
  -u, --update   Update local repositories to tip.
  -s, --push      Push local changes to remote repository.
  -r PATH, --root=PATH  Root folder containing all repositories to search. Defaults to the the same folder as the script.

Update - 2012-01-15 - I completely rewrote the script and it can be found here.