git_remote_helpers: remove little used Python library

When it was originally added, the git_remote_helpers library was used as part of the tests of the remote-helper interface, but since commit fc407f9 (Add new simplified git-remote-testgit, 2012-11-28) a simple shell script is used for this. A search on Ohloh [1] indicates that this library isn't used by any external projects and even the Python remote helpers in contrib/ don't use this library, so it is only used by its own test suite. Since this is the only Python library in Git, removing it will make packaging easier as the Python scripts only need to be installed for one version of Python, whereas the library should be installed for all available versions. [1] http://code.ohloh.net/search?s=%22git_remote_helpers%22 Signed-off-by: John Keeping <john@keeping.me.uk> Acked-by: Sverre Rabbelier <srabbelier@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

John Keeping committed Sep 7, 2013 at 17:19 UTC ae34ac126fa609fb17955b02c685d7de164b4e54
16 files changed -1815
Makefile
-16
@@ -488,11 +488,9 @@ SCRIPT_PERL += git-relink.perl
488 SCRIPT_PERL += git-send-email.perl
489 SCRIPT_PERL += git-svn.perl
490
491 -SCRIPT_PYTHON += git-remote-testpy.py
491 SCRIPT_PYTHON += git-p4.py
492
493 NO_INSTALL += git-remote-testgit
495 -NO_INSTALL += git-remote-testpy
494
495 # Generated files for scripts
496 SCRIPT_SH_GEN = $(patsubst %.sh,%,$(SCRIPT_SH))
@@ -1669,9 +1667,6 @@ ifndef NO_TCLTK
1667 endif
1668 ifndef NO_PERL
1669 $(QUIET_SUBDIR0)perl $(QUIET_SUBDIR1) PERL_PATH='$(PERL_PATH_SQ)' prefix='$(prefix_SQ)' localedir='$(localedir_SQ)' all
1672 -endif
1673 -ifndef NO_PYTHON
1674 - $(QUIET_SUBDIR0)git_remote_helpers $(QUIET_SUBDIR1) PYTHON_PATH='$(PYTHON_PATH_SQ)' prefix='$(prefix_SQ)' all
1670 endif
1671 $(QUIET_SUBDIR0)templates $(QUIET_SUBDIR1) SHELL_PATH='$(SHELL_PATH_SQ)' PERL_PATH='$(PERL_PATH_SQ)'
1672
@@ -1840,12 +1835,7 @@ ifndef NO_PYTHON
1835 $(SCRIPT_PYTHON_GEN): GIT-CFLAGS GIT-PREFIX GIT-PYTHON-VARS
1836 $(SCRIPT_PYTHON_GEN): % : %.py
1837 $(QUIET_GEN)$(RM) $@ $@+ && \
1843 - INSTLIBDIR=`MAKEFLAGS= $(MAKE) -C git_remote_helpers -s \
1844 - --no-print-directory prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' \
1845 - instlibdir` && \
1838 sed -e '1s|#!.*python|#!$(PYTHON_PATH_SQ)|' \
1847 - -e 's|\(os\.getenv("GITPYTHONLIB"\)[^)]*)|\1,"@@INSTLIBDIR@@")|' \
1848 - -e 's|@@INSTLIBDIR@@|'"$$INSTLIBDIR"'|g' \
1839 $< >$@+ && \
1840 chmod +x $@+ && \
1841 mv $@+ $@
@@ -2352,9 +2342,6 @@ ifndef NO_PERL
2342 $(MAKE) -C perl prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' install
2343 $(MAKE) -C gitweb install
2344 endif
2355 -ifndef NO_PYTHON
2356 - $(MAKE) -C git_remote_helpers prefix='$(prefix_SQ)' DESTDIR='$(DESTDIR_SQ)' install
2357 -endif
2345 ifndef NO_TCLTK
2346 $(MAKE) -C gitk-git install
2347 $(MAKE) -C git-gui gitexecdir='$(gitexec_instdir_SQ)' install
@@ -2501,9 +2488,6 @@ clean: profile-clean coverage-clean
2488 ifndef NO_PERL
2489 $(MAKE) -C gitweb clean
2490 $(MAKE) -C perl clean
2504 -endif
2505 -ifndef NO_PYTHON
2506 - $(MAKE) -C git_remote_helpers clean
2491 endif
2492 $(MAKE) -C templates/ clean
2493 $(MAKE) -C t/ clean
git-remote-testpy.py deleted
-305
@@ -1,305 +0,0 @@
1 -#!/usr/bin/env python
2 -
3 -# This command is a simple remote-helper, that is used both as a
4 -# testcase for the remote-helper functionality, and as an example to
5 -# show remote-helper authors one possible implementation.
6 -#
7 -# This is a Git <-> Git importer/exporter, that simply uses git
8 -# fast-import and git fast-export to consume and produce fast-import
9 -# streams.
10 -#
11 -# To understand better the way things work, one can activate debug
12 -# traces by setting (to any value) the environment variables
13 -# GIT_TRANSPORT_HELPER_DEBUG and GIT_DEBUG_TESTGIT, to see messages
14 -# from the transport-helper side, or from this example remote-helper.
15 -
16 -# hashlib is only available in python >= 2.5
17 -try:
18 - import hashlib
19 - _digest = hashlib.sha1
20 -except ImportError:
21 - import sha
22 - _digest = sha.new
23 -import sys
24 -import os
25 -import time
26 -sys.path.insert(0, os.getenv("GITPYTHONLIB","."))
27 -
28 -from git_remote_helpers.util import die, debug, warn
29 -from git_remote_helpers.git.repo import GitRepo
30 -from git_remote_helpers.git.exporter import GitExporter
31 -from git_remote_helpers.git.importer import GitImporter
32 -from git_remote_helpers.git.non_local import NonLocalGit
33 -
34 -if sys.hexversion < 0x02000000:
35 - # string.encode() is the limiter
36 - sys.stderr.write("git-remote-testgit: requires Python 2.0 or later.\n")
37 - sys.exit(1)
38 -
39 -
40 -def encode_filepath(path):
41 - """Encodes a Unicode file path to a byte string.
42 -
43 - On Python 2 this is a no-op; on Python 3 we encode the string as
44 - suggested by [1] which allows an exact round-trip from the command line
45 - to the filesystem.
46 -
47 - [1] http://docs.python.org/3/c-api/unicode.html#file-system-encoding
48 -
49 - """
50 - if sys.hexversion < 0x03000000:
51 - return path
52 - return path.encode(sys.getfilesystemencoding(), 'surrogateescape')
53 -
54 -
55 -def get_repo(alias, url):
56 - """Returns a git repository object initialized for usage.
57 - """
58 -
59 - repo = GitRepo(url)
60 - repo.get_revs()
61 - repo.get_head()
62 -
63 - hasher = _digest()
64 - hasher.update(encode_filepath(repo.path))
65 - repo.hash = hasher.hexdigest()
66 -
67 - repo.get_base_path = lambda base: os.path.join(
68 - base, 'info', 'fast-import', repo.hash)
69 -
70 - prefix = 'refs/testgit/%s/' % alias
71 - debug("prefix: '%s'", prefix)
72 -
73 - repo.gitdir = os.environ["GIT_DIR"]
74 - repo.alias = alias
75 - repo.prefix = prefix
76 -
77 - repo.exporter = GitExporter(repo)
78 - repo.importer = GitImporter(repo)
79 - repo.non_local = NonLocalGit(repo)
80 -
81 - return repo
82 -
83 -
84 -def local_repo(repo, path):
85 - """Returns a git repository object initalized for usage.
86 - """
87 -
88 - local = GitRepo(path)
89 -
90 - local.non_local = None
91 - local.gitdir = repo.gitdir
92 - local.alias = repo.alias
93 - local.prefix = repo.prefix
94 - local.hash = repo.hash
95 - local.get_base_path = repo.get_base_path
96 - local.exporter = GitExporter(local)
97 - local.importer = GitImporter(local)
98 -
99 - return local
100 -
101 -
102 -def do_capabilities(repo, args):
103 - """Prints the supported capabilities.
104 - """
105 -
106 - print("import")
107 - print("export")
108 - print("refspec refs/heads/*:%s*" % repo.prefix)
109 -
110 - dirname = repo.get_base_path(repo.gitdir)
111 -
112 - if not os.path.exists(dirname):
113 - os.makedirs(dirname)
114 -
115 - path = os.path.join(dirname, 'git.marks')
116 -
117 - print("*export-marks %s" % path)
118 - if os.path.exists(path):
119 - print("*import-marks %s" % path)
120 -
121 - print('') # end capabilities
122 -
123 -
124 -def do_list(repo, args):
125 - """Lists all known references.
126 -
127 - Bug: This will always set the remote head to master for non-local
128 - repositories, since we have no way of determining what the remote
129 - head is at clone time.
130 - """
131 -
132 - for ref in repo.revs:
133 - debug("? refs/heads/%s", ref)
134 - print("? refs/heads/%s" % ref)
135 -
136 - if repo.head:
137 - debug("@refs/heads/%s HEAD" % repo.head)
138 - print("@refs/heads/%s HEAD" % repo.head)
139 - else:
140 - debug("@refs/heads/master HEAD")
141 - print("@refs/heads/master HEAD")
142 -
143 - print('') # end list
144 -
145 -
146 -def update_local_repo(repo):
147 - """Updates (or clones) a local repo.
148 - """
149 -
150 - if repo.local:
151 - return repo
152 -
153 - path = repo.non_local.clone(repo.gitdir)
154 - repo.non_local.update(repo.gitdir)
155 - repo = local_repo(repo, path)
156 - return repo
157 -
158 -
159 -def do_import(repo, args):
160 - """Exports a fast-import stream from testgit for git to import.
161 - """
162 -
163 - if len(args) != 1:
164 - die("Import needs exactly one ref")
165 -
166 - if not repo.gitdir:
167 - die("Need gitdir to import")
168 -
169 - ref = args[0]
170 - refs = [ref]
171 -
172 - while True:
173 - line = sys.stdin.readline().decode()
174 - if line == '\n':
175 - break
176 - if not line.startswith('import '):
177 - die("Expected import line.")
178 -
179 - # strip of leading 'import '
180 - ref = line[7:].strip()
181 - refs.append(ref)
182 -
183 - print("feature done")
184 -
185 - if os.environ.get("GIT_REMOTE_TESTGIT_FAILURE"):
186 - die('Told to fail')
187 -
188 - repo = update_local_repo(repo)
189 - repo.exporter.export_repo(repo.gitdir, refs)
190 -
191 - print("done")
192 -
193 -
194 -def do_export(repo, args):
195 - """Imports a fast-import stream from git to testgit.
196 - """
197 -
198 - if not repo.gitdir:
199 - die("Need gitdir to export")
200 -
201 - if os.environ.get("GIT_REMOTE_TESTGIT_FAILURE"):
202 - die('Told to fail')
203 -
204 - update_local_repo(repo)
205 - changed = repo.importer.do_import(repo.gitdir)
206 -
207 - if not repo.local:
208 - repo.non_local.push(repo.gitdir)
209 -
210 - for ref in changed:
211 - print("ok %s" % ref)
212 - print('')
213 -
214 -
215 -COMMANDS = {
216 - 'capabilities': do_capabilities,
217 - 'list': do_list,
218 - 'import': do_import,
219 - 'export': do_export,
220 -}
221 -
222 -
223 -def sanitize(value):
224 - """Cleans up the url.
225 - """
226 -
227 - if value.startswith('testgit::'):
228 - value = value[9:]
229 -
230 - return value
231 -
232 -
233 -def read_one_line(repo):
234 - """Reads and processes one command.
235 - """
236 -
237 - sleepy = os.environ.get("GIT_REMOTE_TESTGIT_SLEEPY")
238 - if sleepy:
239 - debug("Sleeping %d sec before readline" % int(sleepy))
240 - time.sleep(int(sleepy))
241 -
242 - line = sys.stdin.readline()
243 -
244 - cmdline = line.decode()
245 -
246 - if not cmdline:
247 - warn("Unexpected EOF")
248 - return False
249 -
250 - cmdline = cmdline.strip().split()
251 - if not cmdline:
252 - # Blank line means we're about to quit
253 - return False
254 -
255 - cmd = cmdline.pop(0)
256 - debug("Got command '%s' with args '%s'", cmd, ' '.join(cmdline))
257 -
258 - if cmd not in COMMANDS:
259 - die("Unknown command, %s", cmd)
260 -
261 - func = COMMANDS[cmd]
262 - func(repo, cmdline)
263 - sys.stdout.flush()
264 -
265 - return True
266 -
267 -
268 -def main(args):
269 - """Starts a new remote helper for the specified repository.
270 - """
271 -
272 - if len(args) != 3:
273 - die("Expecting exactly three arguments.")
274 - sys.exit(1)
275 -
276 - if os.getenv("GIT_DEBUG_TESTGIT"):
277 - import git_remote_helpers.util
278 - git_remote_helpers.util.DEBUG = True
279 -
280 - alias = sanitize(args[1])
281 - url = sanitize(args[2])
282 -
283 - if not alias.isalnum():
284 - warn("non-alnum alias '%s'", alias)
285 - alias = "tmp"
286 -
287 - args[1] = alias
288 - args[2] = url
289 -
290 - repo = get_repo(alias, url)
291 -
292 - debug("Got arguments %s", args[1:])
293 -
294 - more = True
295 -
296 - # Use binary mode since Python 3 does not permit unbuffered I/O in text
297 - # mode. Unbuffered I/O is required to avoid data that should be going
298 - # to git-fast-import after an "export" command getting caught in our
299 - # stdin buffer instead.
300 - sys.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0)
301 - while (more):
302 - more = read_one_line(repo)
303 -
304 -if __name__ == '__main__':
305 - sys.exit(main(sys.argv))
git_remote_helpers/.gitignore deleted
-3
@@ -1,3 +0,0 @@
1 -/GIT-PYTHON-VERSION
2 -/build
3 -/dist
git_remote_helpers/Makefile deleted
-45
@@ -1,45 +0,0 @@
1 -#
2 -# Makefile for the git_remote_helpers python support modules
3 -#
4 -pysetupfile:=setup.py
5 -
6 -# Shell quote (do not use $(call) to accommodate ancient setups);
7 -DESTDIR_SQ = $(subst ','\'',$(DESTDIR))
8 -
9 -ifndef PYTHON_PATH
10 - ifeq ($(uname_S),FreeBSD)
11 - PYTHON_PATH = /usr/local/bin/python
12 - else
13 - PYTHON_PATH = /usr/bin/python
14 - endif
15 -endif
16 -ifndef prefix
17 - prefix = $(HOME)
18 -endif
19 -ifndef V
20 - QUIET = @
21 - QUIETSETUP = --quiet
22 -endif
23 -
24 -PYLIBDIR=$(shell $(PYTHON_PATH) -c \
25 - "import sys; \
26 - print('lib/python%i.%i/site-packages' % sys.version_info[:2])")
27 -
28 -py_version=$(shell $(PYTHON_PATH) -c \
29 - 'import sys; print("%i.%i" % sys.version_info[:2])')
30 -
31 -all: $(pysetupfile)
32 - $(QUIET)test "$$(cat GIT-PYTHON-VERSION 2>/dev/null)" = "$(py_version)" || \
33 - flags=--force; \
34 - $(PYTHON_PATH) $(pysetupfile) $(QUIETSETUP) build $$flags
35 - $(QUIET)echo "$(py_version)" >GIT-PYTHON-VERSION
36 -
37 -install: $(pysetupfile)
38 - $(PYTHON_PATH) $(pysetupfile) install --prefix $(DESTDIR_SQ)$(prefix)
39 -
40 -instlibdir: $(pysetupfile)
41 - @echo "$(DESTDIR_SQ)$(prefix)/$(PYLIBDIR)"
42 -
43 -clean:
44 - $(QUIET)$(PYTHON_PATH) $(pysetupfile) $(QUIETSETUP) clean -a
45 - $(RM) *.pyo *.pyc GIT-PYTHON-VERSION
git_remote_helpers/__init__.py deleted
-16
@@ -1,16 +0,0 @@
1 -#!/usr/bin/env python
2 -
3 -"""Support library package for git remote helpers.
4 -
5 -Git remote helpers are helper commands that interfaces with a non-git
6 -repository to provide automatic import of non-git history into a Git
7 -repository.
8 -
9 -This package provides the support library needed by these helpers..
10 -The following modules are included:
11 -
12 -- git.git - Interaction with Git repositories
13 -
14 -- util - General utility functionality use by the other modules in
15 - this package, and also used directly by the helpers.
16 -"""
git_remote_helpers/git/__init__.py deleted
-5
@@ -1,5 +0,0 @@
1 -import sys
2 -if sys.hexversion < 0x02040000:
3 - # The limiter is the subprocess module
4 - sys.stderr.write("git_remote_helpers: requires Python 2.4 or later.\n")
5 - sys.exit(1)
git_remote_helpers/git/exporter.py deleted
-58
@@ -1,58 +0,0 @@
1 -import os
2 -import subprocess
3 -import sys
4 -
5 -from git_remote_helpers.util import check_call
6 -
7 -
8 -class GitExporter(object):
9 - """An exporter for testgit repositories.
10 -
11 - The exporter simply delegates to git fast-export.
12 - """
13 -
14 - def __init__(self, repo):
15 - """Creates a new exporter for the specified repo.
16 - """
17 -
18 - self.repo = repo
19 -
20 - def export_repo(self, base, refs=None):
21 - """Exports a fast-export stream for the given directory.
22 -
23 - Simply delegates to git fast-epxort and pipes it through sed
24 - to make the refs show up under the prefix rather than the
25 - default refs/heads. This is to demonstrate how the export
26 - data can be stored under it's own ref (using the refspec
27 - capability).
28 -
29 - If None, refs defaults to ["HEAD"].
30 - """
31 -
32 - if not refs:
33 - refs = ["HEAD"]
34 -
35 - dirname = self.repo.get_base_path(base)
36 - path = os.path.abspath(os.path.join(dirname, 'testgit.marks'))
37 -
38 - if not os.path.exists(dirname):
39 - os.makedirs(dirname)
40 -
41 - print "feature relative-marks"
42 - if os.path.exists(os.path.join(dirname, 'git.marks')):
43 - print "feature import-marks=%s/git.marks" % self.repo.hash
44 - print "feature export-marks=%s/git.marks" % self.repo.hash
45 - sys.stdout.flush()
46 -
47 - args = ["git", "--git-dir=" + self.repo.gitpath, "fast-export", "--export-marks=" + path]
48 -
49 - if os.path.exists(path):
50 - args.append("--import-marks=" + path)
51 -
52 - args.extend(refs)
53 -
54 - p1 = subprocess.Popen(args, stdout=subprocess.PIPE)
55 -
56 - args = ["sed", "s_refs/heads/_" + self.repo.prefix + "_g"]
57 -
58 - check_call(args, stdin=p1.stdout)
git_remote_helpers/git/git.py deleted
-678
@@ -1,678 +0,0 @@
1 -#!/usr/bin/env python
2 -
3 -"""Functionality for interacting with Git repositories.
4 -
5 -This module provides classes for interfacing with a Git repository.
6 -"""
7 -
8 -import os
9 -import re
10 -import time
11 -from binascii import hexlify
12 -from cStringIO import StringIO
13 -import unittest
14 -
15 -from git_remote_helpers.util import debug, error, die, start_command, run_command
16 -
17 -
18 -def get_git_dir ():
19 - """Return the path to the GIT_DIR for this repo."""
20 - args = ("git", "rev-parse", "--git-dir")
21 - exit_code, output, errors = run_command(args)
22 - if exit_code:
23 - die("Failed to retrieve git dir")
24 - assert not errors
25 - return output.strip()
26 -
27 -
28 -def parse_git_config ():
29 - """Return a dict containing the parsed version of 'git config -l'."""
30 - exit_code, output, errors = run_command(("git", "config", "-z", "-l"))
31 - if exit_code:
32 - die("Failed to retrieve git configuration")
33 - assert not errors
34 - return dict([e.split('\n', 1) for e in output.split("\0") if e])
35 -
36 -
37 -def git_config_bool (value):
38 - """Convert the given git config string value to True or False.
39 -
40 - Raise ValueError if the given string was not recognized as a
41 - boolean value.
42 -
43 - """
44 - norm_value = str(value).strip().lower()
45 - if norm_value in ("true", "1", "yes", "on", ""):
46 - return True
47 - if norm_value in ("false", "0", "no", "off", "none"):
48 - return False
49 - raise ValueError("Failed to parse '%s' into a boolean value" % (value))
50 -
51 -
52 -def valid_git_ref (ref_name):
53 - """Return True iff the given ref name is a valid git ref name."""
54 - # The following is a reimplementation of the git check-ref-format
55 - # command. The rules were derived from the git check-ref-format(1)
56 - # manual page. This code should be replaced by a call to
57 - # check_refname_format() in the git library, when such is available.
58 - if ref_name.endswith('/') or \
59 - ref_name.startswith('.') or \
60 - ref_name.count('/.') or \
61 - ref_name.count('..') or \
62 - ref_name.endswith('.lock'):
63 - return False
64 - for c in ref_name:
65 - if ord(c) < 0x20 or ord(c) == 0x7f or c in " ~^:?*[":
66 - return False
67 - return True
68 -
69 -
70 -class GitObjectFetcher(object):
71 -
72 - """Provide parsed access to 'git cat-file --batch'.
73 -
74 - This provides a read-only interface to the Git object database.
75 -
76 - """
77 -
78 - def __init__ (self):
79 - """Initiate a 'git cat-file --batch' session."""
80 - self.queue = [] # List of object names to be submitted
81 - self.in_transit = None # Object name currently in transit
82 -
83 - # 'git cat-file --batch' produces binary output which is likely
84 - # to be corrupted by the default "rU"-mode pipe opened by
85 - # start_command. (Mode == "rU" does universal new-line
86 - # conversion, which mangles carriage returns.) Therefore, we
87 - # open an explicitly binary-safe pipe for transferring the
88 - # output from 'git cat-file --batch'.
89 - pipe_r_fd, pipe_w_fd = os.pipe()
90 - pipe_r = os.fdopen(pipe_r_fd, "rb")
91 - pipe_w = os.fdopen(pipe_w_fd, "wb")
92 - self.proc = start_command(("git", "cat-file", "--batch"),
93 - stdout = pipe_w)
94 - self.f = pipe_r
95 -
96 - def __del__ (self):
97 - """Verify completed communication with 'git cat-file --batch'."""
98 - assert not self.queue
99 - assert self.in_transit is None
100 - self.proc.stdin.close()
101 - assert self.proc.wait() == 0 # Zero exit code
102 - assert self.f.read() == "" # No remaining output
103 -
104 - def _submit_next_object (self):
105 - """Submit queue items to the 'git cat-file --batch' process.
106 -
107 - If there are items in the queue, and there is currently no item
108 - currently in 'transit', then pop the first item off the queue,
109 - and submit it.
110 -
111 - """
112 - if self.queue and self.in_transit is None:
113 - self.in_transit = self.queue.pop(0)
114 - print >> self.proc.stdin, self.in_transit[0]
115 -
116 - def push (self, obj, callback):
117 - """Push the given object name onto the queue.
118 -
119 - The given callback function will at some point in the future
120 - be called exactly once with the following arguments:
121 - - self - this GitObjectFetcher instance
122 - - obj - the object name provided to push()
123 - - sha1 - the SHA1 of the object, if 'None' obj is missing
124 - - t - the type of the object (tag/commit/tree/blob)
125 - - size - the size of the object in bytes
126 - - data - the object contents
127 -
128 - """
129 - self.queue.append((obj, callback))
130 - self._submit_next_object() # (Re)start queue processing
131 -
132 - def process_next_entry (self):
133 - """Read the next entry off the queue and invoke callback."""
134 - obj, cb = self.in_transit
135 - self.in_transit = None
136 - header = self.f.readline()
137 - if header == "%s missing\n" % (obj):
138 - cb(self, obj, None, None, None, None)
139 - return
140 - sha1, t, size = header.split(" ")
141 - assert len(sha1) == 40
142 - assert t in ("tag", "commit", "tree", "blob")
143 - assert size.endswith("\n")
144 - size = int(size.strip())
145 - data = self.f.read(size)
146 - assert self.f.read(1) == "\n"
147 - cb(self, obj, sha1, t, size, data)
148 - self._submit_next_object()
149 -
150 - def process (self):
151 - """Process the current queue until empty."""
152 - while self.in_transit is not None:
153 - self.process_next_entry()
154 -
155 - # High-level convenience methods:
156 -
157 - def get_sha1 (self, objspec):
158 - """Return the SHA1 of the object specified by 'objspec'.
159 -
160 - Return None if 'objspec' does not specify an existing object.
161 -
162 - """
163 - class _ObjHandler(object):
164 - """Helper class for getting the returned SHA1."""
165 - def __init__ (self, parser):
166 - self.parser = parser
167 - self.sha1 = None
168 -
169 - def __call__ (self, parser, obj, sha1, t, size, data):
170 - # FIXME: Many unused arguments. Could this be cheaper?
171 - assert parser == self.parser
172 - self.sha1 = sha1
173 -
174 - handler = _ObjHandler(self)
175 - self.push(objspec, handler)
176 - self.process()
177 - return handler.sha1
178 -
179 - def open_obj (self, objspec):
180 - """Return a file object wrapping the contents of a named object.
181 -
182 - The caller is responsible for calling .close() on the returned
183 - file object.
184 -
185 - Raise KeyError if 'objspec' does not exist in the repo.
186 -
187 - """
188 - class _ObjHandler(object):
189 - """Helper class for parsing the returned git object."""
190 - def __init__ (self, parser):
191 - """Set up helper."""
192 - self.parser = parser
193 - self.contents = StringIO()
194 - self.err = None
195 -
196 - def __call__ (self, parser, obj, sha1, t, size, data):
197 - """Git object callback (see GitObjectFetcher documentation)."""
198 - assert parser == self.parser
199 - if not sha1: # Missing object
200 - self.err = "Missing object '%s'" % obj
201 - else:
202 - assert size == len(data)
203 - self.contents.write(data)
204 -
205 - handler = _ObjHandler(self)
206 - self.push(objspec, handler)
207 - self.process()
208 - if handler.err:
209 - raise KeyError(handler.err)
210 - handler.contents.seek(0)
211 - return handler.contents
212 -
213 - def walk_tree (self, tree_objspec, callback, prefix = ""):
214 - """Recursively walk the given Git tree object.
215 -
216 - Recursively walk all subtrees of the given tree object, and
217 - invoke the given callback passing three arguments:
218 - (path, mode, data) with the path, permission bits, and contents
219 - of all the blobs found in the entire tree structure.
220 -
221 - """
222 - class _ObjHandler(object):
223 - """Helper class for walking a git tree structure."""
224 - def __init__ (self, parser, cb, path, mode = None):
225 - """Set up helper."""
226 - self.parser = parser
227 - self.cb = cb
228 - self.path = path
229 - self.mode = mode
230 - self.err = None
231 -
232 - def parse_tree (self, treedata):
233 - """Parse tree object data, yield tree entries.
234 -
235 - Each tree entry is a 3-tuple (mode, sha1, path)
236 -
237 - self.path is prepended to all paths yielded
238 - from this method.
239 -
240 - """
241 - while treedata:
242 - mode = int(treedata[:6], 10)
243 - # Turn 100xxx into xxx
244 - if mode > 100000:
245 - mode -= 100000
246 - assert treedata[6] == " "
247 - i = treedata.find("\0", 7)
248 - assert i > 0
249 - path = treedata[7:i]
250 - sha1 = hexlify(treedata[i + 1: i + 21])
251 - yield (mode, sha1, self.path + path)
252 - treedata = treedata[i + 21:]
253 -
254 - def __call__ (self, parser, obj, sha1, t, size, data):
255 - """Git object callback (see GitObjectFetcher documentation)."""
256 - assert parser == self.parser
257 - if not sha1: # Missing object
258 - self.err = "Missing object '%s'" % (obj)
259 - return
260 - assert size == len(data)
261 - if t == "tree":
262 - if self.path:
263 - self.path += "/"
264 - # Recurse into all blobs and subtrees
265 - for m, s, p in self.parse_tree(data):
266 - parser.push(s,
267 - self.__class__(self.parser, self.cb, p, m))
268 - elif t == "blob":
269 - self.cb(self.path, self.mode, data)
270 - else:
271 - raise ValueError("Unknown object type '%s'" % (t))
272 -
273 - self.push(tree_objspec, _ObjHandler(self, callback, prefix))
274 - self.process()
275 -
276 -
277 -class GitRefMap(object):
278 -
279 - """Map Git ref names to the Git object names they currently point to.
280 -
281 - Behaves like a dictionary of Git ref names -> Git object names.
282 -
283 - """
284 -
285 - def __init__ (self, obj_fetcher):
286 - """Create a new Git ref -> object map."""
287 - self.obj_fetcher = obj_fetcher
288 - self._cache = {} # dict: refname -> objname
289 -
290 - def _load (self, ref):
291 - """Retrieve the object currently bound to the given ref.
292 -
293 - The name of the object pointed to by the given ref is stored
294 - into this mapping, and also returned.
295 -
296 - """
297 - if ref not in self._cache:
298 - self._cache[ref] = self.obj_fetcher.get_sha1(ref)
299 - return self._cache[ref]
300 -
301 - def __contains__ (self, refname):
302 - """Return True if the given refname is present in this cache."""
303 - return bool(self._load(refname))
304 -
305 - def __getitem__ (self, refname):
306 - """Return the git object name pointed to by the given refname."""
307 - commit = self._load(refname)
308 - if commit is None:
309 - raise KeyError("Unknown ref '%s'" % (refname))
310 - return commit
311 -
312 - def get (self, refname, default = None):
313 - """Return the git object name pointed to by the given refname."""
314 - commit = self._load(refname)
315 - if commit is None:
316 - return default
317 - return commit
318 -
319 -
320 -class GitFICommit(object):
321 -
322 - """Encapsulate the data in a Git fast-import commit command."""
323 -
324 - SHA1RE = re.compile(r'^[0-9a-f]{40}$')
325 -
326 - @classmethod
327 - def parse_mode (cls, mode):
328 - """Verify the given git file mode, and return it as a string."""
329 - assert mode in (644, 755, 100644, 100755, 120000)
330 - return "%i" % (mode)
331 -
332 - @classmethod
333 - def parse_objname (cls, objname):
334 - """Return the given object name (or mark number) as a string."""
335 - if isinstance(objname, int): # Object name is a mark number
336 - assert objname > 0
337 - return ":%i" % (objname)
338 -
339 - # No existence check is done, only checks for valid format
340 - assert cls.SHA1RE.match(objname) # Object name is valid SHA1
341 - return objname
342 -
343 - @classmethod
344 - def quote_path (cls, path):
345 - """Return a quoted version of the given path."""
346 - path = path.replace("\\", "\\\\")
347 - path = path.replace("\n", "\\n")
348 - path = path.replace('"', '\\"')
349 - return '"%s"' % (path)
350 -
351 - @classmethod
352 - def parse_path (cls, path):
353 - """Verify that the given path is valid, and quote it, if needed."""
354 - assert not isinstance(path, int) # Cannot be a mark number
355 -
356 - # These checks verify the rules on the fast-import man page
357 - assert not path.count("//")
358 - assert not path.endswith("/")
359 - assert not path.startswith("/")
360 - assert not path.count("/./")
361 - assert not path.count("/../")
362 - assert not path.endswith("/.")
363 - assert not path.endswith("/..")
364 - assert not path.startswith("./")
365 - assert not path.startswith("../")
366 -
367 - if path.count('"') + path.count('\n') + path.count('\\'):
368 - return cls.quote_path(path)
369 - return path
370 -
371 - def __init__ (self, name, email, timestamp, timezone, message):
372 - """Create a new Git fast-import commit, with the given metadata."""
373 - self.name = name
374 - self.email = email
375 - self.timestamp = timestamp
376 - self.timezone = timezone
377 - self.message = message
378 - self.pathops = [] # List of path operations in this commit
379 -
380 - def modify (self, mode, blobname, path):
381 - """Add a file modification to this Git fast-import commit."""
382 - self.pathops.append(("M",
383 - self.parse_mode(mode),
384 - self.parse_objname(blobname),
385 - self.parse_path(path)))
386 -
387 - def delete (self, path):
388 - """Add a file deletion to this Git fast-import commit."""
389 - self.pathops.append(("D", self.parse_path(path)))
390 -
391 - def copy (self, path, newpath):
392 - """Add a file copy to this Git fast-import commit."""
393 - self.pathops.append(("C",
394 - self.parse_path(path),
395 - self.parse_path(newpath)))
396 -
397 - def rename (self, path, newpath):
398 - """Add a file rename to this Git fast-import commit."""
399 - self.pathops.append(("R",
400 - self.parse_path(path),
401 - self.parse_path(newpath)))
402 -
403 - def note (self, blobname, commit):
404 - """Add a note object to this Git fast-import commit."""
405 - self.pathops.append(("N",
406 - self.parse_objname(blobname),
407 - self.parse_objname(commit)))
408 -
409 - def deleteall (self):
410 - """Delete all files in this Git fast-import commit."""
411 - self.pathops.append("deleteall")
412 -
413 -
414 -class TestGitFICommit(unittest.TestCase):
415 -
416 - """GitFICommit selftests."""
417 -
418 - def test_basic (self):
419 - """GitFICommit basic selftests."""
420 -
421 - def expect_fail (method, data):
422 - """Verify that the method(data) raises an AssertionError."""
423 - try:
424 - method(data)
425 - except AssertionError:
426 - return
427 - raise AssertionError("Failed test for invalid data '%s(%s)'" %
428 - (method.__name__, repr(data)))
429 -
430 - def test_parse_mode (self):
431 - """GitFICommit.parse_mode() selftests."""
432 - self.assertEqual(GitFICommit.parse_mode(644), "644")
433 - self.assertEqual(GitFICommit.parse_mode(755), "755")
434 - self.assertEqual(GitFICommit.parse_mode(100644), "100644")
435 - self.assertEqual(GitFICommit.parse_mode(100755), "100755")
436 - self.assertEqual(GitFICommit.parse_mode(120000), "120000")
437 - self.assertRaises(AssertionError, GitFICommit.parse_mode, 0)
438 - self.assertRaises(AssertionError, GitFICommit.parse_mode, 123)
439 - self.assertRaises(AssertionError, GitFICommit.parse_mode, 600)
440 - self.assertRaises(AssertionError, GitFICommit.parse_mode, "644")
441 - self.assertRaises(AssertionError, GitFICommit.parse_mode, "abc")
442 -
443 - def test_parse_objname (self):
444 - """GitFICommit.parse_objname() selftests."""
445 - self.assertEqual(GitFICommit.parse_objname(1), ":1")
446 - self.assertRaises(AssertionError, GitFICommit.parse_objname, 0)
447 - self.assertRaises(AssertionError, GitFICommit.parse_objname, -1)
448 - self.assertEqual(GitFICommit.parse_objname("0123456789" * 4),
449 - "0123456789" * 4)
450 - self.assertEqual(GitFICommit.parse_objname("2468abcdef" * 4),
451 - "2468abcdef" * 4)
452 - self.assertRaises(AssertionError, GitFICommit.parse_objname,
453 - "abcdefghij" * 4)
454 -
455 - def test_parse_path (self):
456 - """GitFICommit.parse_path() selftests."""
457 - self.assertEqual(GitFICommit.parse_path("foo/bar"), "foo/bar")
458 - self.assertEqual(GitFICommit.parse_path("path/with\n and \" in it"),
459 - '"path/with\\n and \\" in it"')
460 - self.assertRaises(AssertionError, GitFICommit.parse_path, 1)
461 - self.assertRaises(AssertionError, GitFICommit.parse_path, 0)
462 - self.assertRaises(AssertionError, GitFICommit.parse_path, -1)
463 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo//bar")
464 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/")
465 - self.assertRaises(AssertionError, GitFICommit.parse_path, "/foo/bar")
466 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/./bar")
467 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/../bar")
468 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/.")
469 - self.assertRaises(AssertionError, GitFICommit.parse_path, "foo/bar/..")
470 - self.assertRaises(AssertionError, GitFICommit.parse_path, "./foo/bar")
471 - self.assertRaises(AssertionError, GitFICommit.parse_path, "../foo/bar")
472 -
473 -
474 -class GitFastImport(object):
475 -
476 - """Encapsulate communication with git fast-import."""
477 -
478 - def __init__ (self, f, obj_fetcher, last_mark = 0):
479 - """Set up self to communicate with a fast-import process through f."""
480 - self.f = f # File object where fast-import stream is written
481 - self.obj_fetcher = obj_fetcher # GitObjectFetcher instance
482 - self.next_mark = last_mark + 1 # Next mark number
483 - self.refs = set() # Keep track of the refnames we've seen
484 -
485 - def comment (self, s):
486 - """Write the given comment in the fast-import stream."""
487 - assert "\n" not in s, "Malformed comment: '%s'" % (s)
488 - self.f.write("# %s\n" % (s))
489 -
490 - def commit (self, ref, commitdata):
491 - """Make a commit on the given ref, with the given GitFICommit.
492 -
493 - Return the mark number identifying this commit.
494 -
495 - """
496 - self.f.write("""\
497 -commit %(ref)s
498 -mark :%(mark)i
499 -committer %(name)s <%(email)s> %(timestamp)i %(timezone)s
500 -data %(msgLength)i
501 -%(msg)s
502 -""" % {
503 - 'ref': ref,
504 - 'mark': self.next_mark,
505 - 'name': commitdata.name,
506 - 'email': commitdata.email,
507 - 'timestamp': commitdata.timestamp,
508 - 'timezone': commitdata.timezone,
509 - 'msgLength': len(commitdata.message),
510 - 'msg': commitdata.message,
511 -})
512 -
513 - if ref not in self.refs:
514 - self.refs.add(ref)
515 - parent = ref + "^0"
516 - if self.obj_fetcher.get_sha1(parent):
517 - self.f.write("from %s\n" % (parent))
518 -
519 - for op in commitdata.pathops:
520 - self.f.write(" ".join(op))
521 - self.f.write("\n")
522 - self.f.write("\n")
523 - retval = self.next_mark
524 - self.next_mark += 1
525 - return retval
526 -
527 - def blob (self, data):
528 - """Import the given blob.
529 -
530 - Return the mark number identifying this blob.
531 -
532 - """
533 - self.f.write("blob\nmark :%i\ndata %i\n%s\n" %
534 - (self.next_mark, len(data), data))
535 - retval = self.next_mark
536 - self.next_mark += 1
537 - return retval
538 -
539 - def reset (self, ref, objname):
540 - """Reset the given ref to point at the given Git object."""
541 - self.f.write("reset %s\nfrom %s\n\n" %
542 - (ref, GitFICommit.parse_objname(objname)))
543 - if ref not in self.refs:
544 - self.refs.add(ref)
545 -
546 -
547 -class GitNotes(object):
548 -
549 - """Encapsulate access to Git notes.
550 -
551 - Simulates a dictionary of object name (SHA1) -> Git note mappings.
552 -
553 - """
554 -
555 - def __init__ (self, notes_ref, obj_fetcher):
556 - """Create a new Git notes interface, bound to the given notes ref."""
557 - self.notes_ref = notes_ref
558 - self.obj_fetcher = obj_fetcher # Used to get objects from repo
559 - self.imports = [] # list: (objname, note data blob name) tuples
560 -
561 - def __del__ (self):
562 - """Verify that self.commit_notes() was called before destruction."""
563 - if self.imports:
564 - error("Missing call to self.commit_notes().")
565 - error("%i notes are not committed!", len(self.imports))
566 -
567 - def _load (self, objname):
568 - """Return the note data associated with the given git object.
569 -
570 - The note data is returned in string form. If no note is found
571 - for the given object, None is returned.
572 -
573 - """
574 - try:
575 - f = self.obj_fetcher.open_obj("%s:%s" % (self.notes_ref, objname))
576 - ret = f.read()
577 - f.close()
578 - except KeyError:
579 - ret = None
580 - return ret
581 -
582 - def __getitem__ (self, objname):
583 - """Return the note contents associated with the given object.
584 -
585 - Raise KeyError if given object has no associated note.
586 -
587 - """
588 - blobdata = self._load(objname)
589 - if blobdata is None:
590 - raise KeyError("Object '%s' has no note" % (objname))
591 - return blobdata
592 -
593 - def get (self, objname, default = None):
594 - """Return the note contents associated with the given object.
595 -
596 - Return given default if given object has no associated note.
597 -
598 - """
599 - blobdata = self._load(objname)
600 - if blobdata is None:
601 - return default
602 - return blobdata
603 -
604 - def import_note (self, objname, data, gfi):
605 - """Tell git fast-import to store data as a note for objname.
606 -
607 - This method uses the given GitFastImport object to create a
608 - blob containing the given note data. Also an entry mapping the
609 - given object name to the created blob is stored until
610 - commit_notes() is called.
611 -
612 - Note that this method only works if it is later followed by a
613 - call to self.commit_notes() (which produces the note commit
614 - that refers to the blob produced here).
615 -
616 - """
617 - if not data.endswith("\n"):
618 - data += "\n"
619 - gfi.comment("Importing note for object %s" % (objname))
620 - mark = gfi.blob(data)
621 - self.imports.append((objname, mark))
622 -
623 - def commit_notes (self, gfi, author, message):
624 - """Produce a git fast-import note commit for the imported notes.
625 -
626 - This method uses the given GitFastImport object to create a
627 - commit on the notes ref, introducing the notes previously
628 - submitted to import_note().
629 -
630 - """
631 - if not self.imports:
632 - return
633 - commitdata = GitFICommit(author[0], author[1],
634 - time.time(), "0000", message)
635 - for objname, blobname in self.imports:
636 - assert isinstance(objname, int) and objname > 0
637 - assert isinstance(blobname, int) and blobname > 0
638 - commitdata.note(blobname, objname)
639 - gfi.commit(self.notes_ref, commitdata)
640 - self.imports = []
641 -
642 -
643 -class GitCachedNotes(GitNotes):
644 -
645 - """Encapsulate access to Git notes (cached version).
646 -
647 - Only use this class if no caching is done at a higher level.
648 -
649 - Simulates a dictionary of object name (SHA1) -> Git note mappings.
650 -
651 - """
652 -
653 - def __init__ (self, notes_ref, obj_fetcher):
654 - """Set up a caching wrapper around GitNotes."""
655 - GitNotes.__init__(self, notes_ref, obj_fetcher)
656 - self._cache = {} # Cache: object name -> note data
657 -
658 - def __del__ (self):
659 - """Verify that GitNotes' destructor is called."""
660 - GitNotes.__del__(self)
661 -
662 - def _load (self, objname):
663 - """Extend GitNotes._load() with a local objname -> note cache."""
664 - if objname not in self._cache:
665 - self._cache[objname] = GitNotes._load(self, objname)
666 - return self._cache[objname]
667 -
668 - def import_note (self, objname, data, gfi):
669 - """Extend GitNotes.import_note() with a local objname -> note cache."""
670 - if not data.endswith("\n"):
671 - data += "\n"
672 - assert objname not in self._cache
673 - self._cache[objname] = data
674 - GitNotes.import_note(self, objname, data, gfi)
675 -
676 -
677 -if __name__ == '__main__':
678 - unittest.main()
git_remote_helpers/git/importer.py deleted
-69
@@ -1,69 +0,0 @@
1 -import os
2 -import subprocess
3 -
4 -from git_remote_helpers.util import check_call, check_output
5 -
6 -
7 -class GitImporter(object):
8 - """An importer for testgit repositories.
9 -
10 - This importer simply delegates to git fast-import.
11 - """
12 -
13 - def __init__(self, repo):
14 - """Creates a new importer for the specified repo.
15 - """
16 -
17 - self.repo = repo
18 -
19 - def get_refs(self, gitdir):
20 - """Returns a dictionary with refs.
21 -
22 - Note that the keys in the returned dictionary are byte strings as
23 - read from git.
24 - """
25 - args = ["git", "--git-dir=" + gitdir, "for-each-ref", "refs/heads"]
26 - lines = check_output(args).strip().split('\n'.encode('ascii'))
27 - refs = {}
28 - for line in lines:
29 - value, name = line.split(' '.encode('ascii'))
30 - name = name.strip('commit\t'.encode('ascii'))
31 - refs[name] = value
32 - return refs
33 -
34 - def do_import(self, base):
35 - """Imports a fast-import stream to the given directory.
36 -
37 - Simply delegates to git fast-import.
38 - """
39 -
40 - dirname = self.repo.get_base_path(base)
41 - if self.repo.local:
42 - gitdir = self.repo.gitpath
43 - else:
44 - gitdir = os.path.abspath(os.path.join(dirname, '.git'))
45 - path = os.path.abspath(os.path.join(dirname, 'testgit.marks'))
46 -
47 - if not os.path.exists(dirname):
48 - os.makedirs(dirname)
49 -
50 - refs_before = self.get_refs(gitdir)
51 -
52 - args = ["git", "--git-dir=" + gitdir, "fast-import", "--quiet", "--export-marks=" + path]
53 -
54 - if os.path.exists(path):
55 - args.append("--import-marks=" + path)
56 -
57 - check_call(args)
58 -
59 - refs_after = self.get_refs(gitdir)
60 -
61 - changed = {}
62 -
63 - for name, value in refs_after.iteritems():
64 - if refs_before.get(name) == value:
65 - continue
66 -
67 - changed[name] = value
68 -
69 - return changed
git_remote_helpers/git/non_local.py deleted
-61
@@ -1,61 +0,0 @@
1 -import os
2 -import subprocess
3 -
4 -from git_remote_helpers.util import check_call, die, warn
5 -
6 -
7 -class NonLocalGit(object):
8 - """Handler to interact with non-local repos.
9 - """
10 -
11 - def __init__(self, repo):
12 - """Creates a new non-local handler for the specified repo.
13 - """
14 -
15 - self.repo = repo
16 -
17 - def clone(self, base):
18 - """Clones the non-local repo to base.
19 -
20 - Does nothing if a clone already exists.
21 - """
22 -
23 - path = os.path.join(self.repo.get_base_path(base), '.git')
24 -
25 - # already cloned
26 - if os.path.exists(path):
27 - return path
28 -
29 - os.makedirs(path)
30 - args = ["git", "clone", "--bare", "--quiet", self.repo.gitpath, path]
31 -
32 - check_call(args)
33 -
34 - return path
35 -
36 - def update(self, base):
37 - """Updates checkout of the non-local repo in base.
38 - """
39 -
40 - path = os.path.join(self.repo.get_base_path(base), '.git')
41 -
42 - if not os.path.exists(path):
43 - die("could not find repo at %s", path)
44 -
45 - args = ["git", "--git-dir=" + path, "fetch", "--quiet", self.repo.gitpath]
46 - check_call(args)
47 -
48 - args = ["git", "--git-dir=" + path, "update-ref", "refs/heads/master", "FETCH_HEAD"]
49 - child = check_call(args)
50 -
51 - def push(self, base):
52 - """Pushes from the non-local repo to base.
53 - """
54 -
55 - path = os.path.join(self.repo.get_base_path(base), '.git')
56 -
57 - if not os.path.exists(path):
58 - die("could not find repo at %s", path)
59 -
60 - args = ["git", "--git-dir=" + path, "push", "--quiet", self.repo.gitpath, "--all"]
61 - child = check_call(args)
git_remote_helpers/git/repo.py deleted
-76
@@ -1,76 +0,0 @@
1 -import os
2 -import subprocess
3 -
4 -from git_remote_helpers.util import check_call
5 -
6 -
7 -def sanitize(rev, sep='\t'):
8 - """Converts a for-each-ref line to a name/value pair.
9 - """
10 -
11 - splitrev = rev.split(sep)
12 - branchval = splitrev[0]
13 - branchname = splitrev[1].strip()
14 - if branchname.startswith("refs/heads/"):
15 - branchname = branchname[11:]
16 -
17 - return branchname, branchval
18 -
19 -def is_remote(url):
20 - """Checks whether the specified value is a remote url.
21 - """
22 -
23 - prefixes = ["http", "file", "git"]
24 -
25 - for prefix in prefixes:
26 - if url.startswith(prefix):
27 - return True
28 - return False
29 -
30 -class GitRepo(object):
31 - """Repo object representing a repo.
32 - """
33 -
34 - def __init__(self, path):
35 - """Initializes a new repo at the given path.
36 - """
37 -
38 - self.path = path
39 - self.head = None
40 - self.revmap = {}
41 - self.local = not is_remote(self.path)
42 -
43 - if(self.path.endswith('.git')):
44 - self.gitpath = self.path
45 - else:
46 - self.gitpath = os.path.join(self.path, '.git')
47 -
48 - if self.local and not os.path.exists(self.gitpath):
49 - os.makedirs(self.gitpath)
50 -
51 - def get_revs(self):
52 - """Fetches all revs from the remote.
53 - """
54 -
55 - args = ["git", "ls-remote", self.gitpath]
56 - path = ".cached_revs"
57 - ofile = open(path, "w")
58 -
59 - check_call(args, stdout=ofile)
60 - output = open(path).readlines()
61 - self.revmap = dict(sanitize(i) for i in output)
62 - if "HEAD" in self.revmap:
63 - del self.revmap["HEAD"]
64 - self.revs = self.revmap.keys()
65 - ofile.close()
66 -
67 - def get_head(self):
68 - """Determines the head of a local repo.
69 - """
70 -
71 - if not self.local:
72 - return
73 -
74 - path = os.path.join(self.gitpath, "HEAD")
75 - head = open(path).readline()
76 - self.head, _ = sanitize(head, ' ')
git_remote_helpers/setup.cfg deleted
-3
@@ -1,3 +0,0 @@
1 -[build]
2 -build_purelib = build/lib
3 -build_platlib = build/lib
git_remote_helpers/setup.py deleted
-27
@@ -1,27 +0,0 @@
1 -#!/usr/bin/env python
2 -
3 -"""Distutils build/install script for the git_remote_helpers package."""
4 -
5 -from distutils.core import setup
6 -
7 -# If building under Python3 we need to run 2to3 on the code, do this by
8 -# trying to import distutils' 2to3 builder, which is only available in
9 -# Python3.
10 -try:
11 - from distutils.command.build_py import build_py_2to3 as build_py
12 -except ImportError:
13 - # 2.x
14 - from distutils.command.build_py import build_py
15 -
16 -setup(
17 - name = 'git_remote_helpers',
18 - version = '0.1.0',
19 - description = 'Git remote helper program for non-git repositories',
20 - license = 'GPLv2',
21 - author = 'The Git Community',
22 - author_email = 'git@vger.kernel.org',
23 - url = 'http://www.git-scm.com/',
24 - package_dir = {'git_remote_helpers': ''},
25 - packages = ['git_remote_helpers', 'git_remote_helpers.git'],
26 - cmdclass = {'build_py': build_py},
27 -)
git_remote_helpers/util.py deleted
-275
@@ -1,275 +0,0 @@
1 -#!/usr/bin/env python
2 -
3 -"""Misc. useful functionality used by the rest of this package.
4 -
5 -This module provides common functionality used by the other modules in
6 -this package.
7 -
8 -"""
9 -
10 -import sys
11 -import os
12 -import subprocess
13 -
14 -try:
15 - from subprocess import CalledProcessError
16 -except ImportError:
17 - # from python2.7:subprocess.py
18 - # Exception classes used by this module.
19 - class CalledProcessError(Exception):
20 - """This exception is raised when a process run by check_call() returns
21 - a non-zero exit status. The exit status will be stored in the
22 - returncode attribute."""
23 - def __init__(self, returncode, cmd):
24 - self.returncode = returncode
25 - self.cmd = cmd
26 - def __str__(self):
27 - return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
28 -
29 -
30 -# Whether or not to show debug messages
31 -DEBUG = False
32 -
33 -def notify(msg, *args):
34 - """Print a message to stderr."""
35 - print >> sys.stderr, msg % args
36 -
37 -def debug (msg, *args):
38 - """Print a debug message to stderr when DEBUG is enabled."""
39 - if DEBUG:
40 - print >> sys.stderr, msg % args
41 -
42 -def error (msg, *args):
43 - """Print an error message to stderr."""
44 - print >> sys.stderr, "ERROR:", msg % args
45 -
46 -def warn(msg, *args):
47 - """Print a warning message to stderr."""
48 - print >> sys.stderr, "warning:", msg % args
49 -
50 -def die (msg, *args):
51 - """Print as error message to stderr and exit the program."""
52 - error(msg, *args)
53 - sys.exit(1)
54 -
55 -
56 -class ProgressIndicator(object):
57 -
58 - """Simple progress indicator.
59 -
60 - Displayed as a spinning character by default, but can be customized
61 - by passing custom messages that overrides the spinning character.
62 -
63 - """
64 -
65 - States = ("|", "/", "-", "\\")
66 -
67 - def __init__ (self, prefix = "", f = sys.stdout):
68 - """Create a new ProgressIndicator, bound to the given file object."""
69 - self.n = 0 # Simple progress counter
70 - self.f = f # Progress is written to this file object
71 - self.prev_len = 0 # Length of previous msg (to be overwritten)
72 - self.prefix = prefix # Prefix prepended to each progress message
73 - self.prefix_lens = [] # Stack of prefix string lengths
74 -
75 - def pushprefix (self, prefix):
76 - """Append the given prefix onto the prefix stack."""
77 - self.prefix_lens.append(len(self.prefix))
78 - self.prefix += prefix
79 -
80 - def popprefix (self):
81 - """Remove the last prefix from the prefix stack."""
82 - prev_len = self.prefix_lens.pop()
83 - self.prefix = self.prefix[:prev_len]
84 -
85 - def __call__ (self, msg = None, lf = False):
86 - """Indicate progress, possibly with a custom message."""
87 - if msg is None:
88 - msg = self.States[self.n % len(self.States)]
89 - msg = self.prefix + msg
90 - print >> self.f, "\r%-*s" % (self.prev_len, msg),
91 - self.prev_len = len(msg.expandtabs())
92 - if lf:
93 - print >> self.f
94 - self.prev_len = 0
95 - self.n += 1
96 -
97 - def finish (self, msg = "done", noprefix = False):
98 - """Finalize progress indication with the given message."""
99 - if noprefix:
100 - self.prefix = ""
101 - self(msg, True)
102 -
103 -
104 -def start_command (args, cwd = None, shell = False, add_env = None,
105 - stdin = subprocess.PIPE, stdout = subprocess.PIPE,
106 - stderr = subprocess.PIPE):
107 - """Start the given command, and return a subprocess object.
108 -
109 - This provides a simpler interface to the subprocess module.
110 -
111 - """
112 - env = None
113 - if add_env is not None:
114 - env = os.environ.copy()
115 - env.update(add_env)
116 - return subprocess.Popen(args, bufsize = 1, stdin = stdin, stdout = stdout,
117 - stderr = stderr, cwd = cwd, shell = shell,
118 - env = env, universal_newlines = True)
119 -
120 -
121 -def run_command (args, cwd = None, shell = False, add_env = None,
122 - flag_error = True):
123 - """Run the given command to completion, and return its results.
124 -
125 - This provides a simpler interface to the subprocess module.
126 -
127 - The results are formatted as a 3-tuple: (exit_code, output, errors)
128 -
129 - If flag_error is enabled, Error messages will be produced if the
130 - subprocess terminated with a non-zero exit code and/or stderr
131 - output.
132 -
133 - The other arguments are passed on to start_command().
134 -
135 - """
136 - process = start_command(args, cwd, shell, add_env)
137 - (output, errors) = process.communicate()
138 - exit_code = process.returncode
139 - if flag_error and errors:
140 - error("'%s' returned errors:\n---\n%s---", " ".join(args), errors)
141 - if flag_error and exit_code:
142 - error("'%s' returned exit code %i", " ".join(args), exit_code)
143 - return (exit_code, output, errors)
144 -
145 -
146 -# from python2.7:subprocess.py
147 -def call(*popenargs, **kwargs):
148 - """Run command with arguments. Wait for command to complete, then
149 - return the returncode attribute.
150 -
151 - The arguments are the same as for the Popen constructor. Example:
152 -
153 - retcode = call(["ls", "-l"])
154 - """
155 - return subprocess.Popen(*popenargs, **kwargs).wait()
156 -
157 -
158 -# from python2.7:subprocess.py
159 -def check_call(*popenargs, **kwargs):
160 - """Run command with arguments. Wait for command to complete. If
161 - the exit code was zero then return, otherwise raise
162 - CalledProcessError. The CalledProcessError object will have the
163 - return code in the returncode attribute.
164 -
165 - The arguments are the same as for the Popen constructor. Example:
166 -
167 - check_call(["ls", "-l"])
168 - """
169 - retcode = call(*popenargs, **kwargs)
170 - if retcode:
171 - cmd = kwargs.get("args")
172 - if cmd is None:
173 - cmd = popenargs[0]
174 - raise CalledProcessError(retcode, cmd)
175 - return 0
176 -
177 -
178 -# from python2.7:subprocess.py
179 -def check_output(*popenargs, **kwargs):
180 - r"""Run command with arguments and return its output as a byte string.
181 -
182 - If the exit code was non-zero it raises a CalledProcessError. The
183 - CalledProcessError object will have the return code in the returncode
184 - attribute and output in the output attribute.
185 -
186 - The arguments are the same as for the Popen constructor. Example:
187 -
188 - >>> check_output(["ls", "-l", "/dev/null"])
189 - 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
190 -
191 - The stdout argument is not allowed as it is used internally.
192 - To capture standard error in the result, use stderr=STDOUT.
193 -
194 - >>> check_output(["/bin/sh", "-c",
195 - ... "ls -l non_existent_file ; exit 0"],
196 - ... stderr=STDOUT)
197 - 'ls: non_existent_file: No such file or directory\n'
198 - """
199 - if 'stdout' in kwargs:
200 - raise ValueError('stdout argument not allowed, it will be overridden.')
201 - process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
202 - output, unused_err = process.communicate()
203 - retcode = process.poll()
204 - if retcode:
205 - cmd = kwargs.get("args")
206 - if cmd is None:
207 - cmd = popenargs[0]
208 - raise subprocess.CalledProcessError(retcode, cmd)
209 - return output
210 -
211 -
212 -def file_reader_method (missing_ok = False):
213 - """Decorator for simplifying reading of files.
214 -
215 - If missing_ok is True, a failure to open a file for reading will
216 - not raise the usual IOError, but instead the wrapped method will be
217 - called with f == None. The method must in this case properly
218 - handle f == None.
219 -
220 - """
221 - def _wrap (method):
222 - """Teach given method to handle both filenames and file objects.
223 -
224 - The given method must take a file object as its second argument
225 - (the first argument being 'self', of course). This decorator
226 - will take a filename given as the second argument and promote
227 - it to a file object.
228 -
229 - """
230 - def _wrapped_method (self, filename, *args, **kwargs):
231 - if isinstance(filename, file):
232 - f = filename
233 - else:
234 - try:
235 - f = open(filename, 'r')
236 - except IOError:
237 - if missing_ok:
238 - f = None
239 - else:
240 - raise
241 - try:
242 - return method(self, f, *args, **kwargs)
243 - finally:
244 - if not isinstance(filename, file) and f:
245 - f.close()
246 - return _wrapped_method
247 - return _wrap
248 -
249 -
250 -def file_writer_method (method):
251 - """Decorator for simplifying writing of files.
252 -
253 - Enables the given method to handle both filenames and file objects.
254 -
255 - The given method must take a file object as its second argument
256 - (the first argument being 'self', of course). This decorator will
257 - take a filename given as the second argument and promote it to a
258 - file object.
259 -
260 - """
261 - def _new_method (self, filename, *args, **kwargs):
262 - if isinstance(filename, file):
263 - f = filename
264 - else:
265 - # Make sure the containing directory exists
266 - parent_dir = os.path.dirname(filename)
267 - if not os.path.isdir(parent_dir):
268 - os.makedirs(parent_dir)
269 - f = open(filename, 'w')
270 - try:
271 - return method(self, f, *args, **kwargs)
272 - finally:
273 - if not isinstance(filename, file):
274 - f.close()
275 - return _new_method
t/t5800-remote-testpy.sh deleted
-169
@@ -1,169 +0,0 @@
1 -#!/bin/sh
2 -#
3 -# Copyright (c) 2010 Sverre Rabbelier
4 -#
5 -
6 -test_description='Test python remote-helper framework'
7 -
8 -. ./test-lib.sh
9 -
10 -if ! test_have_prereq PYTHON ; then
11 - skip_all='skipping python remote-helper tests, python not available'
12 - test_done
13 -fi
14 -
15 -"$PYTHON_PATH" -c '
16 -import sys
17 -if sys.hexversion < 0x02040000:
18 - sys.exit(1)
19 -' || {
20 - skip_all='skipping python remote-helper tests, python version < 2.4'
21 - test_done
22 -}
23 -
24 -compare_refs() {
25 - git --git-dir="$1/.git" rev-parse --verify $2 >expect &&
26 - git --git-dir="$3/.git" rev-parse --verify $4 >actual &&
27 - test_cmp expect actual
28 -}
29 -
30 -test_expect_success 'setup repository' '
31 - git init --bare server/.git &&
32 - git clone server public &&
33 - (cd public &&
34 - echo content >file &&
35 - git add file &&
36 - git commit -m one &&
37 - git push origin master)
38 -'
39 -
40 -test_expect_success 'cloning from local repo' '
41 - git clone "testpy::${PWD}/server" localclone &&
42 - test_cmp public/file localclone/file
43 -'
44 -
45 -test_expect_success 'cloning from remote repo' '
46 - git clone "testpy::file://${PWD}/server" clone &&
47 - test_cmp public/file clone/file
48 -'
49 -
50 -test_expect_success 'create new commit on remote' '
51 - (cd public &&
52 - echo content >>file &&
53 - git commit -a -m two &&
54 - git push)
55 -'
56 -
57 -test_expect_success 'pulling from local repo' '
58 - (cd localclone && git pull) &&
59 - test_cmp public/file localclone/file
60 -'
61 -
62 -test_expect_success 'pulling from remote remote' '
63 - (cd clone && git pull) &&
64 - test_cmp public/file clone/file
65 -'
66 -
67 -test_expect_success 'pushing to local repo' '
68 - (cd localclone &&
69 - echo content >>file &&
70 - git commit -a -m three &&
71 - git push) &&
72 - compare_refs localclone HEAD server HEAD
73 -'
74 -
75 -# Generally, skip this test. It demonstrates a now-fixed race in
76 -# git-remote-testpy, but is too slow to leave in for general use.
77 -: test_expect_success 'racily pushing to local repo' '
78 - test_when_finished "rm -rf server2 localclone2" &&
79 - cp -R server server2 &&
80 - git clone "testpy::${PWD}/server2" localclone2 &&
81 - (cd localclone2 &&
82 - echo content >>file &&
83 - git commit -a -m three &&
84 - GIT_REMOTE_TESTGIT_SLEEPY=2 git push) &&
85 - compare_refs localclone2 HEAD server2 HEAD
86 -'
87 -
88 -test_expect_success 'synch with changes from localclone' '
89 - (cd clone &&
90 - git pull)
91 -'
92 -
93 -test_expect_success 'pushing remote local repo' '
94 - (cd clone &&
95 - echo content >>file &&
96 - git commit -a -m four &&
97 - git push) &&
98 - compare_refs clone HEAD server HEAD
99 -'
100 -
101 -test_expect_success 'fetch new branch' '
102 - (cd public &&
103 - git checkout -b new &&
104 - echo content >>file &&
105 - git commit -a -m five &&
106 - git push origin new
107 - ) &&
108 - (cd localclone &&
109 - git fetch origin new
110 - ) &&
111 - compare_refs public HEAD localclone FETCH_HEAD
112 -'
113 -
114 -test_expect_success 'fetch multiple branches' '
115 - (cd localclone &&
116 - git fetch
117 - ) &&
118 - compare_refs server master localclone refs/remotes/origin/master &&
119 - compare_refs server new localclone refs/remotes/origin/new
120 -'
121 -
122 -test_expect_success 'push when remote has extra refs' '
123 - (cd clone &&
124 - echo content >>file &&
125 - git commit -a -m six &&
126 - git push
127 - ) &&
128 - compare_refs clone master server master
129 -'
130 -
131 -test_expect_success 'push new branch by name' '
132 - (cd clone &&
133 - git checkout -b new-name &&
134 - echo content >>file &&
135 - git commit -a -m seven &&
136 - git push origin new-name
137 - ) &&
138 - compare_refs clone HEAD server refs/heads/new-name
139 -'
140 -
141 -test_expect_failure 'push new branch with old:new refspec' '
142 - (cd clone &&
143 - git push origin new-name:new-refspec
144 - ) &&
145 - compare_refs clone HEAD server refs/heads/new-refspec
146 -'
147 -
148 -test_expect_success 'proper failure checks for fetching' '
149 - (GIT_REMOTE_TESTGIT_FAILURE=1 &&
150 - export GIT_REMOTE_TESTGIT_FAILURE &&
151 - cd localclone &&
152 - test_must_fail git fetch 2>&1 | \
153 - grep "Error while running fast-import"
154 - )
155 -'
156 -
157 -# We sleep to give fast-export a chance to catch the SIGPIPE
158 -test_expect_failure 'proper failure checks for pushing' '
159 - (GIT_REMOTE_TESTGIT_FAILURE=1 &&
160 - export GIT_REMOTE_TESTGIT_FAILURE &&
161 - GIT_REMOTE_TESTGIT_SLEEPY=1 &&
162 - export GIT_REMOTE_TESTGIT_SLEEPY &&
163 - cd localclone &&
164 - test_must_fail git push --all 2>&1 | \
165 - grep "Error while running fast-export"
166 - )
167 -'
168 -
169 -test_done
t/test-lib.sh
-9
@@ -700,15 +700,6 @@ test -d "$GIT_BUILD_DIR"/templates/blt || {
700 error "You haven't built things yet, have you?"
701 }
702
703 -if test -z "$GIT_TEST_INSTALLED" && test -z "$NO_PYTHON"
704 -then
705 - GITPYTHONLIB="$GIT_BUILD_DIR/git_remote_helpers/build/lib"
706 - export GITPYTHONLIB
707 - test -d "$GIT_BUILD_DIR"/git_remote_helpers/build || {
708 - error "You haven't built git_remote_helpers yet, have you?"
709 - }
710 -fi
711 -
703 if ! test -x "$GIT_BUILD_DIR"/test-chmtime
704 then
705 echo >&2 'You need to build test-chmtime:'