hgsvn-0.1.8/0000755000175000017500000000000011327011330011244 5ustar andiandihgsvn-0.1.8/MANIFEST.in0000644000175000017500000000011511216610734013011 0ustar andiandirecursive-include ez_setup *.py *.txt include *.txt recursive-include man1 * hgsvn-0.1.8/man1/0000755000175000017500000000000011327011330012100 5ustar andiandihgsvn-0.1.8/man1/hgpushsvn.10000644000175000017500000000177311327010761014226 0ustar andiandi.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36. .TH HGPUSHSVN "1" "January 2010" "hgpushsvn 0.1.8" "User Commands" .SH NAME hgpushsvn \- manual page for hgpushsvn 0.1.8 .SH SYNOPSIS .B hgpushsvn [\fI-cf\fR] .SH OPTIONS .TP \fB\-f\fR, \fB\-\-force\fR push even if no hg tag found for current SVN rev. .TP \fB\-c\fR, \fB\-\-collapse\fR collapse all hg changesets in a single SVN commit .TP \fB\-n\fR, \fB\-\-dry\-run\fR show outgoing changes to SVN without pushing them .TP \fB\-e\fR, \fB\-\-edit\fR edit commit message using external editor .TP \fB\-\-version\fR show version and exit .TP \fB\-h\fR, \fB\-\-help\fR show this help message and exit .TP \fB\-v\fR, \fB\-\-verbose\fR enable additional output .TP \fB\-\-debug\fR enable debugging output .SH "SEE ALSO" The full documentation for .B hgpushsvn is maintained as a Texinfo manual. If the .B info and .B hgpushsvn programs are properly installed at your site, the command .IP .B info hgpushsvn .PP should give you access to the complete manual. hgsvn-0.1.8/man1/hgpullsvn.10000644000175000017500000000160411327011004014203 0ustar andiandi.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36. .TH HGPULLSVN "1" "January 2010" "hgpullsvn 0.1.8" "User Commands" .SH NAME hgpullsvn \- manual page for hgpullsvn 0.1.8 .SH SYNOPSIS .B hgpullsvn [\fI-p SVN peg rev\fR] [\fI--help\fR] .SH OPTIONS .TP \fB\-p\fR SVN_PEG, \fB\-\-svn\-peg\fR=\fISVN_PEG\fR SVN peg revision to locate checkout URL .TP \fB\-n\fR, \fB\-\-dry\-run\fR show incoming changesets without pulling them .TP \fB\-\-version\fR show version and exit .TP \fB\-h\fR, \fB\-\-help\fR show this help message and exit .TP \fB\-v\fR, \fB\-\-verbose\fR enable additional output .TP \fB\-\-debug\fR enable debugging output .SH "SEE ALSO" The full documentation for .B hgpullsvn is maintained as a Texinfo manual. If the .B info and .B hgpullsvn programs are properly installed at your site, the command .IP .B info hgpullsvn .PP should give you access to the complete manual. hgsvn-0.1.8/man1/hgimportsvn.10000644000175000017500000000222511327010726014553 0ustar andiandi.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.36. .TH HGIMPORTSVN "1" "January 2010" "hgimportsvn 0.1.8" "User Commands" .SH NAME hgimportsvn \- manual page for hgimportsvn 0.1.8 .SH SYNOPSIS .B hgimportsvn [\fI-r SVN rev\fR] [\fI-p SVN peg rev\fR] \fI \fR[\fIlocal checkout\fR] .SH DESCRIPTION .IP hgimportsvn \fB\-\-local\-only\fR .SH OPTIONS .TP \fB\-r\fR SVN_REV, \fB\-\-svn\-rev\fR=\fISVN_REV\fR SVN revision to checkout from .TP \fB\-p\fR SVN_PEG, \fB\-\-svn\-peg\fR=\fISVN_PEG\fR SVN peg revision to locate checkout URL .TP \fB\-\-no\-hgignore\fR Don't autogenerate .hgignore .TP \fB\-\-local\-only\fR Don't use the server, just build from a local checkout .TP \fB\-\-version\fR show version and exit .TP \fB\-h\fR, \fB\-\-help\fR show this help message and exit .TP \fB\-v\fR, \fB\-\-verbose\fR enable additional output .TP \fB\-\-debug\fR enable debugging output .SH "SEE ALSO" The full documentation for .B hgimportsvn is maintained as a Texinfo manual. If the .B info and .B hgimportsvn programs are properly installed at your site, the command .IP .B info hgimportsvn .PP should give you access to the complete manual. hgsvn-0.1.8/hgsvn.egg-info/0000755000175000017500000000000011327011330014063 5ustar andiandihgsvn-0.1.8/hgsvn.egg-info/dependency_links.txt0000644000175000017500000000000111327011330020131 0ustar andiandi hgsvn-0.1.8/hgsvn.egg-info/top_level.txt0000644000175000017500000000000611327011330016611 0ustar andiandihgsvn hgsvn-0.1.8/hgsvn.egg-info/SOURCES.txt0000644000175000017500000000115411327011330015750 0ustar andiandiAUTHORS.txt COPYING.txt MANIFEST.in README.txt TODO.txt setup.cfg setup.py hgsvn/__init__.py hgsvn/common.py hgsvn/errors.py hgsvn/svnclient.py hgsvn/ui.py hgsvn.egg-info/PKG-INFO hgsvn.egg-info/SOURCES.txt hgsvn.egg-info/dependency_links.txt hgsvn.egg-info/entry_points.txt hgsvn.egg-info/top_level.txt hgsvn/run/__init__.py hgsvn/run/common.py hgsvn/run/hgimportsvn.py hgsvn/run/hgpullsvn.py hgsvn/run/hgpushsvn.py hgsvn/unittests/__init__.py hgsvn/unittests/_test.py hgsvn/unittests/test_common.py hgsvn/unittests/test_hgclient.py hgsvn/unittests/test_svnclient.py man1/hgimportsvn.1 man1/hgpullsvn.1 man1/hgpushsvn.1hgsvn-0.1.8/hgsvn.egg-info/PKG-INFO0000644000175000017500000004452611327011330015173 0ustar andiandiMetadata-Version: 1.0 Name: hgsvn Version: 0.1.8 Summary: A set of scripts to work locally on Subversion checkouts using Mercurial Home-page: UNKNOWN Author: Antoine Pitrou Author-email: antoine@pitrou.net License: GNU GPL Description: ------- Summary ------- This set of scripts allows to work locally on Subversion-managed projects using the Mercurial distributed version control system. Why use Mercurial ? You can do local (disconnected) work, pull the latest changes from the SVN server, manage private branches, submit patches to project maintainers, etc. And of course you have fast local operations like "hg log", "hg annotate"... Three scripts are provided: * ``hgimportsvn`` initializes an SVN checkout which is also a Mercurial repository. * ``hgpullsvn`` pulls the latest changes from the SVN repository, and updates the Mercurial repository accordingly. It can be run multiple times. * ``hgpushsvn`` pushes your local Mercurial commits back to the SVN repository. ------- Example ------- Making a checkout of the Django_ trunk:: $ mkdir django && cd django # Make SVN checkout, initialize hg repository with first SVN revision $ hgimportsvn http://code.djangoproject.com/svn/django/trunk/ $ cd trunk # Pull all history from SVN, creating a new hg changeset for each SVN rev $ hgpullsvn Then make your changes and use the "hg" commands to commit them locally. If you have commit privileges you can push back your changes to the SVN repository:: $ hgpushsvn If you want to see what will be pushed back to SVN, use the "-n/--dry-run" flag. This is much like the "hg outgoing" command:: $ hgpushsvn --dry-run .. _Django: http://www.djangoproject.com ------- Install ------- Just type ``easy_install hgsvn``. If easy_install is not available on your computer, download and uncompress the source tarball, then type ``python setup.py install``. *Note:* hgsvn makes use of the ElementTree library. It is bundled by default with Python 2.5, and the setup script should install it automatically for you if you are using Python 2.4. However, if you get some error messages, you might have to install it manually (at least one user reported he had to). Unstable (development) version ------------------------------ Just run ``hg clone http://bitbucket.org/andialbrecht/hgsvn hgsvn`` and you'll get the contents of the development repository. -------- Features -------- Graceful operation ------------------ ``hgpullsvn`` asks for SVN log entries in chunks, so that pulling history does not put the remote server on its knees. ``hgpullsvn`` can be interrupted at any time, and run again later: you can pull history incrementally. Metadata -------- hgsvn reflects commit times (using the local timezone) and commit author names. Commit messages can contain Unicode characters. File copies and renames as reflected as well, provided they occur inside the branch. Tags ---- ``hgpullsvn`` tags each new Mercurial changeset with a local tag named 'svn.123' where 123 is the number of the corresponding SVN revision. Local tags were chosen because they don't pollute the hg log with superfluous entries, and also because SVN revision numbers are only meaningful for a specific branch: there is no use propagating them (IMHO). Named branches -------------- These scripts encourage the use of named branches. All updates using ``hgpullsvn`` are made in the branch named from the last component of the SVN URL (e.g., if the SVN URL is svn://server/myproj/branches/feature-ZZZ, ``hgpullsvn`` will create and use the named branch 'feature-ZZZ'). You can thus do local development using your own named branches. When you want to fetch latest history from the SVN repository, simply use ``hgpullsvn`` which will update to the original (pristine) branch, leaving your local work intact (you can then merge by yourself if your want). This also means that ``hg di -r name-of-pristine-branch`` will immediately give you a patch against the pristine branch, which you can submit to the project maintainers. (Note: in a non-trivial setup where you work on several features or bugfixes, you will clone the pristine repository for each separate piece of work, which will still give you the benefit of named branches for quickly generating patches). Detecting parent repository --------------------------- If the SVN URL has been created by copying from another SVN URL (this is the standard method for branch creation), ``hgimportsvn`` tries to find an hgsvn repository corresponding to the parent SVN URL. It then creates the new repository by cloning this repository at the revision immediately before the creation of the SVN branch. In other words, let's say you are operating from myworkdir/. In myworkdir/trunk, you already have an hgsvn repository synced from svn://server/myproj/trunk. You then ``hgimport svn://server/myproj/branches/new-feature``. It will find that the 'new-feature' branch has been created by copying from 'trunk' at rev. 1138. It will thus create the 'new-feature' hg repository by cloning from the 'trunk' repository at the revision immediately preceding rev. 1138: for example rev. 1135, identified by the local tag 'svn.1135'. This means you will have an hgsvn repository containing two named branches: 'trunk' for all the changesets in the trunk before rev. 1138, and 'new-feature' for all the changesets in the SVN branch (therefore, after rev. 1138). This way, you can easily track how the branch diverges from the trunk, but also do merges, etc. ----------- Limitations ----------- SVN externals are purposefully ignored and won't be added to your Mercurial repository. ------- History ------- hgsvn 0.1.8 ----------- Improvements: * Convert a local SVN checkout into a hgsvn controlled Mercurial repository with ``hgimportsvn --local-only``. No network access is needed when setting this flag (aka airplane mode). The Mercurial history then starts with the current revision of the SVN checkout. Patch by Matt Fowles. * Commit messages when pushing back to SVN can be edited before committing using the -e/--edit command line flag. Issue #29, patch by eliterr. * It's now possible to use ``hgsvn`` with the mq extensions. Both ``hgpushsvn`` and ``hgpullsvn`` abort with an error message if mq patches are applied when running those commands. Issue #43, patch by sterin. Bug fixes: * Removal of temporary file when pushing new revisions to SVN on Windows fixed. Issue 8 reported by Daniel Dabrowski. * Changed 'hg log' command line arguments that interfered with default options in .hgrc file. Issue 12 reported by Simon Percivall, initial patch by Joel Rosdahl and issue 16 reported by Wladimir Palant. * ``hgpushsvn`` is now compatible with Python 2.4. * If a SVN changeset contains empty changeset comments, ``hgpullsvn`` has failed. Empty changeset messages are now handled correctly. * SVN repositories at revision 0 couldn't be imported. Now it's possible to import empty SVN repositories with ``hgimportsvn``. Issue #13 reported by tiktuk. * ``hgpushsvn`` failed when a non-empty directory was removed from version control. Issue #15 reported by Keith Yang. * Proper encoding of commit messages on Windows systems. Issue #19 reported and patch by Chunlin Yao. * Change svn:executable property on mode changes when pushing back to SVN repository. Issue #24 reported by sterin. * Improved parsing of SVN messages. Issues #27, #14 patch contributed by x63. * ``hgpushsvn`` whiped uncommitted changes in working directory. Issue #32 reported by foxcub. * ``hgpullsvn`` in dry-run-mode displayed latest fetched revision too. Issue #35 reported by Dmitriy Morozov. * New sub-directories are now created properly. Issue #46 reported by Matt Fowles. hgsvn 0.1.7 ----------- Improvements: * ``hgpushsvn`` fully integrated in this version. This command pushes local Mercurial commits back to the SVN repository. * Add a -n/--dry-run flag to ``hgpullsvn`` and ``hgpushsvn`` to list incoming and outgoing changes without committing them to the local or remote repository. * Add verbosity levels to all command line scripts. The default verbosity level limits the output of ``hgpullsvn`` and ``hgpushsvn`` to messages that have a certain relevance to the user. Additional messages will be shown with the -v/--verbose flag. The --debug flag enables the output of debugging messages including shell commands. Bug fixes: * Log files from SVN repositories with path-based authentication caused ``hgpullsvn`` and ``hgimportsvn`` to fail with an XML parsing error. Restricted paths are now silently ignored (issue5, reported by Andreas Sliwka). * Updated the Mercurial-based lock file mechanism introduced in the previous release to work with Mercurial >= 1.2.0. The exception class was moved in Mercurial 1.2.0 (issue4). * ``hgpullsvn`` and ``hgpushsvn`` can now be called from any sub-directory within the working copy. Both scripts now take care to change their working directory to the root of the working copy (issue3). * ``hgimportsvn`` exits with a error message when the target directory is already a Mercurial repository controlled by hgsvn. * Detect conflicts when running SVN update. To avoid conflicts when pulling new SVN revisions, ``hgpullsvn`` checks if the hg repository has uncommitted changes before actually pulling new revisions from SVN (issue6, reported and initial patch by Robert). hgsvn 0.1.6 ----------- Improvements: * Prefix commit messages with [svn r123] (where 123 is the corresponding SVN revision number), rather than just [svn]. Also, trim leading whitespace in the original commit message, to avoid blank changeset summaries when the message begins with a carriage return. * Introduce a .hgsvn private directory at the top of the working copy. This will us to store various things in a common location without polluting the base directory. * Introduce a lock file (named .hgsvn/lock) to disallow running two hgpullsvn instances in parallel on the same repository. The locking mechanism is imported from mercurial's own mercurial.lock. If the mercurial package is not available, a dummy lock is used instead. Initial patch by Ori Peleg. * Add a --no-hgignore option to hgimportsvn, for situations where the source SVN repository already contains a versioned .hgignore file. Patch by Ori Peleg. * hgsvn can now be bundled as standalone executables using py2exe. Patch by Paul Moore. * More descriptive error message when either hg or svn cannot be executed (e.g. not installed). Patch by Joonas Paalasmaa. Bug fixes: * Very long commit messages (> 16000 characters) are provided to Mercurial through a temporary file rather than the command line, which could fail on some platforms. The corresponding commit messages were generated by svnmerge. Reported by Ralf Schmitt. * Filenames starting with a hyphen were considered by hg and SVN as command-line options. Report and patch by Mirko Friedenhagen. * If the last hg changeset mapped to more than one SVN revision, trying to update again with ``hgpullsvn`` failed. * A replaced directory can have added and removed files without them being mentioned in the SVN log; we must detect those files ourselves. * More robust atomicity check for (hg commit, hg tag) sequence. Reported by Florent Guillaume. * Fix a bug when comparing local filesystem paths on Windows. We now invoke os.path.normcase on both paths before comparing. Reported by Pavol Murin. hgsvn 0.1.5 ----------- Improvements: * In the initial import, parse the svn:ignore property and add suggestions to the .hgignore file accordingly. These suggestions are commented by default because they are based on the latest version of the svn:ignore property and could make us miss some files along the SVN history, if enabled blindingly. Bug fixes: * Critical fix for Mercurial 0.9.5, which is stricter with named branches. This bug made ``hgimportsvn`` fail when cloning from an auto-detected parent repository. * Honor the SVN_ASP_DOT_NET_HACK environment variable when deciding the name of private SVN folders (``.svn`` or ``_svn``). Thanks to Anton Daneika for the report and the original patch. Packaging: * Change setuptools options to solve bdist_rpm bug under Fedora and other Linux distributions. Patch by Tim Wegener. hgsvn 0.1.4 ----------- Improvements: * Be able to pull dead (removed) SVN branches by introducing a -p (--svn-peg) option to specify the SVN "peg revision". The option must be used with both hgimportsvn and hgpullsvn. Patch by Cameron Hutchison. Bug fixes: * Allow copying directories with non-ASCII names (reported by Andre Klitzing). * Make rmtree reliable under Windows. Thanks to Mark (mwatts42) for finding both the bug and the solution. * Fix a problem where there is a symbolic link in the SVN repository that points to a directory. Patch by Cameron Hutchison. * ``svn log`` can output invalid XML when a commit message contains control characters. Reported by Tim Wegener. Other: * License upgraded to GNU GPL v3 (or later). hgsvn 0.1.3 ----------- Improvements: * Performance improvement with ``svn log`` command in ``hgpullsvn`` (suggested by Mads Kiilerich and Daniel Berlin). * Less obscure error message when ``svn info`` fails while returning a successful return code. * Two simplistic man pages added. Bug fixes: * Windows compatibility fix by Bill Baxter. * ``hgimportsvn`` failed when used on a whole repository. * Fix crash on empty commit message (also reported by Neil Martinsen-Burrell and Walter Landry). * Handle file and directory renames properly (reported by Bill Baxter). * SVN allows copying from a deleted file by having mixed revisions inside the working copy at commit time, but Mercurial doesn't accept it (reported by Neil Martinsen-Burrell). hgsvn 0.1.2 ----------- Improvements: * Automatically generate ``.hgignore`` file. Not only does it produce cleaner output for commands like ``hg status``, but it speeds things up as well. * ``hgpullsvn`` is more robust in the face of errors and user interruptions. * Try to be Windows-compatible by not using the commands module. * Remove dependency on the pysvn library; we use the XML output option of SVN commands instead. Bug fixes: * Fix a bug in parent repository detection. * Detect the wicked case where the SVN branch has been overwritten with contents of another branch (witnessed with Nose trunk and 0.10-dev branch). We can't properly handle this situation, so fail with an explicit message. * ``svn info`` on base repository URL does not always succeed, use the specific project URL instead (reported by Larry Hastings). hgsvn 0.1.1 ----------- Bug fixes: * pysvn doesn't really ignore externals, so use the command line for ``svn update`` instead (otherwise we get failures for obsolete URLs) * ``.svn`` directories were not always ignored. * On large repositories, adding more than 32765 files at once failed because of too many arguments on the command line. * On slow SVN servers, the chunked log fetching algorithm ended up asking for 0 log entries. hgsvn 0.1 --------- Initial release. Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Version Control hgsvn-0.1.8/hgsvn.egg-info/entry_points.txt0000644000175000017500000000020611327011330017357 0ustar andiandi[console_scripts] hgpullsvn = hgsvn.run.hgpullsvn:main hgpushsvn = hgsvn.run.hgpushsvn:main hgimportsvn = hgsvn.run.hgimportsvn:main hgsvn-0.1.8/setup.cfg0000644000175000017500000000022411327011330013063 0ustar andiandi[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [nosetests] nocapture = 1 [install] optimize = 1 [aliases] release = egg_info -RDb '' hgsvn-0.1.8/setup.py0000755000175000017500000000446211220567234013002 0ustar andiandi#!/usr/bin/env python # Setuptools-based setup script # See: # - http://peak.telecommunity.com/DevCenter/setuptools (*) # - http://peak.telecommunity.com/DevCenter/EasyInstall # (*) QOTD: # "Notice that after each pre or post-release tag, you are free to place another # release number, followed again by more pre- or post-release tags. For example, # 0.6a9.dev-r41475 could denote Subversion revision 41475 of the in- development # version of the ninth alpha of release 0.6. Notice that dev is a pre-release tag, # so this version is a lower version number than 0.6a9, which would be the actual # ninth alpha of release 0.6. But the -r41475 is a post-release tag, so this # version is newer than 0.6a9.dev." from ez_setup import use_setuptools use_setuptools(version="0.6c9", download_delay=3) from setuptools import setup, find_packages from hgsvn import base_version, __doc__ as long_description commands = ['hgimportsvn', 'hgpullsvn', 'hgpushsvn'] install_requires = [] try: from xml.etree import ElementTree except ImportError: try: import elementtree except ImportError: install_requires = ['elementtree'] extra_cmds = {} try: import py2exe extra_cmds['console'] = ["hgimportsvn.py", "hgpullsvn.py", "hgpushsvn.py"] except ImportError: pass setup( name = "hgsvn", author = 'Antoine Pitrou', author_email = 'antoine@pitrou.net', description = ("A set of scripts to work locally on Subversion checkouts " "using Mercurial" ), long_description = long_description, license = 'GNU GPL', # *Next* version, not previous! version = base_version, packages = find_packages(exclude=["ez_setup"]), test_suite = "nose.collector", install_requires = install_requires, entry_points = { 'console_scripts': [ '%s = hgsvn.run.%s:main' % (s, s) for s in commands ], }, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Version Control', ], **extra_cmds ) hgsvn-0.1.8/TODO.txt0000644000175000017500000000024611224551115012562 0ustar andiandi* Add a command to import SVN tags pertaining to the current project from the ``tags`` path in the SVN repo. * Add a config file in a dedicated .hgsvn directory. hgsvn-0.1.8/PKG-INFO0000644000175000017500000004452611327011330012354 0ustar andiandiMetadata-Version: 1.0 Name: hgsvn Version: 0.1.8 Summary: A set of scripts to work locally on Subversion checkouts using Mercurial Home-page: UNKNOWN Author: Antoine Pitrou Author-email: antoine@pitrou.net License: GNU GPL Description: ------- Summary ------- This set of scripts allows to work locally on Subversion-managed projects using the Mercurial distributed version control system. Why use Mercurial ? You can do local (disconnected) work, pull the latest changes from the SVN server, manage private branches, submit patches to project maintainers, etc. And of course you have fast local operations like "hg log", "hg annotate"... Three scripts are provided: * ``hgimportsvn`` initializes an SVN checkout which is also a Mercurial repository. * ``hgpullsvn`` pulls the latest changes from the SVN repository, and updates the Mercurial repository accordingly. It can be run multiple times. * ``hgpushsvn`` pushes your local Mercurial commits back to the SVN repository. ------- Example ------- Making a checkout of the Django_ trunk:: $ mkdir django && cd django # Make SVN checkout, initialize hg repository with first SVN revision $ hgimportsvn http://code.djangoproject.com/svn/django/trunk/ $ cd trunk # Pull all history from SVN, creating a new hg changeset for each SVN rev $ hgpullsvn Then make your changes and use the "hg" commands to commit them locally. If you have commit privileges you can push back your changes to the SVN repository:: $ hgpushsvn If you want to see what will be pushed back to SVN, use the "-n/--dry-run" flag. This is much like the "hg outgoing" command:: $ hgpushsvn --dry-run .. _Django: http://www.djangoproject.com ------- Install ------- Just type ``easy_install hgsvn``. If easy_install is not available on your computer, download and uncompress the source tarball, then type ``python setup.py install``. *Note:* hgsvn makes use of the ElementTree library. It is bundled by default with Python 2.5, and the setup script should install it automatically for you if you are using Python 2.4. However, if you get some error messages, you might have to install it manually (at least one user reported he had to). Unstable (development) version ------------------------------ Just run ``hg clone http://bitbucket.org/andialbrecht/hgsvn hgsvn`` and you'll get the contents of the development repository. -------- Features -------- Graceful operation ------------------ ``hgpullsvn`` asks for SVN log entries in chunks, so that pulling history does not put the remote server on its knees. ``hgpullsvn`` can be interrupted at any time, and run again later: you can pull history incrementally. Metadata -------- hgsvn reflects commit times (using the local timezone) and commit author names. Commit messages can contain Unicode characters. File copies and renames as reflected as well, provided they occur inside the branch. Tags ---- ``hgpullsvn`` tags each new Mercurial changeset with a local tag named 'svn.123' where 123 is the number of the corresponding SVN revision. Local tags were chosen because they don't pollute the hg log with superfluous entries, and also because SVN revision numbers are only meaningful for a specific branch: there is no use propagating them (IMHO). Named branches -------------- These scripts encourage the use of named branches. All updates using ``hgpullsvn`` are made in the branch named from the last component of the SVN URL (e.g., if the SVN URL is svn://server/myproj/branches/feature-ZZZ, ``hgpullsvn`` will create and use the named branch 'feature-ZZZ'). You can thus do local development using your own named branches. When you want to fetch latest history from the SVN repository, simply use ``hgpullsvn`` which will update to the original (pristine) branch, leaving your local work intact (you can then merge by yourself if your want). This also means that ``hg di -r name-of-pristine-branch`` will immediately give you a patch against the pristine branch, which you can submit to the project maintainers. (Note: in a non-trivial setup where you work on several features or bugfixes, you will clone the pristine repository for each separate piece of work, which will still give you the benefit of named branches for quickly generating patches). Detecting parent repository --------------------------- If the SVN URL has been created by copying from another SVN URL (this is the standard method for branch creation), ``hgimportsvn`` tries to find an hgsvn repository corresponding to the parent SVN URL. It then creates the new repository by cloning this repository at the revision immediately before the creation of the SVN branch. In other words, let's say you are operating from myworkdir/. In myworkdir/trunk, you already have an hgsvn repository synced from svn://server/myproj/trunk. You then ``hgimport svn://server/myproj/branches/new-feature``. It will find that the 'new-feature' branch has been created by copying from 'trunk' at rev. 1138. It will thus create the 'new-feature' hg repository by cloning from the 'trunk' repository at the revision immediately preceding rev. 1138: for example rev. 1135, identified by the local tag 'svn.1135'. This means you will have an hgsvn repository containing two named branches: 'trunk' for all the changesets in the trunk before rev. 1138, and 'new-feature' for all the changesets in the SVN branch (therefore, after rev. 1138). This way, you can easily track how the branch diverges from the trunk, but also do merges, etc. ----------- Limitations ----------- SVN externals are purposefully ignored and won't be added to your Mercurial repository. ------- History ------- hgsvn 0.1.8 ----------- Improvements: * Convert a local SVN checkout into a hgsvn controlled Mercurial repository with ``hgimportsvn --local-only``. No network access is needed when setting this flag (aka airplane mode). The Mercurial history then starts with the current revision of the SVN checkout. Patch by Matt Fowles. * Commit messages when pushing back to SVN can be edited before committing using the -e/--edit command line flag. Issue #29, patch by eliterr. * It's now possible to use ``hgsvn`` with the mq extensions. Both ``hgpushsvn`` and ``hgpullsvn`` abort with an error message if mq patches are applied when running those commands. Issue #43, patch by sterin. Bug fixes: * Removal of temporary file when pushing new revisions to SVN on Windows fixed. Issue 8 reported by Daniel Dabrowski. * Changed 'hg log' command line arguments that interfered with default options in .hgrc file. Issue 12 reported by Simon Percivall, initial patch by Joel Rosdahl and issue 16 reported by Wladimir Palant. * ``hgpushsvn`` is now compatible with Python 2.4. * If a SVN changeset contains empty changeset comments, ``hgpullsvn`` has failed. Empty changeset messages are now handled correctly. * SVN repositories at revision 0 couldn't be imported. Now it's possible to import empty SVN repositories with ``hgimportsvn``. Issue #13 reported by tiktuk. * ``hgpushsvn`` failed when a non-empty directory was removed from version control. Issue #15 reported by Keith Yang. * Proper encoding of commit messages on Windows systems. Issue #19 reported and patch by Chunlin Yao. * Change svn:executable property on mode changes when pushing back to SVN repository. Issue #24 reported by sterin. * Improved parsing of SVN messages. Issues #27, #14 patch contributed by x63. * ``hgpushsvn`` whiped uncommitted changes in working directory. Issue #32 reported by foxcub. * ``hgpullsvn`` in dry-run-mode displayed latest fetched revision too. Issue #35 reported by Dmitriy Morozov. * New sub-directories are now created properly. Issue #46 reported by Matt Fowles. hgsvn 0.1.7 ----------- Improvements: * ``hgpushsvn`` fully integrated in this version. This command pushes local Mercurial commits back to the SVN repository. * Add a -n/--dry-run flag to ``hgpullsvn`` and ``hgpushsvn`` to list incoming and outgoing changes without committing them to the local or remote repository. * Add verbosity levels to all command line scripts. The default verbosity level limits the output of ``hgpullsvn`` and ``hgpushsvn`` to messages that have a certain relevance to the user. Additional messages will be shown with the -v/--verbose flag. The --debug flag enables the output of debugging messages including shell commands. Bug fixes: * Log files from SVN repositories with path-based authentication caused ``hgpullsvn`` and ``hgimportsvn`` to fail with an XML parsing error. Restricted paths are now silently ignored (issue5, reported by Andreas Sliwka). * Updated the Mercurial-based lock file mechanism introduced in the previous release to work with Mercurial >= 1.2.0. The exception class was moved in Mercurial 1.2.0 (issue4). * ``hgpullsvn`` and ``hgpushsvn`` can now be called from any sub-directory within the working copy. Both scripts now take care to change their working directory to the root of the working copy (issue3). * ``hgimportsvn`` exits with a error message when the target directory is already a Mercurial repository controlled by hgsvn. * Detect conflicts when running SVN update. To avoid conflicts when pulling new SVN revisions, ``hgpullsvn`` checks if the hg repository has uncommitted changes before actually pulling new revisions from SVN (issue6, reported and initial patch by Robert). hgsvn 0.1.6 ----------- Improvements: * Prefix commit messages with [svn r123] (where 123 is the corresponding SVN revision number), rather than just [svn]. Also, trim leading whitespace in the original commit message, to avoid blank changeset summaries when the message begins with a carriage return. * Introduce a .hgsvn private directory at the top of the working copy. This will us to store various things in a common location without polluting the base directory. * Introduce a lock file (named .hgsvn/lock) to disallow running two hgpullsvn instances in parallel on the same repository. The locking mechanism is imported from mercurial's own mercurial.lock. If the mercurial package is not available, a dummy lock is used instead. Initial patch by Ori Peleg. * Add a --no-hgignore option to hgimportsvn, for situations where the source SVN repository already contains a versioned .hgignore file. Patch by Ori Peleg. * hgsvn can now be bundled as standalone executables using py2exe. Patch by Paul Moore. * More descriptive error message when either hg or svn cannot be executed (e.g. not installed). Patch by Joonas Paalasmaa. Bug fixes: * Very long commit messages (> 16000 characters) are provided to Mercurial through a temporary file rather than the command line, which could fail on some platforms. The corresponding commit messages were generated by svnmerge. Reported by Ralf Schmitt. * Filenames starting with a hyphen were considered by hg and SVN as command-line options. Report and patch by Mirko Friedenhagen. * If the last hg changeset mapped to more than one SVN revision, trying to update again with ``hgpullsvn`` failed. * A replaced directory can have added and removed files without them being mentioned in the SVN log; we must detect those files ourselves. * More robust atomicity check for (hg commit, hg tag) sequence. Reported by Florent Guillaume. * Fix a bug when comparing local filesystem paths on Windows. We now invoke os.path.normcase on both paths before comparing. Reported by Pavol Murin. hgsvn 0.1.5 ----------- Improvements: * In the initial import, parse the svn:ignore property and add suggestions to the .hgignore file accordingly. These suggestions are commented by default because they are based on the latest version of the svn:ignore property and could make us miss some files along the SVN history, if enabled blindingly. Bug fixes: * Critical fix for Mercurial 0.9.5, which is stricter with named branches. This bug made ``hgimportsvn`` fail when cloning from an auto-detected parent repository. * Honor the SVN_ASP_DOT_NET_HACK environment variable when deciding the name of private SVN folders (``.svn`` or ``_svn``). Thanks to Anton Daneika for the report and the original patch. Packaging: * Change setuptools options to solve bdist_rpm bug under Fedora and other Linux distributions. Patch by Tim Wegener. hgsvn 0.1.4 ----------- Improvements: * Be able to pull dead (removed) SVN branches by introducing a -p (--svn-peg) option to specify the SVN "peg revision". The option must be used with both hgimportsvn and hgpullsvn. Patch by Cameron Hutchison. Bug fixes: * Allow copying directories with non-ASCII names (reported by Andre Klitzing). * Make rmtree reliable under Windows. Thanks to Mark (mwatts42) for finding both the bug and the solution. * Fix a problem where there is a symbolic link in the SVN repository that points to a directory. Patch by Cameron Hutchison. * ``svn log`` can output invalid XML when a commit message contains control characters. Reported by Tim Wegener. Other: * License upgraded to GNU GPL v3 (or later). hgsvn 0.1.3 ----------- Improvements: * Performance improvement with ``svn log`` command in ``hgpullsvn`` (suggested by Mads Kiilerich and Daniel Berlin). * Less obscure error message when ``svn info`` fails while returning a successful return code. * Two simplistic man pages added. Bug fixes: * Windows compatibility fix by Bill Baxter. * ``hgimportsvn`` failed when used on a whole repository. * Fix crash on empty commit message (also reported by Neil Martinsen-Burrell and Walter Landry). * Handle file and directory renames properly (reported by Bill Baxter). * SVN allows copying from a deleted file by having mixed revisions inside the working copy at commit time, but Mercurial doesn't accept it (reported by Neil Martinsen-Burrell). hgsvn 0.1.2 ----------- Improvements: * Automatically generate ``.hgignore`` file. Not only does it produce cleaner output for commands like ``hg status``, but it speeds things up as well. * ``hgpullsvn`` is more robust in the face of errors and user interruptions. * Try to be Windows-compatible by not using the commands module. * Remove dependency on the pysvn library; we use the XML output option of SVN commands instead. Bug fixes: * Fix a bug in parent repository detection. * Detect the wicked case where the SVN branch has been overwritten with contents of another branch (witnessed with Nose trunk and 0.10-dev branch). We can't properly handle this situation, so fail with an explicit message. * ``svn info`` on base repository URL does not always succeed, use the specific project URL instead (reported by Larry Hastings). hgsvn 0.1.1 ----------- Bug fixes: * pysvn doesn't really ignore externals, so use the command line for ``svn update`` instead (otherwise we get failures for obsolete URLs) * ``.svn`` directories were not always ignored. * On large repositories, adding more than 32765 files at once failed because of too many arguments on the command line. * On slow SVN servers, the chunked log fetching algorithm ended up asking for 0 log entries. hgsvn 0.1 --------- Initial release. Platform: UNKNOWN Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Version Control hgsvn-0.1.8/hgsvn/0000755000175000017500000000000011327011330012371 5ustar andiandihgsvn-0.1.8/hgsvn/common.py0000644000175000017500000002773111327001030014241 0ustar andiandi from hgsvn import ui from hgsvn.errors import ExternalCommandFailed, HgSVNError import os import locale from datetime import datetime import time from subprocess import Popen, PIPE, STDOUT import shutil import stat import sys import traceback try: import commands except ImportError: commands = None class _SimpleFileLock(object): def __init__(self, filename, timeout=None): self.file = filename self.lock() def lock(self): if os.path.exists(self.file): raise LockHeld("Lock file exists.") open(self.file, "wb").close() def release(self): if os.path.exists(self.file): os.remove(self.file) class _LockHeld(Exception): pass # We import the lock logic from Mercurial if it is available, and fall back # to a dummy (always successful) lock if not. try: from mercurial.lock import lock as _lock try: from mercurial.error import LockHeld except ImportError: # LockHeld was defined in mercurial.lock in Mercurial < 1.2 from mercurial.lock import LockHeld except ImportError: _lock = _SimpleFileLock LockHeld = _LockHeld hgsvn_private_dir = ".hgsvn" hgsvn_lock_file = "lock" if "SVN_ASP_DOT_NET_HACK" in os.environ: svn_private_dir = "_svn" else: svn_private_dir = '.svn' hg_commit_prefix = "[svn r%d] " # This seems sufficient for excluding all .svn (sub)directories hg_exclude_options = ["-X", svn_private_dir, "-X", "**/%s" % svn_private_dir] # Windows compatibility code by Bill Baxter if os.name == "nt": def find_program(name): """ Find the name of the program for Popen. Windows is finnicky about having the complete file name. Popen won't search the %PATH% for you automatically. (Adapted from ctypes.find_library) """ # See MSDN for the REAL search order. base, ext = os.path.splitext(name) if ext: exts = [ext] else: exts = ['.bat', '.exe'] for directory in os.environ['PATH'].split(os.pathsep): for e in exts: fname = os.path.join(directory, base + e) if os.path.exists(fname): return fname return name else: def find_program(name): """ Find the name of the program for Popen. On Unix, popen isn't picky about having absolute paths. """ return name def _rmtree_error_handler(func, path, exc_info): """ Error handler for rmtree. Helps removing the read-only protection under Windows (and others?). Adapted from http://www.proaxis.com/~darkwing/hot-backup.py and http://patchwork.ozlabs.org/bazaar-ng/patch?id=4243 """ if func in (os.remove, os.rmdir) and os.path.exists(path): # Change from read-only to writeable os.chmod(path, os.stat(path).st_mode | stat.S_IWRITE) func(path) else: # something else must be wrong... raise def rmtree(path): """ Wrapper around shutil.rmtree(), to provide more error-resistent behaviour. """ return shutil.rmtree(path, False, _rmtree_error_handler) locale_encoding = locale.getpreferredencoding() def shell_quote(s): if os.name == "nt": q = '"' else: q = "'" return q + s.replace('\\', '\\\\').replace("'", "'\"'\"'") + q def _run_raw_command(cmd, args, fail_if_stderr=False): cmd_string = "%s %s" % (cmd, " ".join(map(shell_quote, args))) ui.status("* %s", cmd_string, level=ui.DEBUG) try: pipe = Popen([cmd] + args, executable=cmd, stdout=PIPE, stderr=PIPE) except OSError: etype, value = sys.exc_info()[:2] raise ExternalCommandFailed( "Failed running external program: %s\nError: %s" % (cmd_string, "".join(traceback.format_exception_only(etype, value)))) out, err = pipe.communicate() if pipe.returncode != 0 or (fail_if_stderr and err.strip()): raise ExternalCommandFailed( "External program failed (return code %d): %s\n%s" % (pipe.returncode, cmd_string, err)) return out def _run_raw_shell_command(cmd): ui.status("* %s", cmd, level=ui.DEBUG) st, out = commands.getstatusoutput(cmd) if st != 0: raise ExternalCommandFailed( "External program failed with non-zero return code (%d): %s\n%s" % (st, cmd, out)) return out def run_command(cmd, args=None, bulk_args=None, encoding=None, fail_if_stderr=False): """ Run a command without using the shell. """ args = args or [] bulk_args = bulk_args or [] def _transform_arg(a): if isinstance(a, unicode): a = a.encode(encoding or locale_encoding or 'UTF-8') elif not isinstance(a, str): a = str(a) return a cmd = find_program(cmd) if not bulk_args: return _run_raw_command(cmd, map(_transform_arg, args), fail_if_stderr) # If one of bulk_args starts with a slash (e.g. '-foo.php'), # hg and svn will take this as an option. Adding '--' ends the search for # further options. for a in bulk_args: if a.strip().startswith('-'): args.append("--") break max_args_num = 254 i = 0 out = "" while i < len(bulk_args): stop = i + max_args_num - len(args) sub_args = [] for a in bulk_args[i:stop]: sub_args.append(_transform_arg(a)) out += _run_raw_command(cmd, args + sub_args, fail_if_stderr) i = stop return out def run_shell_command(cmd, args=None, bulk_args=None, encoding=None): """ Run a shell command, properly quoting and encoding arguments. Probably only works on Un*x-like systems. """ def _quote_arg(a): if isinstance(a, unicode): a = a.encode(encoding or locale_encoding) elif not isinstance(a, str): a = str(a) return shell_quote(a) if args: cmd += " " + " ".join(_quote_arg(a) for a in args) max_args_num = 254 i = 0 out = "" if not bulk_args: return _run_raw_shell_command(cmd) while i < len(bulk_args): stop = i + max_args_num - len(args) sub_args = [] for a in bulk_args[i:stop]: sub_args.append(_quote_arg(a)) sub_cmd = cmd + " " + " ".join(sub_args) out += _run_raw_shell_command(sub_cmd) i = stop return out def run_hg(args=None, bulk_args=None, output_is_locale_encoding=False): """ Run a Mercurial command, returns the (unicode) output. """ default_args = ["--encoding", "utf-8"] output = run_command("hg", args=default_args + (args or []), bulk_args=bulk_args) if output_is_locale_encoding: enc = locale_encoding else: enc = 'utf-8' return output.decode(enc) def run_svn(args=None, bulk_args=None, fail_if_stderr=False): """ Run an SVN command, returns the (bytes) output. """ return run_command("svn", args=args, bulk_args=bulk_args, fail_if_stderr=fail_if_stderr) def skip_dirs(paths, basedir="."): """ Skip all directories from path list, including symbolic links to real dirs. """ # NOTE: both tests are necessary (Cameron Hutchison's patch for symbolic # links to directories) return [p for p in paths if not os.path.isdir(os.path.join(basedir, p)) or os.path.islink(os.path.join(basedir, p))] def hg_commit_from_svn_log_entry(entry, files=None): """ Given an SVN log entry and an optional sequence of files, turn it into an appropriate hg changeset on top of the current branch. """ # This will use the local timezone for displaying commit times timestamp = int(entry['date']) hg_date = str(datetime.fromtimestamp(timestamp)) # Uncomment this one one if you prefer UTC commit times #hg_date = "%d 0" % timestamp message = (hg_commit_prefix % entry['revision']) + entry['message'].lstrip() commit_file = None try: commit_file = os.path.join(hgsvn_private_dir, "commit-%r.txt" % entry['revision']) f = open(commit_file, "wb") f.write(message.encode('utf-8')) f.close() msg_options = ["-l", commit_file] # the -m will now work on windows with utf-8 encoding argument # the CreateProcess win32api convert bytes to uicode by locale codepage # msg.encode('utf-8').decode('cp932').encode('cp932').decode('utf-8') options = ["ci"] + msg_options + ["-d", hg_date] if entry['author']: options.extend(["-u", entry['author']]) if files: run_hg(options, files) else: run_hg(options) finally: if commit_file and os.path.exists(commit_file): os.remove(commit_file) try: hg_tag_svn_rev(entry['revision']) except: # Rollback the transaction. last_rev = get_svn_rev_from_hg() if last_rev != entry['revision']: run_hg(["rollback"]) raise def hg_tag_svn_rev(rev_number): """ Put a local hg tag according to the SVN revision. """ run_hg(["tag", "-l", "svn.%d" % rev_number]) def get_svn_rev_from_hg(): """ Get the current SVN revision as reflected by the hg working copy, or None if no match found. """ tags = run_hg(['parents', '--template', '{tags}']).strip().split() revs = [int(tag[4:]) for tag in tags if tag.startswith('svn.')] # An hg changeset can map onto several SVN revisions, for example if a # revision only changed SVN properties. if revs: return max(revs) return None def fixup_hgsvn_dir(basedir='.'): """ Create the hgsvn directory if it does not exist. Useful when using repos created by a previous version. """ target = os.path.join(basedir, hgsvn_private_dir) if not os.path.exists(target): os.mkdir(target) def get_hgsvn_lock(basedir='.'): """ Get a lock using the hgsvn lock file. """ return _lock(os.path.join(basedir, hgsvn_private_dir, hgsvn_lock_file), timeout=0) def change_to_rootdir(): """Changes working directory to root of checkout. Raises HgSVNError if the current working directory isn't a Mercurial repository. """ try: root = run_hg(["root"]).strip() except ExternalCommandFailed, err: raise HgSVNError('No Mercurial repository found.') os.chdir(root) def hg_is_clean(current_branch): """Returns False if the local Mercurial repository has uncommitted changes.""" if run_hg(['st', '-mard'], output_is_locale_encoding=True).strip(): ui.status(("\nThe Mercurial working copy contains pending changes " "in branch '%s'!\n" "Please either commit or discard them before running " "'%s' again." % (current_branch, get_script_name())), level=ui.ERROR) return False return True def get_script_name(): """Helper to return the name of the command line script that was called.""" return os.path.basename(sys.argv[0]) def hg_switch_branch(current_branch, new_branch): """Safely switch the Mercurial branch. The function will only switch to new_branch iff there are no uncommitted changed in the current branch. True is returned if the switch was successful otherwise False. """ hg_branches = [l.split()[0] for l in run_hg(["branches"]).splitlines()] if new_branch in hg_branches: # We want to run "hg up -C" (to force changing branches) but we # don't want to erase uncommitted changes. if not hg_is_clean(current_branch): return False run_hg(['up', '-C', new_branch]) run_hg(["branch", new_branch]) return True def check_for_applied_patches(): """Check for applied mq patches. Returns ``True`` if any mq patches are applied, otherwise ``False``. """ try: out = run_hg(["qapplied"]) patches = [s.strip() for s in out.splitlines()] if len(patches) > 0: return True except ExternalCommandFailed, err: pass return False hgsvn-0.1.8/hgsvn/unittests/0000755000175000017500000000000011327011330014433 5ustar andiandihgsvn-0.1.8/hgsvn/unittests/test_hgclient.py0000644000175000017500000001357611305257161017667 0ustar andiandiimport locale import os import shutil import subprocess import tempfile import unittest from hgsvn.run import hgpushsvn class RepoTest(unittest.TestCase): def _run_cmd(self, cmd_args): p = subprocess.Popen(cmd_args) p.wait() def _write_file(self, fname, content, commit=False, added=False, msg='test'): f = open(os.path.join(self.repo_dir, fname), 'w') f.write(content) f.close() if added: self._run_cmd(['hg', 'add', fname]) if commit: self._run_cmd(['hg', 'commit', '-m', msg]) def _remove_file(self, fname, commit=False): self._run_cmd(['hg', 'rm', fname]) if commit: self._run_cmd(['hg', 'commit', '-m', 'test']) def _move_file(self, source, dest, commit=False): self._run_cmd(['hg', 'mv', source, dest]) if commit: self._run_cmd(['hg', 'commit', '-m', '"Copied %s -> %s"' % (source, dest)]) def setUp(self): self.repo_dir = tempfile.mkdtemp() self._currdir = os.getcwd() os.chdir(self.repo_dir) self._run_cmd(['hg', 'init']) self.test_file = os.path.join(self.repo_dir, 'foo') f = open(self.test_file, 'w') f.write('foo') f.close() self._run_cmd(['hg', 'add', 'foo']) self._run_cmd(['hg', 'commit', '-m', '"Initial."']) def tearDown(self): shutil.rmtree(self.repo_dir) os.chdir(self._currdir) class TestHgClient(RepoTest): def test_get_hg_cset(self): ret = hgpushsvn.get_hg_cset('tip') self.assert_(isinstance(ret, basestring)) self.assertEqual(ret, ret.strip()) self.assertEqual(ret.count(':'), 1) first, last = ret.split(':') self.assert_(first.isdigit()) self.assert_(last.isalnum()) def test_strip_hg_rev(self): self.assertEqual(hgpushsvn.strip_hg_rev('1:2'), '2') self.assertEqual(hgpushsvn.strip_hg_rev('1:2\n'), '2') def test_get_hg_changes(self): ret = hgpushsvn.get_hg_changes('tip') self.assert_(isinstance(ret, tuple)) self.assertEqual(len(ret), 4) added, removed, modified, copied = ret self.assert_(isinstance(added, list)) self.assert_(isinstance(removed, list)) self.assert_(isinstance(modified, list)) self.assert_(isinstance(copied, dict)) self.assertEqual(len(added), 0) self.assertEqual(len(removed), 0) self.assertEqual(len(modified), 0) self.assertEqual(len(copied), 0) rev1 = hgpushsvn.strip_hg_rev(hgpushsvn.get_hg_cset('tip')) self._write_file('foo', 'bar') self._write_file('bar', 'foo', commit=True, added=True) rev2 = hgpushsvn.strip_hg_rev(hgpushsvn.get_hg_cset('tip')) ret = hgpushsvn.get_hg_changes('%s:%s' % (rev1, rev2)) self.assert_(isinstance(ret, tuple)) self.assertEqual(len(ret), 4) added, removed, modified, copied = ret self.assert_(isinstance(added, list)) self.assert_(isinstance(removed, list)) self.assert_(isinstance(modified, list)) self.assertEqual(len(added), 1) self.assertEqual(len(removed), 0) self.assertEqual(len(modified), 1) rev1 = rev2 self._remove_file('bar', commit=True) rev2 = hgpushsvn.strip_hg_rev(hgpushsvn.get_hg_cset('tip')) ret = hgpushsvn.get_hg_changes('%s:%s' % (rev1, rev2)) self.assert_(isinstance(ret, tuple)) self.assertEqual(len(ret), 4) added, removed, modified, copied = ret self.assert_(isinstance(added, list)) self.assert_(isinstance(removed, list)) self.assert_(isinstance(modified, list)) self.assertEqual(len(added), 0) self.assertEqual(len(removed), 1) self.assertEqual(len(modified), 0) def test_moved_file(self): self._move_file('foo', 'bar') ret = hgpushsvn.get_hg_changes('tip') self.assert_(isinstance(ret, tuple)) self.assertEqual(len(ret), 4) added, removed, modified, copied = ret self.assertEqual(len(copied), 1) self.assertEqual(len(modified), 0) self.assertEqual(len(added), 0) self.assertEqual(len(removed), 1) def test_get_hg_revs(self): rev = hgpushsvn.strip_hg_rev(hgpushsvn.get_hg_cset('tip')) self._write_file('foo', 'bar', commit=True) rev2 = hgpushsvn.strip_hg_rev(hgpushsvn.get_hg_cset('tip')) revs = hgpushsvn.get_hg_revs(rev, 'default') self.assert_(isinstance(revs, list)) self.assertEqual(len(revs), 2) self.assertEqual(revs[0], rev) self.assertEqual(revs[1], rev2) self._write_file('foo', 'bar2', commit=True) revs = hgpushsvn.get_hg_revs(rev, 'default') self.assert_(isinstance(revs, list)) self.assertEqual(len(revs), 3) self.assertEqual(revs[0], rev) self.assertEqual(revs[1], rev2) # Change test file in different branch self._run_cmd(['hg', 'branch', 'testing']) self._write_file('foo', 'bar3', commit=True) revs = hgpushsvn.get_hg_revs(rev, 'default') self.assert_(isinstance(revs, list)) self.assertEqual(len(revs), 3) self.assertEqual(revs[0], rev) self.assertEqual(revs[1], rev2) def test_get_hg_cset_description(self): self._write_file('foo', 'bar', commit=True, msg='123') rev_raw = hgpushsvn.get_hg_cset('tip') rev = hgpushsvn.strip_hg_rev(rev_raw) ret = hgpushsvn.get_hg_cset_description(rev) self.assert_(isinstance(ret, basestring)) self.assertEqual(ret, '123') self._write_file('foo', 'bar', commit=True, msg=' 123\n') rev_raw = hgpushsvn.get_hg_cset('tip') rev = hgpushsvn.strip_hg_rev(rev_raw) ret = hgpushsvn.get_hg_cset_description(rev) self.assert_(isinstance(ret, basestring)) self.assertEqual(ret, '123') hgsvn-0.1.8/hgsvn/unittests/_test.py0000644000175000017500000000006311220567234016135 0ustar andiandifrom nose import SkipTest from nose.tools import * hgsvn-0.1.8/hgsvn/unittests/test_common.py0000644000175000017500000001003011225023521017330 0ustar andiandiimport os import shutil import tempfile from _test import * from hgsvn import common class TestCommands(object): def test_hg(self): s = common.run_hg(['version', '-q']) s = s.split()[0] eq_(s.lower(), 'mercurial') def test_svn(self): s = common.run_svn(['--version', '-q']) eq_(s.split('.')[0], '1') class CommandsBase(object): def test_echo(self): echo_string = 'foo' s = self.command_func('echo', [echo_string]) eq_(s.rstrip(), echo_string) def test_echo_with_escapes(self): echo_string = 'foo \n"\' baz' s = self.command_func('echo', [echo_string]) eq_(s.rstrip(), echo_string) def test_bulk_args(self): sep = '-' args = ['a', 'b', 'c'] n_args = len(args) bulk_args = ['%d' % i for i in xrange(3000)] out = self.command_func('echo', [sep] + args, bulk_args) sub_results = out.split(sep) eq_(sub_results.pop(0).strip(), "") bulk_pos = 0 for s in sub_results: l = s.split() eq_(l[:n_args], args) n_bulk = len(l) - n_args assert n_bulk < 256 eq_(l[n_args:], bulk_args[bulk_pos:bulk_pos + n_bulk]) bulk_pos += n_bulk eq_(bulk_pos, len(bulk_args)) class TestShellCommands(CommandsBase): command_func = staticmethod(common.run_shell_command) class TestNonShellCommands(CommandsBase): command_func = staticmethod(common.run_command) class TestLock(object): test_mercurial = True def setUp(self): if self.test_mercurial: try: from mercurial.lock import lock except ImportError: raise SkipTest # mercurial not installed self._test_base = tempfile.mkdtemp() common.fixup_hgsvn_dir(self._test_base) def tearDown(self): shutil.rmtree(self._test_base) def test_lock_set_release(self): def lock_exists(): private_dir = os.path.join(self._test_base, common.hgsvn_private_dir) return common.hgsvn_lock_file in os.listdir(private_dir) l = common.get_hgsvn_lock(self._test_base) lock_file = os.path.join(self._test_base, common.hgsvn_private_dir, common.hgsvn_lock_file) assert_true(lock_exists()) l.release() assert_false(lock_exists()) def test_locked(self): l = common.get_hgsvn_lock(self._test_base) assert_raises(common.LockHeld, common.get_hgsvn_lock, self._test_base) l.release() class TestSimpleFileLock(TestLock): test_mercurial = False def setUp(self): self._real_lock = common._lock self._real_lock_held = common.LockHeld common._lock = common._SimpleFileLock common.LockHeld = common._LockHeld super(TestSimpleFileLock, self).setUp() def tearDown(self): super(TestSimpleFileLock, self).tearDown() common._lock = self._real_lock common.LockHeld = self._real_lock_held class TestSwitchBranch(object): def setUp(self): self._wd = tempfile.mkdtemp() self._cwd = os.getcwd() os.chdir(self._wd) common.run_hg(["init"]) f = open("foo", "w") f.write("foo") f.close() common.run_hg(["add", "foo"]) common.run_hg(["commit", "-m", "Initial"]) def tearDown(self): os.chdir(self._cwd) shutil.rmtree(self._wd) def test_switch_clean_repo(self): common.run_hg(["branch", "test"]) f = open("bar", "w") f.write("bar") f.close() common.run_hg(["add", "bar"]) common.run_hg(["commit", "-m", '"bar added."']) eq_(True, common.hg_switch_branch("test", "default")) def test_switch_dirty_repo(self): common.run_hg(["branch", "test"]) f = open("bar", "w") f.write("bar") f.close() common.run_hg(["add", "bar"]) eq_(False, common.hg_switch_branch("test", "default")) hgsvn-0.1.8/hgsvn/unittests/__init__.py0000644000175000017500000000000011216610734016544 0ustar andiandihgsvn-0.1.8/hgsvn/unittests/test_svnclient.py0000644000175000017500000001773111254507724020102 0ustar andiandi from _test import * from hgsvn import svnclient import time def eq_utc_timestamp(timestamp, time_tuple): eq_(time.gmtime(timestamp)[:6], time_tuple) class TestSVNDate(object): """ Tests for SVN date handling. """ def test_parse(self): """ Parsing SVN dates. """ svn_date = "2007-05-01T18:33:32.749605Z" timestamp = svnclient.svn_date_to_timestamp(svn_date) eq_(timestamp, 1178044412) eq_utc_timestamp(timestamp, (2007, 5, 1, 18, 33, 32)) svn_info_xml = """ svn://svn.twistedmatrix.com/svn/Twisted/trunk svn://svn.twistedmatrix.com/svn/Twisted bbbe8e31-12d6-0310-92fd-ac37d47ddeeb ralphm 2007-05-04T10:47:32.843908Z """ svn_info_xml_rev0 = """ file:///home/foo/bar file:///home/foo/bar 936c9acc-016e-4cc8-a158-a434ae94e2dd 2009-09-17T19:21:13.394243Z """ class TestSVNInfo(object): """ Tests for handling SVN wc/repo information. """ def test_parse(self): """ Parsing the output of 'svn info --xml'. """ d = svnclient.parse_svn_info_xml(svn_info_xml) eq_(d['url'], 'svn://svn.twistedmatrix.com/svn/Twisted/trunk') eq_(d['repos_url'], 'svn://svn.twistedmatrix.com/svn/Twisted') eq_(d['revision'], 20191) eq_(d['last_changed_rev'], 20185) def test_parse_rev0(self): """ Parsing the output of 'svn info --xml' for revision 0. """ d = svnclient.parse_svn_info_xml(svn_info_xml_rev0) eq_(d['url'], 'file:///home/foo/bar') eq_(d['repos_url'], 'file:///home/foo/bar') eq_(d['revision'], 0) svn_log_xml = """ apitrou 2007-03-29T09:37:56.023608Z /hgsvn /scripts move dir to better-named location apitrou 2007-03-28T16:51:15.339713Z /scripts/hgimportsvn.py automatically detect a parent hg repo tracking the parent SVN branch, and pull from it. """ svn_log_xml_with_empty_msg = """ apitrou 2007-03-28T16:51:15.339713Z /scripts/hgimportsvn.py """ svn_log_xml_with_invalid_chars = ('' + '\n\n\nsynic\n' + '2006-11-08T19:56:30.120180Z\n' + 'fixed some plugin bugs===+=\x1f\x1f\x1f---\n\n\n\n') svn_log_xml_with_path_restricted = """ aalbrecht 2009-06-22T05:53:13.019086Z Added bar. aalbrecht 2009-06-22T05:52:54.418773Z Initial layout. """ class TestSVNLog(object): """ Tests for handling SVN logs. """ def test_parse(self): """ Parsing an SVN log in XML format. """ entries = svnclient.parse_svn_log_xml(svn_log_xml) eq_(len(entries), 2) e = entries[0] eq_(e['author'], 'apitrou') eq_(e['revision'], 1777) eq_utc_timestamp(e['date'], (2007, 3, 29, 9, 37, 56)) eq_(e['message'], "move dir to better-named location\n\n") paths = e['changed_paths'] eq_(len(paths), 2) p = paths[0] eq_(p, { 'path': '/hgsvn', 'action': 'A', 'copyfrom_path': '/scripts', 'copyfrom_revision': 1776, }) p = paths[1] eq_(p, { 'path': '/scripts', 'action': 'D', 'copyfrom_path': None, 'copyfrom_revision': None, }) e = entries[1] eq_(e['author'], 'apitrou') eq_(e['revision'], 1776) eq_utc_timestamp(e['date'], (2007, 3, 28, 16, 51, 15)) eq_(len(e['changed_paths']), 1) def test_parse_with_empty_msg(self): """ Parsing an SVN log entry with an empty commit message. """ entries = svnclient.parse_svn_log_xml(svn_log_xml_with_empty_msg) eq_(len(entries), 1) e = entries[0] eq_(e['message'], "") def test_parse_with_invalid_xml(self): """ Parsing an SVN log entry with invalid XML characters. """ entries = svnclient.parse_svn_log_xml(svn_log_xml_with_invalid_chars) eq_(len(entries), 1) msg = entries[0]['message'] assert msg.startswith('fixed some plugin bugs===+=') assert msg.strip().endswith('---') def test_parse_with_path_based_restrictions(self): # Stub log entries appear when there is path-based authentication # enabled on specific directories. entries = svnclient.parse_svn_log_xml(svn_log_xml_with_path_restricted) eq_(len(entries), 3) msg = entries[1]['message'] assert msg.startswith('Added bar.') keys = ('revision', 'author', 'date', 'message', 'changed_paths') eq_(set(keys), set(entries[0])) eq_([], entries[0]['changed_paths']) svn_status_xml = """ apitrou 2007-03-28T15:22:22.975800Z apitrou 2007-05-04T19:59:06.567367Z """ svn_status_xml_with_base_dir = """ """ class TestSVNStatus(object): """ Tests for handling status of an SVN working copy. """ def test_parse(self): """ Parsing the output of 'svn st --xml'. """ entries = svnclient.parse_svn_status_xml(svn_status_xml) eq_(len(entries), 4) e = entries[0] eq_(e['path'], '_doc.html') eq_(e['type'], 'unversioned') e = entries[1] eq_(e['path'], 'ez_setup') eq_(e['type'], 'external') e = entries[2] eq_(e['path'], 'hgcreatesvn.py') eq_(e['type'], 'normal') e = entries[3] eq_(e['path'], 'hgsvn/svnclient.py') eq_(e['type'], 'normal') def test_parse_with_base_dir(self): """ Parsing the output of 'svn st --xml' with an explicit base dir. """ entries = svnclient.parse_svn_status_xml( svn_status_xml_with_base_dir, '/home/antoine/hgsvn') eq_(len(entries), 1) e = entries[0] eq_(e['path'], 'build') eq_(e['type'], 'unversioned') def test_get_svn_client_version(): version = svnclient.get_svn_client_version() assert_true(isinstance(version, tuple)) assert_true(len(version) >= 2) for part in version: assert_true(isinstance(part, int)) eq_(version[0], 1) hgsvn-0.1.8/hgsvn/run/0000755000175000017500000000000011327011330013175 5ustar andiandihgsvn-0.1.8/hgsvn/run/common.py0000644000175000017500000000566711302034544015062 0ustar andiandi from hgsvn import base_version, full_version, ui from hgsvn.common import change_to_rootdir, fixup_hgsvn_dir, get_hgsvn_lock, LockHeld from hgsvn.errors import HgSVNError import sys import os from optparse import SUPPRESS_HELP copyright_message = """\ Copyright (C) 2007 Antoine Pitrou. Copyright (C) 2009 Andi Albrecht. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Written by Antoine Pitrou and Andi Albrecht. """ def run_parser(parser, long_help=""): """ Add common options to an OptionParser instance, and run parsing. A hidden option is added to ease man page production with the help2man tool. For example, the following produces a (rather terse) man page for hgpullsvn: $ help2man -N "hgpullsvn --help2man" -o man1/hgpullsvn.1 """ parser.add_option("", "--version", dest="show_version", action="store_true", help="show version and exit") parser.add_option("", "--help2man", dest="help2man", action="store_true", help=SUPPRESS_HELP) parser.remove_option("--help") parser.add_option("-h", "--help", dest="show_help", action="store_true", help="show this help message and exit") parser.add_option("-v", "--verbose", dest="verbosity", const=20, default=10, action="store_const", help="enable additional output") parser.add_option("--debug", dest="verbosity", const=30, action="store_const", help="enable debugging output") options, args = parser.parse_args() if options.show_help: if options.help2man and long_help: print long_help print parser.print_help() sys.exit(0) if options.show_version: prog_name = os.path.basename(sys.argv[0]) if options.help2man: print prog_name, base_version print print copyright_message else: print prog_name, full_version sys.exit(0) ui.update_config(options) return options, args def display_parser_error(parser, message): """ Display an options error, and terminate. """ print "error:", message print parser.print_help() sys.exit(1) def locked_main(real_main, *args, **kwds): """Wrapper for main() functions, that takes care of .hgsvn/lock.""" # Make sure that we work in the checkout's top-level directory (issue3). try: change_to_rootdir() except HgSVNError, err: sys.stderr.write("%s\n" % err) return 1 # We must do this before trying to take the lock file fixup_hgsvn_dir('.') try: l = get_hgsvn_lock() except LockHeld, e: print "Aborting:", e return 1 try: return real_main(*args, **kwds) finally: l.release() hgsvn-0.1.8/hgsvn/run/hgpushsvn.py0000644000175000017500000003777511327005234015625 0ustar andiandi"""hgpushsvn must be run in a repository created by hgimportsvn. It pushes local Mercurial changesets one by one or optionally collapsed into a single commit back to the SVN repository. """ import codecs import os import stat import sys import re from optparse import OptionParser from hgsvn import ui from hgsvn.common import ( run_hg, run_svn, hg_switch_branch, hgsvn_private_dir, check_for_applied_patches, ) from hgsvn.errors import ExternalCommandFailed, EmptySVNLog from hgsvn.run.common import run_parser, display_parser_error from hgsvn.run.common import locked_main from hgsvn.svnclient import get_svn_info, get_svn_status def map_svn_rev_to_hg(svn_rev, hg_rev="tip", local=False): """ Record the mapping from an SVN revision number and an hg revision (default "tip"). """ args = ["tag"] if local: args.append("-l") args.extend(["-r", strip_hg_rev(hg_rev), "svn.%d" % svn_rev]) run_hg(args) def strip_hg_rev(rev_string): """ Given a string identifying an hg revision, return a string identifying the same hg revision and suitable for revrange syntax (r1:r2). """ if ":" in rev_string: return rev_string.rsplit(":", 1)[1].strip() return rev_string.strip() def get_hg_cset(rev_string): """ Given a string identifying an hg revision, get the canonical changeset ID. """ args = ["log", "--template", "{rev}:{node|short}\n", "-r", rev_string] return run_hg(args).strip() def get_hg_revs(first_rev, svn_branch, last_rev="tip"): """ Get a chronological list of revisions (changeset IDs) between the two revisions (included). """ args = ["log", "--template", '{rev}:{node|short}\n', "-b", svn_branch, '--limit', '1000', "-r", "%s:%s" % (strip_hg_rev(first_rev), strip_hg_rev(last_rev))] out = run_hg(args) return [strip_hg_rev(s) for s in out.splitlines()] def get_pairs(l): """ Given a list, return a list of consecutive pairs of values. """ return [(l[i], l[i+1]) for i in xrange(len(l) - 1)] def get_hg_changes(rev_string): """ Get paths of changed files from a previous revision. Returns a tuple of (added files, removed files, modified files, copied files) Copied files are dict of (dest=>src), others are lists. """ args = ["st", "-armC", "--rev", rev_string] out = run_hg(args, output_is_locale_encoding=True) added = [] removed = [] modified = [] copied = {} skipnext = False for line in out.splitlines(): st = line[0] path = line[2:] if st == 'A': added.append(path) lastadded=path elif st == 'R': removed.append(path) elif st == 'M': modified.append(path) elif st == ' ': added.remove(lastadded) copied[lastadded] = path #print "added:", added #print "removed:", removed #print "modified:", modified return added, removed, modified, copied def get_ordered_dirs(l): """ Given a list of relative file paths, return an ordered list of dirs such that creating those dirs creates the directory structure necessary to hold those files. """ dirs = set() for path in l: while True: path = os.path.dirname(path) if not path or path in dirs: break dirs.add(path) return list(sorted(dirs)) def get_hg_csets_description(start_rev, end_rev): """Get description of a given changeset range.""" return run_hg(["log", "--template", "{desc|strip}\n", "--rev", start_rev+":"+end_rev, "--prune", start_rev]) def get_hg_cset_description(rev_string): """Get description of a given changeset.""" return run_hg(["log", "--template", "{desc|strip}", "-r", rev_string]) def get_hg_log(start_rev, end_rev): """Get log messages for given changeset range.""" log_args=["log", "--verbose", "--rev", start_rev+":"+end_rev, "--prune", start_rev] return run_hg(log_args) def get_svn_subdirs(top_dir): """ Given the top directory of a working copy, get the list of subdirectories (relative to the top directory) tracked by SVN. """ subdirs = [] def _walk_subdir(d): svn_dir = os.path.join(top_dir, d, ".svn") if os.path.exists(svn_dir) and os.path.isdir(svn_dir): subdirs.append(d) for f in os.listdir(os.path.join(top_dir, d)): d2 = os.path.join(d, f) if f != ".svn" and os.path.isdir(os.path.join(top_dir, d2)): _walk_subdir(d2) _walk_subdir(".") return subdirs def strip_nested_removes(targets): """Strip files within removed folders and return a cleaned up list.""" # We're going a safe way here: "svn info" fails on items within removed # dirs. clean_targets = [] for target in targets: try: run_svn(['info', '--xml', target]) except ExternalCommandFailed, err: ui.status(str(err), level=ui.DEBUG) continue clean_targets.append(target) return clean_targets def cleanup_svn_unversioned(files): svn_status = get_svn_status(".") for entry in svn_status: if(entry['type'] == 'unversioned') and entry['path'] in files: files.remove(entry['path']) return files def adjust_executable_property(files): execflags = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH svn_map = {} for fname in files: if run_svn(['propget', 'svn:executable', fname]).strip(): svn_map[fname] = True else: svn_map[fname] = False for fname in files: m = os.stat(fname).st_mode & 0777 is_exec = bool(m & execflags) if is_exec and not svn_map[fname]: run_svn(['propset', 'svn:executable', 'ON', fname]) elif not is_exec and svn_map[fname]: run_svn(['propdel', 'svn:executable', fname]) def do_svn_copy(src, dest): """ Call Svn copy command to record copying file src to file dest. If src is present then backup src before other tasks. Before issuing copy command move dest to src and remove src after """ backup_src = '' if os.path.exists(src): backup_src = os.path.join(hgsvn_private_dir, "hgpushsvn_backup.tmp") os.rename(src, backup_src) try: try: # We assume that src is cotrolled by svn os.rename(dest, src) # Create svn subdirectories if needed # We know that subdirectories themselves are present # as dest is present pos = 0 while(True): pos = dest.find('/', pos + 1) if pos == -1: break run_svn(['add'], [dest[:pos]]) # Do the copy itself run_svn(['copy', src, dest]) except ExternalCommandFailed: # Revert rename os.rename(src, dest) finally: if os.path.isfile(src): os.remove(src) if(backup_src): os.rename(backup_src, src) def hg_push_svn(start_rev, end_rev, edit): """ Commit the changes between two hg revisions into the SVN repository. Returns the SVN revision object, or None if nothing needed checking in. """ added, removed, modified, copied = get_hg_changes(start_rev+':'+end_rev) # Before replicating changes revert directory to previous state... run_hg(['revert', '--all', '--no-backup']) # ... and restore .svn directories, if we lost some of them due to removes run_svn(['revert', '--recursive', '.']) # Record copyies into svn for dest, src in copied.iteritems(): do_svn_copy(src,dest) # As copies are recorded we can do the rest over up-to-date working copy run_hg(["up", "-C", end_rev]) # Add new files and dirs if added: bulk_args = get_ordered_dirs(added) + added run_svn(["add"], bulk_args) removed = cleanup_svn_unversioned(removed) modified = cleanup_svn_unversioned(modified) # Remove old files and empty dirs if removed: empty_dirs = [d for d in reversed(get_ordered_dirs(removed)) if not run_hg(["st", "-c", "%s" %d])] # When running "svn rm" all files within removed folders needs to # be removed from "removed". Otherwise "svn rm" will fail. For example # instead of "svn rm foo/bar foo" it should be "svn rm foo". # See issue15. svn_removed = strip_nested_removes(removed + empty_dirs) run_svn(["rm"], svn_removed) if added or removed or modified: svn_sep_line = "--This line, and those below, will be ignored--\n" adjust_executable_property(added+modified) # issue24 description = get_hg_csets_description(start_rev, end_rev) fname = os.path.join(hgsvn_private_dir, 'commit-%s.txt' % end_rev) lines = description.splitlines()+[""] lines.append(svn_sep_line) lines.append("To cancel commit just delete text in top message part") lines.append("") lines.append("Changes to be committed into svn:") lines.extend(run_svn(["st", "-q"]).splitlines()) lines.append("") lines.append(("These changes are produced from the following " "Hg changesets:")) lines.extend(get_hg_log(start_rev, end_rev).splitlines()) f = codecs.open(fname, "wb", "utf-8") f.write(os.linesep.join(lines)) f.close() try: if edit: editor=(os.environ.get("HGEDITOR") or os.environ.get("SVNEDITOR") or os.environ.get("VISUAL") or os.environ.get("EDITOR", "vi")) rc = os.system("%s \"%s\"" % (editor, fname) ) if(rc): raise ExternalCommandFailed("Can't launch editor") empty = True f=open(fname, "r") for line in f: if(line == svn_sep_line): break if(line.strip() != ""): empty = False break f.close() if(empty): raise EmptySVNLog("Commit cancelled by user\n") svn_rev = None old_lc_all = os.getenv('LC_ALL') os.environ['LC_ALL'] = 'C' try: out = run_svn(["commit", "-F", fname]) finally: if old_lc_all: os.environ['LC_ALL'] = old_lc_all else: del os.environ['LC_ALL'] for line in out.splitlines(): match = re.search("^Committed revision (\d*)", line) if match: svn_rev = int(match.group(1)) break return svn_rev finally: # Exceptions are handled by main(). os.remove(fname) else: print "*", "svn: nothing to do" return None def real_main(options, args): if run_hg(["st", "-m"]): print ("There are uncommitted changes. Either commit them or put " "them aside before running hgpushsvn.") return 1 if check_for_applied_patches(): print ("There are applied mq patches. Put them aside before " "running hgpsuhsvn.") return 1 svn_info = get_svn_info(".") svn_current_rev = svn_info["last_changed_rev"] # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted' repos_url = svn_info["repos_url"] # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted/branches/xmpp-subprotocols-2178-2' wc_url = svn_info["url"] assert wc_url.startswith(repos_url) # e.g. u'/branches/xmpp-subprotocols-2178-2' wc_base = wc_url[len(repos_url):] svn_branch = wc_url.split("/")[-1] # Get remote SVN info svn_greatest_rev = get_svn_info(wc_url)['last_changed_rev'] if svn_greatest_rev != svn_current_rev: # We can't go on if the pristine branch isn't up to date. # If the pristine branch lacks some revisions from SVN we are not # able to pull them afterwards. # For example, if the last SVN revision in out hgsvn repository is # r100 and the latest SVN revision is r101, hgpushsvn would create # a tag svn.102 on top of svn.100, but svn.101 isn't in hg history. print ("Branch '%s' out of date. Run 'hgpullsvn' first." % svn_branch) return 1 # Switch branches if necessary. orig_branch = run_hg(["branch"]).strip() if orig_branch != svn_branch: if not hg_switch_branch(orig_branch, svn_branch): return 1 hg_start_rev = "svn.%d" % svn_current_rev hg_revs = None try: hg_start_cset = get_hg_cset(hg_start_rev) except RuntimeError: if not options.force: raise hg_start_cset = get_hg_cset("0") print "Warning: revision '%s' not found, forcing to first rev '%s'" % ( hg_start_rev, hg_start_cset) else: if not options.collapse: hg_revs = get_hg_revs(hg_start_cset, svn_branch) if hg_revs is None: hg_revs = [strip_hg_rev(hg_start_cset), strip_hg_rev(get_hg_cset("tip"))] pushed_svn_revs = [] try: if options.dryrun: print "Outgoing revisions that would be pushed to SVN:" try: for prev_rev, next_rev in get_pairs(hg_revs): if not options.dryrun: if not options.edit: ui.status("Committing changes up to revision %s", get_hg_cset(next_rev)) svn_rev = hg_push_svn(prev_rev, next_rev, edit=options.edit) if svn_rev: map_svn_rev_to_hg(svn_rev, next_rev, local=True) pushed_svn_revs.append(svn_rev) else: print run_hg(["log", "-r", next_rev, "--template", "{rev}:{node|short} {desc}"]) except: # TODO: Add --no-backup to leave a "clean" repo behind if something # fails? run_hg(["revert", "--all"]) raise finally: work_branch = orig_branch or svn_branch if work_branch != svn_branch: run_hg(["up", "-C", work_branch]) run_hg(["branch", work_branch]) if pushed_svn_revs: if len(pushed_svn_revs) == 1: msg = "Pushed one revision to SVN: " else: msg = "Pushed %d revisions to SVN: " % len(pushed_svn_revs) run_svn(["up"]) ui.status("%s %s", msg, ", ".join(str(x) for x in pushed_svn_revs)) for line in run_hg(["st"]).splitlines(): if line.startswith("M"): ui.status(("Mercurial repository has local changes after " "SVN update.")) ui.status(("This may happen with SVN keyword expansions.")) break elif not options.dryrun: ui.status("Nothing to do.") def main(): # Defined as entry point. Must be callable without arguments. usage = "usage: %prog [-cf]" parser = OptionParser(usage) parser.add_option("-f", "--force", default=False, action="store_true", dest="force", help="push even if no hg tag found for current SVN rev.") parser.add_option("-c", "--collapse", default=False, action="store_true", dest="collapse", help="collapse all hg changesets in a single SVN commit") parser.add_option("-n", "--dry-run", default=False, action="store_true", dest="dryrun", help="show outgoing changes to SVN without pushing them") parser.add_option("-e", "--edit", default=False, action="store_true", dest="edit", help="edit commit message using external editor") (options, args) = run_parser(parser, __doc__) if args: display_parser_error(parser, "incorrect number of arguments") return locked_main(real_main, options, args) if __name__ == "__main__": sys.exit(main() or 0) hgsvn-0.1.8/hgsvn/run/hgpullsvn.py0000644000175000017500000003145211327001345015603 0ustar andiandi"""hgpullsvn must be run in a repository created by hgimportsvn. It pulls new revisions one by one from the SVN repository and converts them into local Mercurial changesets. """ from hgsvn import ui from hgsvn.common import ( run_hg, run_svn, hg_commit_from_svn_log_entry, hg_exclude_options, get_svn_rev_from_hg, hg_switch_branch, hg_is_clean, check_for_applied_patches, ) from hgsvn.svnclient import ( get_svn_info, get_svn_versioned_files, iter_svn_log_entries, run_svn_log, get_svn_client_version, get_svn_status ) from hgsvn.errors import ( ExternalCommandFailed, OverwrittenSVNBranch, UnsupportedSVNAction, ) from hgsvn.run.common import run_parser, display_parser_error from hgsvn.run.common import locked_main import sys import os import time import traceback from optparse import OptionParser """ NOTE: interesting tests: * http://svn.python.org/projects/python/trunk/Mac : - files with space characters in them just before 45000 - file and dir renames/removes between 46701 and 46723 """ # TODO: an option to enable/disable svn:externals (disabled by default?) def detect_overwritten_svn_branch(wc_url, svn_rev): """ Detect whether the current SVN branch was in a different location at the given revision. This means the current branch was later overwritten by another one. """ remote_url = get_svn_info(wc_url, svn_rev)['url'] if remote_url != wc_url: msg = ("The current branch (%s) has been\noverwritten with contents from %s.\n" + "hgsvn is unable to fetch history of the original branch.\n" + "Also, you will have to do a separate 'hgsvnimport' to pull recent history.\n" ) % (wc_url, remote_url) raise OverwrittenSVNBranch(msg) def pull_svn_rev(log_entry, current_rev, svn_wc, wc_url, wc_base): """ Pull SVN changes from the given log entry. Returns the new SVN revision. If an exception occurs, it will rollback to revision 'current_rev'. """ svn_rev = log_entry['revision'] added_paths = [] copied_paths = [] removed_paths = [] changed_paths = [] unrelated_paths = [] replaced_paths = {} for d in log_entry['changed_paths']: # e.g. u'/branches/xmpp-subprotocols-2178-2/twisted/words/test/test_jabberxmlstream.py' p = d['path'] if not p.startswith(wc_base + "/"): # Ignore changed files that are not part of this subdir if p != wc_base: unrelated_paths.append(p) continue action = d['action'] if action not in 'MARD': raise UnsupportedSVNAction("In SVN rev. %d: action '%s' not supported. Please report a bug!" % (svn_rev, action)) # e.g. u'twisted/words/test/test_jabberxmlstream.py' p = p[len(wc_base):].strip("/") # Record for commit changed_paths.append(p) # Detect special cases old_p = d['copyfrom_path'] if old_p and old_p.startswith(wc_base + "/"): old_p = old_p[len(wc_base):].strip("/") # Both paths can be identical if copied from an old rev. # We treat like it a normal change. if old_p != p: # Try to hint hg about file and dir copies if not os.path.isdir(old_p): copied_paths.append((old_p, p)) if action == 'R': removed_paths.append(old_p) else: # Extract actual copied files (hg doesn't track dirs # and will refuse "hg copy -A" with dirs) r = run_hg(["st", "-nc"], [old_p], output_is_locale_encoding=True) for old_f in r.splitlines(): f = p + old_f[len(old_p):] copied_paths.append((old_f, f)) if action == 'R': removed_paths.append(old_f) continue if d['action'] == 'A': added_paths.append(p) elif d['action'] == 'D': removed_paths.append(p) elif d['action'] == 'R': # (R)eplaced directories can have added and removed files without # them being mentioned in the SVN log => we must detect those files # ourselves. # (http://svn.python.org/projects/python/branches/py3k, rev 59625) if os.path.isdir(p): replaced_paths[p] = get_svn_versioned_files( os.path.join(svn_wc, p)) else: # We never know what twisty semantics (R) can have. addremove # is safest. added_paths.append(p) # Update SVN + add/remove/commit hg try: if changed_paths: args = ["up", "--ignore-externals"] if get_svn_client_version() >= (1, 5): args.extend(['--accept', 'postpone']) run_svn(args + ["-r", svn_rev, svn_wc]) conflicts = [] for status_entry in get_svn_status('.'): if status_entry['status'] == 'conflicted': conflicts.append(status_entry['path']) if conflicts: ui.status('SVN updated resulted in conflicts!', level=ui.ERROR) ui.status('Conflicted files: %s', ','.join(conflicts)) ui.status('Please report a bug.') return None for p, old_contents in replaced_paths.items(): old_contents = set(old_contents) new_contents = set(get_svn_versioned_files( os.path.join(svn_wc, p))) added_paths.extend(p + '/' + f for f in new_contents - old_contents) removed_paths.extend(p + '/' + f for f in old_contents - new_contents) if added_paths: # Use 'addremove' because an added SVN directory may # overwrite a previous directory with the same name. # XXX what about untracked files in those directories? run_hg(["addremove"] + hg_exclude_options, added_paths) for old, new in copied_paths: try: run_hg(["copy", "-A"], [old, new]) except ExternalCommandFailed: # Maybe the "old" path is obsolete, i.e. it comes from an # old SVN revision and was later removed. s = run_hg(['st', '-nd'], [old], output_is_locale_encoding=True) if s.strip(): # The old path is known by hg, something else happened. raise run_hg(["add"], [new]) if removed_paths: run_hg(["remove", "-A"], removed_paths) hg_commit_from_svn_log_entry(log_entry) elif unrelated_paths: detect_overwritten_svn_branch(wc_url, svn_rev) # NOTE: in Python 2.5, KeyboardInterrupt isn't a subclass of Exception anymore except (Exception, KeyboardInterrupt), e: ui.status("\nInterrupted, please wait for cleanup!\n", level=ui.ERROR) # NOTE: at this point, running SVN sometimes gives "write lock failures" # which leave the WC in a weird state. time.sleep(0.3) run_svn(["cleanup"]) hgsvn_rev = get_svn_rev_from_hg() if hgsvn_rev != svn_rev: # Unless the tag is there, revert to the last stable state run_svn(["up", "--ignore-externals", "-r", current_rev, svn_wc]) run_hg(["revert", "--all"]) raise return svn_rev def real_main(options, args): if check_for_applied_patches(): print ("There are applied mq patches. Put them aside before " "running hgpsuhsvn.") return 1 svn_wc = "." svn_peg_wc = svn_wc if options.svn_peg: svn_peg_wc += "@" + str(options.svn_peg) # Get SVN info svn_info = get_svn_info('.') current_rev = svn_info['revision'] next_rev = current_rev + 1 # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted' repos_url = svn_info['repos_url'] # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted/branches/xmpp-subprotocols-2178-2' wc_url = svn_info['url'] if options.svn_peg: svn_peg_wc = wc_url + "@" + str(options.svn_peg) assert wc_url.startswith(repos_url) # e.g. u'/branches/xmpp-subprotocols-2178-2' wc_base = wc_url[len(repos_url):] # e.g. 'xmpp-subprotocols-2178-2' svn_branch = wc_url.split("/")[-1] if options.svn_peg: wc_url += "@" + str(options.svn_peg) # Get remote SVN info ui.status("Retrieving remote SVN info...", level=ui.VERBOSE) svn_greatest_rev = get_svn_info(wc_url)['last_changed_rev'] if svn_greatest_rev < next_rev: ui.status("No revisions after %s in SVN repo, nothing to do", svn_greatest_rev) return # Show incoming changes if in dry-run mode. if options.dryrun: ui.status("Incoming SVN revisions:") for entry in run_svn_log(repos_url, next_rev, svn_greatest_rev, 100): if entry["message"]: msg = entry["message"].splitlines()[0].strip() else: msg = "" line = "[%d] %s (%s)" % (entry["revision"], msg, entry["author"]) # TODO: Line stripping should be done by some simple UI interface. if len(line) > 79: line = line[:77]+"..." ui.status(line) return # Prepare and/or switch named branches orig_branch = run_hg(["branch"]).strip() if orig_branch != svn_branch: # Update to or create the "pristine" branch if not hg_switch_branch(orig_branch, svn_branch): return 1 elif not hg_is_clean(svn_branch): return 1 # Detect that a previously aborted hgpullsvn retrieved an SVN revision # without committing it to hg. # If there is no SVN tag in current head, we may have been interrupted # during the previous "hg tag". hgsvn_rev = get_svn_rev_from_hg() if hgsvn_rev is not None and hgsvn_rev != current_rev: ui.status(("\nNote: hgsvn repository is in an unclean state " "(probably because of an aborted hgpullsvn). \n" "Let's first update to the last good SVN rev."), level=ui.VERBOSE) run_svn(["revert", "-R", "."]) run_svn(["up", "--ignore-externals", "-r", hgsvn_rev, svn_wc]) next_rev = hgsvn_rev + 1 # Reset working branch to last svn head to have a clean and linear SVN # histoy. heads_before = None if hgsvn_rev is None: heads_before = run_hg(["heads", "--template", "{node}%s" % os.linesep]).splitlines() run_hg(["update", "-C", "svn.%d" % current_rev]) # Load SVN log starting from current rev it_log_entries = iter_svn_log_entries(svn_peg_wc, next_rev, svn_greatest_rev) try: try: for log_entry in it_log_entries: current_rev = pull_svn_rev(log_entry, current_rev, svn_wc, wc_url, wc_base) if current_rev is None: return 1 ui.status("Pulled r%d %s (%s)", log_entry["revision"], log_entry["message"], log_entry["author"]) # TODO: detect externals with "svn status" and update them as well finally: if heads_before is not None: # we have reset the SVN branch heads_now = run_hg(["heads", "--template", "{node}%s" % os.linesep]).splitlines() if len(heads_now) != len(heads_before): ui.status("created new head in branch '%s'", svn_branch) work_branch = orig_branch or svn_branch if work_branch != svn_branch: run_hg(["up", '-C', work_branch]) run_hg(["branch", work_branch]) except KeyboardInterrupt: ui.status("\nStopped by user.", level=ui.ERROR) except ExternalCommandFailed, e: ui.status(str(e), level=ui.ERROR) except: ui.status("\nCommand failed with following error:\n", level=ui.ERROR) traceback.print_exc() def main(): # Defined as entry point. Must be callable without arguments. usage = "usage: %prog [-p SVN peg rev] [--help]" parser = OptionParser(usage) parser.add_option("-p", "--svn-peg", type="int", dest="svn_peg", help="SVN peg revision to locate checkout URL") parser.add_option("-n", "--dry-run", dest="dryrun", default=False, action="store_true", help="show incoming changesets without pulling them") (options, args) = run_parser(parser, __doc__) if args: display_parser_error(parser, "incorrect number of arguments") return locked_main(real_main, options, args) if __name__ == "__main__": sys.exit(main() or 0) hgsvn-0.1.8/hgsvn/run/__init__.py0000644000175000017500000000000011216610734015306 0ustar andiandihgsvn-0.1.8/hgsvn/run/hgimportsvn.py0000644000175000017500000002527411326767340016163 0ustar andiandi"""hgimportsvn checks out the given Subversion URL, either from the specified revision or from the first revision in the branch. The SVN checkout is then augmented with a Mercurial repository containing the same files. The SVN checkout and the Mercurial repository are created either in the specified directory, or in a directory named after the last component of the SVN URL (for example 'trunk'). """ from hgsvn.common import ( run_hg, run_svn, skip_dirs, rmtree, hg_commit_from_svn_log_entry, hg_exclude_options, svn_private_dir, hgsvn_private_dir, fixup_hgsvn_dir, ) from hgsvn.svnclient import ( get_first_svn_log_entry, get_last_svn_log_entry, get_svn_info, get_svn_status, svn_checkout, get_svn_versioned_files, ) from hgsvn.run.common import run_parser, display_parser_error import sys import os import tempfile import urllib # for unquoting URLs from itertools import chain from optparse import OptionParser # XXX add an option to enable/disable svn:externals? def main(): usage = """%prog [-r SVN rev] [-p SVN peg rev] [local checkout] %prog --local-only """ parser = OptionParser(usage) parser.add_option("-r", "--svn-rev", type="int", dest="svn_rev", help="SVN revision to checkout from") parser.add_option("-p", "--svn-peg", type="int", dest="svn_peg", help="SVN peg revision to locate checkout URL") parser.add_option("--no-hgignore", dest="hgignore", action="store_false", default=True, help="Don't autogenerate .hgignore") parser.add_option("--local-only", action="store_true", default=False, help="Don't use the server, just build from a local checkout") (options, args) = run_parser(parser, __doc__) if not 1 <= len(args) <= 2: display_parser_error(parser, "incorrect number of arguments") target_svn_url = args.pop(0).rstrip("/") local_repo = args and args.pop(0) or None if options.svn_peg: target_svn_url += "@" + str(options.svn_peg) if options.local_only: if options.svn_peg: display_parser_error(parser, "--local-only and --svn-peg are mutually exclusive") if options.svn_rev: display_parser_error(parser, "--local-only and --svn-rev are mutually exclusive") if local_repo: display_parser_error(parser, "--local-only does not accept a target directory") # Get SVN info svn_info = get_svn_info(target_svn_url, options.svn_rev) # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted' repos_url = svn_info['repos_url'] # e.g. u'svn://svn.twistedmatrix.com/svn/Twisted/branches/xmpp-subprotocols-2178-2' actual_svn_url = svn_info['url'] assert actual_svn_url.startswith(repos_url) # if we are allowed to go to the server, lets use it if options.local_only: target_svn_url = os.path.abspath(target_svn_url) local_repo = target_svn_url # e.g. u'/branches/xmpp-subprotocols-2178-2' svn_path = actual_svn_url[len(repos_url):] # e.g. 'xmpp-subprotocols-2178-2' svn_branch = actual_svn_url.split("/")[-1] svn_greatest_rev = svn_info['last_changed_rev'] if options.svn_peg: actual_svn_url += "@" + str(options.svn_peg) if not local_repo: local_repo = svn_branch if os.path.exists(local_repo): if not os.path.isdir(local_repo): raise ValueError("%s is not a directory" % local_repo) is_svn_dir = os.path.isdir(os.path.join(local_repo, '.svn')) if is_svn_dir and not options.local_only: nlocal_repo = os.path.abspath(local_repo) print "%s is already a SVN checkout." % nlocal_repo sys.exit(1) elif not is_svn_dir and options.local_only: nlocal_repo = os.path.abspath(local_repo) print "%s must be a SVN checkout for --local-only" % nlocal_repo sys.exit(1) elif options.local_only and is_svn_dir: status = get_svn_status(local_repo, quiet=True) if status: print ("There are uncommitted changes. Either commit them " "or put them aside before running hgimportsvn.") sys.exit(1) else: os.mkdir(local_repo) fixup_hgsvn_dir(local_repo) os.chdir(local_repo) # Get log entry for the SVN revision we will check out svn_copyfrom_path = None svn_copyfrom_revision = None if options.local_only or svn_greatest_rev == 0: # fake up a log message for the initial commit svn_start_log = {} svn_start_log['message'] = 'initial import by hgimportsvn' svn_start_log['revision'] = svn_info['last_changed_rev'] svn_start_log['author'] = svn_info.get('last_changed_author') svn_start_log['date'] = svn_info['last_changed_date'] elif options.svn_rev: # If a specific rev was requested, get log entry just before or at rev svn_start_log = get_last_svn_log_entry(actual_svn_url, 1, options.svn_rev) else: # Otherwise, get log entry of branch creation svn_start_log = get_first_svn_log_entry(actual_svn_url, 1, svn_greatest_rev) for p in svn_start_log['changed_paths']: if p['path'] == svn_path: svn_copyfrom_path = p['copyfrom_path'] svn_copyfrom_revision = p['copyfrom_revision'] break if svn_copyfrom_path: print "SVN branch was copied from '%s' at rev %s" % ( svn_copyfrom_path, svn_copyfrom_revision) else: print "SVN branch isn't a copy" # This is the revision we will checkout from svn_rev = svn_start_log['revision'] # Initialize hg repo if not os.path.exists(".hg"): run_hg(["init"]) if svn_copyfrom_path: # Try to find an hg repo tracking the SVN branch which was copied copyfrom_branch = svn_copyfrom_path.split("/")[-1] hg_copyfrom = os.path.join("..", copyfrom_branch) if (os.path.exists(os.path.join(hg_copyfrom, ".hg")) and os.path.exists(os.path.join(hg_copyfrom, svn_private_dir))): u = get_svn_info(hg_copyfrom)['url'] if u != repos_url + svn_copyfrom_path: print "SVN URL %s in working copy %s doesn't match, ignoring" % (u, hg_copyfrom) else: # Find closest hg tag before requested SVN rev best_tag = None for line in run_hg(["tags", "-R", hg_copyfrom]).splitlines(): if not line.startswith("svn."): continue tag = line.split(None, 1)[0] tag_num = int(tag.split(".")[1]) if tag_num <= svn_copyfrom_revision and (not best_tag or best_tag < tag_num): best_tag = tag_num if not best_tag: print "No hg tag matching rev %s in %s" % (svn_rev, hg_copyfrom) else: # Don't use "pull -u" because it fails with hg 0.9.5 # ("branch default not found") run_hg(["pull", "-r", "svn.%d" % best_tag, hg_copyfrom]) # Not specifying "tip" fails with hg 0.9.5 # ("branch default not found") run_hg(["up", "tip"]) run_hg(["branch", svn_branch]) # Stay on the same filesystem so as to have fast moves if options.local_only: checkout_dir = target_svn_url else: checkout_dir = tempfile.mkdtemp(dir=".") try: # Get SVN manifest and checkout if not options.local_only: svn_checkout(target_svn_url, checkout_dir, svn_rev) svn_manifest = get_svn_versioned_files(checkout_dir) svn_files = set(skip_dirs(svn_manifest, checkout_dir)) svn_dirs = sorted(set(svn_manifest) - svn_files) svn_files = list(svn_files) # in the local case the files here already if not options.local_only: # All directories must exist, including empty ones # (both for hg and for moving .svn dirs later) for d in svn_dirs: if not os.path.isdir(d): if os.path.exists(d): os.remove(d) os.mkdir(d) # Replace checked out files for f in svn_files: if os.path.exists(f): os.remove(f) os.rename(os.path.join(checkout_dir, f), f) try: # Add/remove new/old files if svn_files: run_hg(["addremove"] + hg_exclude_options, svn_files) hg_commit_from_svn_log_entry(svn_start_log) #hg_commit_from_svn_log_entry(svn_start_log, svn_files) except: run_hg(["revert", "--all"]) raise # in the local case the files here already if not options.local_only: # Move SVN working copy here (don't forget base directory) for d in chain([""], svn_dirs): os.rename(os.path.join(checkout_dir, d, svn_private_dir), os.path.join(d, svn_private_dir)) finally: # in the local case the checkout_dir is the target, so don't delete it if not options.local_only: rmtree(checkout_dir) if options.hgignore: svn_ignores = [] # we use '.' because that it the location of the hg repo that we are # building and at this point we have already copied all of svn to the # checkout (for both the local and non-local case) for (path, dirs, files) in os.walk('.'): if '.svn' in dirs: dirs.remove('.svn') # the [2:] strips off the initial './' local_ignores = [os.path.join(path, s.strip())[2:] for s in run_svn(['propget', 'svn:ignore', path]).splitlines() if bool(s.strip()) ] svn_ignores += local_ignores else: # if we are not inside an svn world # we can just bail del dirs[:] # Generate .hgignore file to ignore .svn and .hgsvn directories f = open(".hgignore", "a") try: f.write("\n# Automatically generated by `hgimportsvn`\n") f.write("syntax:glob\n%s\n" % "\n".join([svn_private_dir, hgsvn_private_dir])) f.write("\n# These lines are suggested according to the svn:ignore property") f.write("\n# Feel free to enable them by uncommenting them") f.write("\nsyntax:glob\n") f.write("".join("#%s\n" % s for s in svn_ignores)) finally: f.close() print "Finished! You can now pull all SVN history with 'hgpullsvn'." if __name__ == "__main__": main() hgsvn-0.1.8/hgsvn/errors.py0000644000175000017500000000171711302033265014271 0ustar andiandi """ Exception sub-hierarchy: RuntimeError +-- ExternalCommandFailed +-- CommitCancelled +-- HgSVNError +-- UnsupportedSVNFeature | +-- OverwrittenSVNBranch | +-- UnsupportedSVNAction +-- SVNOutputError +-- EmptySVNLog """ class ExternalCommandFailed(RuntimeError): """ An external command failed. """ class HgSVNError(RuntimeError): """ A generic hgsvn error. """ class UnsupportedSVNFeature(HgSVNError): """ An unsuppported SVN (mis)feature. """ class OverwrittenSVNBranch(UnsupportedSVNFeature): """ The current SVN branch was overwritten with another one. """ class UnsupportedSVNAction(UnsupportedSVNFeature): """ An unknown/unsupported SVN action in an SVN log entry. """ class SVNOutputError(HgSVNError): """ A generic error with the output of an SVN command. """ class EmptySVNLog(SVNOutputError): """ An empty SVN log entry. """ hgsvn-0.1.8/hgsvn/svnclient.py0000644000175000017500000002311611326767340014775 0ustar andiandi from hgsvn import ui from hgsvn.common import run_svn from hgsvn.errors import EmptySVNLog import os import time import calendar import operator try: from xml.etree import cElementTree as ET except ImportError: try: from xml.etree import ElementTree as ET except ImportError: try: import cElementTree as ET except ImportError: from elementtree import ElementTree as ET svn_log_args = ['log', '--xml', '-v'] svn_info_args = ['info', '--xml'] svn_checkout_args = ['checkout', '-q'] svn_status_args = ['status', '--xml', '--ignore-externals'] _identity_table = "".join(map(chr, range(256))) _forbidden_xml_chars = "".join( set(map(chr, range(32))) - set('\x09\x0A\x0D') ) def strip_forbidden_xml_chars(xml_string): """ Given an XML string, strips forbidden characters as per the XML spec. (these are all control characters except 0x9, 0xA and 0xD). """ return xml_string.translate(_identity_table, _forbidden_xml_chars) def svn_date_to_timestamp(svn_date): """ Parse an SVN date as read from the XML output and return the corresponding timestamp. """ # Strip microseconds and timezone (always UTC, hopefully) # XXX there are various ISO datetime parsing routines out there, # cf. http://seehuhn.de/comp/pdate date = svn_date.split('.', 2)[0] time_tuple = time.strptime(date, "%Y-%m-%dT%H:%M:%S") return calendar.timegm(time_tuple) def parse_svn_info_xml(xml_string): """ Parse the XML output from an "svn info" command and extract useful information as a dict. """ d = {} xml_string = strip_forbidden_xml_chars(xml_string) tree = ET.fromstring(xml_string) entry = tree.find('.//entry') d['url'] = entry.find('url').text d['revision'] = int(entry.get('revision')) d['repos_url'] = tree.find('.//repository/root').text d['last_changed_rev'] = int(tree.find('.//commit').get('revision')) author_element = tree.find('.//commit/author') if author_element is not None: d['last_changed_author'] = author_element.text d['last_changed_date'] = svn_date_to_timestamp(tree.find('.//commit/date').text) return d def parse_svn_log_xml(xml_string): """ Parse the XML output from an "svn log" command and extract useful information as a list of dicts (one per log changeset). """ l = [] xml_string = strip_forbidden_xml_chars(xml_string) tree = ET.fromstring(xml_string) for entry in tree.findall('logentry'): d = {} d['revision'] = int(entry.get('revision')) # Some revisions don't have authors, most notably the first revision # in a repository. # logentry nodes targeting directories protected by path-based # authentication have no child nodes at all. We return an entry # in that case. Anyway, as it has no path entries, no further # processing will be made. author = entry.find('author') date = entry.find('date') msg = entry.find('msg') d['author'] = author is not None and author.text or None if date is not None: d['date'] = svn_date_to_timestamp(date.text) else: d['date'] = None d['message'] = msg is not None and msg.text or "" paths = d['changed_paths'] = [] for path in entry.findall('.//path'): copyfrom_rev = path.get('copyfrom-rev') if copyfrom_rev: copyfrom_rev = int(copyfrom_rev) paths.append({ 'path': path.text, 'action': path.get('action'), 'copyfrom_path': path.get('copyfrom-path'), 'copyfrom_revision': copyfrom_rev, }) l.append(d) return l def parse_svn_status_xml(xml_string, base_dir=None): """ Parse the XML output from an "svn status" command and extract useful info as a list of dicts (one per status entry). """ if base_dir: base_dir = os.path.normcase(base_dir) l = [] xml_string = strip_forbidden_xml_chars(xml_string) tree = ET.fromstring(xml_string) for entry in tree.findall('.//entry'): d = {} path = entry.get('path') if base_dir is not None: assert os.path.normcase(path).startswith(base_dir) path = path[len(base_dir):].lstrip('/\\') d['path'] = path wc_status = entry.find('wc-status') if wc_status.get('item') == 'external': d['type'] = 'external' elif wc_status.get('revision') is not None: d['type'] = 'normal' else: d['type'] = 'unversioned' d['status'] = wc_status.get('item') l.append(d) return l def get_svn_info(svn_url_or_wc, rev_number=None): """ Get SVN information for the given URL or working copy, with an optionally specified revision number. Returns a dict as created by parse_svn_info_xml(). """ if rev_number is not None: args = ['-r', rev_number] else: args = [] xml_string = run_svn(svn_info_args + args + [svn_url_or_wc], fail_if_stderr=True) return parse_svn_info_xml(xml_string) def svn_checkout(svn_url, checkout_dir, rev_number=None): """ Checkout the given URL at an optional revision number. """ args = [] if rev_number is not None: args += ['-r', rev_number] args += [svn_url, checkout_dir] return run_svn(svn_checkout_args + args) def run_svn_log(svn_url_or_wc, rev_start, rev_end, limit, stop_on_copy=False): """ Fetch up to 'limit' SVN log entries between the given revisions. """ if stop_on_copy: args = ['--stop-on-copy'] else: args = [] args += ['-r', '%s:%s' % (rev_start, rev_end), '--limit', limit, svn_url_or_wc] xml_string = run_svn(svn_log_args + args) return parse_svn_log_xml(xml_string) def get_svn_status(svn_wc, quiet=False): """ Get SVN status information about the given working copy. """ # Ensure proper stripping by canonicalizing the path svn_wc = os.path.abspath(svn_wc) args = [svn_wc] if quiet: args += ['-q'] else: args += ['-v'] xml_string = run_svn(svn_status_args + args) return parse_svn_status_xml(xml_string, svn_wc) def get_svn_versioned_files(svn_wc): """ Get the list of versioned files in the SVN working copy. """ contents = [] for e in get_svn_status(svn_wc): if e['path'] and e['type'] == 'normal': contents.append(e['path']) return contents def get_one_svn_log_entry(svn_url, rev_start, rev_end, stop_on_copy=False): """ Get the first SVN log entry in the requested revision range. """ entries = run_svn_log(svn_url, rev_start, rev_end, 1, stop_on_copy) if entries: return entries[0] raise EmptySVNLog("No SVN log for %s between revisions %s and %s" % (svn_url, rev_start, rev_end)) def get_first_svn_log_entry(svn_url, rev_start, rev_end): """ Get the first log entry after (or at) the given revision number in an SVN branch. By default the revision number is set to 0, which will give you the log entry corresponding to the branch creaction. NOTE: to know whether the branch creation corresponds to an SVN import or a copy from another branch, inspect elements of the 'changed_paths' entry in the returned dictionary. """ return get_one_svn_log_entry(svn_url, rev_start, rev_end, stop_on_copy=True) def get_last_svn_log_entry(svn_url, rev_start, rev_end): """ Get the last log entry before (or at) the given revision number in an SVN branch. By default the revision number is set to HEAD, which will give you the log entry corresponding to the latest commit in branch. """ return get_one_svn_log_entry(svn_url, rev_end, rev_start, stop_on_copy=True) log_duration_threshold = 10.0 log_min_chunk_length = 10 def iter_svn_log_entries(svn_url, first_rev, last_rev): """ Iterate over SVN log entries between first_rev and last_rev. This function features chunked log fetching so that it isn't too nasty to the SVN server if many entries are requested. """ cur_rev = first_rev chunk_length = log_min_chunk_length chunk_interval_factor = 1.0 while last_rev == "HEAD" or cur_rev <= last_rev: start_t = time.time() stop_rev = min(last_rev, cur_rev + int(chunk_length * chunk_interval_factor)) ui.status("Fetching SVN log for revisions %d-%d...", cur_rev, stop_rev, level=ui.VERBOSE) entries = run_svn_log(svn_url, cur_rev, stop_rev, chunk_length) duration = time.time() - start_t if not entries: if stop_rev == last_rev: break cur_rev = stop_rev + 1 chunk_interval_factor *= 2.0 continue for e in entries: yield e cur_rev = e['revision'] + 1 # Adapt chunk length based on measured request duration if duration < log_duration_threshold: chunk_length = int(chunk_length * 2.0) elif duration > log_duration_threshold * 2: chunk_length = max(log_min_chunk_length, int(chunk_length / 2.0)) _svn_client_version = None def get_svn_client_version(): """Returns the SVN client version as a tuple. The returned tuple only contains numbers, non-digits in version string are silently ignored. """ global _svn_client_version if _svn_client_version is None: raw = run_svn(['--version', '-q']).strip() _svn_client_version = tuple(map(int, [x for x in raw.split('.') if x.isdigit()])) return _svn_client_version hgsvn-0.1.8/hgsvn/__init__.py0000644000175000017500000003623111327005735014523 0ustar andiandi""" ------- Summary ------- This set of scripts allows to work locally on Subversion-managed projects using the Mercurial distributed version control system. Why use Mercurial ? You can do local (disconnected) work, pull the latest changes from the SVN server, manage private branches, submit patches to project maintainers, etc. And of course you have fast local operations like "hg log", "hg annotate"... Three scripts are provided: * ``hgimportsvn`` initializes an SVN checkout which is also a Mercurial repository. * ``hgpullsvn`` pulls the latest changes from the SVN repository, and updates the Mercurial repository accordingly. It can be run multiple times. * ``hgpushsvn`` pushes your local Mercurial commits back to the SVN repository. ------- Example ------- Making a checkout of the Django_ trunk:: $ mkdir django && cd django # Make SVN checkout, initialize hg repository with first SVN revision $ hgimportsvn http://code.djangoproject.com/svn/django/trunk/ $ cd trunk # Pull all history from SVN, creating a new hg changeset for each SVN rev $ hgpullsvn Then make your changes and use the "hg" commands to commit them locally. If you have commit privileges you can push back your changes to the SVN repository:: $ hgpushsvn If you want to see what will be pushed back to SVN, use the "-n/--dry-run" flag. This is much like the "hg outgoing" command:: $ hgpushsvn --dry-run .. _Django: http://www.djangoproject.com ------- Install ------- Just type ``easy_install hgsvn``. If easy_install is not available on your computer, download and uncompress the source tarball, then type ``python setup.py install``. *Note:* hgsvn makes use of the ElementTree library. It is bundled by default with Python 2.5, and the setup script should install it automatically for you if you are using Python 2.4. However, if you get some error messages, you might have to install it manually (at least one user reported he had to). Unstable (development) version ------------------------------ Just run ``hg clone http://bitbucket.org/andialbrecht/hgsvn hgsvn`` and you'll get the contents of the development repository. -------- Features -------- Graceful operation ------------------ ``hgpullsvn`` asks for SVN log entries in chunks, so that pulling history does not put the remote server on its knees. ``hgpullsvn`` can be interrupted at any time, and run again later: you can pull history incrementally. Metadata -------- hgsvn reflects commit times (using the local timezone) and commit author names. Commit messages can contain Unicode characters. File copies and renames as reflected as well, provided they occur inside the branch. Tags ---- ``hgpullsvn`` tags each new Mercurial changeset with a local tag named 'svn.123' where 123 is the number of the corresponding SVN revision. Local tags were chosen because they don't pollute the hg log with superfluous entries, and also because SVN revision numbers are only meaningful for a specific branch: there is no use propagating them (IMHO). Named branches -------------- These scripts encourage the use of named branches. All updates using ``hgpullsvn`` are made in the branch named from the last component of the SVN URL (e.g., if the SVN URL is svn://server/myproj/branches/feature-ZZZ, ``hgpullsvn`` will create and use the named branch 'feature-ZZZ'). You can thus do local development using your own named branches. When you want to fetch latest history from the SVN repository, simply use ``hgpullsvn`` which will update to the original (pristine) branch, leaving your local work intact (you can then merge by yourself if your want). This also means that ``hg di -r name-of-pristine-branch`` will immediately give you a patch against the pristine branch, which you can submit to the project maintainers. (Note: in a non-trivial setup where you work on several features or bugfixes, you will clone the pristine repository for each separate piece of work, which will still give you the benefit of named branches for quickly generating patches). Detecting parent repository --------------------------- If the SVN URL has been created by copying from another SVN URL (this is the standard method for branch creation), ``hgimportsvn`` tries to find an hgsvn repository corresponding to the parent SVN URL. It then creates the new repository by cloning this repository at the revision immediately before the creation of the SVN branch. In other words, let's say you are operating from myworkdir/. In myworkdir/trunk, you already have an hgsvn repository synced from svn://server/myproj/trunk. You then ``hgimport svn://server/myproj/branches/new-feature``. It will find that the 'new-feature' branch has been created by copying from 'trunk' at rev. 1138. It will thus create the 'new-feature' hg repository by cloning from the 'trunk' repository at the revision immediately preceding rev. 1138: for example rev. 1135, identified by the local tag 'svn.1135'. This means you will have an hgsvn repository containing two named branches: 'trunk' for all the changesets in the trunk before rev. 1138, and 'new-feature' for all the changesets in the SVN branch (therefore, after rev. 1138). This way, you can easily track how the branch diverges from the trunk, but also do merges, etc. ----------- Limitations ----------- SVN externals are purposefully ignored and won't be added to your Mercurial repository. ------- History ------- hgsvn 0.1.8 ----------- Improvements: * Convert a local SVN checkout into a hgsvn controlled Mercurial repository with ``hgimportsvn --local-only``. No network access is needed when setting this flag (aka airplane mode). The Mercurial history then starts with the current revision of the SVN checkout. Patch by Matt Fowles. * Commit messages when pushing back to SVN can be edited before committing using the -e/--edit command line flag. Issue #29, patch by eliterr. * It's now possible to use ``hgsvn`` with the mq extensions. Both ``hgpushsvn`` and ``hgpullsvn`` abort with an error message if mq patches are applied when running those commands. Issue #43, patch by sterin. Bug fixes: * Removal of temporary file when pushing new revisions to SVN on Windows fixed. Issue 8 reported by Daniel Dabrowski. * Changed 'hg log' command line arguments that interfered with default options in .hgrc file. Issue 12 reported by Simon Percivall, initial patch by Joel Rosdahl and issue 16 reported by Wladimir Palant. * ``hgpushsvn`` is now compatible with Python 2.4. * If a SVN changeset contains empty changeset comments, ``hgpullsvn`` has failed. Empty changeset messages are now handled correctly. * SVN repositories at revision 0 couldn't be imported. Now it's possible to import empty SVN repositories with ``hgimportsvn``. Issue #13 reported by tiktuk. * ``hgpushsvn`` failed when a non-empty directory was removed from version control. Issue #15 reported by Keith Yang. * Proper encoding of commit messages on Windows systems. Issue #19 reported and patch by Chunlin Yao. * Change svn:executable property on mode changes when pushing back to SVN repository. Issue #24 reported by sterin. * Improved parsing of SVN messages. Issues #27, #14 patch contributed by x63. * ``hgpushsvn`` whiped uncommitted changes in working directory. Issue #32 reported by foxcub. * ``hgpullsvn`` in dry-run-mode displayed latest fetched revision too. Issue #35 reported by Dmitriy Morozov. * New sub-directories are now created properly. Issue #46 reported by Matt Fowles. hgsvn 0.1.7 ----------- Improvements: * ``hgpushsvn`` fully integrated in this version. This command pushes local Mercurial commits back to the SVN repository. * Add a -n/--dry-run flag to ``hgpullsvn`` and ``hgpushsvn`` to list incoming and outgoing changes without committing them to the local or remote repository. * Add verbosity levels to all command line scripts. The default verbosity level limits the output of ``hgpullsvn`` and ``hgpushsvn`` to messages that have a certain relevance to the user. Additional messages will be shown with the -v/--verbose flag. The --debug flag enables the output of debugging messages including shell commands. Bug fixes: * Log files from SVN repositories with path-based authentication caused ``hgpullsvn`` and ``hgimportsvn`` to fail with an XML parsing error. Restricted paths are now silently ignored (issue5, reported by Andreas Sliwka). * Updated the Mercurial-based lock file mechanism introduced in the previous release to work with Mercurial >= 1.2.0. The exception class was moved in Mercurial 1.2.0 (issue4). * ``hgpullsvn`` and ``hgpushsvn`` can now be called from any sub-directory within the working copy. Both scripts now take care to change their working directory to the root of the working copy (issue3). * ``hgimportsvn`` exits with a error message when the target directory is already a Mercurial repository controlled by hgsvn. * Detect conflicts when running SVN update. To avoid conflicts when pulling new SVN revisions, ``hgpullsvn`` checks if the hg repository has uncommitted changes before actually pulling new revisions from SVN (issue6, reported and initial patch by Robert). hgsvn 0.1.6 ----------- Improvements: * Prefix commit messages with [svn r123] (where 123 is the corresponding SVN revision number), rather than just [svn]. Also, trim leading whitespace in the original commit message, to avoid blank changeset summaries when the message begins with a carriage return. * Introduce a .hgsvn private directory at the top of the working copy. This will us to store various things in a common location without polluting the base directory. * Introduce a lock file (named .hgsvn/lock) to disallow running two hgpullsvn instances in parallel on the same repository. The locking mechanism is imported from mercurial's own mercurial.lock. If the mercurial package is not available, a dummy lock is used instead. Initial patch by Ori Peleg. * Add a --no-hgignore option to hgimportsvn, for situations where the source SVN repository already contains a versioned .hgignore file. Patch by Ori Peleg. * hgsvn can now be bundled as standalone executables using py2exe. Patch by Paul Moore. * More descriptive error message when either hg or svn cannot be executed (e.g. not installed). Patch by Joonas Paalasmaa. Bug fixes: * Very long commit messages (> 16000 characters) are provided to Mercurial through a temporary file rather than the command line, which could fail on some platforms. The corresponding commit messages were generated by svnmerge. Reported by Ralf Schmitt. * Filenames starting with a hyphen were considered by hg and SVN as command-line options. Report and patch by Mirko Friedenhagen. * If the last hg changeset mapped to more than one SVN revision, trying to update again with ``hgpullsvn`` failed. * A replaced directory can have added and removed files without them being mentioned in the SVN log; we must detect those files ourselves. * More robust atomicity check for (hg commit, hg tag) sequence. Reported by Florent Guillaume. * Fix a bug when comparing local filesystem paths on Windows. We now invoke os.path.normcase on both paths before comparing. Reported by Pavol Murin. hgsvn 0.1.5 ----------- Improvements: * In the initial import, parse the svn:ignore property and add suggestions to the .hgignore file accordingly. These suggestions are commented by default because they are based on the latest version of the svn:ignore property and could make us miss some files along the SVN history, if enabled blindingly. Bug fixes: * Critical fix for Mercurial 0.9.5, which is stricter with named branches. This bug made ``hgimportsvn`` fail when cloning from an auto-detected parent repository. * Honor the SVN_ASP_DOT_NET_HACK environment variable when deciding the name of private SVN folders (``.svn`` or ``_svn``). Thanks to Anton Daneika for the report and the original patch. Packaging: * Change setuptools options to solve bdist_rpm bug under Fedora and other Linux distributions. Patch by Tim Wegener. hgsvn 0.1.4 ----------- Improvements: * Be able to pull dead (removed) SVN branches by introducing a -p (--svn-peg) option to specify the SVN "peg revision". The option must be used with both hgimportsvn and hgpullsvn. Patch by Cameron Hutchison. Bug fixes: * Allow copying directories with non-ASCII names (reported by Andre Klitzing). * Make rmtree reliable under Windows. Thanks to Mark (mwatts42) for finding both the bug and the solution. * Fix a problem where there is a symbolic link in the SVN repository that points to a directory. Patch by Cameron Hutchison. * ``svn log`` can output invalid XML when a commit message contains control characters. Reported by Tim Wegener. Other: * License upgraded to GNU GPL v3 (or later). hgsvn 0.1.3 ----------- Improvements: * Performance improvement with ``svn log`` command in ``hgpullsvn`` (suggested by Mads Kiilerich and Daniel Berlin). * Less obscure error message when ``svn info`` fails while returning a successful return code. * Two simplistic man pages added. Bug fixes: * Windows compatibility fix by Bill Baxter. * ``hgimportsvn`` failed when used on a whole repository. * Fix crash on empty commit message (also reported by Neil Martinsen-Burrell and Walter Landry). * Handle file and directory renames properly (reported by Bill Baxter). * SVN allows copying from a deleted file by having mixed revisions inside the working copy at commit time, but Mercurial doesn't accept it (reported by Neil Martinsen-Burrell). hgsvn 0.1.2 ----------- Improvements: * Automatically generate ``.hgignore`` file. Not only does it produce cleaner output for commands like ``hg status``, but it speeds things up as well. * ``hgpullsvn`` is more robust in the face of errors and user interruptions. * Try to be Windows-compatible by not using the commands module. * Remove dependency on the pysvn library; we use the XML output option of SVN commands instead. Bug fixes: * Fix a bug in parent repository detection. * Detect the wicked case where the SVN branch has been overwritten with contents of another branch (witnessed with Nose trunk and 0.10-dev branch). We can't properly handle this situation, so fail with an explicit message. * ``svn info`` on base repository URL does not always succeed, use the specific project URL instead (reported by Larry Hastings). hgsvn 0.1.1 ----------- Bug fixes: * pysvn doesn't really ignore externals, so use the command line for ``svn update`` instead (otherwise we get failures for obsolete URLs) * ``.svn`` directories were not always ignored. * On large repositories, adding more than 32765 files at once failed because of too many arguments on the command line. * On slow SVN servers, the chunked log fetching algorithm ended up asking for 0 log entries. hgsvn 0.1 --------- Initial release. """ __all__ = [] __author__ = 'Antoine Pitrou, Andi Albrecht' __license__ = 'GNU General Public License (version 3 or later)' __versioninfo__ = (0, 1, 8) base_version = '.'.join(map(str, __versioninfo__)) full_version = base_version try: import pkg_resources except ImportError: pass else: try: full_version = pkg_resources.get_distribution("hgsvn").version except pkg_resources.DistributionNotFound: pass __version__ = full_version hgsvn-0.1.8/hgsvn/ui.py0000644000175000017500000000417611273303042013374 0ustar andiandi# -*- coding: utf-8 -*- """User interface functions.""" import os import sys try: # First try to import the Mercurial implementation. from mercurial.util import termwidth except ImportError: # Fallback to local copy of Mercurial's implementation. def termwidth(): if 'COLUMNS' in os.environ: try: return int(os.environ['COLUMNS']) except ValueError: pass try: import termios, array, fcntl for dev in (sys.stdout, sys.stdin): try: fd = dev.fileno() if not os.isatty(fd): continue arri = fcntl.ioctl(fd, termios.TIOCGWINSZ, '\0' * 8) return array.array('h', arri)[1] except ValueError: pass except ImportError: pass return 80 # Log levels ERROR = 0 DEFAULT = 10 VERBOSE = 20 DEBUG = 30 # Configuration _level = DEFAULT def status(msg, *args, **kwargs): """Write a status message. args are treated as substitutions for msg. The following keyword arguments are allowed: level : One of DEFAULT, VERBOSE or DEBUG. linebreak: If True a new line is appended to msg (default: True). trunkate : Trunkate output if larger then term width (default: True). """ global _level level = kwargs.get('level', DEFAULT) if level > _level: return width = termwidth() if args: msg = msg % args if kwargs.get('linebreak', True): msg = '%s%s' % (msg, os.linesep) if level == ERROR: stream = sys.stderr else: stream = sys.stdout if kwargs.get('trunkate', True) and level != ERROR: add_newline = msg.endswith('\n') msg = os.linesep.join(x[:width] for x in msg.splitlines()) if add_newline: msg = '%s%s' % (msg, os.linesep) if isinstance(msg, unicode): msg = msg.encode('utf-8') stream.write(msg) stream.flush() def update_config(options): """Update UI configuration.""" global _level _level = options.verbosity hgsvn-0.1.8/AUTHORS.txt0000644000175000017500000000006711224551115013143 0ustar andiandiAntoine Pitrou Andi Albrecht hgsvn-0.1.8/COPYING.txt0000644000175000017500000010451311216610734013133 0ustar andiandi GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . hgsvn-0.1.8/README.txt0000644000175000017500000000022211224551115012744 0ustar andiandi----- hgsvn ----- To read the documentation, either type `pydoc hgsvn`, or go to the following Web page: http://cheeseshop.python.org/pypi/hgsvn