pax_global_header00006660000000000000000000000064126303363520014515gustar00rootroot0000000000000052 comment=2ef02d06a105b01922a17e1416f2ce254f7fe946 git-remote-hg-0.3/000077500000000000000000000000001263033635200140275ustar00rootroot00000000000000git-remote-hg-0.3/.travis.yml000066400000000000000000000024441263033635200161440ustar00rootroot00000000000000language: python install: - if [ "$HG_VERSION" != "dev" ]; then pip install -q Mercurial${HG_VERSION+==$HG_VERSION}; else pip install -q http://selenic.com/repo/hg/archive/tip.tar.gz; fi - if [ "$HG_GIT_VERSION" != "dev" ]; then pip install -q dulwich${HG_GIT_VERSION+==$HG_GIT_VERSION}; else pip install -q https://bitbucket.org/durin42/hg-git/get/tip.tar.bz2; fi - if [ -n "$USE_LATEST_GIT" ]; then sudo add-apt-repository -y ppa:pdoes/ppa; sudo apt-get update; sudo apt-get install -qq git; fi before_script: - git --version - hg --version - pip show hg-git dulwich script: - make test matrix: include: - env: HG_VERSION=2.7.2 - env: HG_VERSION=2.8.2 - env: HG_VERSION=2.9.1 - env: HG_VERSION=3.0.1 - env: HG_VERSION=3.1.2 - env: HG_VERSION=3.2.4 - env: HG_VERSION=2.7.2 USE_LATEST_GIT= - env: HG_VERSION=2.8.2 USE_LATEST_GIT= - env: HG_VERSION=2.9.1 USE_LATEST_GIT= - env: HG_VERSION=3.0.1 USE_LATEST_GIT= - env: HG_VERSION=3.1.2 USE_LATEST_GIT= - env: HG_VERSION=3.2.4 USE_LATEST_GIT= # FIXME: hg 3.3 requires hg-git > 0.7.0, but we are incompatible with that. # See issue felipec/git-remote-hg#35 #- env: HG_VERSION=dev HG_GIT_VERSION=dev - python: 2.7 - python: 2.6 git-remote-hg-0.3/LICENSE000066400000000000000000000432541263033635200150440ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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. git-remote-hg-0.3/Makefile000066400000000000000000000010171263033635200154660ustar00rootroot00000000000000prefix := $(HOME) bindir := $(prefix)/bin mandir := $(prefix)/share/man/man1 all: doc doc: doc/git-remote-hg.1 test: $(MAKE) -C test doc/git-remote-hg.1: doc/git-remote-hg.txt a2x -d manpage -f manpage $< clean: $(RM) doc/git-remote-hg.1 D = $(DESTDIR) install: install -d -m 755 $(D)$(bindir)/ install -m 755 git-remote-hg $(D)$(bindir)/git-remote-hg install-doc: doc install -d -m 755 $(D)$(mandir)/ install -m 644 doc/git-remote-hg.1 $(D)$(mandir)/git-remote-hg.1 .PHONY: all test install install-doc clean git-remote-hg-0.3/README.asciidoc000066400000000000000000000112631263033635200164670ustar00rootroot00000000000000'git-remote-hg' is the semi-official Mercurial bridge from Git project, once installed, it allows you to clone, fetch and push to and from Mercurial repositories as if they were Git ones: -------------------------------------- git clone "hg::http://selenic.com/repo/hello" -------------------------------------- To enable this (e.g. under Linux), first make sure that you have Python 2 and Mercurial installed. Then simply add the 'git-remote-hg' script anywhere in your `$PATH` and make sure it is executable, e.g.: -------------------------------------- curl -o ~/bin/git-remote-hg https://raw.githubusercontent.com/fingolfin/git-remote-hg/master/git-remote-hg chmod +x ~/bin/git-remote-hg -------------------------------------- If your system does not have curl, but wget, you can use this command: -------------------------------------- wget https://raw.github.com/fingolfin/git-remote-hg/master/git-remote-hg -O ~/bin/git-remote-hg chmod +x ~/bin/git-remote-hg -------------------------------------- That's it. :) == Configuration == If you want to see Mercurial revisions as Git commit notes: -------------------------------------- % git config core.notesRef refs/notes/hg -------------------------------------- If you are not interested in Mercurial permanent and global branches (aka. commit labels): -------------------------------------- % git config --global remote-hg.track-branches false -------------------------------------- With this configuration, the 'branches/foo' refs won't appear. If you want the equivalent of 'hg clone --insecure': -------------------------------------- % git config --global remote-hg.insecure true -------------------------------------- If you want 'git-remote-hg' to be compatible with 'hg-git', and generate exactly the same commits: -------------------------------------- % git config --global remote-hg.hg-git-compat true -------------------------------------- == Notes == Remember to run `git gc --aggressive` after cloning a repository, specially if it's a big one. Otherwise lots of space will be wasted. The oldest version of mercurial supported is 1.9. For the most part 1.8 works, but you might experience some issues. === Pushing branches === To push a branch, you need to use the "branches/" prefix: -------------------------------------- % git checkout branches/next # do stuff % git push origin branches/next -------------------------------------- All the pushed commits will receive the "next" Mercurial named branch. *Note*: Make sure you don't have +remote-hg.track-branches+ disabled. === Cloning HTTPS === The simplest way is to specify the user and password in the URL: -------------------------------------- git clone hg::https://user:password@bitbucket.org/user/repo -------------------------------------- You can also use the http://mercurial.selenic.com/wiki/SchemesExtension[schemes extension]: -------------------------------------- [auth] bb.prefix = https://bitbucket.org/user/ bb.username = user bb.password = password -------------------------------------- Finally, you can also use the https://pypi.python.org/pypi/mercurial_keyring[keyring extension]. However, some of these features require very new versions of 'git-remote-hg', so you might have better luck simply specifying the username and password in the URL. === Caveats === The only major incompatibility is that Git octopus merges (a merge with more than two parents) are not supported. Mercurial branches and bookmarks have some limitations of Git branches: you can't have both 'dev/feature' and 'dev' (as Git uses files and directories to store them). Multiple anonymous heads (which are useless anyway) are not supported; you would only see the latest head. Closed branches are not supported; they are not shown and you can't close or reopen. Additionally in certain rare situations a synchronization issue can occur (https://github.com/felipec/git/issues/65[Bug #65]). Limitations of the remote-helpers' framework apply. In particular, these commands don't work: * `git push origin :branch-to-delete` * `git push origin old:new` (it will push 'old') (patches available) * `git push --dry-run origin branch` (it will push) (patches available) == Other projects == There are other 'git-remote-hg' projects out there, do not confuse this one, this is the one distributed officially by the Git project: * https://github.com/msysgit/msysgit/wiki/Guide-to-git-remote-hg[msysgit's git-remote-hg] * https://github.com/rfk/git-remote-hg[rfk's git-remote-hg] For a comparison between these and other projects go https://github.com/felipec/git/wiki/Comparison-of-git-remote-hg-alternatives[here]. == Contributing == Consider submitting a [pull request](https://github.com/fingolfin/git-remote-hg/pulls). And thanks! git-remote-hg-0.3/doc/000077500000000000000000000000001263033635200145745ustar00rootroot00000000000000git-remote-hg-0.3/doc/.gitignore000066400000000000000000000000201263033635200165540ustar00rootroot00000000000000git-remote-hg.1 git-remote-hg-0.3/doc/SubmittingPatches000066400000000000000000000003361263033635200201560ustar00rootroot00000000000000Please send your patches using `git format-patch` to the mailing list: git-fc@googlegroups.com. Make sure all the tests pass by running `make test`, and if possible add a new test to exercise the code you are submitting. git-remote-hg-0.3/doc/git-remote-hg.txt000066400000000000000000000063471263033635200200170ustar00rootroot00000000000000git-remote-hg(1) ================ NAME ---- git-remote-hg - bidirectional bridge between Git and Mercurial SYNOPSIS -------- [verse] 'git clone' hg:: DESCRIPTION ----------- This tool allows you to transparently clone, fetch and push to and from Mercurial repositories as if they were Git ones. To use it you simply need to use the "'hg::'" prefix when specifying a remote URL (e.g. when cloning). EXAMPLE ------- ------------ $ git clone hg::http://selenic.com/repo/hello ------------ CONFIGURATION ------------- If you want to see Mercurial revisions as Git commit notes: -------------------------------------- % git config core.notesRef refs/notes/hg -------------------------------------- If you are not interested in Mercurial permanent and global branches (aka. commit labels): -------------------------------------- % git config --global remote-hg.track-branches false -------------------------------------- With this configuration, the 'branches/foo' refs won't appear. If you want the equivalent of `hg clone --insecure`: -------------------------------------- % git config --global remote-hg.insecure true -------------------------------------- If you want 'git-remote-hg' to be compatible with 'hg-git', and generate exactly the same commits: -------------------------------------- % git config --global remote-hg.hg-git-compat true -------------------------------------- NOTES ----- Remember to run `git gc --aggressive` after cloning a repository, specially if it's a big one. Otherwise lots of space will be wasted. The oldest version of Mercurial supported is 1.9. For the most part 1.8 works, but you might experience some issues. Pushing branches ~~~~~~~~~~~~~~~~ To push a Mercurial named branch, you need to use the "branches/" prefix: -------------------------------------- % git checkout branches/next # do stuff % git push origin branches/next -------------------------------------- All the pushed commits will receive the "next" Mercurial named branch. *Note*: Make sure you don't have +remote-hg.track-branches+ disabled. Cloning HTTPS ~~~~~~~~~~~~~ The simplest way is to specify the user and password in the URL: -------------------------------------- git clone hg::https://user:password@bitbucket.org/user/repo -------------------------------------- You can also use the http://mercurial.selenic.com/wiki/SchemesExtension[schemes extension]: -------------------------------------- [auth] bb.prefix = https://bitbucket.org/user/ bb.username = user bb.password = password -------------------------------------- Finally, you can also use the https://pypi.python.org/pypi/mercurial_keyring[keyring extension]. CAVEATS ------- The only major incompatibility is that Git octopus merges (a merge with more than two parents) are not supported. Mercurial branches and bookmarks have some limitations of Git branches: you can't have both 'dev/feature' and 'dev' (as Git uses files and directories to store them). Multiple anonymous heads (which are useless anyway) are not supported; you would only see the latest head. Closed branches are not supported; they are not shown and you can't close or reopen. Additionally in certain rare situations a synchronization issue can occur (https://github.com/felipec/git/issues/65[Bug #65]). git-remote-hg-0.3/git-marks-check000077500000000000000000000036651263033635200167400ustar00rootroot00000000000000#!/usr/bin/env ruby require 'json' $fix = false $verbose = false $git_marks = {} $r_marks = {} $mode = 'hg' # Parse arguments ARGV.delete_if do |cur| next false if cur[0] != '-' case cur when /^-f$/, /^--fix$/ $fix = true true when /^-v$/, /^--verbose$/ $verbose = true true when /^-m(.+)$/, /^--mode=(.+)$/ $mode = $1 true end end $remote = ARGV[0] $dir = File.join('.git', $mode, $remote) $git_file = File.join($dir, 'marks-git') $r_file = File.join($dir, 'marks-' + $mode) # TODO $r_file = File.join($dir, 'marks-int') if $mode == 'bzr' # Get git marks File.open($git_file).each do |l| if l =~ /:(\d+) (\h+)$/ $git_marks[$1.to_i] = $2 end end # Remove non commit objects File.popen(%w[git cat-file --batch-check], 'r+') do |p| $git_marks.each do |mark,id| p.write(id + "\n") if p.readline =~ /(\h+) (\w+) (\d+)/ type = $2 $git_marks.delete(mark) unless type == 'commit' end end end # Remove notes File.popen(%W[git rev-list refs/notes/#{$mode}], 'r', :err => File::NULL) do |p| p.each do |l| $git_marks.delete_if { |mark,id| id == l.chomp } end end # Get remote marks r_data = JSON.parse(File.read($r_file)) $r_marks = r_data['marks'].invert r_missing = $git_marks.reject { |mark,id| $r_marks[mark] } git_missing = $r_marks.reject { |mark,id| $git_marks[mark] } if $verbose r_missing.each do |mark,id| puts "Missing %s (%d) from #{$mode}" % [id, mark] end git_missing.each do |mark,id| puts "Missing %s (%d) from git" % [id, mark] end end if $fix # Fix remote marks r_data['marks'].delete_if { |mark,id| git_missing.has_key?(id) } File.write($r_file, r_data.to_json) # Fix git marks File.open($git_file, 'w') do |f| $git_marks.each do |mark,id| next if r_missing.has_key?(mark) f.puts ':%d %s' % [mark, id] end end end if r_missing.empty? and git_missing.empty? puts 'Everything OK' else puts 'Issues detected' exit 1 endgit-remote-hg-0.3/git-remote-hg000077500000000000000000001153751263033635200164410ustar00rootroot00000000000000#!/usr/bin/env python2 # # Copyright (c) 2012 Felipe Contreras # # Inspired by Rocco Rutte's hg-fast-export # Just copy to your ~/bin, or anywhere in your $PATH. # Then you can clone with: # git clone hg::/path/to/mercurial/repo/ # # For remote repositories a local clone is stored in # "$GIT_DIR/hg/origin/clone/.hg/". from mercurial import hg, ui, bookmarks, context, encoding from mercurial import node, error, extensions, discovery, util from mercurial import changegroup import re import sys import os import posixpath import json import shutil import subprocess import urllib import atexit import urlparse import hashlib import time as ptime # # If you want to see Mercurial revisions as Git commit notes: # git config core.notesRef refs/notes/hg # # If you are not in hg-git-compat mode and want to disable the tracking of # named branches: # git config --global remote-hg.track-branches false # # If you want the equivalent of hg's clone/pull--insecure option: # git config --global remote-hg.insecure true # # If you want to switch to hg-git compatibility mode: # git config --global remote-hg.hg-git-compat true # # The 'mode' variable indicates whether we are in 'git' or 'hg' compatibility mode. # This has the following effects: # # git: # Sensible defaults for git. # hg bookmarks are exported as git branches, hg branches are prefixed # with 'branches/', HEAD is a special case. # # hg: # Emulate hg-git. # Only hg bookmarks are exported as git branches. # Commits are modified to preserve hg information and allow bidirectionality. # mode = 'git' DEBUG_REMOTEHG = os.environ.get("DEBUG_REMOTEHG") != None NAME_RE = re.compile('^([^<>]+)') AUTHOR_RE = re.compile('^([^<>]+?)? ?[<>]([^<>]*)(?:$|>)') EMAIL_RE = re.compile(r'([^ \t<>]+@[^ \t<>]+)') AUTHOR_HG_RE = re.compile('^(.*?) ?<(.*?)(?:>(.*))?$') RAW_AUTHOR_RE = re.compile('^(\w+) (?:(.+)? )?<(.*)> (\d+) ([+-]\d+)') VERSION = 2 def die(msg, *args): sys.stderr.write('ERROR: %s\n' % (msg % args)) sys.exit(1) def warn(msg, *args): sys.stderr.write('WARNING: %s\n' % (msg % args)) # convert between git timezone and mercurial timezone data. # git stores timezone as a string in the form "+HHMM" or "-HHMM". # Mercurial instead encodes the timezone as an offset to UTC in seconds. # This offset has the opposite sign from the one used by git. # # To convert between the two, we have to be a bit careful, as # dividing a negativ integer in python 2 rounds differently than # in C. # hg->git: convert timezone offset in seconds to string '+HHMM' or '-HHMM' def gittz(tz): if tz < 0: tz = -tz sign = +1 else: sign = -1 hours = tz / 3600 minutes = tz % 3600 / 60 return '%+03d%02d' % (sign * hours, minutes) # git->hg: convert timezone string '+HHMM' or '-HHMM' to time offset in seconds def hgtz(tz): tz = int(tz) if tz < 0: tz = -tz sign = +1 else: sign = -1 tz = ((tz / 100) * 3600) + ((tz % 100) * 60) return sign * tz # hg->git: convert hg flags to git file mode def gitmode(flags): return 'l' in flags and '120000' or 'x' in flags and '100755' or '100644' # git->hg: convert git file mode to hg flags def hgmode(mode): m = { '100755': 'x', '120000': 'l' } return m.get(mode, '') def hghex(n): return node.hex(n) def hgbin(n): return node.bin(n) def hgref(ref): return ref.replace('___', ' ') def gitref(ref): return ref.replace(' ', '___') def check_version(*check): if not hg_version: return True return hg_version >= check def get_config(config): cmd = ['git', 'config', '--get', config] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) output, _ = process.communicate() return output def get_config_bool(config, default=False): value = get_config(config).rstrip('\n') if value == "true": return True elif value == "false": return False else: return default # Handle loading and storing git marks files class Marks: def __init__(self, path, repo): self.path = path self.repo = repo self.clear() self.load() if self.version < VERSION: if self.version == 1: self.upgrade_one() # upgraded? if self.version < VERSION: self.clear() self.version = VERSION def clear(self): self.tips = {} self.marks = {} self.rev_marks = {} self.last_mark = 0 self.version = 0 self.last_note = 0 def load(self): if not os.path.exists(self.path): return tmp = json.load(open(self.path)) self.tips = tmp['tips'] self.marks = tmp['marks'] self.last_mark = tmp['last-mark'] self.version = tmp.get('version', 1) self.last_note = tmp.get('last-note', 0) for rev, mark in self.marks.iteritems(): self.rev_marks[mark] = rev def upgrade_one(self): def get_id(rev): return hghex(self.repo.changelog.node(int(rev))) self.tips = dict((name, get_id(rev)) for name, rev in self.tips.iteritems()) self.marks = dict((get_id(rev), mark) for rev, mark in self.marks.iteritems()) self.rev_marks = dict((mark, get_id(rev)) for mark, rev in self.rev_marks.iteritems()) self.version = 2 def dict(self): return { 'tips': self.tips, 'marks': self.marks, 'last-mark': self.last_mark, 'version': self.version, 'last-note': self.last_note } def store(self): json.dump(self.dict(), open(self.path, 'w')) def __str__(self): return str(self.dict()) def from_rev(self, rev): return self.marks[rev] def to_rev(self, mark): return str(self.rev_marks[mark]) def next_mark(self): self.last_mark += 1 return self.last_mark def get_mark(self, rev): self.last_mark += 1 self.marks[rev] = self.last_mark return self.last_mark def new_mark(self, rev, mark): self.marks[rev] = mark self.rev_marks[mark] = rev self.last_mark = mark def is_marked(self, rev): return rev in self.marks def get_tip(self, branch): return str(self.tips[branch]) def set_tip(self, branch, tip): self.tips[branch] = tip # Parser class for the input git feeds to us. See # - http://git-scm.com/docs/gitremote-helpers # - http://git-scm.com/docs/git-fast-import class Parser: def __init__(self, repo): self.repo = repo self.line = self.get_line() def get_line(self): return sys.stdin.readline().strip() def __getitem__(self, i): return self.line.split()[i] def check(self, word): return self.line.startswith(word) def each_block(self, separator): while self.line != separator: yield self.line self.line = self.get_line() def __iter__(self): return self.each_block('') def next(self): self.line = self.get_line() if self.line == 'done': self.line = None def get_mark(self): i = self.line.index(':') + 1 return int(self.line[i:]) def get_data(self): if not self.check('data'): return None i = self.line.index(' ') + 1 size = int(self.line[i:]) return sys.stdin.read(size) def get_author(self): ex = None m = RAW_AUTHOR_RE.match(self.line) if not m: return None _, name, email, date, tz = m.groups() if name and 'ext:' in name: m = re.match('^(.+?) ext:\((.+)\)$', name) if m: name = m.group(1) ex = urllib.unquote(m.group(2)) if email != bad_mail: if name: user = '%s <%s>' % (name, email) else: user = '<%s>' % (email) else: user = name if ex: user += ex return (user, int(date), hgtz(tz)) # hg->git: helper function for export_files, which modifies the given # file path, taken from a hg commit, for use in a fast-import stream. def fix_file_path(path): path = posixpath.normpath(path) if not os.path.isabs(path): return path return posixpath.relpath(path, '/') # hg->git: export files from hg to git. That is, read them from the hg # repository, and print them into the fast-import stream we are feeding # to git. def export_files(files): final = [] for f in files: fid = node.hex(f.filenode()) if fid in filenodes: mark = filenodes[fid] else: mark = marks.next_mark() filenodes[fid] = mark d = f.data() print "blob" print "mark :%u" % mark print "data %d" % len(d) print d path = fix_file_path(f.path()) final.append((gitmode(f.flags()), mark, path)) return final # hg->git: determine which files changed on the hg side. def get_filechanges(repo, ctx, parent): modified = set() added = set() removed = set() # load earliest manifest first for caching reasons prev = parent.manifest().copy() cur = ctx.manifest() for fn in cur: if fn in prev: if (cur.flags(fn) != prev.flags(fn) or cur[fn] != prev[fn]): modified.add(fn) del prev[fn] else: added.add(fn) removed |= set(prev.keys()) return added | modified, removed def fixup_user_git(user): name = mail = None user = user.replace('"', '') m = AUTHOR_RE.match(user) if m: name = m.group(1) mail = m.group(2).strip() else: m = EMAIL_RE.match(user) if m: mail = m.group(1) else: m = NAME_RE.match(user) if m: name = m.group(1).strip() return (name, mail) def fixup_user_hg(user): def sanitize(name): # stole this from hg-git return re.sub('[<>\n]', '?', name.lstrip('< ').rstrip('> ')) m = AUTHOR_HG_RE.match(user) if m: name = sanitize(m.group(1)) mail = sanitize(m.group(2)) ex = m.group(3) if ex: name += ' ext:(' + urllib.quote(ex) + ')' else: name = sanitize(user) if '@' in user: mail = name else: mail = None return (name, mail) def fixup_user(user): if mode == 'git': name, mail = fixup_user_git(user) else: name, mail = fixup_user_hg(user) if not name: name = bad_name if not mail: mail = bad_mail return '%s <%s>' % (name, mail) # helper function for get_repo def updatebookmarks(repo, peer): remotemarks = peer.listkeys('bookmarks') localmarks = repo._bookmarks if not remotemarks: return for k, v in remotemarks.iteritems(): localmarks[k] = hgbin(v) if hasattr(localmarks, 'write'): localmarks.write() else: bookmarks.write(repo) # instantiate a Mercurial "repo" object so that # we can interact with the hg repository. # Also pulls remote changes. def get_repo(url, alias): global peer myui = ui.ui() myui.setconfig('ui', 'interactive', 'off') myui.fout = sys.stderr if get_config_bool('remote-hg.insecure'): myui.setconfig('web', 'cacerts', '') extensions.loadall(myui) if hg.islocal(url) and not os.environ.get('GIT_REMOTE_HG_TEST_REMOTE'): repo = hg.repository(myui, url) if not os.path.exists(dirname): os.makedirs(dirname) else: shared_path = os.path.join(gitdir, 'hg') # check and upgrade old organization hg_path = os.path.join(shared_path, '.hg') if os.path.exists(shared_path) and not os.path.exists(hg_path): repos = os.listdir(shared_path) for x in repos: local_hg = os.path.join(shared_path, x, 'clone', '.hg') if not os.path.exists(local_hg): continue if not os.path.exists(hg_path): shutil.move(local_hg, hg_path) shutil.rmtree(os.path.join(shared_path, x, 'clone')) # setup shared repo (if not there) try: hg.peer(myui, {}, shared_path, create=True) except error.RepoError: pass if not os.path.exists(dirname): os.makedirs(dirname) local_path = os.path.join(dirname, 'clone') if not os.path.exists(local_path): hg.share(myui, shared_path, local_path, update=False) else: # make sure the shared path is always up-to-date util.writefile(os.path.join(local_path, '.hg', 'sharedpath'), hg_path) repo = hg.repository(myui, local_path) peer = hg.peer(repo.ui, {}, url) if check_version(3, 2): from mercurial import exchange exchange.pull(repo, peer, heads=None, force=True) else: repo.pull(peer, heads=None, force=True) updatebookmarks(repo, peer) return repo # hg->git: helper function for export_ref def rev_to_mark(rev): return marks.from_rev(rev.hex()) # git->hg: helper function for parse_reset and parse_commit def mark_to_rev(mark): return marks.to_rev(mark) # hg->git: helper function for export_ref # Get a range of hg revisions in the form of a..b (git committish) def gitrange(repo, a, b): positive = [] pending = set([int(b)]) negative = set([int(a)]) for cur in xrange(b, -1, -1): if not pending: break parents = [p for p in repo.changelog.parentrevs(cur) if p >= 0] if cur in pending: positive.append(cur) pending.remove(cur) for p in parents: if p not in negative: pending.add(p) elif cur in negative: negative.remove(cur) for p in parents: if p not in pending: negative.add(p) else: pending.discard(p) positive.reverse() return positive # hg->git: export ref from hg to git def export_ref(repo, name, kind, head): ename = '%s/%s' % (kind, name) try: tip = marks.get_tip(ename) tip = repo[tip] except: tip = repo[-1] revs = gitrange(repo, tip, head) total = len(revs) tip = tip.rev() for rev in revs: c = repo[rev] node = c.node() if marks.is_marked(c.hex()): continue (manifest, user, (time, tz), files, desc, extra) = repo.changelog.read(node) rev_branch = extra['branch'] author = "%s %d %s" % (fixup_user(user), time, gittz(tz)) if 'committer' in extra: try: cuser, ctime, ctz = extra['committer'].rsplit(' ', 2) committer = "%s %s %s" % (fixup_user(cuser), ctime, gittz(int(ctz))) except ValueError: cuser = extra['committer'] committer = "%s %d %s" % (fixup_user(cuser), time, gittz(tz)) else: committer = author parents = [repo[p] for p in repo.changelog.parentrevs(rev) if p >= 0] if len(parents) == 0: modified = c.manifest().keys() removed = [] else: modified, removed = get_filechanges(repo, c, parents[0]) desc += '\n' if mode == 'hg': extra_msg = '' if rev_branch != 'default': extra_msg += 'branch : %s\n' % rev_branch renames = [] for f in c.files(): if f not in c.manifest(): continue rename = c.filectx(f).renamed() if rename: renames.append((rename[0], f)) for e in renames: extra_msg += "rename : %s => %s\n" % e for key, value in extra.iteritems(): if key in ('author', 'committer', 'encoding', 'message', 'branch', 'hg-git'): continue else: extra_msg += "extra : %s : %s\n" % (key, urllib.quote(value)) if extra_msg: desc += '\n--HG--\n' + extra_msg if len(parents) == 0 and rev: print 'reset %s/%s' % (prefix, ename) modified_final = export_files(c.filectx(f) for f in modified) print "commit %s/%s" % (prefix, ename) print "mark :%d" % (marks.get_mark(c.hex())) print "author %s" % (author) print "committer %s" % (committer) print "data %d" % (len(desc)) print desc if len(parents) > 0: print "from :%s" % (rev_to_mark(parents[0])) if len(parents) > 1: print "merge :%s" % (rev_to_mark(parents[1])) for f in removed: print "D %s" % (fix_file_path(f)) for f in modified_final: print "M %s :%u %s" % f print progress = (rev - tip) if (progress % 100 == 0): print "progress revision %d '%s' (%d/%d)" % (rev, name, progress, total) # make sure the ref is updated print "reset %s/%s" % (prefix, ename) print "from :%u" % rev_to_mark(head) print pending_revs = set(revs) - notes if pending_revs: note_mark = marks.next_mark() ref = "refs/notes/hg" print "commit %s" % ref print "mark :%d" % (note_mark) print "committer remote-hg <> %d %s" % (ptime.time(), gittz(ptime.timezone)) desc = "Notes for %s\n" % (name) print "data %d" % (len(desc)) print desc if marks.last_note: print "from :%u" % marks.last_note for rev in pending_revs: notes.add(rev) c = repo[rev] print "N inline :%u" % rev_to_mark(c) msg = c.hex() print "data %d" % (len(msg)) print msg print marks.last_note = note_mark marks.set_tip(ename, head.hex()) # hg->git: export tag ref from hg to git def export_tag(repo, tag): export_ref(repo, tag, 'tags', repo[hgref(tag)]) # hg->git: export bookmark ref from hg to git def export_bookmark(repo, bmark): head = bmarks[hgref(bmark)] export_ref(repo, bmark, 'bookmarks', head) # hg->git: export branch ref from hg to git def export_branch(repo, branch): tip = get_branch_tip(repo, branch) head = repo[tip] export_ref(repo, branch, 'branches', head) # hg->git: export HEAD ref from hg to git def export_head(repo): export_ref(repo, g_head[0], 'bookmarks', g_head[1]) # Handle the 'capabilities' remote-helper command. def do_capabilities(parser): print "import" print "export" print "refspec refs/heads/branches/*:%s/branches/*" % prefix print "refspec refs/heads/*:%s/bookmarks/*" % prefix print "refspec refs/tags/*:%s/tags/*" % prefix path = os.path.join(dirname, 'marks-git') # capabilities preceded with * are mandatory if os.path.exists(path): print "*import-marks %s" % path print "*export-marks %s" % path print "option" print def branch_tip(branch): return branches[branch][-1] def get_branch_tip(repo, branch): heads = branches.get(hgref(branch), None) if not heads: return None # verify there's only one head if (len(heads) > 1): warn("Branch '%s' has more than one head, consider merging" % branch) return branch_tip(hgref(branch)) return heads[0] # helper function for do_list # hg->git: figure out the 'head' of the hg repository def list_head(repo, cur): global g_head, fake_bmark if 'default' not in branches: # empty repo return node = repo[branch_tip('default')] head = 'master' if 'master' not in bmarks else 'default' fake_bmark = head bmarks[head] = node head = gitref(head) print "@refs/heads/%s HEAD" % head g_head = (head, node) # Handle the 'list' remote-helper command. # hg->git: list refs available in the hg repository def do_list(parser): repo = parser.repo for bmark, node in bookmarks.listbookmarks(repo).iteritems(): bmarks[bmark] = repo[node] cur = repo.dirstate.branch() orig = peer if peer else repo for branch, heads in orig.branchmap().iteritems(): # only open heads heads = [h for h in heads if 'close' not in repo.changelog.read(h)[5]] if heads: branches[branch] = heads list_head(repo, cur) if track_branches: for branch in branches: print "? refs/heads/branches/%s" % gitref(branch) for bmark in bmarks: if bmarks[bmark].hex() == '0' * 40: warn("Ignoring invalid bookmark '%s'", bmark) else: print "? refs/heads/%s" % gitref(bmark) for tag, node in repo.tagslist(): if tag == 'tip': continue print "? refs/tags/%s" % gitref(tag) print # Handle the 'import' remote-helper command. # hg->git: read the hg repository and generate a fast-import stream from # it which git then parses. def do_import(parser): repo = parser.repo path = os.path.join(dirname, 'marks-git') print "feature done" if os.path.exists(path): print "feature import-marks=%s" % path print "feature export-marks=%s" % path print "feature force" sys.stdout.flush() tmp = encoding.encoding encoding.encoding = 'utf-8' # lets get all the import lines while parser.check('import'): ref = parser[1] if (ref == 'HEAD'): export_head(repo) elif ref.startswith('refs/heads/branches/'): branch = ref[len('refs/heads/branches/'):] export_branch(repo, branch) elif ref.startswith('refs/heads/'): bmark = ref[len('refs/heads/'):] export_bookmark(repo, bmark) elif ref.startswith('refs/tags/'): tag = ref[len('refs/tags/'):] export_tag(repo, tag) parser.next() encoding.encoding = tmp print 'done' # git->hg: parse 'blob' in the fast-import stream git feeds us def parse_blob(parser): parser.next() mark = parser.get_mark() parser.next() data = parser.get_data() blob_marks[mark] = data parser.next() # git->hg: helper function for parse_commit def get_merge_files(repo, p1, p2, files): for e in repo[p1].files(): if e not in files: if e not in repo[p1].manifest(): continue f = { 'ctx': repo[p1][e] } files[e] = f # git->hg: helper function for parse_commit def c_style_unescape(string): if string[0] == string[-1] == '"': return string.decode('string-escape')[1:-1] return string # git->hg: parse 'commit' in the fast-import stream git feeds us def parse_commit(parser): from_mark = merge_mark = None ref = parser[1] parser.next() commit_mark = parser.get_mark() parser.next() author = parser.get_author() parser.next() committer = parser.get_author() parser.next() data = parser.get_data() parser.next() if parser.check('from'): from_mark = parser.get_mark() parser.next() if parser.check('merge'): merge_mark = parser.get_mark() parser.next() if parser.check('merge'): die('octopus merges are not supported yet') # fast-export adds an extra newline if data[-1] == '\n': data = data[:-1] files = {} for line in parser: if parser.check('M'): t, m, mark_ref, path = line.split(' ', 3) if m == '160000': warn("Git submodules are not supported, ignoring '%s'", path) continue mark = int(mark_ref[1:]) f = { 'mode': hgmode(m), 'data': blob_marks[mark] } elif parser.check('D'): t, path = line.split(' ', 1) f = { 'deleted': True } else: die('Unknown file command: %s' % line) path = c_style_unescape(path) files[path] = f # only export the commits if we are on an internal proxy repo if dry_run and not peer: parsed_refs[ref] = None return def getfilectx(repo, memctx, f): of = files[f] if 'deleted' in of: # the file is not available anymore - was deleted if check_version(3, 2): return None else: raise IOError if 'ctx' in of: return of['ctx'] is_exec = of['mode'] == 'x' is_link = of['mode'] == 'l' rename = of.get('rename', None) if check_version(3, 1): return context.memfilectx(repo, f, of['data'], is_link, is_exec, rename) else: return context.memfilectx(f, of['data'], is_link, is_exec, rename) repo = parser.repo user, date, tz = author extra = {} if committer != author: extra['committer'] = "%s %u %u" % committer if from_mark: p1 = mark_to_rev(from_mark) else: p1 = '0' * 40 if merge_mark: p2 = mark_to_rev(merge_mark) else: p2 = '0' * 40 # # If files changed from any of the parents, hg wants to know, but in git if # nothing changed from the first parent, nothing changed. # if merge_mark: get_merge_files(repo, p1, p2, files) # Check if the ref is supposed to be a named branch if ref.startswith('refs/heads/branches/'): branch = ref[len('refs/heads/branches/'):] extra['branch'] = hgref(branch) if mode == 'hg': i = data.find('\n--HG--\n') if i >= 0: tmp = data[i + len('\n--HG--\n'):].strip() for k, v in [e.split(' : ', 1) for e in tmp.split('\n')]: if k == 'rename': old, new = v.split(' => ', 1) files[new]['rename'] = old elif k == 'branch': extra[k] = v elif k == 'extra': ek, ev = v.split(' : ', 1) extra[ek] = urllib.unquote(ev) data = data[:i] ctx = context.memctx(repo, (p1, p2), data, files.keys(), getfilectx, user, (date, tz), extra) tmp = encoding.encoding encoding.encoding = 'utf-8' node = hghex(repo.commitctx(ctx)) encoding.encoding = tmp parsed_refs[ref] = node marks.new_mark(node, commit_mark) # git->hg: parse 'reset' in the fast-import stream git feeds us def parse_reset(parser): ref = parser[1] parser.next() # ugh if parser.check('commit'): parse_commit(parser) return if not parser.check('from'): return from_mark = parser.get_mark() parser.next() try: rev = mark_to_rev(from_mark) except KeyError: rev = None parsed_refs[ref] = rev # git->hg: parse 'tag' in the fast-import stream git feeds us def parse_tag(parser): name = parser[1] parser.next() from_mark = parser.get_mark() parser.next() tagger = parser.get_author() parser.next() data = parser.get_data() parser.next() parsed_tags[name] = (tagger, data) def write_tag(repo, tag, node, msg, author): branch = repo[node].branch() tip = branch_tip(branch) tip = repo[tip] def getfilectx(repo, memctx, f): try: fctx = tip.filectx(f) data = fctx.data() except error.ManifestLookupError: data = "" content = data + "%s %s\n" % (node, tag) if check_version(3, 1): return context.memfilectx(repo, f, content, False, False, None) else: return context.memfilectx(f, content, False, False, None) p1 = tip.hex() p2 = '0' * 40 if author: user, date, tz = author date_tz = (date, tz) else: cmd = ['git', 'var', 'GIT_COMMITTER_IDENT'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) output, _ = process.communicate() m = re.match('^.* <.*>', output) if m: user = m.group(0) else: user = repo.ui.username() date_tz = None ctx = context.memctx(repo, (p1, p2), msg, ['.hgtags'], getfilectx, user, date_tz, {'branch': branch}) tmp = encoding.encoding encoding.encoding = 'utf-8' tagnode = repo.commitctx(ctx) encoding.encoding = tmp return (tagnode, branch) def checkheads_bmark(repo, ref, ctx): bmark = ref[len('refs/heads/'):] if bmark not in bmarks: # new bmark return True ctx_old = bmarks[bmark] ctx_new = ctx if not ctx.rev(): print "error %s unknown" % ref return False if not repo.changelog.descendant(ctx_old.rev(), ctx_new.rev()): if force_push: print "ok %s forced update" % ref else: print "error %s non-fast forward" % ref return False return True def checkheads(repo, remote, p_revs): remotemap = remote.branchmap() if not remotemap: # empty repo return True new = {} ret = True for node, ref in p_revs.iteritems(): ctx = repo[node] branch = ctx.branch() if branch not in remotemap: # new branch continue if not ref.startswith('refs/heads/branches'): if ref.startswith('refs/heads/'): if not checkheads_bmark(repo, ref, ctx): ret = False # only check branches continue new.setdefault(branch, []).append(ctx.rev()) for branch, heads in new.iteritems(): old = [repo.changelog.rev(x) for x in remotemap[branch]] for rev in heads: if check_version(2, 3): ancestors = repo.changelog.ancestors([rev], stoprev=min(old)) else: ancestors = repo.changelog.ancestors(rev) found = False for x in old: if x in ancestors: found = True break if found: continue node = repo.changelog.node(rev) ref = p_revs[node] if force_push: print "ok %s forced update" % ref else: print "error %s non-fast forward" % ref ret = False return ret def push_unsafe(repo, remote, parsed_refs, p_revs): force = force_push fci = discovery.findcommonincoming commoninc = fci(repo, remote, force=force) common, _, remoteheads = commoninc if not checkheads(repo, remote, p_revs): return None if check_version(3, 2): cg = changegroup.getchangegroup(repo, 'push', heads=list(p_revs), common=common) elif check_version(3, 0): cg = changegroup.getbundle(repo, 'push', heads=list(p_revs), common=common) else: cg = repo.getbundle('push', heads=list(p_revs), common=common) unbundle = remote.capable('unbundle') if unbundle: if force: remoteheads = ['force'] ret = remote.unbundle(cg, remoteheads, 'push') else: ret = remote.addchangegroup(cg, 'push', repo.url()) phases = remote.listkeys('phases') if phases: for head in p_revs: # update to public remote.pushkey('phases', hghex(head), '1', '0') return ret def push(repo, remote, parsed_refs, p_revs): if hasattr(remote, 'canpush') and not remote.canpush(): print "error cannot push" if not p_revs: # nothing to push return lock = None unbundle = remote.capable('unbundle') if not unbundle: lock = remote.lock() try: ret = push_unsafe(repo, remote, parsed_refs, p_revs) finally: if lock is not None: lock.release() return ret def check_tip(ref, kind, name, heads): try: ename = '%s/%s' % (kind, name) tip = marks.get_tip(ename) except KeyError: return True else: return tip in heads # Handle the 'export' remote-helper command. # git->hg: parse the fast-import stream git feeds us, # and add the commits and data in it to the hg repository. def do_export(parser): p_bmarks = [] p_revs = {} parser.next() # parse the fast-import stream # see also http://git-scm.com/docs/git-fast-import for line in parser.each_block('done'): if parser.check('blob'): parse_blob(parser) elif parser.check('commit'): parse_commit(parser) elif parser.check('reset'): parse_reset(parser) elif parser.check('tag'): parse_tag(parser) elif parser.check('feature'): pass else: die('unhandled export command: %s' % line) need_fetch = False for ref, node in parsed_refs.iteritems(): bnode = hgbin(node) if node else None if ref.startswith('refs/heads/branches'): branch = ref[len('refs/heads/branches/'):] if branch in branches and bnode in branches[branch]: # up to date continue if peer: remotemap = peer.branchmap() if remotemap and branch in remotemap: heads = [hghex(e) for e in remotemap[branch]] if not check_tip(ref, 'branches', branch, heads): print "error %s fetch first" % ref need_fetch = True continue p_revs[bnode] = ref print "ok %s" % ref elif ref.startswith('refs/heads/'): bmark = ref[len('refs/heads/'):] new = node old = bmarks[bmark].hex() if bmark in bmarks else '' if old == new: continue print "ok %s" % ref if bmark != fake_bmark and \ not (bmark == 'master' and bmark not in parser.repo._bookmarks): p_bmarks.append((ref, bmark, old, new)) if peer: remote_old = peer.listkeys('bookmarks').get(bmark) if remote_old: if not check_tip(ref, 'bookmarks', bmark, remote_old): print "error %s fetch first" % ref need_fetch = True continue p_revs[bnode] = ref elif ref.startswith('refs/tags/'): if dry_run: print "ok %s" % ref continue tag = ref[len('refs/tags/'):] tag = hgref(tag) author, msg = parsed_tags.get(tag, (None, None)) if mode == 'git': if not msg: msg = 'Added tag %s for changeset %s' % (tag, node[:12]) tagnode, branch = write_tag(parser.repo, tag, node, msg, author) p_revs[tagnode] = 'refs/heads/branches/' + gitref(branch) else: fp = parser.repo.opener('localtags', 'a') fp.write('%s %s\n' % (node, tag)) fp.close() p_revs[bnode] = ref print "ok %s" % ref else: # transport-helper/fast-export bugs continue if need_fetch: print return if dry_run: if peer and not force_push: checkheads(parser.repo, peer, p_revs) print return if peer: if not push(parser.repo, peer, parsed_refs, p_revs): # do not update bookmarks print return # update remote bookmarks remote_bmarks = peer.listkeys('bookmarks') for ref, bmark, old, new in p_bmarks: if force_push: old = remote_bmarks.get(bmark, '') if not peer.pushkey('bookmarks', bmark, old, new): print "error %s" % ref else: # update local bookmarks for ref, bmark, old, new in p_bmarks: if not bookmarks.pushbookmark(parser.repo, bmark, old, new): print "error %s" % ref print # Handle the 'option' remote-helper command. def do_option(parser): global dry_run, force_push _, key, value = parser.line.split(' ') if key == 'dry-run': dry_run = (value == 'true') print 'ok' elif key == 'force': force_push = (value == 'true') print 'ok' else: print 'unsupported' def fix_path(alias, repo, orig_url): url = urlparse.urlparse(orig_url, 'file') if url.scheme != 'file' or os.path.isabs(os.path.expanduser(url.path)): return abs_url = urlparse.urljoin("%s/" % os.getcwd(), orig_url) cmd = ['git', 'config', 'remote.%s.url' % alias, "hg::%s" % abs_url] subprocess.call(cmd) def main(args): global prefix, gitdir, dirname, branches, bmarks global marks, blob_marks, parsed_refs global peer, mode, bad_mail, bad_name global track_branches, force_push, is_tmp global parsed_tags global filenodes global fake_bmark, hg_version global dry_run global notes, alias marks = None is_tmp = False gitdir = os.environ.get('GIT_DIR', None) if len(args) < 3: die('Not enough arguments.') if not gitdir: die('GIT_DIR not set') alias = args[1] url = args[2] peer = None hg_git_compat = get_config_bool('remote-hg.hg-git-compat') track_branches = get_config_bool('remote-hg.track-branches', True) force_push = False if hg_git_compat: mode = 'hg' bad_mail = 'none@none' bad_name = '' else: mode = 'git' bad_mail = 'unknown' bad_name = 'Unknown' if alias[4:] == url: is_tmp = True alias = hashlib.sha1(alias).hexdigest() dirname = os.path.join(gitdir, 'hg', alias) branches = {} bmarks = {} blob_marks = {} parsed_refs = {} parsed_tags = {} filenodes = {} fake_bmark = None try: version, _, extra = util.version().partition('+') version = list(int(e) for e in version.split('.')) if extra: version[1] += 1 hg_version = tuple(version) except: hg_version = None dry_run = False notes = set() repo = get_repo(url, alias) prefix = 'refs/hg/%s' % alias if not is_tmp: fix_path(alias, peer or repo, url) marks_path = os.path.join(dirname, 'marks-hg') marks = Marks(marks_path, repo) if sys.platform == 'win32': import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) parser = Parser(repo) for line in parser: if parser.check('capabilities'): do_capabilities(parser) elif parser.check('list'): do_list(parser) elif parser.check('import'): do_import(parser) elif parser.check('export'): do_export(parser) elif parser.check('option'): do_option(parser) else: die('unhandled command: %s' % line) sys.stdout.flush() marks.store() def bye(): if is_tmp: shutil.rmtree(dirname) if __name__ == "__main__": atexit.register(bye) try: sys.exit(main(sys.argv)) except Exception, e: if DEBUG_REMOTEHG: raise die(str(e)) git-remote-hg-0.3/test/000077500000000000000000000000001263033635200150065ustar00rootroot00000000000000git-remote-hg-0.3/test/.gitignore000066400000000000000000000000501263033635200167710ustar00rootroot00000000000000test-results/ trash directory.*/ .prove git-remote-hg-0.3/test/Makefile000066400000000000000000000003531263033635200164470ustar00rootroot00000000000000RM ?= rm -f T = $(wildcard *.t) TEST_DIRECTORY := $(CURDIR) export TEST_DIRECTORY all: test test: $(T) $(MAKE) clean $(T): $(SHELL) $@ $(TEST_OPTS) clean: $(RM) -r 'trash directory'.* test-results .PHONY: all test $(T) clean git-remote-hg-0.3/test/bidi.t000077500000000000000000000115421263033635200161100ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2012 Felipe Contreras # # Base commands from hg-git tests: # https://bitbucket.org/durin42/hg-git/src # test_description='Test bidirectionality of remote-hg' test -n "$TEST_DIRECTORY" || TEST_DIRECTORY=$(dirname $0)/ . "$TEST_DIRECTORY"/test-lib.sh # clone to a git repo git_clone () { git clone -q "hg::$1" $2 } # clone to an hg repo hg_clone () { ( hg init $2 && cd $1 && git push -q "hg::../$2" 'refs/tags/*:refs/tags/*' 'refs/heads/*:refs/heads/*' ) && (cd $2 && hg -q update) } # push an hg repo hg_push () { ( cd $2 git checkout -q -b tmp && git fetch -q "hg::../$1" 'refs/tags/*:refs/tags/*' 'refs/heads/*:refs/heads/*' && git checkout -q @{-1} && git branch -q -D tmp 2> /dev/null || true ) } hg_log () { hg -R $1 log --graph --debug } setup () { cat > "$HOME"/.hgrc <<-EOF && [ui] username = A U Thor [defaults] backout = -d "0 0" commit = -d "0 0" debugrawcommit = -d "0 0" tag = -d "0 0" [extensions]" graphlog = EOF git config --global remote-hg.hg-git-compat true git config --global remote-hg.track-branches true HGEDITOR=/usr/bin/true GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0230" GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" export HGEDITOR GIT_AUTHOR_DATE GIT_COMMITTER_DATE } setup test_expect_success 'encoding' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add älphà" && GIT_AUTHOR_NAME="tést èncödîng" && export GIT_AUTHOR_NAME && echo beta > beta && git add beta && git commit -m "add beta" && echo gamma > gamma && git add gamma && git commit -m "add gämmâ" && : TODO git config i18n.commitencoding latin-1 && echo delta > delta && git add delta && git commit -m "add déltà" ) && hg_clone gitrepo hgrepo && git_clone hgrepo gitrepo2 && hg_clone gitrepo2 hgrepo2 && HGENCODING=utf-8 hg_log hgrepo > expected && HGENCODING=utf-8 hg_log hgrepo2 > actual && test_cmp expected actual ' test_expect_success 'file removal' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add alpha" && echo beta > beta && git add beta && git commit -m "add beta" mkdir foo && echo blah > foo/bar && git add foo && git commit -m "add foo" && git rm alpha && git commit -m "remove alpha" && git rm foo/bar && git commit -m "remove foo/bar" ) && hg_clone gitrepo hgrepo && git_clone hgrepo gitrepo2 && hg_clone gitrepo2 hgrepo2 && hg_log hgrepo > expected && hg_log hgrepo2 > actual && test_cmp expected actual ' test_expect_success 'git tags' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && git config receive.denyCurrentBranch ignore && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git tag alpha && echo beta > beta && git add beta && git commit -m "add beta" && git tag -a -m "added tag beta" beta ) && hg_clone gitrepo hgrepo && git_clone hgrepo gitrepo2 && hg_clone gitrepo2 hgrepo2 && hg_log hgrepo > expected && hg_log hgrepo2 > actual && test_cmp expected actual ' test_expect_success 'git submodules' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git tag alpha && git init -q subrepo && cd subrepo echo beta > beta && git add beta && git commit -m "add beta" && cd .. && git submodule add ./subrepo ext && git commit -m "add submodule" ) && hg_clone gitrepo hgrepo && git_clone hgrepo gitrepo2 && hg_clone gitrepo2 hgrepo2 && hg_log hgrepo > expected && hg_log hgrepo2 > actual && test_cmp expected actual ' test_expect_success 'hg branch' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -q -m "add alpha" && git checkout -q -b not-master ) && ( hg_clone gitrepo hgrepo && cd hgrepo && hg -q co default && hg mv alpha beta && hg -q commit -m "rename alpha to beta" && hg branch gamma | grep -v "permanent and global" && hg -q commit -m "started branch gamma" ) && hg_push hgrepo gitrepo && hg_clone gitrepo hgrepo2 && : Back to the common revision && (cd hgrepo && hg checkout default) && hg_log hgrepo > expected && hg_log hgrepo2 > actual && test_cmp expected actual ' test_expect_success 'hg tags' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git checkout -q -b not-master ) && ( hg_clone gitrepo hgrepo && cd hgrepo && hg co default && hg tag alpha ) && hg_push hgrepo gitrepo && hg_clone gitrepo hgrepo2 && hg_log hgrepo > expected && hg_log hgrepo2 > actual && test_cmp expected actual ' test_done git-remote-hg-0.3/test/hg-git.t000077500000000000000000000237411263033635200163640ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2012 Felipe Contreras # # Base commands from hg-git tests: # https://bitbucket.org/durin42/hg-git/src # test_description='Test remote-hg output compared to hg-git' test -n "$TEST_DIRECTORY" || TEST_DIRECTORY=$(dirname $0)/ . "$TEST_DIRECTORY"/test-lib.sh if python2 -c 'import hggit' > /dev/null 2>&1 then hggit=hggit elif python2 -c 'import hgext.git' > /dev/null 2>&1 then hggit=hgext.git else skip_all='skipping remote-hg tests; hg-git not available' test_done fi hg_version=$(python2 -c 'from mercurial import util; print util.version()') # clone to a git repo with git git_clone_git () { git clone -q "hg::$1" $2 && (cd $2 && git checkout master && git branch -D default) } # clone to an hg repo with git hg_clone_git () { ( hg init $2 && hg -R $2 bookmark -i master && cd $1 && git push -q "hg::../$2" 'refs/tags/*:refs/tags/*' 'refs/heads/*:refs/heads/*' ) && (cd $2 && hg -q update) } # clone to a git repo with hg git_clone_hg () { ( git init -q $2 && cd $1 && hg bookmark -i -f -r tip master && hg -q push -r master ../$2 || true ) } # clone to an hg repo with hg hg_clone_hg () { hg -q clone $1 $2 } # push an hg repo with git hg_push_git () { ( cd $2 git checkout -q -b tmp && git fetch -q "hg::../$1" 'refs/tags/*:refs/tags/*' 'refs/heads/*:refs/heads/*' && git branch -D default && git checkout -q @{-1} && git branch -q -D tmp 2> /dev/null || true ) } # push an hg git repo with hg hg_push_hg () { ( cd $1 && hg -q push ../$2 || true ) } hg_log () { hg -R $1 log --graph --debug > log && grep -v 'tag: *default/' log } git_log () { git --git-dir=$1/.git fast-export --branches } setup () { cat > "$HOME"/.hgrc <<-EOF && [ui] username = A U Thor [defaults] backout = -d "0 0" commit = -d "0 0" debugrawcommit = -d "0 0" tag = -d "0 0" [extensions] $hggit = graphlog = EOF git config --global receive.denycurrentbranch warn git config --global remote-hg.hg-git-compat true git config --global remote-hg.track-branches false HGEDITOR=true HGMERGE=true GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0230" GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" export HGEDITOR HGMERGE GIT_AUTHOR_DATE GIT_COMMITTER_DATE } setup test_expect_success 'executable bit' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && chmod 0644 alpha && git add alpha && git commit -m "add alpha" && chmod 0755 alpha && git add alpha && git commit -m "set executable bit" && chmod 0644 alpha && git add alpha && git commit -m "clear executable bit" ) && for x in hg git do ( hg_clone_$x gitrepo hgrepo-$x && cd hgrepo-$x && hg_log . && hg manifest -r 1 -v && hg manifest -v ) > "output-$x" && git_clone_$x hgrepo-$x gitrepo2-$x && git_log gitrepo2-$x > "log-$x" done && test_cmp output-hg output-git && test_cmp log-hg log-git ' test_expect_success 'symlink' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add alpha" && ln -s alpha beta && git add beta && git commit -m "add beta" ) && for x in hg git do ( hg_clone_$x gitrepo hgrepo-$x && cd hgrepo-$x && hg_log . && hg manifest -v ) > "output-$x" && git_clone_$x hgrepo-$x gitrepo2-$x && git_log gitrepo2-$x > "log-$x" done && test_cmp output-hg output-git && test_cmp log-hg log-git ' test_expect_success 'merge conflict 1' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( hg init hgrepo1 && cd hgrepo1 && echo A > afile && hg add afile && hg ci -m "origin" && echo B > afile && hg ci -m "A->B" && hg up -r0 && echo C > afile && hg ci -m "A->C" && hg merge -r1 && echo C > afile && hg resolve -m afile && hg ci -m "merge to C" ) && for x in hg git do git_clone_$x hgrepo1 gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && hg_log hgrepo2-$x > "hg-log-$x" && git_log gitrepo-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_success 'merge conflict 2' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( hg init hgrepo1 && cd hgrepo1 && echo A > afile && hg add afile && hg ci -m "origin" && echo B > afile && hg ci -m "A->B" && hg up -r0 && echo C > afile && hg ci -m "A->C" && hg merge -r1 || true && echo B > afile && hg resolve -m afile && hg ci -m "merge to B" ) && for x in hg git do git_clone_$x hgrepo1 gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && hg_log hgrepo2-$x > "hg-log-$x" && git_log gitrepo-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_success 'converged merge' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( hg init hgrepo1 && cd hgrepo1 && echo A > afile && hg add afile && hg ci -m "origin" && echo B > afile && hg ci -m "A->B" && echo C > afile && hg ci -m "B->C" && hg up -r0 && echo C > afile && hg ci -m "A->C" && hg merge -r2 || true && hg ci -m "merge" ) && for x in hg git do git_clone_$x hgrepo1 gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && hg_log hgrepo2-$x > "hg-log-$x" && git_log gitrepo-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_success 'encoding' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add älphà" && GIT_AUTHOR_NAME="tést èncödîng" && export GIT_AUTHOR_NAME && echo beta > beta && git add beta && git commit -m "add beta" && echo gamma > gamma && git add gamma && git commit -m "add gämmâ" && : TODO git config i18n.commitencoding latin-1 && echo delta > delta && git add delta && git commit -m "add déltà" ) && for x in hg git do hg_clone_$x gitrepo hgrepo-$x && git_clone_$x hgrepo-$x gitrepo2-$x && HGENCODING=utf-8 hg_log hgrepo-$x > "hg-log-$x" && git_log gitrepo2-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_success 'file removal' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && echo alpha > alpha && git add alpha && git commit -m "add alpha" && echo beta > beta && git add beta && git commit -m "add beta" mkdir foo && echo blah > foo/bar && git add foo && git commit -m "add foo" && git rm alpha && git commit -m "remove alpha" && git rm foo/bar && git commit -m "remove foo/bar" ) && for x in hg git do ( hg_clone_$x gitrepo hgrepo-$x && cd hgrepo-$x && hg_log . && hg manifest -r 3 && hg manifest ) > "output-$x" && git_clone_$x hgrepo-$x gitrepo2-$x && git_log gitrepo2-$x > "log-$x" done && test_cmp output-hg output-git && test_cmp log-hg log-git ' test_expect_success 'git tags' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( git init -q gitrepo && cd gitrepo && git config receive.denyCurrentBranch ignore && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git tag alpha && echo beta > beta && git add beta && git commit -m "add beta" && git tag -a -m "added tag beta" beta ) && for x in hg git do hg_clone_$x gitrepo hgrepo-$x && hg_log hgrepo-$x > "log-$x" done && test_cmp log-hg log-git ' test_expect_success 'hg author' ' test_when_finished "rm -rf gitrepo* hgrepo*" && for x in hg git do ( git init -q gitrepo-$x && cd gitrepo-$x && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git checkout -q -b not-master ) && ( hg_clone_$x gitrepo-$x hgrepo-$x && cd hgrepo-$x && hg co master && echo beta > beta && hg add beta && hg commit -u "test" -m "add beta" && echo gamma >> beta && hg commit -u "test (comment)" -m "modify beta" && echo gamma > gamma && hg add gamma && hg commit -u "" -m "add gamma" && echo delta > delta && hg add delta && hg commit -u "name" -m "add delta" && echo epsilon > epsilon && hg add epsilon && hg commit -u "name zeta && hg add zeta && hg commit -u " test " -m "add zeta" && echo eta > eta && hg add eta && hg commit -u "test < test@example.com >" -m "add eta" && echo theta > theta && hg add theta && hg commit -u "test >test@example.com>" -m "add theta" && echo iota > iota && hg add iota && hg commit -u "test example com>" -m "add iota" ) && hg_push_$x hgrepo-$x gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && hg_log hgrepo2-$x > "hg-log-$x" && git_log gitrepo-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_failure 'hg branch' ' test_when_finished "rm -rf gitrepo* hgrepo*" && for x in hg git do ( git init -q gitrepo-$x && cd gitrepo-$x && echo alpha > alpha && git add alpha && git commit -q -m "add alpha" && git checkout -q -b not-master ) && ( hg_clone_$x gitrepo-$x hgrepo-$x && cd hgrepo-$x && hg -q co master && hg mv alpha beta && hg -q commit -m "rename alpha to beta" && hg branch gamma | grep -v "permanent and global" && hg -q commit -m "started branch gamma" ) && hg_push_$x hgrepo-$x gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && hg_log hgrepo2-$x > "hg-log-$x" && git_log gitrepo-$x > "git-log-$x" done && test_cmp hg-log-hg hg-log-git && test_cmp git-log-hg git-log-git ' test_expect_success 'hg tags' ' test_when_finished "rm -rf gitrepo* hgrepo*" && for x in hg git do ( git init -q gitrepo-$x && cd gitrepo-$x && echo alpha > alpha && git add alpha && git commit -m "add alpha" && git checkout -q -b not-master ) && ( hg_clone_$x gitrepo-$x hgrepo-$x && cd hgrepo-$x && hg co master && hg tag alpha ) && hg_push_$x hgrepo-$x gitrepo-$x && hg_clone_$x gitrepo-$x hgrepo2-$x && ( git --git-dir=gitrepo-$x/.git tag -l && hg_log hgrepo2-$x && cat hgrepo2-$x/.hgtags ) > "output-$x" done && test_cmp output-hg output-git ' test_done git-remote-hg-0.3/test/main.t000077500000000000000000000465171263033635200161370ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2012 Felipe Contreras # # Base commands from hg-git tests: # https://bitbucket.org/durin42/hg-git/src # test_description='Test remote-hg' test -n "$TEST_DIRECTORY" || TEST_DIRECTORY=$(dirname $0)/ . "$TEST_DIRECTORY"/test-lib.sh check () { echo $3 > expected && git --git-dir=$1/.git log --format='%s' -1 $2 > actual && test_cmp expected actual } check_branch () { if test -n "$3" then echo $3 > expected && hg -R $1 log -r $2 --template '{desc}\n' > actual && test_cmp expected actual else hg -R $1 branches > out && ! grep $2 out fi } check_bookmark () { if test -n "$3" then echo $3 > expected && hg -R $1 log -r "bookmark('$2')" --template '{desc}\n' > actual && test_cmp expected actual else hg -R $1 bookmarks > out && ! grep $2 out fi } check_files () { git --git-dir=$1/.git ls-files > actual && if test $# -gt 1 then printf "%s\n" "$2" > expected else > expected fi && test_cmp expected actual } check_push () { expected_ret=$1 ret=0 ref_ret=0 shift git push origin "$@" 2> error ret=$? cat error while IFS=':' read branch kind do case "$kind" in 'new') grep "^ \* \[new branch\] *${branch} -> ${branch}$" error || ref_ret=1 ;; 'non-fast-forward') grep "^ ! \[rejected\] *${branch} -> ${branch} (non-fast-forward)$" error || ref_ret=1 ;; 'fetch-first') grep "^ ! \[rejected\] *${branch} -> ${branch} (fetch first)$" error || ref_ret=1 ;; 'forced-update') grep "^ + [a-f0-9]*\.\.\.[a-f0-9]* *${branch} -> ${branch} (forced update)$" error || ref_ret=1 ;; '') grep "^ [a-f0-9]*\.\.[a-f0-9]* *${branch} -> ${branch}$" error || ref_ret=1 ;; esac test $ref_ret -ne 0 && echo "match for '$branch' failed" && break done if test $expected_ret -ne $ret || test $ref_ret -ne 0 then return 1 fi return 0 } setup () { cat > "$HOME"/.hgrc <<-EOF && [ui] username = H G Wells [extensions] mq = EOF GIT_AUTHOR_DATE="2007-01-01 00:00:00 +0230" && GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE" && export GIT_COMMITTER_DATE GIT_AUTHOR_DATE } setup test_expect_success 'setup' ' ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero ) ' test_expect_success 'cloning' ' test_when_finished "rm -rf gitrepo*" && git clone "hg::hgrepo" gitrepo && check gitrepo HEAD zero ' test_expect_success 'cloning with branches' ' test_when_finished "rm -rf gitrepo*" && ( cd hgrepo && hg branch next && echo next > content && hg commit -m next ) && git clone "hg::hgrepo" gitrepo && check gitrepo origin/branches/next next ' test_expect_success 'cloning with bookmarks' ' test_when_finished "rm -rf gitrepo*" && ( cd hgrepo && hg checkout default && hg bookmark feature-a && echo feature-a > content && hg commit -m feature-a ) && git clone "hg::hgrepo" gitrepo && check gitrepo origin/feature-a feature-a ' test_expect_success 'update bookmark' ' test_when_finished "rm -rf gitrepo*" && ( cd hgrepo && hg bookmark devel ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git checkout --quiet devel && echo devel > content && git commit -a -m devel && git push --quiet ) && check_bookmark hgrepo devel devel ' test_expect_success 'new bookmark' ' test_when_finished "rm -rf gitrepo*" && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git checkout --quiet -b feature-b && echo feature-b > content && git commit -a -m feature-b && git push --quiet origin feature-b ) && check_bookmark hgrepo feature-b feature-b ' # cleanup previous stuff rm -rf hgrepo author_test () { echo $1 >> content && hg commit -u "$2" -m "add $1" && echo "$3" >> ../expected } test_expect_success 'authors' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && touch content && hg add content && > ../expected && author_test alpha "" "H G Wells " && author_test beta "beta" "beta " && author_test gamma "gamma (comment)" "gamma " && author_test delta "" "Unknown " && author_test epsilon "epsilon" "epsilon " && author_test zeta "zeta " && author_test eta " eta " "eta " && author_test theta "theta < test@example.com >" "theta " && author_test iota "iota >test@example.com>" "iota " && author_test kappa "kappa < test example com>" "kappa " && author_test lambda "lambda@example.com" "Unknown " && author_test mu "mu.mu@example.com" "Unknown " ) && git clone "hg::hgrepo" gitrepo && git --git-dir=gitrepo/.git log --reverse --format="%an <%ae>" > actual && test_cmp expected actual ' test_expect_success 'strip' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one >> content && hg add content && hg commit -m one && echo two >> content && hg commit -m two ) && git clone "hg::hgrepo" gitrepo && ( cd hgrepo && hg strip 1 && echo three >> content && hg commit -m three && echo four >> content && hg commit -m four ) && ( cd gitrepo && git fetch && git log --format="%s" origin/master > ../actual ) && hg -R hgrepo log --template "{desc}\n" > expected && test_cmp actual expected ' test_expect_success 'remote push with master bookmark' ' test_when_finished "rm -rf hgrepo gitrepo*" && ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero && hg bookmark master && echo one > content && hg commit -m one ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && echo two > content && git commit -a -m two && git push ) && check_branch hgrepo default two ' cat > expected <<\EOF changeset: 0:6e2126489d3d tag: tip user: A U Thor date: Mon Jan 01 00:00:00 2007 +0230 summary: one EOF test_expect_success 'remote push from master branch' ' test_when_finished "rm -rf hgrepo gitrepo*" && hg init hgrepo && ( git init gitrepo && cd gitrepo && git remote add origin "hg::../hgrepo" && echo one > content && git add content && git commit -a -m one && git push origin master ) && hg -R hgrepo log > actual && cat actual && test_cmp expected actual && check_branch hgrepo default one ' GIT_REMOTE_HG_TEST_REMOTE=1 export GIT_REMOTE_HG_TEST_REMOTE test_expect_success 'remote cloning' ' test_when_finished "rm -rf gitrepo*" && ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero ) && git clone "hg::hgrepo" gitrepo && check gitrepo HEAD zero ' test_expect_success 'moving remote clone' ' test_when_finished "rm -rf gitrepo*" && ( git clone "hg::hgrepo" gitrepo && mv gitrepo gitrepo2 && cd gitrepo2 && git fetch ) ' test_expect_success 'remote update bookmark' ' test_when_finished "rm -rf gitrepo*" && ( cd hgrepo && hg bookmark devel ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git checkout --quiet devel && echo devel > content && git commit -a -m devel && git push --quiet ) && check_bookmark hgrepo devel devel ' test_expect_success 'remote new bookmark' ' test_when_finished "rm -rf gitrepo*" && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git checkout --quiet -b feature-b && echo feature-b > content && git commit -a -m feature-b && git push --quiet origin feature-b ) && check_bookmark hgrepo feature-b feature-b ' test_expect_success 'remote push diverged' ' test_when_finished "rm -rf gitrepo*" && git clone "hg::hgrepo" gitrepo && ( cd hgrepo && hg checkout default && echo bump > content && hg commit -m bump ) && ( cd gitrepo && echo diverge > content && git commit -a -m diverged && check_push 1 <<-\EOF master:non-fast-forward EOF ) && check_branch hgrepo default bump ' test_expect_success 'remote update bookmark diverge' ' test_when_finished "rm -rf gitrepo*" && ( cd hgrepo && hg checkout tip^ && hg bookmark diverge ) && git clone "hg::hgrepo" gitrepo && ( cd hgrepo && echo "bump bookmark" > content && hg commit -m "bump bookmark" ) && ( cd gitrepo && git checkout --quiet diverge && echo diverge > content && git commit -a -m diverge && check_push 1 <<-\EOF diverge:fetch-first EOF ) && check_bookmark hgrepo diverge "bump bookmark" ' test_expect_success 'remote new bookmark multiple branch head' ' test_when_finished "rm -rf gitrepo*" && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git checkout --quiet -b feature-c HEAD^ && echo feature-c > content && git commit -a -m feature-c && git push --quiet origin feature-c ) && check_bookmark hgrepo feature-c feature-c ' # cleanup previous stuff rm -rf hgrepo test_expect_success 'fetch special filenames' ' test_when_finished "rm -rf hgrepo gitrepo && LC_ALL=C" && LC_ALL=C.UTF-8 export LC_ALL ( hg init hgrepo && cd hgrepo && echo test >> "æ rø" && hg add "æ rø" && echo test >> "ø~?" && hg add "ø~?" && hg commit -m add-utf-8 && echo test >> "æ rø" && hg commit -m test-utf-8 && hg rm "ø~?" && hg mv "æ rø" "ø~?" && hg commit -m hg-mv-utf-8 ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git -c core.quotepath=false ls-files > ../actual ) && echo "ø~?" > expected && test_cmp expected actual ' test_expect_success 'push special filenames' ' test_when_finished "rm -rf hgrepo gitrepo && LC_ALL=C" && mkdir -p tmp && cd tmp && LC_ALL=C.UTF-8 export LC_ALL ( hg init hgrepo && cd hgrepo && echo one >> content && hg add content && hg commit -m one ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && echo test >> "æ rø" && git add "æ rø" && git commit -m utf-8 && git push ) && (cd hgrepo && hg update && hg manifest > ../actual ) && printf "content\næ rø\n" > expected && test_cmp expected actual ' setup_big_push () { ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero && hg bookmark bad_bmark1 && echo one > content && hg commit -m one && hg bookmark bad_bmark2 && hg bookmark good_bmark && hg bookmark -i good_bmark && hg -q branch good_branch && echo "good branch" > content && hg commit -m "good branch" && hg -q branch bad_branch && echo "bad branch" > content && hg commit -m "bad branch" ) && git clone "hg::hgrepo" gitrepo && ( cd gitrepo && echo two > content && git commit -q -a -m two && git checkout -q good_bmark && echo three > content && git commit -q -a -m three && git checkout -q bad_bmark1 && git reset --hard HEAD^ && echo four > content && git commit -q -a -m four && git checkout -q bad_bmark2 && git reset --hard HEAD^ && echo five > content && git commit -q -a -m five && git checkout -q -b new_bmark master && echo six > content && git commit -q -a -m six && git checkout -q branches/good_branch && echo seven > content && git commit -q -a -m seven && echo eight > content && git commit -q -a -m eight && git checkout -q branches/bad_branch && git reset --hard HEAD^ && echo nine > content && git commit -q -a -m nine && git checkout -q -b branches/new_branch master && echo ten > content && git commit -q -a -m ten ) } test_expect_success 'remote big push' ' test_when_finished "rm -rf hgrepo gitrepo*" && setup_big_push ( cd gitrepo && check_push 1 --all <<-\EOF master good_bmark branches/good_branch new_bmark:new branches/new_branch:new bad_bmark1:non-fast-forward bad_bmark2:non-fast-forward branches/bad_branch:non-fast-forward EOF ) && check_branch hgrepo default one && check_branch hgrepo good_branch "good branch" && check_branch hgrepo bad_branch "bad branch" && check_branch hgrepo new_branch '' && check_bookmark hgrepo good_bmark one && check_bookmark hgrepo bad_bmark1 one && check_bookmark hgrepo bad_bmark2 one && check_bookmark hgrepo new_bmark '' ' test_expect_success 'remote big push fetch first' ' test_when_finished "rm -rf hgrepo gitrepo*" && ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero && hg bookmark bad_bmark && hg bookmark good_bmark && hg bookmark -i good_bmark && hg -q branch good_branch && echo "good branch" > content && hg commit -m "good branch" && hg -q branch bad_branch && echo "bad branch" > content && hg commit -m "bad branch" ) && git clone "hg::hgrepo" gitrepo && ( cd hgrepo && hg bookmark -f bad_bmark && echo update_bmark > content && hg commit -m "update bmark" ) && ( cd gitrepo && echo two > content && git commit -q -a -m two && git checkout -q good_bmark && echo three > content && git commit -q -a -m three && git checkout -q bad_bmark && echo four > content && git commit -q -a -m four && git checkout -q branches/bad_branch && echo five > content && git commit -q -a -m five && check_push 1 --all <<-\EOF && master good_bmark bad_bmark:fetch-first branches/bad_branch:festch-first EOF git fetch && check_push 1 --all <<-\EOF master good_bmark bad_bmark:non-fast-forward branches/bad_branch:non-fast-forward EOF ) ' test_expect_success GIT_2_0 'remote big push force' ' test_when_finished "rm -rf hgrepo gitrepo*" && setup_big_push ( cd gitrepo && check_push 0 --force --all <<-\EOF master good_bmark branches/good_branch new_bmark:new branches/new_branch:new bad_bmark1:forced-update bad_bmark2:forced-update branches/bad_branch:forced-update EOF ) && check_branch hgrepo default six && check_branch hgrepo good_branch eight && check_branch hgrepo bad_branch nine && check_branch hgrepo new_branch ten && check_bookmark hgrepo good_bmark three && check_bookmark hgrepo bad_bmark1 four && check_bookmark hgrepo bad_bmark2 five && check_bookmark hgrepo new_bmark six ' test_expect_success GIT_2_0 'remote big push dry-run' ' test_when_finished "rm -rf hgrepo gitrepo*" && setup_big_push ( cd gitrepo && check_push 1 --dry-run --all <<-\EOF && master good_bmark branches/good_branch new_bmark:new branches/new_branch:new bad_bmark1:non-fast-forward bad_bmark2:non-fast-forward branches/bad_branch:non-fast-forward EOF check_push 0 --dry-run master good_bmark new_bmark branches/good_branch branches/new_branch <<-\EOF master good_bmark branches/good_branch new_bmark:new branches/new_branch:new EOF ) && check_branch hgrepo default one && check_branch hgrepo good_branch "good branch" && check_branch hgrepo bad_branch "bad branch" && check_branch hgrepo new_branch '' && check_bookmark hgrepo good_bmark one && check_bookmark hgrepo bad_bmark1 one && check_bookmark hgrepo bad_bmark2 one && check_bookmark hgrepo new_bmark '' ' test_expect_success 'remote double failed push' ' test_when_finished "rm -rf hgrepo gitrepo*" && ( hg init hgrepo && cd hgrepo && echo zero > content && hg add content && hg commit -m zero && echo one > content && hg commit -m one ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git reset --hard HEAD^ && echo two > content && git commit -a -m two && test_expect_code 1 git push && test_expect_code 1 git push ) ' test_expect_success 'clone remote with null bookmark, then push' ' test_when_finished "rm -rf gitrepo* hgrepo*" && ( hg init hgrepo && cd hgrepo && echo a > a && hg add a && hg commit -m a && hg bookmark -r null bookmark ) && ( git clone "hg::hgrepo" gitrepo && check gitrepo HEAD a && cd gitrepo && git checkout --quiet -b bookmark && git remote -v && echo b > b && git add b && git commit -m b && git push origin bookmark ) ' test_expect_success 'notes' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one && echo two > content && hg commit -m two ) && git clone "hg::hgrepo" gitrepo && hg -R hgrepo log --template "{node}\n\n" > expected && git --git-dir=gitrepo/.git log --pretty="tformat:%N" --notes=hg > actual && test_cmp expected actual ' test_expect_failure 'push updates notes' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one ) && git clone "hg::hgrepo" gitrepo && ( cd gitrepo && echo two > content && git commit -a -m two git push ) && hg -R hgrepo log --template "{node}\n\n" > expected && git --git-dir=gitrepo/.git log --pretty="tformat:%N" --notes=hg > actual && test_cmp expected actual ' test_expect_success 'pull tags' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one ) && git clone "hg::hgrepo" gitrepo && (cd hgrepo && hg tag v1.0) && (cd gitrepo && git pull) && echo "v1.0" > expected && git --git-dir=gitrepo/.git tag > actual && test_cmp expected actual ' test_expect_success 'push merged named branch' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one && hg branch feature && echo two > content && hg commit -m two && hg update default && echo three > content && hg commit -m three ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git merge -m Merge -Xtheirs origin/branches/feature && git push ) && cat > expected <<-EOF Merge three two one EOF hg -R hgrepo log --template "{desc}\n" > actual && test_cmp expected actual ' test_expect_success 'light tag sets author' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git tag v1.0 && git push --tags ) && echo "C O Mitter " > expected && hg -R hgrepo log --template "{author}\n" -r tip > actual && test_cmp expected actual ' test_expect_success 'push tag different branch' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo one > content && hg add content && hg commit -m one hg branch feature && echo two > content && hg commit -m two ) && ( git clone "hg::hgrepo" gitrepo && cd gitrepo && git branch && git checkout branches/feature && git tag v1.0 && git push --tags ) && echo feature > expected && hg -R hgrepo log --template="{branch}\n" -r tip > actual && test_cmp expected actual ' test_expect_success 'cloning a removed file works' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo test > test_file && hg add test_file && hg commit -m add && hg rm test_file && hg commit -m remove ) && git clone "hg::hgrepo" gitrepo && check_files gitrepo ' test_expect_success 'cloning a file replaced with a directory' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && echo test > dir_or_file && hg add dir_or_file && hg commit -m add && hg rm dir_or_file && mkdir dir_or_file && echo test > dir_or_file/test_file && hg add dir_or_file/test_file && hg commit -m replase ) && git clone "hg::hgrepo" gitrepo && check_files gitrepo "dir_or_file/test_file" ' test_expect_success 'clone replace directory with a file' ' test_when_finished "rm -rf hgrepo gitrepo" && ( hg init hgrepo && cd hgrepo && mkdir dir_or_file && echo test > dir_or_file/test_file && hg add dir_or_file/test_file && hg commit -m add && hg rm dir_or_file/test_file && echo test > dir_or_file && hg add dir_or_file && hg commit -m add && hg rm dir_or_file ) && git clone "hg::hgrepo" gitrepo && check_files gitrepo "dir_or_file" ' test_done git-remote-hg-0.3/test/sharness.sh000066400000000000000000000441111263033635200171710ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2011-2012 Mathias Lafeldt # Copyright (c) 2005-2012 Git project # Copyright (c) 2005-2012 Junio C Hamano # # 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 2 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 http://www.gnu.org/licenses/ . # Public: Current version of Sharness. SHARNESS_VERSION="0.3.0" export SHARNESS_VERSION # Public: The file extension for tests. By default, it is set to "t". : ${SHARNESS_TEST_EXTENSION:=t} export SHARNESS_TEST_EXTENSION # Keep the original TERM for say_color ORIGINAL_TERM=$TERM # For repeatability, reset the environment to a known state. LANG=C LC_ALL=C PAGER=cat TZ=UTC TERM=dumb EDITOR=: export LANG LC_ALL PAGER TZ TERM EDITOR unset VISUAL CDPATH GREP_OPTIONS # Line feed LF=' ' [ "x$ORIGINAL_TERM" != "xdumb" ] && ( TERM=$ORIGINAL_TERM && export TERM && [ -t 1 ] && tput bold >/dev/null 2>&1 && tput setaf 1 >/dev/null 2>&1 && tput sgr0 >/dev/null 2>&1 ) && color=t while test "$#" -ne 0; do case "$1" in -d|--d|--de|--deb|--debu|--debug) debug=t; shift ;; -i|--i|--im|--imm|--imme|--immed|--immedi|--immedia|--immediat|--immediate) immediate=t; shift ;; -l|--l|--lo|--lon|--long|--long-|--long-t|--long-te|--long-tes|--long-test|--long-tests) TEST_LONG=t; export TEST_LONG; shift ;; -h|--h|--he|--hel|--help) help=t; shift ;; -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose) verbose=t; shift ;; -q|--q|--qu|--qui|--quie|--quiet) # Ignore --quiet under a TAP::Harness. Saying how many tests # passed without the ok/not ok details is always an error. test -z "$HARNESS_ACTIVE" && quiet=t; shift ;; --no-color) color=; shift ;; --root=*) root=$(expr "z$1" : 'z[^=]*=\(.*\)') shift ;; *) echo "error: unknown test option '$1'" >&2; exit 1 ;; esac done if test -n "$color"; then say_color() { ( TERM=$ORIGINAL_TERM export TERM case "$1" in error) tput bold; tput setaf 1;; # bold red skip) tput setaf 4;; # blue warn) tput setaf 3;; # brown/yellow pass) tput setaf 2;; # green info) tput setaf 6;; # cyan *) test -n "$quiet" && return;; esac shift printf "%s" "$*" tput sgr0 echo ) } else say_color() { test -z "$1" && test -n "$quiet" && return shift printf "%s\n" "$*" } fi error() { say_color error "error: $*" EXIT_OK=t exit 1 } say() { say_color info "$*" } test -n "$test_description" || error "Test script did not set test_description." if test "$help" = "t"; then echo "$test_description" exit 0 fi exec 5>&1 exec 6<&0 if test "$verbose" = "t"; then exec 4>&2 3>&1 else exec 4>/dev/null 3>/dev/null fi test_failure=0 test_count=0 test_fixed=0 test_broken=0 test_success=0 die() { code=$? if test -n "$EXIT_OK"; then exit $code else echo >&5 "FATAL: Unexpected exit with code $code" exit 1 fi } EXIT_OK= trap 'die' EXIT # Public: Define that a test prerequisite is available. # # The prerequisite can later be checked explicitly using test_have_prereq or # implicitly by specifying the prerequisite name in calls to test_expect_success # or test_expect_failure. # # $1 - Name of prerequiste (a simple word, in all capital letters by convention) # # Examples # # # Set PYTHON prerequisite if interpreter is available. # command -v python >/dev/null && test_set_prereq PYTHON # # # Set prerequisite depending on some variable. # test -z "$NO_GETTEXT" && test_set_prereq GETTEXT # # Returns nothing. test_set_prereq() { satisfied_prereq="$satisfied_prereq$1 " } satisfied_prereq=" " # Public: Check if one or more test prerequisites are defined. # # The prerequisites must have previously been set with test_set_prereq. # The most common use of this is to skip all the tests if some essential # prerequisite is missing. # # $1 - Comma-separated list of test prerequisites. # # Examples # # # Skip all remaining tests if prerequisite is not set. # if ! test_have_prereq PERL; then # skip_all='skipping perl interface tests, perl not available' # test_done # fi # # Returns 0 if all prerequisites are defined or 1 otherwise. test_have_prereq() { # prerequisites can be concatenated with ',' save_IFS=$IFS IFS=, set -- $* IFS=$save_IFS total_prereq=0 ok_prereq=0 missing_prereq= for prerequisite; do case "$prerequisite" in !*) negative_prereq=t prerequisite=${prerequisite#!} ;; *) negative_prereq= esac total_prereq=$(($total_prereq + 1)) case "$satisfied_prereq" in *" $prerequisite "*) satisfied_this_prereq=t ;; *) satisfied_this_prereq= esac case "$satisfied_this_prereq,$negative_prereq" in t,|,t) ok_prereq=$(($ok_prereq + 1)) ;; *) # Keep a list of missing prerequisites; restore # the negative marker if necessary. prerequisite=${negative_prereq:+!}$prerequisite if test -z "$missing_prereq"; then missing_prereq=$prerequisite else missing_prereq="$prerequisite,$missing_prereq" fi esac done test $total_prereq = $ok_prereq } # You are not expected to call test_ok_ and test_failure_ directly, use # the text_expect_* functions instead. test_ok_() { test_success=$(($test_success + 1)) say_color "" "ok $test_count - $@" } test_failure_() { test_failure=$(($test_failure + 1)) say_color error "not ok $test_count - $1" shift echo "$@" | sed -e 's/^/# /' test "$immediate" = "" || { EXIT_OK=t; exit 1; } } test_known_broken_ok_() { test_fixed=$(($test_fixed + 1)) say_color error "ok $test_count - $@ # TODO known breakage vanished" } test_known_broken_failure_() { test_broken=$(($test_broken + 1)) say_color warn "not ok $test_count - $@ # TODO known breakage" } # Public: Execute commands in debug mode. # # Takes a single argument and evaluates it only when the test script is started # with --debug. This is primarily meant for use during the development of test # scripts. # # $1 - Commands to be executed. # # Examples # # test_debug "cat some_log_file" # # Returns the exit code of the last command executed in debug mode or 0 # otherwise. test_debug() { test "$debug" = "" || eval "$1" } test_eval_() { # This is a separate function because some tests use # "return" to end a test_expect_success block early. eval &3 2>&4 "$*" } test_run_() { test_cleanup=: expecting_failure=$2 test_eval_ "$1" eval_ret=$? if test -z "$immediate" || test $eval_ret = 0 || test -n "$expecting_failure"; then test_eval_ "$test_cleanup" fi if test "$verbose" = "t" && test -n "$HARNESS_ACTIVE"; then echo "" fi return "$eval_ret" } test_skip_() { test_count=$(($test_count + 1)) to_skip= for skp in $SKIP_TESTS; do case $this_test.$test_count in $skp) to_skip=t break esac done if test -z "$to_skip" && test -n "$test_prereq" && ! test_have_prereq "$test_prereq"; then to_skip=t fi case "$to_skip" in t) of_prereq= if test "$missing_prereq" != "$test_prereq"; then of_prereq=" of $test_prereq" fi say_color skip >&3 "skipping test: $@" say_color skip "ok $test_count # skip $1 (missing $missing_prereq${of_prereq})" : true ;; *) false ;; esac } # Public: Run test commands and expect them to succeed. # # When the test passed, an "ok" message is printed and the number of successful # tests is incremented. When it failed, a "not ok" message is printed and the # number of failed tests is incremented. # # With --immediate, exit test immediately upon the first failed test. # # Usually takes two arguments: # $1 - Test description # $2 - Commands to be executed. # # With three arguments, the first will be taken to be a prerequisite: # $1 - Comma-separated list of test prerequisites. The test will be skipped if # not all of the given prerequisites are set. To negate a prerequisite, # put a "!" in front of it. # $2 - Test description # $3 - Commands to be executed. # # Examples # # test_expect_success \ # 'git-write-tree should be able to write an empty tree.' \ # 'tree=$(git-write-tree)' # # # Test depending on one prerequisite. # test_expect_success TTY 'git --paginate rev-list uses a pager' \ # ' ... ' # # # Multiple prerequisites are separated by a comma. # test_expect_success PERL,PYTHON 'yo dawg' \ # ' test $(perl -E 'print eval "1 +" . qx[python -c "print 2"]') == "4" ' # # Returns nothing. test_expect_success() { test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq= test "$#" = 2 || error "bug in the test script: not 2 or 3 parameters to test_expect_success" export test_prereq if ! test_skip_ "$@"; then say >&3 "expecting success: $2" if test_run_ "$2"; then test_ok_ "$1" else test_failure_ "$@" fi fi echo >&3 "" } # Public: Run test commands and expect them to fail. Used to demonstrate a known # breakage. # # This is NOT the opposite of test_expect_success, but rather used to mark a # test that demonstrates a known breakage. # # When the test passed, an "ok" message is printed and the number of fixed tests # is incremented. When it failed, a "not ok" message is printed and the number # of tests still broken is incremented. # # Failures from these tests won't cause --immediate to stop. # # Usually takes two arguments: # $1 - Test description # $2 - Commands to be executed. # # With three arguments, the first will be taken to be a prerequisite: # $1 - Comma-separated list of test prerequisites. The test will be skipped if # not all of the given prerequisites are set. To negate a prerequisite, # put a "!" in front of it. # $2 - Test description # $3 - Commands to be executed. # # Returns nothing. test_expect_failure() { test "$#" = 3 && { test_prereq=$1; shift; } || test_prereq= test "$#" = 2 || error "bug in the test script: not 2 or 3 parameters to test_expect_failure" export test_prereq if ! test_skip_ "$@"; then say >&3 "checking known breakage: $2" if test_run_ "$2" expecting_failure; then test_known_broken_ok_ "$1" else test_known_broken_failure_ "$1" fi fi echo >&3 "" } # Public: Run command and ensure that it fails in a controlled way. # # Use it instead of "! ". For example, when dies due to a # segfault, test_must_fail diagnoses it as an error, while "! " would # mistakenly be treated as just another expected failure. # # This is one of the prefix functions to be used inside test_expect_success or # test_expect_failure. # # $1.. - Command to be executed. # # Examples # # test_expect_success 'complain and die' ' # do something && # do something else && # test_must_fail git checkout ../outerspace # ' # # Returns 1 if the command succeeded (exit code 0). # Returns 1 if the command died by signal (exit codes 130-192) # Returns 1 if the command could not be found (exit code 127). # Returns 0 otherwise. test_must_fail() { "$@" exit_code=$? if test $exit_code = 0; then echo >&2 "test_must_fail: command succeeded: $*" return 1 elif test $exit_code -gt 129 -a $exit_code -le 192; then echo >&2 "test_must_fail: died by signal: $*" return 1 elif test $exit_code = 127; then echo >&2 "test_must_fail: command not found: $*" return 1 fi return 0 } # Public: Run command and ensure that it succeeds or fails in a controlled way. # # Similar to test_must_fail, but tolerates success too. Use it instead of # " || :" to catch failures caused by a segfault, for instance. # # This is one of the prefix functions to be used inside test_expect_success or # test_expect_failure. # # $1.. - Command to be executed. # # Examples # # test_expect_success 'some command works without configuration' ' # test_might_fail git config --unset all.configuration && # do something # ' # # Returns 1 if the command died by signal (exit codes 130-192) # Returns 1 if the command could not be found (exit code 127). # Returns 0 otherwise. test_might_fail() { "$@" exit_code=$? if test $exit_code -gt 129 -a $exit_code -le 192; then echo >&2 "test_might_fail: died by signal: $*" return 1 elif test $exit_code = 127; then echo >&2 "test_might_fail: command not found: $*" return 1 fi return 0 } # Public: Run command and ensure it exits with a given exit code. # # This is one of the prefix functions to be used inside test_expect_success or # test_expect_failure. # # $1 - Expected exit code. # $2.. - Command to be executed. # # Examples # # test_expect_success 'Merge with d/f conflicts' ' # test_expect_code 1 git merge "merge msg" B master # ' # # Returns 0 if the expected exit code is returned or 1 otherwise. test_expect_code() { want_code=$1 shift "$@" exit_code=$? if test $exit_code = $want_code; then return 0 fi echo >&2 "test_expect_code: command exited with $exit_code, we wanted $want_code $*" return 1 } # Public: Compare two files to see if expected output matches actual output. # # The TEST_CMP variable defines the command used for the comparision; it # defaults to "diff -u". Only when the test script was started with --verbose, # will the command's output, the diff, be printed to the standard output. # # This is one of the prefix functions to be used inside test_expect_success or # test_expect_failure. # # $1 - Path to file with expected output. # $2 - Path to file with actual output. # # Examples # # test_expect_success 'foo works' ' # echo expected >expected && # foo >actual && # test_cmp expected actual # ' # # Returns the exit code of the command set by TEST_CMP. test_cmp() { ${TEST_CMP:-diff -u} "$@" } # Public: Schedule cleanup commands to be run unconditionally at the end of a # test. # # If some cleanup command fails, the test will not pass. With --immediate, no # cleanup is done to help diagnose what went wrong. # # This is one of the prefix functions to be used inside test_expect_success or # test_expect_failure. # # $1.. - Commands to prepend to the list of cleanup commands. # # Examples # # test_expect_success 'test core.capslock' ' # git config core.capslock true && # test_when_finished "git config --unset core.capslock" && # do_something # ' # # Returns the exit code of the last cleanup command executed. test_when_finished() { test_cleanup="{ $* } && (exit \"\$eval_ret\"); eval_ret=\$?; $test_cleanup" } # Public: Summarize test results and exit with an appropriate error code. # # Must be called at the end of each test script. # # Can also be used to stop tests early and skip all remaining tests. For this, # set skip_all to a string explaining why the tests were skipped before calling # test_done. # # Examples # # # Each test script must call test_done at the end. # test_done # # # Skip all remaining tests if prerequisite is not set. # if ! test_have_prereq PERL; then # skip_all='skipping perl interface tests, perl not available' # test_done # fi # # Returns 0 if all tests passed or 1 if there was a failure. test_done() { EXIT_OK=t if test -z "$HARNESS_ACTIVE"; then test_results_dir="$SHARNESS_TEST_DIRECTORY/test-results" mkdir -p "$test_results_dir" test_results_path="$test_results_dir/${SHARNESS_TEST_FILE%.$SHARNESS_TEST_EXTENSION}.$$.counts" cat >>"$test_results_path" <<-EOF total $test_count success $test_success fixed $test_fixed broken $test_broken failed $test_failure EOF fi if test "$test_fixed" != 0; then say_color error "# $test_fixed known breakage(s) vanished; please update test(s)" fi if test "$test_broken" != 0; then say_color warn "# still have $test_broken known breakage(s)" fi if test "$test_broken" != 0 || test "$test_fixed" != 0; then test_remaining=$(( $test_count - $test_broken - $test_fixed )) msg="remaining $test_remaining test(s)" else test_remaining=$test_count msg="$test_count test(s)" fi case "$test_failure" in 0) # Maybe print SKIP message if test -n "$skip_all" && test $test_count -gt 0; then error "Can't use skip_all after running some tests" fi [ -z "$skip_all" ] || skip_all=" # SKIP $skip_all" if test $test_remaining -gt 0; then say_color pass "# passed all $msg" fi say "1..$test_count$skip_all" test -d "$remove_trash" && cd "$(dirname "$remove_trash")" && rm -rf "$(basename "$remove_trash")" exit 0 ;; *) say_color error "# failed $test_failure among $msg" say "1..$test_count" exit 1 ;; esac } # Public: Root directory containing tests. Tests can override this variable, # e.g. for testing Sharness itself. : ${SHARNESS_TEST_DIRECTORY:=$(pwd)} export SHARNESS_TEST_DIRECTORY # Public: Build directory that will be added to PATH. By default, it is set to # the parent directory of SHARNESS_TEST_DIRECTORY. : ${SHARNESS_BUILD_DIRECTORY:="$SHARNESS_TEST_DIRECTORY/.."} PATH="$SHARNESS_BUILD_DIRECTORY:$PATH" export PATH SHARNESS_BUILD_DIRECTORY # Public: Path to test script currently executed. SHARNESS_TEST_FILE="$0" export SHARNESS_TEST_FILE # Prepare test area. test_dir="trash directory.$(basename "$SHARNESS_TEST_FILE" ".$SHARNESS_TEST_EXTENSION")" test -n "$root" && test_dir="$root/$test_dir" case "$test_dir" in /*) SHARNESS_TRASH_DIRECTORY="$test_dir" ;; *) SHARNESS_TRASH_DIRECTORY="$SHARNESS_TEST_DIRECTORY/$test_dir" ;; esac test "$debug" = "t" || remove_trash="$SHARNESS_TRASH_DIRECTORY" rm -rf "$test_dir" || { EXIT_OK=t echo >&5 "FATAL: Cannot prepare test area" exit 1 } # Public: Empty trash directory, the test area, provided for each test. The HOME # variable is set to that directory too. export SHARNESS_TRASH_DIRECTORY HOME="$SHARNESS_TRASH_DIRECTORY" export HOME mkdir -p "$test_dir" || exit 1 # Use -P to resolve symlinks in our working directory so that the cwd # in subprocesses like git equals our $PWD (for pathname comparisons). cd -P "$test_dir" || exit 1 this_test=${SHARNESS_TEST_FILE##*/} this_test=${this_test%.$SHARNESS_TEST_EXTENSION} for skp in $SKIP_TESTS; do case "$this_test" in $skp) say_color info >&3 "skipping test $this_test altogether" skip_all="skip all tests in $this_test" test_done esac done # vi: set ts=4 sw=4 noet : git-remote-hg-0.3/test/test-lib.sh000066400000000000000000000014451263033635200170710ustar00rootroot00000000000000#!/bin/sh . ./sharness.sh if ! command -v python2 >/dev/null then skip_all='skipping remote-hg tests; python not available' test_done fi if ! python2 -c 'import mercurial' > /dev/null 2>&1 then skip_all='skipping remote-hg tests; mercurial not available' test_done fi if ! command -v git >/dev/null then skip_all='skipping remote-hg tests; git not available' test_done fi GIT_VERSION=$(git --version) GIT_MAJOR=$(expr "$GIT_VERSION" : '[^0-9]*\([0-9]*\)') GIT_MINOR=$(expr "$GIT_VERSION" : '[^0-9]*[0-9]*\.\([0-9]*\)') test "$GIT_MAJOR" -ge 2 && test_set_prereq GIT_2_0 GIT_AUTHOR_EMAIL=author@example.com GIT_AUTHOR_NAME='A U Thor' GIT_COMMITTER_EMAIL=committer@example.com GIT_COMMITTER_NAME='C O Mitter' export GIT_AUTHOR_EMAIL GIT_AUTHOR_NAME export GIT_COMMITTER_EMAIL GIT_COMMITTER_NAME