git-remote-hg: improve sanitation of local repo urls
[git] / git-remote-testgit.py
1 #!/usr/bin/env python
2
3 # hashlib is only available in python >= 2.5
4 try:
5     import hashlib
6     _digest = hashlib.sha1
7 except ImportError:
8     import sha
9     _digest = sha.new
10 import sys
11 import os
12 sys.path.insert(0, os.getenv("GITPYTHONLIB","."))
13
14 from git_remote_helpers.util import die, debug, warn
15 from git_remote_helpers.git.repo import GitRepo
16 from git_remote_helpers.git.exporter import GitExporter
17 from git_remote_helpers.git.importer import GitImporter
18 from git_remote_helpers.git.non_local import NonLocalGit
19
20 def get_repo(alias, url):
21     """Returns a git repository object initialized for usage.
22     """
23
24     repo = GitRepo(url)
25     repo.get_revs()
26     repo.get_head()
27
28     hasher = _digest()
29     hasher.update(repo.path)
30     repo.hash = hasher.hexdigest()
31
32     repo.get_base_path = lambda base: os.path.join(
33         base, 'info', 'fast-import', repo.hash)
34
35     prefix = 'refs/testgit/%s/' % alias
36     debug("prefix: '%s'", prefix)
37
38     repo.gitdir = ""
39     repo.alias = alias
40     repo.prefix = prefix
41
42     repo.exporter = GitExporter(repo)
43     repo.importer = GitImporter(repo)
44     repo.non_local = NonLocalGit(repo)
45
46     return repo
47
48
49 def local_repo(repo, path):
50     """Returns a git repository object initalized for usage.
51     """
52
53     local = GitRepo(path)
54
55     local.non_local = None
56     local.gitdir = repo.gitdir
57     local.alias = repo.alias
58     local.prefix = repo.prefix
59     local.hash = repo.hash
60     local.get_base_path = repo.get_base_path
61     local.exporter = GitExporter(local)
62     local.importer = GitImporter(local)
63
64     return local
65
66
67 def do_capabilities(repo, args):
68     """Prints the supported capabilities.
69     """
70
71     print "import"
72     print "export"
73     print "gitdir"
74
75     sys.stdout.flush()
76     if not read_one_line(repo):
77         die("Expected gitdir, got empty line")
78
79     print "refspec refs/heads/*:%s*" % repo.prefix
80
81     dirname = repo.get_base_path(repo.gitdir)
82
83     if not os.path.exists(dirname):
84         os.makedirs(dirname)
85
86     path = os.path.join(dirname, 'testgit.marks')
87
88     print "*export-marks %s" % path
89     if os.path.exists(path):
90         print "*import-marks %s" % path
91
92     print # end capabilities
93
94
95 def do_list(repo, args):
96     """Lists all known references.
97
98     Bug: This will always set the remote head to master for non-local
99     repositories, since we have no way of determining what the remote
100     head is at clone time.
101     """
102
103     for ref in repo.revs:
104         debug("? refs/heads/%s", ref)
105         print "? refs/heads/%s" % ref
106
107     if repo.head:
108         debug("@refs/heads/%s HEAD" % repo.head)
109         print "@refs/heads/%s HEAD" % repo.head
110     else:
111         debug("@refs/heads/master HEAD")
112         print "@refs/heads/master HEAD"
113
114     print # end list
115
116
117 def update_local_repo(repo):
118     """Updates (or clones) a local repo.
119     """
120
121     if repo.local:
122         return repo
123
124     path = repo.non_local.clone(repo.gitdir)
125     repo.non_local.update(repo.gitdir)
126     repo = local_repo(repo, path)
127     return repo
128
129
130 def do_import(repo, args):
131     """Exports a fast-import stream from testgit for git to import.
132     """
133
134     if args:
135         die("Import expects its ref seperately")
136
137     if not repo.gitdir:
138         die("Need gitdir to import")
139
140     refs = []
141
142     while True:
143         line = sys.stdin.readline()
144         if line == '\n':
145             break
146         refs.append(line.strip())
147
148     repo = update_local_repo(repo)
149     repo.exporter.export_repo(repo.gitdir)
150
151     print "done"
152
153
154 def do_export(repo, args):
155     """Imports a fast-import stream from git to testgit.
156     """
157
158     if not repo.gitdir:
159         die("Need gitdir to export")
160
161     refs = []
162
163     while True:
164         line = sys.stdin.readline()
165         if line == '\n':
166             break
167         refs.append(line.strip())
168
169     update_local_repo(repo)
170     repo.importer.do_import(repo.gitdir)
171
172     if not repo.local:
173         repo.non_local.push(repo.gitdir)
174
175     for ref in refs:
176         print "ok %s" % ref
177
178     print
179
180
181 def do_gitdir(repo, args):
182     """Stores the location of the gitdir.
183     """
184
185     if not args:
186         die("gitdir needs an argument")
187
188     repo.gitdir = ' '.join(args)
189
190
191 COMMANDS = {
192     'capabilities': do_capabilities,
193     'list': do_list,
194     'import': do_import,
195     'export': do_export,
196     'gitdir': do_gitdir,
197 }
198
199
200 def sanitize(value):
201     """Cleans up the url.
202     """
203
204     if value.startswith('testgit::'):
205         value = value[9:]
206
207     return value
208
209
210 def read_one_line(repo):
211     """Reads and processes one command.
212     """
213
214     line = sys.stdin.readline()
215
216     cmdline = line
217
218     if not cmdline:
219         warn("Unexpected EOF")
220         return False
221
222     cmdline = cmdline.strip().split()
223     if not cmdline:
224         # Blank line means we're about to quit
225         return False
226
227     cmd = cmdline.pop(0)
228     debug("Got command '%s' with args '%s'", cmd, ' '.join(cmdline))
229
230     if cmd not in COMMANDS:
231         die("Unknown command, %s", cmd)
232
233     func = COMMANDS[cmd]
234     func(repo, cmdline)
235     sys.stdout.flush()
236
237     return True
238
239
240 def main(args):
241     """Starts a new remote helper for the specified repository.
242     """
243
244     if len(args) != 3:
245         die("Expecting exactly three arguments.")
246         sys.exit(1)
247
248     if os.getenv("GIT_DEBUG_TESTGIT"):
249         import git_remote_helpers.util
250         git_remote_helpers.util.DEBUG = True
251
252     alias = sanitize(args[1])
253     url = sanitize(args[2])
254
255     if not alias.isalnum():
256         warn("non-alnum alias '%s'", alias)
257         alias = "tmp"
258
259     args[1] = alias
260     args[2] = url
261
262     repo = get_repo(alias, url)
263
264     debug("Got arguments %s", args[1:])
265
266     more = True
267
268     while (more):
269         more = read_one_line(repo)
270
271 if __name__ == '__main__':
272     sys.exit(main(sys.argv))