guestrepo / guestrepo / guestrepo.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# Guestrepo: A Mercurial Extension for the managing of components
# Copyright (C) 2012   Schweitzer Engineering Laboratories, Inc.

# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Contact information:

# opensource@selinc.com

# Schweitzer Engineering Laboratories, Inc.
# 2350 NE Hopkins Court
# Pullman, WA 99163 - USA


from collections import deque
import errno
import glob
import itertools
import os

import lockedui
import mercurial.ui
from mercurial import util, config, hg, commands, \
                      error, node, scmutil, bookmarks, localrepo

from workerpool import workerpool

GR_CONFIG = '.hgguestrepo'
GR_MAPPING = '.hggrmapping'
GR_AUTHFILENAME = '.grauth'

#####################
# Commands
#####################
def grupdate(ui, repo, *args, **opts):
    '''update guest repos

    Update each guest repo to the changeset identifier in the .hgguestrepo file.
    The changeset identifier can be a branch, tag, changeset hex, bookmark, or
    any other identifier that can be given to Mercurial's update command.

    A warning will be raised if a guest is updated to a branch with multiple
    heads.

    Grupdate is recursive. If the update operation adds a new guest, it is
    cloned to the newly added identifier.

    Grupdate will present an error and do nothing if there are local changes in any
    guest repository.
    This prevents the update from causing a merge with local changes.

    The `--local` flag causes the .hggrmapping file in the working copy of the
    repository to be used.
    This changes the default behavior of using the mapping file in the tip of
    the current branch. Use this option if hggrmapping is modified but not yet
    committed.

    The `--pull` flag causes a grpull to happen before the grupdate. If the grpull
    fails the grupdate will not begin.

    see help for the guestrepo extension for more information on the files used
    '''
    actions = [pull] if opts.get('pull') else []
    actions.append(update)
    return repoactions(ui, repo, actions, args, opts)

def grpush(ui, repo, *args, **opts):
    '''push guest repos

    Push each guest to the path specified in the mapping file.

    Push is run recursively on guest repositories. Does not clone guests that do
    not exist locally.

    The `--local` flag causes the .hggrmapping file in the working directory
    to be used.
    This changes the default behavior of using the mapping file in the tip of
    the current branch. Use this option if hggrmapping is modified but not yet
    committed.

    see help for the guestrepo extension for more information on the files used
    '''
    return repoactions(ui, repo, [push], args, opts)

def grpull(ui, repo, *args, **opts):
    '''pull  guest repos

    Pull each guest repo from the location specified in the mapping file.
    If any guest repo does not exist it is cloned and updated to the specified
    changeset id in the .hgguestrepo file.
    See grupdate for information on how guests are updated.
    A pull to an existing repo will not update.

    Pull is run recursively on guest repositories.

    The `--local` flag causes the .hggrmapping file in the working directory
    to be used.
    This changes the default behavior of using the mapping file in the tip of
    the current branch. Use this option if hggrmapping is modified but not yet
    committed.

    The `--update` flag causes a grupdate to happen after the grpull. If the grpull
    fails the grupdate will not begin. Equivalent to grupdate --pull.

    see help for the guestrepo extension for more information on the files used
    '''
    actions = [pull]
    if opts.get('update'): actions.append(update)
    return repoactions(ui,repo, actions, args, opts)

def summary(ui, repo, **opts):
    '''print a summary of the guest repos

    Summary presents a description of the state of guest repositories in the
    following format:

      local_directory (branch) [tags] [bookmarks] [*current bookmark] [*]
    '''
    guests = getguests(repo)
    for guest in filterwarnguests(ui, guests):
        guestrepo = hg.repository(ui, guest.root, create=False)
        guestctx = guestrepo[None]

        output = [guest.canonpath, "(%s)" % guestctx.branch() ]

        if opts.get('id'):
           status = util.any(guestrepo.status()) and "+" or ""
           parents = guestctx.parents()
           id = (' '.join(['+'.join([node.hex(p.node()) for p in parents]), ]))[:12]
           output.append(str(id))

        tags = guestctx.tags()
        if tags:
            output.append( '/'.join(tags) )

        bmarks = guestctx.bookmarks()
        if bmarks:
            output.append( '/'.join(bmarks) )

        currentbookmark = bookmarks.readcurrent(guestrepo)
        if currentbookmark:
            output.append('*' + currentbookmark)

        if changed(guestrepo):
            output.append('*')

        if currentbookmark:
            currentbookmarkstr = currentbookmark

        ui.write("%s\n" % ' '.join(output))

def state(ui, repo, **opts):
    '''print the exact changeset of all guests to stdout, as in .hgguestrepo

    The state command outputs the state of the guest repositories to standard
    out.
    It uses same format as the .hgguestrepo file, but only outputs the absolute
    changeset hash.'''
    guests = getguests(repo)
    statestr = getstatestr(ui, repo, guests)
    ui.write(statestr)

def freeze(ui, repo, **opts):
    '''write the current state of the guests to .hgguestrepo

    The freeze command outputs the state of the current repository's
    guestrepo to the .hgguestrepo file.
    It uses same format as the .hgguestrepo file, but only outputs the absolute
    changeset hash.

    It is equivalent to piping the output of the ``grstate`` command to the
    ``.hgguestrepo`` file.
    '''
    guests = getguests(repo)
    statestr = getstatestr(ui, repo, guests)
    repo.wwrite(GR_CONFIG, statestr, '')

def grout(ui, repo, **opts):
   """
   List the outgoing changes for all guestrepos.
   """
   guests = getguests(repo)

   mapping = True

   def action(ui, repo, guest):
      commands.outgoing(ui, repo, guest.uri)

   return 0 if runparallelaction(ui, repo, mapping, guests, action, False, opts) else 1

def grin(ui,repo,**opts):
   """
   List the incoming changes for all guestrepos.
   """
   guests = getguests(repo)

   # just say no for now
   opts['bundle'] = None
   opts['force'] = False

   mapping = True

   def action(ui, repo, guest):
      commands.incoming(ui, repo, guest.uri, **opts)

   return 0 if runparallelaction(ui, repo, mapping, guests, action, False, opts) else 1

#####################

def repoactions(ui, repo, orderedactions, args, opts):
    '''Assumes orderedactions is a non-empty list of actions which return True on success.
     Returns 1 iff one or more actions fail.'''
    local = opts.get('local')
    mapping = 'local' if local else True
    continueOnError = opts.get('forcepartial')
    silentnoguests = opts.get('silentnoop')

    try:
        guests = getguests(repo, None, continueOnError)
    except IOError:
        ui.warn(" no guest repositories defined for '{0}'.\n".format(os.path.basename(repo.origroot)))
        return not silentnoguests

    if args:
       guests = matchguests(repo.root, os.getcwd(), args, guests)

    failed = list(not action(ui, repo, mapping, guests, opts) for action in orderedactions )
    return any(failed)

def pull(ui, repo, mapping, guests, opts):
    '''Return true on success'''
    def pullaction(ui, repo, guest):
        ui.status('pulling %s\n' % guest.canonpath)
        commands.pull(ui, repo, guest.uri)

    return runparallelaction(ui, repo, mapping, guests, pullaction, True, opts)

def update(ui, repo, mapping, guests, opts):
    '''Return true on success'''
    local = mapping=='local'
    path = dirtyrecursive(ui, repo, local, guests)
    if path:
        raise util.Abort("repository %s contains uncommitted changes" % path)

    def updateaction(ui, repo, guest):
        ui.status('GR updating %s\n' % guest.canonpath)
        warnbranch(ui, guest.name, repo, guest.csid)
        commands.update(ui, repo, guest.csid)

    return runparallelaction(ui, repo, mapping, guests, updateaction, True, opts)

def push(ui, repo, mapping, guests, opts):
    '''Return true on success'''
    def pushaction(ui, repo, guest):
        commands.push(ui, repo, guest.uri)
    return runparallelaction(ui, repo, mapping, guests, pushaction, False, opts)

def runparallelaction(ui, repo, mapping, guests, action, create, opts):
    workers = makeworkers(ui, opts)
    try:
        applyguests(ui, repo, guests, workers, action,
                    [], mapping, create)
    finally:
        workers.join()
    if len(workers.errors) > 0:
        showerrors(ui, workers)
        return False
    else:
        return True
#####################

class guestrepo(object):
    '''An aggregate representing a guest repository'''
    def __init__(self, name, configpath, canonpath, uri, csid, root):
        self.name = name
        self.configpath = configpath
        self.canonpath = canonpath
        self.uri = uri
        self.csid = csid
        self.root = root

    def isrepo(self, warn=False):
        return os.path.exists(os.path.join(self.root, '.hg'))

def showerrors(ui, workers):
    ''' Print errors that occurred during use of the worker pool'''
    if len(workers.errors) == 0:
        return

    ui.warn("\nfinished with errors\n")
    for (errtype, errvalue, errtraceback), guest in workers.errors:
        ui.write_err("\n%s: %s\n" % (guest.canonpath, errvalue))
        ui.traceback((errtype, errvalue, errtraceback))
        try:
            ui.write_err('verifying %s\n' % guest.canonpath)
            repo = hg.repository(ui, guest.root, create=False)
            hg.verify(repo)
        except Exception, err:
            ui.write_err('%s\n' % err)

def makeworkers(ui, opts):
    '''Instantiates and returns a worker pool'''
    threads = opts.get('threads')
    if threads < 1:
        raise util.Abort("number of threads must be at least one")
    # workerpool takes an error function and number of threads
    return workerpool(lambda err: ui.write_err('%s\n' % err), threads)

def resolvemapping(guests, mapping):
    '''given a list of guests and a remote mapping, update each guest's remote
       location
    '''
    for guest in guests:
        try:
            guest.uri = mapping[guest.name]
        except KeyError:
            raise util.Abort("Could not resolve guest repo mapping %s" %
                                guest.name)

def getmapping(repo, useworkingmap=False):
    ''' Parse the mapping file of a repo and return the config object.
        The file is taken from the most recently committed head of the current
        branch.

        The useworkingmap option takes the mapping file from the working
        directory.
    '''
    currentctx = repo[None]
    if useworkingmap:
        ctx = currentctx
    else:
        # detect case of uncommitted branch
        currentbranch = currentctx.branch()
        if currentbranch not in repo.branchmap():
            raise util.Abort("cannot find %s: "
                             "no commits on current branch" % GR_MAPPING)
        ctx = repo[currentbranch]

    mappingconfig = readconfig(GR_MAPPING, ctx)

    # return the items in the null section
    return mappingconfig['']


def getguests(repo, ctx=None, skipUnauthorized=False):
    ''' Get the guest repos by parsing the .hgguestrepo.

        The uri field of the guests is not set until they are matched using the
        mapping file
    '''

    if ctx is None:
        ctx = repo[None]

    # parse .hgguestrepo file
    guestconfig = readconfig(GR_CONFIG, ctx)

    guests = []
    pathauditor = scmutil.pathauditor(repo.root)
    for configpath, value in guestconfig[''].items():
        try:
           canonpath = scmutil.canonpath(repo.root,
                                      repo.root,
                                      configpath,
                                      auditor = pathauditor)
        except util.Abort:
               canonpath = authorizedoutisderoot(os.path.join(repo.root, configpath), skipUnauthorized)

        if canonpath == None:
           continue

        if canonpath == '':
            raise util.Abort("guest path '%s' refers to parent repository!" %
                                configpath)

        # parse the name, csid pair
        split = value.rsplit(' ', 1)
        name = split[0].rstrip(' ')
        if len( split ) != 2:
            raise util.Abort("guest at path '%s' has no changeset identifier" %
                                configpath)
        csid = split[1]

        root = os.path.join(repo.root, canonpath)

        guests.append(guestrepo(name, configpath, canonpath, None, csid, root))

    rejectnestedguests(guests)

    return guests

def authorizedoutisderoot(path, continueOnError=False):
    '''A path is authorized if anywhere above it in the file tree there's a file called .grauth
       If the given path is authorized the normalized path is returned.
       If the given path is not authorized, an Abort exception is thrown if abortIfInvalid==True, or None is returned otherwise.
    '''
    #Don't check the path itself
    path = util.pconvert(os.path.normpath(path))
    previouspath = path

    while True:
          currentpath, p = os.path.split(previouspath)
          if currentpath == previouspath:
             break

          authfile = os.path.join(currentpath, GR_AUTHFILENAME)
          if os.path.exists(authfile):
             return path
          previouspath = currentpath

    bestgrauthlocation, p = os.path.split(path)
    bestgrauthlocation = os.path.join(bestgrauthlocation, GR_AUTHFILENAME)
    if not continueOnError:
       raise util.Abort("'{0}' not under root. To override this check, add an empty file called '{1}'".format(path, bestgrauthlocation))
    return None

def rejectnestedguests(guests):
    ''' Given a collection of guests, throw an exception if the path of any
        guest is a prefix of the path of any other guest

        guest.canonpath must be normalized
    '''
    guests = sorted(guests, key=lambda guest: guest.canonpath)
    paths = map(lambda guest: util.splitpath(guest.canonpath), guests)
    for i in range(len(paths) - 1):
        j = i + 1
        if paths[i] == paths[j][:len(paths[i])]:
            raise util.Abort("guest at '%s' is nested in guest at '%s'"
                                % (guests[j].canonpath, guests[i].canonpath))

# TODO: add globbing for windows users
def matchguests(root, cwd, paths, guests):
    '''return guests that are matched by a path in paths
       raises an exception if any path does not match a guest

       root must be the same root used to generate guest.canonpath
    '''
    pathauditor = scmutil.pathauditor(root)

    ret = []
    for path in paths:
        canonpath = scmutil.canonpath(root, cwd, path, pathauditor)
        try:
            guest = filter(lambda guest: guest.canonpath == canonpath,
                           guests)[0]
        except IndexError:
            raise util.Abort("%s is not a guest repository" % path)
        ret.append(guest)
    return ret

def getguestsmissing(repo, missing, **opts):
    ''' Like getguests, but catches exceptions caused by missing files
        and returns a given placeholder
    '''
    try:
        guests = getguests(repo, **opts)
    except IOError, err:
        if err.errno == errno.ENOENT:
            return missing
        else:
            raise
    except error.LookupError:
        return missing
    return guests

def readconfig(filename, ctx):
    ''' read a config file at a context

        throws IOError when config file missing from the working directory,
        error. LookupError if config is missing from a changeset
    '''
    p = config.config()
    p.parse(filename, ctx[filename].data())
    return p

def warnbranch(ui, guestname, repo, branchname):
    branchmap = repo.branchmap()
    try:
        if len(branchmap[branchname]) > 1:
            ui.warn("%s: multiple heads for branch %s\n" %
                        (guestname, branchname))
    except KeyError:
        pass

def changed(repo):
    modified, added, removed, deleted = repo.status()[:4]
    return modified + added + removed + deleted != []

# This method creates and destroys lots of repos, better for memory, worse
# for speed
# May also want to cache parsed guestlists
def dirtyrecursive(ui, repo, useworkingmap, guests=None):
    ''' Recursively test for any dirty repos
        Returns the path of the first dirty repo
    '''
    if changed(repo):
        return repo.root
    if not guests:
        guests = getguestsmissing(repo, None)
        if not guests:
            return None

        resolvemapping(guests, getmapping(repo, useworkingmap))

    for guest in guests:
        root = repo.wjoin(guest.canonpath)
        if os.path.exists(os.path.join(root, '.hg')):
            guestrepo = hg.repository(ui, root, create=False)
            path = dirtyrecursive(ui, guestrepo, useworkingmap)
            if path:
                return path
    return None

def checkcycles(loc, bannedlocs):
    if loc in bannedlocs:
        raise util.Abort("Detected guestrepo cycle: %s" % loc)

def warnguest(ui, guest):
    ui.warn("guest repo '%s' does not exist in %s\n" %
            (guest.name, guest.configpath))

def filterwarnguests(ui, guests):
    ret = []
    for guest in guests:
        if guest.isrepo():
            ret.append(guest)
        else:
            warnguest(ui, guest)
    return ret

# It is important to be sure that every username and password prompt is called
# through a locked ui object when threading is used.
# All threaded calls go through this function, and the the ui object is checked
# to be sure it will handle prompts correctly
def applyguests(ui, repo, guests, workers, func,
                bannedlocs, mapping, create):
    '''apply a function to each given guest repository, and their own guests
       recursively.

       arguments:
        ui:         a ui object, does not have to be a lockedui
        repo:       repository containing guests
        guests:     the initial list of guests to use
        workers:    a workerpool object
        func:       a function to be run on each guest.
                    signature: func(ui, repo, guest)
        bannedlocs: used for detecting cylces, should be an empty list
        mapping:    -- False if mapping information is not needed
                    -- True if mapping is needed
                    -- 'local' if mapping should be taken from the local
                       directory
        create:     recursively create nonexistent repos, func is not run on
                    new repos
    '''
    if guests == []:
        return
    if mapping:
        resolvemapping(guests, getmapping(repo, mapping == 'local'))
    for guest in guests:
        newui = lockedui.lockedui(ui)
        if guest.isrepo():
            def work(guest=guest,newui=newui):
                checkcycles(guest.uri, bannedlocs)
                newrepo = localrepo.localrepository(newui, guest.root, False)

                # be certain password prompts go to the right place
                assert(newui.guest == guest)

                func(newui, newrepo, guest)
                newguests = getguestsmissing(newrepo, [])
                applyguests(newui, newrepo, newguests, workers, func,
                            bannedlocs + [guest.uri],
                            mapping, create)
        elif create:
            def work(guest=guest,newui=newui):
                checkcycles(guest.uri, bannedlocs)
                ui.status('cloning %s\n' % guest.canonpath)
                if not os.path.exists(guest.root):
                    os.makedirs(guest.root)

                # be certain password prompts go to the right place
                assert(newui.guest == guest)

                srcrepo, newrepo = hg.clone(newui,
                                            {},
                                            guest.uri,
                                            update=guest.csid,
                                            dest=guest.root)

                # mercurial 2.3 adds the wrapper class 'peerrepository'
                # which is returned by clone
                #
                # use the 'local' method to get the local repo
                # from inside the peer
                if hasattr(newrepo, 'local'):
                    newrepo = newrepo.local()

                srcrepo = None
                warnbranch(newui, guest.name, newrepo, guest.csid)

                newguests = getguestsmissing(newrepo, [])
                applyguests(newui, newrepo, newguests, workers, func,
                            bannedlocs + [guest.uri],
                            mapping, True)
        else:
            warnguest(newui, guest)
            work = None
        if work:
            workers.run(work, guest)

def getstatestr(ui, repo, guests):
    '''create a description of the state of a repos's guests, in the format
       of .hgguestrepo
    '''
    lines = []
    for guest in filterwarnguests(ui, guests):
        guestrepo = hg.repository(ui, guest.root, create=False)
        lines.append("%s = %s %s\n" %
                        (guest.configpath.ljust(10),
                         guest.name.ljust(10),
                         node.hex(guestrepo[None].parents()[0].node())))
    return ''.join(lines)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.