/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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# deployment.py
#
# Copyright (C) 2013 to 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 os, re, shutil, filecmp
import the, util


class Deployment:


	def __init__( self ):
		self.load_deployment_state()
		self.conflicts_checked = False


	def load_deployment_state( self ):

		# list of files that were copied-in (or at least given the opportunity
        # to be) and updated through the vcs update.  This means that, while
        # there may have been conflicts during the update (which will be dealt
        # with in the repo), any arising conflicts with the filesystem are now
        # assumed to be because of the vcs update and can be ignored (that is to
        # say, we no longer care about the file in the home directory).  In
        # short, this is a list of files that it is safe to deploy, regardless
        # of the state of the filesystem.
		self.deploy_files = None

		# do we have a repo?
		if not os.path.exists( the.repo.full_dir ): return

		# if no file list exists, we're done
		file = os.path.join( the.full_mddir, "deploy.%s" % the.repo.name )
		if not os.path.isfile( file ):
			if the.verbose: print "no deployment state found"
			return

		# read the file list
		if the.verbose: print "loading deployment state"
		f = open( file, 'r' )
		self.deploy_files = f.read().splitlines()


	def save_deployment_state( self ):
		if the.verbose: print "saving deployment state"

		# create metadata directory, as necessary
		if not os.path.isdir( the.full_mddir ):
			os.mkdir( the.full_mddir )

		# create file
		file = os.path.join( the.full_mddir, "deploy.%s" % the.repo.name )
		f = open( file, 'w' )
		f.write( '\n'.join( self.deploy_files ) + '\n' )


	def remove_deployment_state( self ):

		# delete it, if it exists
		file = os.path.join( the.full_mddir, "deploy.%s" % the.repo.name )
		if( os.path.isfile( file ) ):
			os.unlink( file )


	def is_ongoing( self ):
		return False if self.deploy_files is None else True


	def check_ongoing( self, ongoing = True ):
		if( ongoing ):
			if self.deploy_files is None:
				raise self.DeploymentOngoing( False )
		else:
			if self.deploy_files is not None:
				raise self.DeploymentOngoing( True )


	def confirm( self, message ):
		# TODO: write interactive confirmation routine
		return False


	def walk_repo( self, dir_func = None, file_func = None, link_func = None,
				   relative_dir = '', ignore_errors = False ):
		"""Walk through all files and directories in the repo, passing the relative path
		to each to the provided functions.
		"""
		full_dir = os.path.join( the.repo.full_dir, relative_dir )
		for file in os.listdir( full_dir ):
			relative_file = os.path.join( relative_dir, file )

			# skip some stuff
			if relative_file == '.bzr': continue

			repo_file = os.path.join( the.repo.full_dir, relative_file )
			fs_file = os.path.join( the.full_fsdir, relative_file )
			if os.path.islink( repo_file ):
				if link_func is not None:
					link_func( relative_file, repo_file, fs_file )
			elif os.path.isfile( repo_file ):
				if file_func is not None:
					file_func( relative_file, repo_file, fs_file )
			elif os.path.isdir( repo_file ):
				if dir_func is not None:
					dir_func( relative_path, repo_file, fs_file )
				# recurse in directories
				self.walk_repo( dir_func, file_func, link_func, relative_dir,
								ignore_errors )
			elif not ignore_errors:
				raise RuntimeError(
					'repo contains unknown/missing entity' )


	def copy_in( self ):

		def copy_in_dir( relative_file, dst, src ):
			self.deploy_files.append( relative_file )

			# if src doesn't exist, delete it from the repo
			if not os.path.lexists( src ):
				if the.verbose: print " _<d " + relative_file
				shutil.rmtree( dst )

			# if src is a directory, copy permissions, as necessary
			elif os.path.isdir( src ):
				# TODO: should check permissions and only do as necessary
				if the.verbose: print " d<d " + relative_file
				shutil.copystat( src, dst )

			# TODO: serious differences in between ~/ and repo (e.g., files in
			# one that are directories in the other) should be ignored (e.g.,
			# not copied-in).  And the stuff that is ignored during copy-in
			# should also be ignored during copy-out and must not be added to
			# the deploy_files list.  Since these ignored files/directories are
			# transparent to the user, they should have to explicitly permit
			# them via an ignore file (e.g., ~/.stdhome/.ignore, akin to bzr's
			# .bzrignore file).  If these serious differences are not matched by
			# the ignore file, an error should show (which will requie a
			# separate "check" walk of the repo, as is done in copy_out).
			else:
				raise self.Conflict( "%s differs too severely from the repo" %
									 os.path.join( the.fsdir, relative_file ) )

		def copy_in_file( relative_file, dst, src ):
			self.deploy_files.append( relative_file )

			# if src doesn't exist, delete it in the repo
			if not os.path.lexists( src ):
				if the.verbose: print " ?<f " + relative_file
				os.unlink( dst )

			# if src is a symlink, replace it in repo
			elif os.path.islink( src ):
				if the.verbose: print " l<f " + relative_file
				os.unlink( dst )
				os.symlink( os.readlink( src ), dst )

			# if src is a file, replace it if different
			elif os.path.isfile( src ):
				if not filecmp.cmp( src, dst ):
					if the.verbose: print " f<f " + relative_file
					os.unlink( dst )
					shutil.copy( src, dst )
					shutil.copystat( src, dst )
				else:
					if the.verbose: print " f=f " + relative_file

			# TODO: serious differences in between ~/ and repo (e.g., files in
			# one that are directories in the other) should be ignored (e.g.,
			# not copied-in).  And the stuff that is ignored during copy-in
			# should also be ignored during copy-out and must not be added to
			# the deploy_files list.  Since these ignored files/directories are
			# transparent to the user, they should have to explicitly permit
			# them via an ignore file (e.g., ~/.stdhome/.ignore, akin to bzr's
			# .bzrignore file).  If these serious differences are not matched by
			# the ignore file, an error should show (which will requie a
			# separate "check" walk of the repo, as is done in copy_out).
			else:
				raise self.Conflict( "%s differs too severely from the repo" %
									 os.path.join( the.fsdir, relative_file ) )

		def copy_in_link( relative_file, dst, src ):
			self.deploy_files.append( relative_file )

			# if src doesn't exist, delete it in the repo
			if not os.path.lexists( src ):
				if the.verbose: print " _<l " + relative_file
				os.unlink( dst )

			# if src is a symlink, replace it if different in repo
			elif os.path.islink( src ):
				if os.readlink( src ) != os.readlink( dst ):
					if the.verbose: print " l<l " + relative_file
					os.unlink( dst )
					os.symlink( os.readlink( src ), dst )
				else:
					if the.verbose: print " l=l " + relative_file

			# if src is a file, replace it in repo
			elif os.path.isfile( src ):
				if the.verbose: print " f<l " + relative_file
				os.unlink( dst )
				shutil.copy( src, dst )
				shutil.copystat( src, dst )

			# TODO: serious differences in between ~/ and repo (e.g., files in
			# one that are directories in the other) should be ignored (e.g.,
			# not copied-in).  And the stuff that is ignored during copy-in
			# should also be ignored during copy-out and must not be added to
			# the deploy_files list.  Since these ignored files/directories are
			# transparent to the user, they should have to explicitly permit
			# them via an ignore file (e.g., ~/.stdhome/.ignore, akin to bzr's
			# .bzrignore file).  If these serious differences are not matched by
			# the ignore file, an error should show (which will requie a
			# separate "check" walk of the repo, as is done in copy_out).
			else:
				raise self.Conflict( "%s differs too severely from the repo" %
									 os.path.join( the.fsdir, relative_file ) )

		# check we don't already have a file list
		self.check_ongoing( False )

		# new file list
		self.deploy_files = list()

		# if the repo doesn't exist, we're done
		if not os.path.exists( the.repo.full_dir ): return

		# copy in
		if the.verbose: print "importing files"
		self.walk_repo( dir_func = copy_in_dir, file_func = copy_in_file,
					   link_func = copy_in_link, ignore_errors = True )

		# save state
		self.save_deployment_state()


	def copy_out( self ):

		def copy_out_dir( relative_file, src, dst ):

			# if dst doesn't exist, create it
			if not os.path.lexists( dst ):
				if the.verbose: print " d>_ " + relative_file
				os.mkdir( dst )
				shutil.copystat( src, dst )

			# if dst is a file/symlink, replace it
			elif os.path.isfile( dst ):
				if the.verbose: print " d>f " + relative_file
				os.unlink( dst )
				os.mkdir( dst )
				shutil.copystat( src, dst )

			# if dst is a directory, copy permissions as required
			elif os.path.isdir( dst ):
				# TODO: should check permission and only do as necessary
				if the.verbose: print " d>d " + relative_file
				shutil.copystat( src, dst )

			else:
				raise NotImplementedError()

		def copy_out_file( relative_file, src, dst ):

			# if dst doesn't exist, copy
			if not os.path.lexists( dst ):
				if the.verbose: print " f>_ " + relative_file

				shutil.copy( src, dst )
				shutil.copystat( src, dst )

			# if dst is a symlink, replace it
			elif os.path.islink( dst ):
				if the.verbose: print " f>l " + relative_file
				os.unlink( dst )
				shutil.copy( src, dst )
				shutil.copystat( src, dst )

			# if dst is a file, replace it if different
			elif os.path.isfile( dst ):
				if not filecmp.cmp( src, dst ):
					if the.verbose: print " f>f " + relative_file
					os.unlink( dst )
					shutil.copy( src, dst )
					shutil.copystat( src, dst )
				else:
					if the.verbose: print " f=f " + relative_file

			# if dst is a directory, replace it
			elif os.path.isdir( dst ):
				if the.verbose: print " f>d " + relative_file
				shutil.rmtree( dst )
				shutil.copy( src, dst )
				shutil.copystat( src, dst )

			else:
				raise NotImplementedError()

		def copy_out_link( relative_file, src, dst ):

			# if dst doesn't exist, copy
			if not os.path.lexists( dst ):
				if the.verbose: print " l>_ " + relative_file
				os.symlink( os.readlink( src ), dst )

			# if dst is a symlink, replace it if different
			elif os.path.islink( dst ):
				if os.readlink( src ) != os.readlink( dst ):
					if the.verbose: print " l>l " + relative_file
					os.unlink( dst )
					os.symlink( os.readlink( src ), dst )
				else:
					if the.verbose: print " l=l " + relative_file

			# if dst is a file, replace it
			elif os.path.isfile( dst ):
				if the.verbose: print " l>f " + relative_file
				os.unlink( dst )
				os.symlink( os.readlink( src ), dst )

			# if dst is a directory, replace it
			elif os.path.isdir( dst ):
				if the.verbose: print " l>d " + relative_file
				shutil.rmtree( dst )
				os.symlink( os.readlink( src ), dst )

			else:
				raise NotImplementedError()

		# check we have a file list
		self.check_ongoing( True )

		# we should already have handled conflicts
		if not self.conflicts_checked:
			raise RuntimeError(
				'logic error: conflicts should have been checked!' )

		# copy out
		if the.verbose: print "exporting files"
		self.walk_repo( dir_func = copy_out_dir, file_func = copy_out_file,
					   link_func = copy_out_link, ignore_errors = True )

		# clear state
		self.remove_deployment_state()


	def get_conflicts( self ):

		def check_dir( relative_file, src, dst ):

			# files that existed at copy-in can be copied-out and overwritten
			if self.deploy_files is not None and \
			   relative_file in self.deploy_files: return

			# files that don't exist in the filesystem can be copied-out
			if not os.path.lexists( dst ): return

			# accept/reject existing files
			if os.path.islink( dst ):
				self.files.append( "%s already exists (as a symlink)" %
								   os.path.join( the.fsdir, relative_file ) )
			elif os.path.isfile( dst ):
				self.files.append( "%s already exists (as a file)" %
								   os.path.join( the.fsdir, relative_file ) )
			elif os.path.isdir( dst ):
				return
			else:
				self.files.append( "%s already exists" %
								   os.path.join( the.fsdir, relative_file ) )

		def check_file( relative_file, src, dst ):

			# files that existed at copy-in can be copied-out and overwritten
			if self.deploy_files is not None and \
			   relative_file in self.deploy_files: return

			# files that don't exist in the filesystem can be copied-out
			if not os.path.lexists( dst ): return

			# accept/reject existing files
			if os.path.isfile( dst ):
				self.files.append( "%s already exists" %
								   os.path.join( the.fsdir, relative_file ) )
			elif os.path.isdir( dst ):
				self.files.append( "%s already exists (as a directory)" %
								   os.path.join( the.fsdir, relative_file ) )
			else:
				self.files.append( "%s already exists" %
								   os.path.join( the.fsdir, relative_file ) )

		self.conflicts_checked = True

		# check for conflicts
		self.files = list()
		self.walk_repo( dir_func = check_dir, file_func = check_file,
					   link_func = check_file )
		return self.files


	class DeploymentOngoing( the.program.FatalError ):

		def __init__( self, ongoing ):
			if( ongoing ):
				self.msg = "there is an ongoing deployment"
			else:
				self.msg = "there is no ongoing deployment"


	class Conflict( Exception ):

		def __init__( self, message ):
			self.msg = message