Explicitly specify utf-8 coding in file
[stgit] / stgit / git.py
CommitLineData
41a6d859
CM
1"""Python GIT interface
2"""
3
4__copyright__ = """
5Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7This program is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License version 2 as
9published by the Free Software Foundation.
10
11This program is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with this program; if not, write to the Free Software
18Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19"""
20
3659ef88 21import sys, os, popen2, re, gitmergeonefile
41a6d859 22
170f576b 23from stgit import basedir
41a6d859
CM
24from stgit.utils import *
25
26# git exception class
27class GitException(Exception):
28 pass
29
30
41a6d859 31
41a6d859
CM
32#
33# Classes
34#
35class Commit:
36 """Handle the commit objects
37 """
38 def __init__(self, id_hash):
39 self.__id_hash = id_hash
41a6d859 40
26dba451 41 lines = _output_lines('git-cat-file commit %s' % id_hash)
37a4d1bf 42 self.__parents = []
26dba451
BL
43 for i in range(len(lines)):
44 line = lines[i]
41a6d859
CM
45 if line == '\n':
46 break
47 field = line.strip().split(' ', 1)
48 if field[0] == 'tree':
49 self.__tree = field[1]
50 elif field[0] == 'parent':
37a4d1bf 51 self.__parents.append(field[1])
41a6d859
CM
52 if field[0] == 'author':
53 self.__author = field[1]
dad310d0 54 if field[0] == 'committer':
41a6d859 55 self.__committer = field[1]
0618ea9c 56 self.__log = ''.join(lines[i+1:])
41a6d859
CM
57
58 def get_id_hash(self):
59 return self.__id_hash
60
61 def get_tree(self):
62 return self.__tree
63
64 def get_parent(self):
37a4d1bf
CM
65 return self.__parents[0]
66
67 def get_parents(self):
68 return self.__parents
41a6d859
CM
69
70 def get_author(self):
71 return self.__author
72
73 def get_committer(self):
74 return self.__committer
75
37a4d1bf
CM
76 def get_log(self):
77 return self.__log
78
8e29bcd2
CM
79# dictionary of Commit objects, used to avoid multiple calls to git
80__commits = dict()
41a6d859
CM
81
82#
83# Functions
84#
bae29ddd 85
8e29bcd2
CM
86def get_commit(id_hash):
87 """Commit objects factory. Save/look-up them in the __commits
88 dictionary
89 """
3237b6e4
CM
90 global __commits
91
8e29bcd2
CM
92 if id_hash in __commits:
93 return __commits[id_hash]
94 else:
95 commit = Commit(id_hash)
96 __commits[id_hash] = commit
97 return commit
98
41a6d859
CM
99def get_conflicts():
100 """Return the list of file conflicts
101 """
170f576b 102 conflicts_file = os.path.join(basedir.get(), 'conflicts')
41a6d859
CM
103 if os.path.isfile(conflicts_file):
104 f = file(conflicts_file)
105 names = [line.strip() for line in f.readlines()]
106 f.close()
107 return names
108 else:
109 return None
110
0d2cd1e4 111def _input(cmd, file_desc):
741f2784 112 p = popen2.Popen3(cmd, True)
6fe6b1bd
CM
113 while True:
114 line = file_desc.readline()
115 if not line:
116 break
0d2cd1e4
CM
117 p.tochild.write(line)
118 p.tochild.close()
119 if p.wait():
120 raise GitException, '%s failed' % str(cmd)
121
26dba451 122def _output(cmd):
741f2784 123 p=popen2.Popen3(cmd, True)
7cc615f3 124 output = p.fromchild.read()
26dba451
BL
125 if p.wait():
126 raise GitException, '%s failed' % str(cmd)
7cc615f3 127 return output
26dba451 128
d3cf7d86 129def _output_one_line(cmd, file_desc = None):
741f2784 130 p=popen2.Popen3(cmd, True)
d3cf7d86
PBG
131 if file_desc != None:
132 for line in file_desc:
133 p.tochild.write(line)
134 p.tochild.close()
7cc615f3 135 output = p.fromchild.readline().strip()
26dba451
BL
136 if p.wait():
137 raise GitException, '%s failed' % str(cmd)
7cc615f3 138 return output
41a6d859 139
26dba451 140def _output_lines(cmd):
741f2784 141 p=popen2.Popen3(cmd, True)
26dba451
BL
142 lines = p.fromchild.readlines()
143 if p.wait():
144 raise GitException, '%s failed' % str(cmd)
145 return lines
146
147def __run(cmd, args=None):
148 """__run: runs cmd using spawnvp.
149
150 Runs cmd using spawnvp. The shell is avoided so it won't mess up
151 our arguments. If args is very large, the command is run multiple
152 times; args is split xargs style: cmd is passed on each
153 invocation. Unlike xargs, returns immediately if any non-zero
154 return code is received.
155 """
156
157 args_l=cmd.split()
158 if args is None:
159 args = []
160 for i in range(0, len(args)+1, 100):
161 r=os.spawnvp(os.P_WAIT, args_l[0], args_l + args[i:min(i+100, len(args))])
162 if r:
163 return r
164 return 0
165
9216b602 166def __tree_status(files = None, tree_id = 'HEAD', unknown = False,
be24d874 167 noexclude = True):
41a6d859
CM
168 """Returns a list of pairs - [status, filename]
169 """
f8fb5747 170 refresh_index()
41a6d859 171
9216b602
CL
172 if not files:
173 files = []
41a6d859
CM
174 cache_files = []
175
176 # unknown files
177 if unknown:
170f576b 178 exclude_file = os.path.join(basedir.get(), 'info', 'exclude')
be24d874
CM
179 base_exclude = ['--exclude=%s' % s for s in
180 ['*.[ao]', '*.pyc', '.*', '*~', '#*', 'TAGS', 'tags']]
181 base_exclude.append('--exclude-per-directory=.gitignore')
182
41a6d859 183 if os.path.exists(exclude_file):
3c6fbd2c 184 extra_exclude = ['--exclude-from=%s' % exclude_file]
be24d874
CM
185 else:
186 extra_exclude = []
4d4c0e3a
PBG
187 if noexclude:
188 extra_exclude = base_exclude = []
be24d874 189
2c02c3b7
PBG
190 lines = _output_lines(['git-ls-files', '--others', '--directory']
191 + base_exclude + extra_exclude)
26dba451 192 cache_files += [('?', line.strip()) for line in lines]
41a6d859
CM
193
194 # conflicted files
195 conflicts = get_conflicts()
196 if not conflicts:
197 conflicts = []
198 cache_files += [('C', filename) for filename in conflicts]
199
200 # the rest
fec7f658 201 for line in _output_lines(['git-diff-index', tree_id] + files):
26dba451 202 fs = tuple(line.rstrip().split(' ',4)[-1].split('\t',1))
41a6d859
CM
203 if fs[1] not in conflicts:
204 cache_files.append(fs)
41a6d859
CM
205
206 return cache_files
207
208def local_changes():
209 """Return true if there are local changes in the tree
210 """
211 return len(__tree_status()) != 0
212
aa01a285
CM
213# HEAD value cached
214__head = None
215
41a6d859 216def get_head():
3097799d 217 """Verifies the HEAD and returns the SHA1 id that represents it
41a6d859 218 """
aa01a285
CM
219 global __head
220
221 if not __head:
222 __head = rev_parse('HEAD')
223 return __head
41a6d859
CM
224
225def get_head_file():
226 """Returns the name of the file pointed to by the HEAD link
227 """