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.

11 thoughts on “Updated Mercurial Batch Pull/Update Python Script

  1. Lionel says:

    Hi,

    I’m trying to make a simple python script for using mercurial.. but I have the issue
    abort: error: _ssl.c:503: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
    Did you have the same problem.. and would you know how to fix it?
    Thanks!

  2. PatrickT says:

    looks like what I was looking for, but being very much ignorant I can’t understand two things,
    1. how to specify the remote directory, e.g. /media/myusb
    2. how to specify the local directory (I do understand that it will default to wherever the file is)
    thanks!

    • Patrick,

      The script only initiates a push or pull on the repositories that it finds. Each repository has to have the push/pull setup individual, just like would normally do with mercurial. The remote directory is specified in the hgrc file located in the .hg folder of your repository. Edit or add a section called paths:

      [paths]
      default = /path/to/my/repository

      Alternatively you could use a client like TortoiseHG and in the repo properties setup the sync paths that way.

      When running the script you can specify the path to the repos that you want to automatically push/pull/update. If you point to a parent folder, it will recursively search for all repostories and deal with them individually.

      You should check out the article and updated script.

      Cheers,
      Troy

  3. PatrickT says:

    Thanks Troy, it’s all cleared up. I’m new to Mercurial and haven’t yet set it up to work this way, I’m doing everything manually at this time, specifying the paths to push each time. This will be a great way to save time. Thanks for answering so fast. Cheers to you, Patrick.

  4. SeenR says:

    Hi, Thanks for this script and something I was looking for and helps a lot.
    I have one issue while running this python script from cron with a shell script wrapper.
    Shell script works when running from the terminal but not working with cron.
    The error I am getting is:

    Found: .
    Traceback (most recent call last):
    File “/root/scripts/hg_utilities/HgUtilities.py”, line 187, in
    status = main()
    File “/root/scripts/hg_utilities/HgUtilities.py”, line 177, in main
    if repo.has_pending_commits():
    File “/root/scripts/hg_utilities/HgHelper.py”, line 99, in has_pending_commits
    self.status()
    File “/root/scripts/hg_utilities/HgHelper.py”, line 87, in status
    self.run_repo_command(self.commands[‘status’])
    File “/root/scripts/hg_utilities/HgHelper.py”, line 42, in run_repo_command
    working_directory=self.path)
    File “/root/scripts/hg_utilities/SubprocessHelper.py”, line 66, in run
    cwd=kwargs.get(‘working_directory’, None))
    File “/usr/lib64/python2.6/subprocess.py”, line 639, in __init__
    errread, errwrite)
    File “/usr/lib64/python2.6/subprocess.py”, line 1228, in _execute_child
    raise child_exception
    OSError: [Errno 2] No such file or directory

    Could you please help? Thanks.

Leave a reply to PatrickT Cancel reply