-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkiln_local_backup.py
executable file
·513 lines (426 loc) · 18.9 KB
/
kiln_local_backup.py
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/usr/bin/env python
# encoding: utf-8
"""
kiln_local_backup.py
Copyright (c) 2010-2016 Nate Silva, Ken Morse
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
__version__ = "0.4.0"
import sys
import os
import urllib2
import time
import urllib
import urlparse
from operator import itemgetter
from subprocess import Popen, PIPE
from optparse import OptionParser, IndentedHelpFormatter
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
sys.exit('For versions of Python earlier than 2.6, you must ' +
'install simplejson (http://pypi.python.org/pypi/simplejson/).')
CONFIG_FILE = 'backup.config'
debug = False
def parse_command_line(args):
"""
Parse the command line arguments.
Returns a tuple of (options, destination_dir).
Calls sys.exit() if the command line could not be parsed.
"""
global debug
usage = 'usage: %prog [options] DESTINATION-DIR'
description = 'Backs up all available Mercurial and Git repositories on Kiln ' + \
'by cloning them (if they have not been backed up before), or by pulling ' + \
'changes. In order to run this without user interaction, you must install ' + \
'the FogBugz "KilnAuth" Mercurial extension and appropriate Git extension ' + \
'then clone at least one repository so that your credentials are saved.'
version = "%prog, v" + __version__
parser = OptionParser(usage=usage, description=description, version=version)
parser.formatter = IndentedHelpFormatter(max_help_position=30)
parser.add_option('-t', '--token', dest='token', help='FogBugz API token')
parser.add_option('-s', '--server', dest='server', help='Kiln server name, e.g.: ' + \
'https://name.kilnhg.com')
parser.add_option('--ssh', dest='ssh', action='store_true',
default=False, help='Use SSH when connecting to repos')
parser.add_option('-q', '--quiet', dest='verbose', action='store_false',
default=True, help='non-verbose output')
parser.add_option('-d', '--debug', dest='debug', action='store_true',
default=False, help='additional output for debugging')
parser.add_option('-l', '--limit', dest='limit', metavar='PATH',
help='only backup repos in the specified project/group (ex.: ' + \
'MyProject) (or: MyProject/MyGroup)')
parser.add_option('-u', '--update', dest='update', action='store_true',
default=False, help='update working copy when cloning or pulling')
(options, args) = parser.parse_args(args)
# Get the destination directory, which should be the one and
# only non-option argument.
if len(args) == 0:
parser.error('Must specify the destination directory for the backups.')
if len(args) > 1:
parser.error('Unknown arguments passed after destination directory')
destination_dir = args[0]
debug = options.debug
# Now get any saved options from the configuration file and use
# them to fill in any missing options.
configfile_path = os.path.join(destination_dir, CONFIG_FILE)
if os.path.exists(configfile_path):
configfile = open(configfile_path, 'r')
config_data = json.load(configfile)
configfile.close()
if not options.token and 'token' in config_data:
options.token = config_data['token']
if not options.server and 'server' in config_data:
options.server = config_data['server']
return (options, destination_dir)
def get_repos(server, token, ssh, verbose):
"""
Query Kiln to get the list of available repositories. Return the
list, sorted by the Kiln “full name” of each repository.
"""
if verbose:
print console_encode('Getting the list of repositories from %s' % server)
url = '%s/Api/2.0/Project/?token=%s' % (server, token)
if debug:
print "get Projects: url:", url
projects = json.load(urllib2.urlopen(url))
if 'errors' in projects:
sys.exit('Error from server: ' + projects['errors'][0]['sError'])
ourRepos = []
numHgRepos = 0
numGitRepos = 0
for project in projects:
for repoGroup in project['repoGroups']:
# watch for empty Groups
if repoGroup['sSlug'] == '':
repoGroup['sSlug'] = 'Group'
if repoGroup['sName'] == '':
repoGroup['sName'] = 'Group'
for repo in repoGroup['repos']:
# we'll get the appropriate full URL but also save the human-readable
# names for sorting our list by VCS type, project, group, repo
# Per https://developers.fogbugz.com/default.asp?W166:
# VCS=1 is Mercurial (Hg), VCS=2 is Git
localPath = project['sSlug'] + '/' + repoGroup['sSlug'] + '/' + repo['sSlug']
if repo['vcs'] == 1:
numHgRepos += 1
if ssh:
repoPath = repo['sHgSshUrl']
else:
repoPath = repo['sHgUrl']
elif repo['vcs'] == 2:
numGitRepos += 1
if ssh:
repoPath = repo['sGitSshUrl']
else:
repoPath = repo['sGitUrl']
else:
sys.exit('Unknown VCS type for repo: ' + localPath)
if repo['sStatus'] != 'deleted':
ourRepos.append({'repoPath': repoPath, 'localPath': localPath, 'project': project['sName'],
'repoGroup': repoGroup['sName'], 'repo': repo['sName'], 'vcs': repo['vcs']})
if verbose:
print console_encode('Found %d repositories (%d Hg, %d Git)' % (len(ourRepos), numHgRepos, numGitRepos))
return sorted(ourRepos, key=itemgetter('vcs', 'project', 'repoGroup', 'repo'))
def backup_hg_repo(clone_url, target_dir, verbose, update):
"""
Backup the specified Hg repository. Returns True if successful. If
the backup fails, prints an error message and returns False.
"""
backup_method = 'clone'
# If the filesystem does not use Unicode (from Python’s
# perspective), convert target_dir to plain ASCII.
if not sys.getfilesystemencoding().upper().startswith('UTF'):
target_dir = target_dir.encode('ascii', 'xmlcharrefreplace')
# Does the target directory already exist?
if os.path.isdir(target_dir):
# Yes, it exists. Does it refer to the same repository?
default = Popen(['hg', 'paths', '-R', target_dir, 'default'],
stdout=PIPE, stderr=PIPE).communicate()[0].strip()
default = urllib2.unquote(default)
if default == clone_url:
# It exists and is identical. We will pull.
backup_method = 'pull'
else:
# It exists but refers to a different repo or is not a
# repo. Move it to an archive directory.
(parent_dir, repo_name) = os.path.split(target_dir)
if verbose:
print console_encode('exists but is not the same repo'),
sys.stdout.flush()
new_name = 'archive/%f-%s' % (time.time(), repo_name)
new_dir = os.path.join(parent_dir, new_name)
os.renames(target_dir, new_dir)
if verbose:
print console_encode('(archived); continuing backup...'),
sys.stdout.flush()
else:
# Path doesn’t exist: create it
os.makedirs(target_dir)
# Back it up
if backup_method == 'clone':
if update:
args = ['hg', 'clone', clone_url, target_dir]
else:
args = ['hg', 'clone', '--noupdate', clone_url, target_dir]
else:
if update:
args = ['hg', 'pull', '-u', '-R', target_dir]
else:
args = ['hg', 'pull', '-R', target_dir]
if debug:
print "Backup Method:", backup_method
print "args:", args
# KilnAuth uses os.path.expanduser which should use
# %USERPROFILE%. When run from Scheduled Tasks, it does not seem
# to work unless you also set %HOMEDRIVE% and %HOMEPATH%.
child_env = os.environ
if os.name == 'nt':
(drive, path) = os.path.splitdrive(os.environ['USERPROFILE'])
child_env['HOMEDRIVE'] = drive
child_env['HOMEPATH'] = path
proc = Popen(args, stdout=PIPE, stderr=PIPE, env=child_env)
(_, stderrdata) = proc.communicate()
if proc.returncode:
print console_encode('**** FAILED ****')
print console_encode('*' * 60)
print console_encode(u'Error backing up Hg repository %s\nError was: %s' %
(clone_url, stderrdata))
print console_encode('*' * 60)
return False
if verbose:
print console_encode('backed up using Hg method %s' %
backup_method.upper())
return True
def backup_git_repo(clone_url, target_dir, verbose, update):
"""
Backup the specified Git repository. Returns True if successful. If
the backup fails, prints an error message and returns False.
"""
backup_method = 'clone'
# If the filesystem does not use Unicode (from Python’s
# perspective), convert target_dir to plain ASCII.
if not sys.getfilesystemencoding().upper().startswith('UTF'):
target_dir = target_dir.encode('ascii', 'xmlcharrefreplace')
# Does the target directory already exist?
if os.path.isdir(target_dir):
# Yes, it exists. Does it refer to the same repository?
default = Popen(['git', '-C', target_dir, 'config', '--get', 'remote.origin.url'],
stdout=PIPE, stderr=PIPE).communicate()[0].strip()
default = urllib2.unquote(default)
if default == clone_url:
# It exists and is identical. We will pull.
backup_method = 'pull'
else:
# It exists but refers to a different repo or is not a
# repo. Move it to an archive directory.
(parent_dir, repo_name) = os.path.split(target_dir)
if verbose:
print console_encode('exists but is not the same repo'),
sys.stdout.flush()
new_name = 'archive/%f-%s' % (time.time(), repo_name)
new_dir = os.path.join(parent_dir, new_name)
os.renames(target_dir, new_dir)
if verbose:
print console_encode('(archived); continuing backup...'),
sys.stdout.flush()
else:
# Path doesn’t exist: create it
os.makedirs(target_dir)
# Back it up
if backup_method == 'clone':
if update:
args = ['git', 'clone', clone_url, target_dir]
else:
args = ['git', 'clone', '--no-checkout', clone_url, target_dir]
else:
if update:
args = ['git', '-C', target_dir, 'pull', target_dir]
else:
args = ['git', '-C', target_dir, 'fetch', target_dir]
if debug:
print "Backup Method:", backup_method
print "args:", args
# KilnAuth uses os.path.expanduser which should use
# %USERPROFILE%. When run from Scheduled Tasks, it does not seem
# to work unless you also set %HOMEDRIVE% and %HOMEPATH%.
child_env = os.environ
if os.name == 'nt':
(drive, path) = os.path.splitdrive(os.environ['USERPROFILE'])
child_env['HOMEDRIVE'] = drive
child_env['HOMEPATH'] = path
proc = Popen(args, stdout=PIPE, stderr=PIPE, env=child_env)
(_, stderrdata) = proc.communicate()
if proc.returncode:
print console_encode('**** FAILED ****')
print console_encode('*' * 60)
print console_encode(u'Error backing up Git repository %s\nError was: %s' %
(clone_url, stderrdata))
print console_encode('*' * 60)
return False
if verbose:
print console_encode('backed up using Git method %s' %
backup_method.upper())
return True
def console_encode(message):
"""
Encodes the message as appropriate for output to sys.stdout.
This is needed especially for Windows, where stdout is often a
non-Unicode encoding.
"""
if sys.stdout.encoding == None:
# Encoding not available. Force ASCII.
return unicode(message).encode('ASCII', 'xmlcharrefreplace')
if sys.stdout.encoding.upper().startswith('UTF'):
# Unicode console. No need to convert.
return message
else:
return unicode(message).encode(sys.stdout.encoding,
'xmlcharrefreplace')
def encode_url(url):
"""
URLs returned by Kiln may have unencoded Unicode characters in
them. Encode them.
"""
url_parts = list(urlparse.urlsplit(url.encode('utf-8')))
url_parts[2] = urllib.quote(url_parts[2])
return urlparse.urlunsplit(url_parts)
def main():
"""
Main entry point for Kiln backup utility.
"""
# Parse the command line
(options, destination_dir) = parse_command_line(sys.argv[1:])
# If token or server were not specified, prompt the user.
if not options.token:
options.token = raw_input('Your FogBugz API token: ')
if not options.token:
sys.exit('FogBugz API token is required.')
if not options.server:
options.server = \
raw_input('Kiln server name (e.g. company.kilnhg.com): ')
if not options.server:
sys.exit('Kiln server name is required.')
# If the destination directory doesn’t exist, try to create it.
if not os.path.isdir(destination_dir):
os.makedirs(destination_dir)
if not os.path.isdir(destination_dir):
sys.exit('Destination directory "' + destination_dir + '"'
+ " doesn't exist and couldn't be created.")
# Save configuration
configfile = open(os.path.join(destination_dir, CONFIG_FILE), 'w+')
config = {'server': options.server, 'token': options.token}
json.dump(config, configfile, indent=4)
configfile.write('\n')
configfile.close()
# Keep track of state for printing status messages
if options.verbose:
count = 0
last_subdirectory = ''
current_group = None
# Keep track of overall success status. We continue backing up
# even if there’s an error.
overall_success = True
# Back up the repositories
repos = get_repos(options.server, options.token, options.ssh, options.verbose)
if debug:
print "Server:", options.server
print "token:", options.token
# If using --limit, filter repos we don’t want to backup.
if options.limit:
# Normalize the limit. Convert backslashes. Remove any
# leading or trailing slash.
limit = '%s' % options.limit.replace('\\', '/').strip('/')
# Replace spaces with dashes, as Kiln does (in case the
# user typed a human-readable repo name that has spaces)
limit = limit.replace(' ', '-')
# Filter. Case-insensitive. (Kiln won’t let you create two
# groups or projects with the same name but different case.)
repos = [_ for _ in repos if
_['localPath'].lower().startswith(limit.lower())]
if options.verbose:
if len(repos) == 0:
message = 'No repositories match the specified limit. '
message += 'Nothing to back up!'
else:
if len(repos) == 1:
message = '1 repository matches '
else:
message = '%d repositories match ' % len(repos)
message += 'the specified limit and will be backed up'
print console_encode(message)
# Return an error code if there are no repos to back up. This
# probably indicates a typo or similar mistake.
if len(repos) == 0:
overall_success = False
for repo in repos:
# Convert the repo path for subdirectory use if necessary
# on Windows (/ to \).
if os.sep == '/':
subdirectory = repo['localPath']
else:
subdirectory = os.path.normpath(repo['localPath'])
if options.verbose:
# For the progress message, show the project and group
# name as a header, and under that, list the repo names
# being backed up. Also show a counter.
group = os.path.commonprefix([last_subdirectory,
os.path.dirname(subdirectory)])
if group != current_group:
current_group = os.path.dirname(subdirectory)
print console_encode('\n%s' % current_group)
last_subdirectory = subdirectory
count += 1
print console_encode(' >> [%d/%d] %s ' % (count, len(repos),
os.path.basename(subdirectory))),
# The following line fixes Issue 1. Python conveniently
# inserts a space when a print statement ends with a
# comma. Unfortunately if Mercurial is going to prompt
# for a password, it does not know about the space that
# is “supposed” to be there and the result looks like:
# "reponamepassword:". The following line prevents
# Python from inserting the space. Instead we manually
# forced a space to the end of the print statement above.
sys.stdout.write('')
sys.stdout.flush()
clone_url = encode_url(repo['repoPath'])
target_dir = unicode(os.path.join(destination_dir, subdirectory))
if debug:
print
print "repo['repoPath']:", repo['repoPath']
print "clone_url:", clone_url
print "target_dir:", target_dir
print "options.verbose:", options.verbose
print "options.update:", options.update
if repo['vcs'] == 1:
success = backup_hg_repo(clone_url, target_dir, options.verbose, options.update)
elif repo['vcs'] == 2:
success = backup_git_repo(clone_url, target_dir, options.verbose, options.update)
overall_success = overall_success and success
if overall_success:
print 'All repositories backed up successfully.'
return 0
else:
print 'Completed with errors.'
return 1
if __name__ == '__main__':
sys.exit(main())