Incorrect accquiring bugdir command line argument
[be.git] / libbe / storage / vcs / git.py
1 # Copyright (C) 2008-2012 Ben Finney <benf@cybersource.com.au>
2 #                         Chris Ball <cjb@laptop.org>
3 #                         Gianluca Montecchi <gian@grys.it>
4 #                         Robert Lehmann <mail@robertlehmann.de>
5 #                         W. Trevor King <wking@tremily.us>
6 #
7 # This file is part of Bugs Everywhere.
8 #
9 # Bugs Everywhere is free software: you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by the Free
11 # Software Foundation, either version 2 of the License, or (at your option) any
12 # later version.
13 #
14 # Bugs Everywhere is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
17 # more details.
18 #
19 # You should have received a copy of the GNU General Public License along with
20 # Bugs Everywhere.  If not, see <http://www.gnu.org/licenses/>.
21
22 """Git_ backend.
23
24 .. _Git: http://git-scm.com/
25 """
26
27 import os
28 import os.path
29 import re
30 import shutil
31 import unittest
32
33 try:
34     import pygit2 as _pygit2
35 except ImportError, error:
36     _pygit2 = None
37     _pygit2_import_error = error
38 else:
39     if getattr(_pygit2, '__version__', '0.17.3') == '0.17.3':
40         _pygit2 = None
41         _pygit2_import_error = NotImplementedError(
42             'pygit2 <= 0.17.3 not supported')
43
44 import libbe
45 from ...ui.util import user as _user
46 from ...util import encoding as _encoding
47 from ..base import EmptyCommit as _EmptyCommit
48 from . import base
49
50 if libbe.TESTING == True:
51     import doctest
52     import sys
53
54
55 def new():
56     if _pygit2:
57         return PygitGit()
58     else:
59         return ExecGit()
60
61
62 class PygitGit(base.VCS):
63     """:py:class:`base.VCS` implementation for Git.
64
65     Using :py:mod:`pygit2` for the Git activity.
66     """
67     name='pygit2'
68     _null_hex = u'0' * 40
69     _null_oid = '\00' * 20
70
71     def __init__(self, *args, **kwargs):
72         base.VCS.__init__(self, *args, **kwargs)
73         self.versioned = True
74         self._pygit_repository = None
75
76     def __getstate__(self):
77         """`pygit2.Repository`\s don't seem to pickle well.
78         """
79         attrs = dict(self.__dict__)
80         if self._pygit_repository is not None:
81             attrs['_pygit_repository'] = self._pygit_repository.path
82         return attrs
83
84     def __setstate__(self, state):
85         """`pygit2.Repository`\s don't seem to pickle well.
86         """
87         self.__dict__.update(state)
88         if self._pygit_repository is not None:
89             gitdir = self._pygit_repository
90             self._pygit_repository = _pygit2.Repository(gitdir)
91
92     def _vcs_version(self):
93         if _pygit2:
94             return getattr(_pygit2, '__verison__', '?')
95         return None
96
97     def _vcs_get_user_id(self):
98         try:
99             name = self._pygit_repository.config['user.name']
100         except KeyError:
101             name = ''
102         try:
103             email = self._pygit_repository.config['user.email']
104         except KeyError:
105             email = ''
106         if name != '' or email != '': # got something!
107             # guess missing info, if necessary
108             if name == '':
109                 name = _user.get_fallback_fullname()
110             if email == '':
111                 email = _user.get_fallback_email()
112             if '@' not in email:
113                 raise ValueError((name, email))
114             return _user.create_user_id(name, email)
115         return None # Git has no infomation
116
117     def _vcs_detect(self, path):
118         try:
119             _pygit2.discover_repository(path)
120         except KeyError:
121             return False
122         return True
123
124     def _vcs_root(self, path):
125         """Find the root of the deepest repository containing path."""
126         # Assume that nothing funny is going on; in particular, that we aren't
127         # dealing with a bare repo.
128         gitdir = _pygit2.discover_repository(path)
129         self._pygit_repository = _pygit2.Repository(gitdir)
130         dirname,tip = os.path.split(gitdir)
131         if tip == '':  # split('x/y/z/.git/') == ('x/y/z/.git', '')
132             dirname,tip = os.path.split(dirname)
133         assert tip == '.git', tip
134         return dirname
135
136     def _vcs_init(self, path):
137         bare = False
138         self._pygit_repository = _pygit2.init_repository(path, bare)
139
140     def _vcs_destroy(self):
141         vcs_dir = os.path.join(self.repo, '.git')
142         if os.path.exists(vcs_dir):
143             shutil.rmtree(vcs_dir)
144
145     def _vcs_add(self, path):
146         abspath = self._u_abspath(path)
147         if os.path.isdir(abspath):
148             return
149         self._pygit_repository.index.read()
150         self._pygit_repository.index.add(path)
151         self._pygit_repository.index.write()
152
153     def _vcs_remove(self, path):
154         abspath = self._u_abspath(path)
155         if not os.path.isdir(self._u_abspath(abspath)):
156             self._pygit_repository.index.read()
157             del self._pygit_repository.index[path]
158             self._pygit_repository.index.write()
159             os.remove(os.path.join(self.repo, path))
160
161     def _vcs_update(self, path):
162         self._vcs_add(path)
163
164     def _git_get_commit(self, revision):
165         if isinstance(revision, str):
166             revision = unicode(revision, 'ascii')
167         commit = self._pygit_repository.revparse_single(revision)
168         assert commit.type == _pygit2.GIT_OBJ_COMMIT, commit
169         return commit
170
171     def _git_get_object(self, path, revision):
172         commit = self._git_get_commit(revision=revision)
173         tree = commit.tree
174         sections = path.split(os.path.sep)
175         for section in sections[:-1]:  # traverse trees
176             child_tree = None
177             for entry in tree:
178                 if entry.name == section:
179                     eobj = entry.to_object()
180                     if eobj.type == _pygit2.GIT_OBJ_TREE:
181                         child_tree = eobj
182                         break
183                     else:
184                         raise ValueError(path)  # not a directory
185             if child_tree is None:
186                 raise ValueError((path, sections, section, [e.name for e in tree]))
187                 raise ValueError(path)  # not found
188             tree = child_tree
189         eobj = None
190         for entry in tree:
191             if entry.name == sections[-1]:
192                 eobj = entry.to_object()
193         return eobj
194
195     def _vcs_get_file_contents(self, path, revision=None):
196         if revision == None:
197             return base.VCS._vcs_get_file_contents(self, path, revision)
198         else:
199             blob = self._git_get_object(path=path, revision=revision)
200             if blob.type != _pygit2.GIT_OBJ_BLOB:
201                 raise ValueError(path)  # not a file
202             return blob.read_raw()
203
204     def _vcs_path(self, id, revision):
205         return self._u_find_id(id, revision)
206
207     def _vcs_isdir(self, path, revision):
208         obj = self._git_get_object(path=path, revision=revision)
209         return obj.type == _pygit2.GIT_OBJ_TREE
210
211     def _vcs_listdir(self, path, revision):
212         tree = self._git_get_object(path=path, revision=revision)
213         assert tree.type == _pygit2.GIT_OBJ_TREE, tree
214         return [e.name for e in tree]
215
216     def _vcs_commit(self, commitfile, allow_empty=False):
217         self._pygit_repository.index.read()
218         tree_oid = self._pygit_repository.index.write_tree()
219         try:
220             self._pygit_repository.head
221         except _pygit2.GitError:  # no head; this is the first commit
222             parents = []
223             tree = self._pygit_repository[tree_oid]
224             if not allow_empty and len(tree) == 0:
225                 raise _EmptyCommit()
226         else:
227             parents = [self._pygit_repository.head.oid]
228             if (not allow_empty and
229                 tree_oid == self._pygit_repository.head.tree.oid):
230                 raise _EmptyCommit()
231         update_ref = 'HEAD'
232         user_id = self.get_user_id()
233         name,email = _user.parse_user_id(user_id)
234         # using default times is recent, see
235         #   https://github.com/libgit2/pygit2/pull/129
236         author = _pygit2.Signature(name, email)
237         committer = author
238         message = _encoding.get_file_contents(commitfile, decode=False)
239         encoding = _encoding.get_text_file_encoding()
240         commit_oid = self._pygit_repository.create_commit(
241             update_ref, author, committer, message, tree_oid, parents,
242             encoding)
243         commit = self._pygit_repository[commit_oid]
244         return commit.hex
245
246     def _vcs_revision_id(self, index):
247         walker = self._pygit_repository.walk(
248             self._pygit_repository.head.oid, _pygit2.GIT_SORT_TIME)
249         if index < 0:
250             target_i = -1 - index  # -1: 0, -2: 1, ...
251             for i,commit in enumerate(walker):
252                 if i == target_i:
253                     return commit.hex
254         elif index > 0:
255             revisions = [commit.hex for commit in walker]
256             # revisions is [newest, older, ..., oldest]
257             if index > len(revisions):
258                 return None
259             return revisions[len(revisions) - index]
260         else:
261             raise NotImplementedError('initial revision')
262         return None
263
264     def _vcs_changed(self, revision):
265         commit = self._git_get_commit(revision=revision)
266         diff = commit.tree.diff(self._pygit_repository.head.tree)
267         new = set()
268         modified = set()
269         removed = set()
270         for hunk in diff.changes['hunks']:
271             if hunk.old_oid == self._null_hex:  # pygit2 uses hex in hunk.*_oid
272                 new.add(hunk.new_file)
273             elif hunk.new_oid == self._null_hex:
274                 removed.add(hunk.old_file)
275             else:
276                 modified.add(hunk.new_file)
277         return (list(new), list(modified), list(removed))
278
279
280 class ExecGit (PygitGit):
281     """:py:class:`base.VCS` implementation for Git.
282     """
283     name='git'
284     client='git'
285
286     def _vcs_version(self):
287         try:
288             status,output,error = self._u_invoke_client('--version')
289         except CommandError:  # command not found?
290             return None
291         return output.strip()
292
293     def _vcs_get_user_id(self):
294         status,output,error = self._u_invoke_client(
295             'config', 'user.name', expect=(0,1))
296         if status == 0:
297             name = output.rstrip('\n')
298         else:
299             name = ''
300         status,output,error = self._u_invoke_client(
301             'config', 'user.email', expect=(0,1))
302         if status == 0:
303             email = output.rstrip('\n')
304         else:
305             email = ''
306         if name != '' or email != '': # got something!
307             # guess missing info, if necessary
308             if name == '':
309                 name = _user.get_fallback_fullname()
310             if email == '':
311                 email = _user.get_fallback_email()
312             return _user.create_user_id(name, email)
313         return None # Git has no infomation
314
315     def _vcs_detect(self, path):
316         if self._u_search_parent_directories(path, '.git') != None :
317             return True
318         return False
319
320     def _vcs_root(self, path):
321         """Find the root of the deepest repository containing path."""
322         # Assume that nothing funny is going on; in particular, that we aren't
323         # dealing with a bare repo.
324         if os.path.isdir(path) != True:
325             path = os.path.dirname(path)
326         status,output,error = self._u_invoke_client('rev-parse', '--git-dir',
327                                                     cwd=path)
328         gitdir = os.path.join(path, output.rstrip('\n'))
329         dirname = os.path.abspath(os.path.dirname(gitdir))
330         return dirname
331
332     def _vcs_init(self, path):
333         self._u_invoke_client('init', cwd=path)
334
335     def _vcs_destroy(self):
336         vcs_dir = os.path.join(self.repo, '.git')
337         if os.path.exists(vcs_dir):
338             shutil.rmtree(vcs_dir)
339
340     def _vcs_add(self, path):
341         if os.path.isdir(path):
342             return
343         self._u_invoke_client('add', path)
344
345     def _vcs_remove(self, path):
346         if not os.path.isdir(self._u_abspath(path)):
347             self._u_invoke_client('rm', '-f', path)
348
349     def _vcs_update(self, path):
350         self._vcs_add(path)
351
352     def _vcs_get_file_contents(self, path, revision=None):
353         if revision == None:
354             return base.VCS._vcs_get_file_contents(self, path, revision)
355         else:
356             arg = '%s:%s' % (revision,path)
357             status,output,error = self._u_invoke_client('show', arg)
358             return output
359
360     def _vcs_path(self, id, revision):
361         return self._u_find_id(id, revision)
362
363     def _vcs_isdir(self, path, revision):
364         arg = '%s:%s' % (revision,path)
365         args = ['ls-tree', arg]
366         kwargs = {'expect':(0,128)}
367         status,output,error = self._u_invoke_client(*args, **kwargs)
368         if status != 0:
369             if 'not a tree object' in error:
370                 return False
371             raise base.CommandError(args, status, stderr=error)
372         return True
373
374     def _vcs_listdir(self, path, revision):
375         arg = '%s:%s' % (revision,path)
376         status,output,error = self._u_invoke_client(
377             'ls-tree', '--name-only', arg)
378         return output.rstrip('\n').splitlines()
379
380     def _vcs_commit(self, commitfile, allow_empty=False):
381         args = ['commit', '--file', commitfile]
382         if allow_empty == True:
383             args.append('--allow-empty')
384             status,output,error = self._u_invoke_client(*args)
385         else:
386             kwargs = {'expect':(0,1)}
387             status,output,error = self._u_invoke_client(*args, **kwargs)
388             strings = ['nothing to commit',
389                        'nothing added to commit']
390             if self._u_any_in_string(strings, output) == True:
391                 raise base.EmptyCommit()
392         full_revision = self._vcs_revision_id(-1)
393         assert full_revision[:7] in output, \
394             'Mismatched revisions:\n%s\n%s' % (full_revision, output)
395         return full_revision
396
397     def _vcs_revision_id(self, index):
398         args = ['rev-list', '--first-parent', '--reverse', 'HEAD']
399         kwargs = {'expect':(0,128)}
400         status,output,error = self._u_invoke_client(*args, **kwargs)
401         if status == 128:
402             if error.startswith("fatal: ambiguous argument 'HEAD': unknown "):
403                 return None
404             raise base.CommandError(args, status, stderr=error)
405         revisions = output.splitlines()
406         try:
407             if index > 0:
408                 return revisions[index-1]
409             elif index < 0:
410                 return revisions[index]
411             else:
412                 return None
413         except IndexError:
414             return None
415
416     def _diff(self, revision):
417         status,output,error = self._u_invoke_client('diff', revision)
418         return output
419
420     def _parse_diff(self, diff_text):
421         """_parse_diff(diff_text) -> (new,modified,removed)
422
423         `new`, `modified`, and `removed` are lists of files.
424
425         Example diff text::
426
427           diff --git a/dir/changed b/dir/changed
428           index 6c3ea8c..2f2f7c7 100644
429           --- a/dir/changed
430           +++ b/dir/changed
431           @@ -1,3 +1,3 @@
432            hi
433           -there
434           +everyone and
435            joe
436           diff --git a/dir/deleted b/dir/deleted
437           deleted file mode 100644
438           index 225ec04..0000000
439           --- a/dir/deleted
440           +++ /dev/null
441           @@ -1,3 +0,0 @@
442           -in
443           -the
444           -beginning
445           diff --git a/dir/moved b/dir/moved
446           deleted file mode 100644
447           index 5ef102f..0000000
448           --- a/dir/moved
449           +++ /dev/null
450           @@ -1,4 +0,0 @@
451           -the
452           -ants
453           -go
454           -marching
455           diff --git a/dir/moved2 b/dir/moved2
456           new file mode 100644
457           index 0000000..5ef102f
458           --- /dev/null
459           +++ b/dir/moved2
460           @@ -0,0 +1,4 @@
461           +the
462           +ants
463           +go
464           +marching
465           diff --git a/dir/new b/dir/new
466           new file mode 100644
467           index 0000000..94954ab
468           --- /dev/null
469           +++ b/dir/new
470           @@ -0,0 +1,2 @@
471           +hello
472           +world
473         """
474         new = []
475         modified = []
476         removed = []
477         lines = diff_text.splitlines()
478         for i,line in enumerate(lines):
479             if not line.startswith('diff '):
480                 continue
481             file_a,file_b = line.split()[-2:]
482             assert file_a.startswith('a/'), \
483                 'missformed file_a %s' % file_a
484             assert file_b.startswith('b/'), \
485                 'missformed file_b %s' % file_b
486             file = file_a[2:]
487             assert file_b[2:] == file, \
488                 'diff file missmatch %s != %s' % (file_a, file_b)
489             if lines[i+1].startswith('new '):
490                 new.append(file)
491             elif lines[i+1].startswith('index '):
492                 modified.append(file)
493             elif lines[i+1].startswith('deleted '):
494                 removed.append(file)
495         return (new,modified,removed)
496
497     def _vcs_changed(self, revision):
498         return self._parse_diff(self._diff(revision))
499
500
501 if libbe.TESTING == True:
502     base.make_vcs_testcase_subclasses(PygitGit, sys.modules[__name__])
503     base.make_vcs_testcase_subclasses(ExecGit, sys.modules[__name__])
504
505     unitsuite =unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
506     suite = unittest.TestSuite([unitsuite, doctest.DocTestSuite()])