/stdhome

To get this branch, use:
bzr branch http://bzr.ed.am/stdhome
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# bzr.py
#
# Copyright (C) 2014 Tim Marston <tim@edm.am>
#
# This file is part of stdhome (hereafter referred to as "this program").
# See http://ed.am/dev/stdhome for more information.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import io
import os
import re
import shutil
import subprocess
from subprocess import Popen

from stdhome import the

from .vcs import Vcs


class BzrVcs( Vcs ):


	def __init__( self, dir ):
		"""Init class

		@param dir the fully-qualified directory to work in.
		"""

		self.dir = dir
		self.ignored_files = [ '.bzr', '.bzrignore' ]


	def has_authority( self ):
		"""Check that the directory is under this VCS's control.
		"""

		return os.path.exists( os.path.join( self.dir, '.bzr' ) )


	def expand_repo_url( self, url ):
		"""Convert a simple hostname in to an URL that the VCS can use.
		"""

		return 'bzr+ssh://%s/%s/%s' % ( url, the.dir, the.repo.name )


	def init( self ):
		"""Create a new, empty branch
		"""

		# the directory shouldn't exist
		os.mkdir( self.dir )

		# bzr init
		try:
			self.run( [ 'bzr', 'init', '.' ] )
		except self.VcsError as e:

			# attempt to clean-up dir
			try:
				shutil.rmtree( self.dir )
			except OSError:
				pass

			raise


	def checkout( self, url ):
		"""Checkout a new copy of a remote branch.

		@param url the remote repository URL
		"""

		# the directory shouldn't exist
		os.mkdir( self.dir )

		# bzr co
		try:
			self.run( [ 'bzr', 'checkout', url, '.' ] )
		except self.VcsError as e:

			# attempt to clean-up dir
			try:
				shutil.rmtree( self.dir )
			except OSError:
				pass

			raise


	def get_revno( self ):
		"""Obtain some sort of revision identifier
		"""

		# bzr revno
		output = self.run( [ 'bzr', 'revno', '--tree' ] )

		# parse revno
		buf = io.StringIO( output )
		return buf.readline().rstrip()


	def revert( self, revno = None ):
		"""Revert the branch so that there are no outstanding changes or unknown files.
		If a revno is supplied, then the repository is reverted to that
		revision.
		"""

		# bzr st
		output = self.run( [ 'bzr', 'status' ] )
		files = self.parse_file_blocks( output )

		# remove kind changed files (or they can cause `bzr revert` to break in
		# strange situations, like when a directory has been replaced with a
		# symlink to a non-existant file)
		if 'kind changed' in files:
			for file in files[ 'kind changed' ]:
				matches = re.search( '^(.+?)[/@+]? \([^)]+\)$', file )
				if not matches:
					raise RunTimeError(
						'failed to parse bzr kind change: %s' % file )
				file = matches.group( 1 )
				if the.verbose >= 2: print("removing (kind changed): " + file)
				full_file = os.path.join( self.dir, file )
				if os.path.isfile( full_file ) or os.path.islink( full_file ):
					os.unlink( full_file )
				elif os.path.isdir( full_file ):
					shutil.rmtree( full_file )
				else:
					raise RuntimeError( 'exotic file in repo: %s' % file )

		# bzr revert
		self.run( [ 'bzr', 'revert', '--no-backup' ] )

		# bzr st
		output = self.run( [ 'bzr', 'status' ] )
		files = self.parse_file_blocks( output )

		# remove unknown files
		if 'unknown' in files:
			for file in files[ 'unknown' ]:
				matches = re.search( r'^(.+?)[/@+]?$', file )
				if not matches:
					raise RunTimeError(
						'failed to parse bzr unknowns: %s' % file )
				file = matches.group( 1 )
				if the.verbose >= 2: print("removing (unknown): " + file)
				full_file = os.path.join( self.dir, file )
				if os.path.isfile( full_file ) or os.path.islink( full_file ):
					os.unlink( full_file )
				elif os.path.isdir( full_file ):
					shutil.rmtree( full_file )
				else:
					raise RuntimeError( 'exotic file in repo: %s' % file )

		# if a revision identifier has been given, ensure we're updated to that
		if revno is not None and self.get_revno() != revno:

			# bzr update
			self.run( [ 'bzr', 'update', '-r', revno ] )


	def update( self ):
		"""Update the branch, pulling down any upstream changes and merging them.  This
		method returns a list of the files that were modified as part of this
		operation.
		"""

#		WARNING: the following might cause bzr to ask for your ssh password more than
#		once during an update!!!
#
#		# get revno
#		revno = self.get_revno()
#
#		# update to current revision (pull in history without updating tree)
#		self.run( [ 'bzr', 'update', '-r', revno ] )
#
#		# get log output
#		next_revno = str( int( revno ) + 1 )
#		output = self.run( [ 'bzr', 'log', '-r', next_revno + '..' ] )
#
#		# parse output
#		keep_files = list()
#		buf = StringIO.StringIO( output )
#		in_message = False
#		for line in buf:
#			line = line.rstrip( '\n' )
#			if line.lower() == 'message:':
#				in_message = True
#			elif in_message:
#				if line[ : 2 ] != '  ':
#					in_message = False
#				else:
#					line = line[ 2 : ]
#
#					# process directives
#					if line[ : 6 ].lower() == 'keep: ':
#						file = line[ 6 : ]
#						if file in rename_files: file = rename_files[ file ]
#						keep_files.append( file )
#					elif line[ : 8 ].lower() == 'rename: ':
#						rename_from = line[ 8 : ]
#					elif line[ : 4 ].lower() == 'to: ':
#						if rename_from in rename_files:
#							rename_from = rename_files[ rename_from ]
#						rename_files[ line[ 4 : ] ] = rename_from

		# bzr update properly
		output = self.run( [ 'bzr', 'update' ] )

		# parse output (see logic in report() in bzrlib/delta.py)
		files = list()
		buf = io.StringIO( output )
		for line in buf:
			if not re.search( '^[-R+ ?][K NMD!][* ] ', line ): continue
			line = line.rstrip()

			# renames show before and after file names
			matches = re.search( '^R.. (.*?)[/@+]? => (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				files.append( matches.group( 2 ) )
				continue

			# kind changes shows the same name twice
			matches = re.search( '^.K. (.*?)[/@+]? => (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				continue

			# other entries have only one filename
			matches = re.search( '^... (.*?)[/@+]?$', line )
			if matches:
				files.append( matches.group( 1 ) )
				continue

			raise RuntimeError(
				'failed to parse bzr update output line:\n%s' % line )

		return files


	def status( self ):
		"""Get a list of any local modifications.  This method returns a list of files
		which are modified.

		"""

		# bzr status
		output = self.run( [ 'bzr', 'status', '--no-pending' ] )

		# parse output
		return self.parse_file_blocks( output )


	def has_changes( self ):
		"""Check if the branch has any local modifications.
		"""

		# bzr status
		output = self.run( [ 'bzr', 'status', '--no-pending' ] )

		# parse output
		files = self.parse_file_blocks( output )
		return True if len( files ) else False


	def get_conflicts( self ):
		"""Return a list of files that have conflicts.
		"""

		# bzr status
		output = self.run( [ 'bzr', 'status', '--no-pending' ] )

		# parse output
		files = self.parse_file_blocks( output )
		return files['conflicts'] if 'conflicts' in files else None


	def add( self, files ):
		"""Make sure files are added to version control.
		@param files a list of relative filenames
		"""

		# bzr add
		self.run( [ 'bzr', 'add', '-N' ] + files )


	def commit( self ):
		"""Commit changes to the repo.
		"""

		# bzr commit
		try:
			self.run( [ 'bzr', 'commit', '-m', '' ] )
		except self.VcsError as e:
			if re.search( 'Working tree is out of date', e.output ):
				raise the.program.FatalError(
					'you must update your files first.\n' +
					'Hint: see "%s update --help"' % the.program.name );
			else:
				raise e


	def run( self, cmd ):
		if the.verbose >= 2: print('exec: %s' % ' '.join( cmd ))
		p = Popen( cmd, cwd = self.dir,
				   stdout = subprocess.PIPE, stderr = subprocess.STDOUT )
		output = p.communicate()[ 0 ].decode()
		if p.returncode > 0:
			raise self.VcsError( ' '.join( cmd[ : 2 ] ), output )
		if the.verbose >= 2:
			verbose_output = output.rstrip()
			if len( verbose_output ):
				print(re.sub( '(^|\n)', '\\1  : ', verbose_output ))
		return output


	def parse_file_blocks( self, output ):
		res = dict()
		current = None
		buf = io.StringIO( output )
		for line in buf:
			matches = re.search( '^([a-z ]+):$', line, re.I )
			if matches:
				current = matches.group( 1 )
				continue
			if current:
				matches = re.search( '^  ([^ ].*)$', line )
				if matches:
					if not current in res:
						res[ current ] = list()
					res[ current ].append( matches.group( 1 ) )
					continue
			if re.search( '^[0-9]+ shel(?:f|ves) exists?', line ): continue
			if re.search( '^working tree is out of date', line ): continue
			raise self.ParseError( "unrecognised line: %s" % line )
		return res


	class ParseError( Exception ):
		pass