Source

mutable-history / hgext / obsolete.py

The default branch has multiple heads

  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
# obsolete.py - introduce the obsolete concept in mercurial.
#
# Copyright 2011 Pierre-Yves David <pierre-yves.david@ens-lyon.org>
#                Logilab SA        <contact@logilab.fr>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""Introduce the Obsolete concept to mercurial

General concept
===============

This extension introduces the *obsolete* concept. It adds a new *obsolete*
relation between two changesets. A relation ``<changeset B> obsolete <changeset
A>`` is set to denote that ``<changeset B>`` is new version of ``<changeset
A>``.

The *obsolete* relation act as a **perpendicular history** to the standard
changeset history. Standard changeset history versions files. The *obsolete*
relation versions changesets.

:obsolete:     a changeset that have been replace by another one.
:unstable:     a non-obsolet changeset based on another one.
:suspended:    an obsolete changeset with unstable descendant.

Another name for unstable could be out of sync.



Usage and Feature
=================


Display and Exchange
....................

obsolete changesets are hidden. (except if they have non obsolete changeset)

obsolete changesets are currently not exchange. This will probably change later
but it was the simpler solution for now.

New commands
............

a ``debugobsolete`` command has been added.

It add an obsolete relation between too relation.

Context object
..............

Context gain a ``obsolete`` method that return True if a changeset is obsolete
False otherwise.

revset
......

Add an ``obsolete()`` entry.

repo extension
..............

To Do
-----

* refuse to obsolete published changesets

* handle split

* handle conflict

* handle unstable // out of sync

"""
import os
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

from mercurial.i18n import _

import base64

from mercurial import util
from mercurial import context
from mercurial import revset
from mercurial import scmutil
from mercurial import extensions
from mercurial import pushkey
from mercurial import discovery
from mercurial import error
from mercurial import commands
from mercurial.node import hex, bin, short, nullid
from mercurial.lock import release

### Patch changectx
#############################

def obsolete(ctx):
    """is the changeset obsolete by other"""
    if ctx.node()is None:
        return False
    return bool(ctx._repo.obsoletedby(ctx.node())) and ctx.state().mutable

context.changectx.obsolete = obsolete

ohidden = context.changectx.hidden
def hidden(ctx):
    """hacked version fo hidden that also initialize hiddenrevs set

    XXX we need something cleaner"""
    # hack to fill hiddenrevs
    # compute hidden (XXX should move elsewhere)
    if not getattr(ctx._repo.changelog, 'hiddeninit', False):
        shown = ['not obsolete()', '.', 'bookmark()', 'tagged()',
                 'publishedheads()']
        basicquery = 'obsolete() - (::(%s))' % (' or '.join(shown))
        for rev in scmutil.revrange(ctx._repo, [basicquery]):
            ctx._repo.changelog.hiddenrevs.add(rev)
        ctx._repo.changelog.hiddeninit = True

    return ohidden(ctx)
context.changectx.hidden = hidden

### revset
#############################

def revsetobsolete(repo, subset, x):
    """filter obsolet entry"""
    args = revset.getargs(x, 0, 0, 'publicheads takes no arguments')
    # XXX slow stop using context
    return [r for r in subset if repo[r].obsolete()]

### Other Extension compat
############################

def concludenode(orig, repo, rev, *args, **kwargs):
    """wrapper for rebase 's concludenode that set obsolete relation"""
    newrev = orig(repo, rev, *args, **kwargs)
    oldnode = repo[rev].node()
    newnode = repo[newrev].node()
    repo.addobsolete(newnode, oldnode)
    return newrev

def cmdrebase(orig, repo, ui, *args, **kwargs):
    oldkeep = kwargs.pop('keep', False)
    if oldkeep:
        ui.warn('WARNING --keep option ignored by experimental obsolete extension')
    kwargs['keep'] = True
    return orig(repo, ui, *args, **kwargs)


### Filter obsolet changeset
############################

def filterobsoleteout(orig, repo, remote, *args,**kwargs):
    """wrapper for findcommonoutgoing that remove obsolete changeset

    This behaviour is temporary"""
    common, heads = orig(repo, remote, *args, **kwargs)

    # filter obsolete
    heads = set(map(repo.changelog.rev, heads))
    obsoletes = set()
    for obj in repo._obsobjrels:
        try:
            obsoletes.add(repo.changelog.rev(obj))
        except error.LookupError:
            pass # we don't have this node locally

    outgoing = set(repo.changelog.ancestors(*heads))
    outgoing.update(heads)

    selected = outgoing - obsoletes
    heads = sorted(map(repo.changelog.node, selected))

    return common, heads

def extsetup(ui):
    try:
        rebase = extensions.find('states')
    except KeyError:
        raise error.Abort(_('obsolete extension require states extension.'))

    revset.symbols["obsolete"] = revsetobsolete

    extensions.wrapfunction(discovery, 'findcommonoutgoing', filterobsoleteout)

    try:
        rebase = extensions.find('rebase')
        if rebase:
            extensions.wrapfunction(rebase, 'concludenode', concludenode)
            extensions.wrapcommand(rebase.cmdtable, "rebase", cmdrebase)
    except KeyError:
        pass # rebase not found

# Pushkey mechanism for mutable
#########################################

def pushobsolete(repo, key, old, raw):
    """push obsolete relation through pushkey"""
    assert key == "relations"
    w = repo.wlock()
    try:
        tmp = StringIO()
        tmp.write(raw)
        tmp.seek(0)
        relations = _obsdeserialise(tmp)
        for sub, objs in relations.iteritems():
            for obj in objs:
                try:
                    repo.addobsolete(sub, obj)
                except error.RepoLookupError:
                    pass
        return 0
    finally:
        w.release()

def listobsolete(repo):
    """dump all obsolete relation in

    XXX this have be improved"""
    tmp = StringIO()
    _obsserialise(repo._obssubrels, tmp)
    return {'relations': base64.b64encode(tmp.getvalue())}

pushkey.register('obsolete', pushobsolete, listobsolete)

### New commands
#############################


def cmddebugobsolete(ui, repo, subject, object):
    """Add an obsolete relation between a too node

    The subject is expected to be a newer version of the object"""
    sub = repo[subject]
    obj = repo[object]
    repo.addobsolete(sub.node(), obj.node())
    return 0

cmdtable = {'debugobsolete': (cmddebugobsolete, [], '<subject> <object>')}

### Altering existing command
#############################

def wrapmayobsoletewc(origfn, ui, repo, *args, **opts):
    res = origfn(ui, repo, *args, **opts)
    if repo['.'].obsolete():
        ui.warn(_('Working directory parent is obsolete\n'))
    return res

def uisetup(ui):
    extensions.wrapcommand(commands.table, "update", wrapmayobsoletewc)
    extensions.wrapcommand(commands.table, "pull", wrapmayobsoletewc)

### serialisation
#############################

def _obsserialise(obssubrels, flike):
    """serialise an obsolete relation mapping in a plain text one

    this is for subject -> [objects] mapping

    format is::

        <subject-full-hex> <object-full-hex>\n"""
    for sub, objs in obssubrels.iteritems():
        for obj in objs:
            if sub is None:
                sub = nullid
            flike.write('%s %s\n' % (hex(sub), hex(obj)))

def _obsdeserialise(flike):
    """read a file like object serialised with _obsserialise

    this desierialize into a {subject -> objects} mapping"""
    rels = {}
    for line in flike:
        subhex, objhex = line.split()
        subnode = bin(subhex)
        if subnode == nullid:
            subnode = None
        rels.setdefault( subnode, set()).add(bin(objhex))
    return rels

### diagnostique tools
#############################

def unstables(repo):
    """Return all unstable changeset"""
    return scmutil.revrange(repo, ['obsolete():: and (not obsolete())'])

def newerversion(repo, obs):
    """Return the newer version of an obsolete changeset"""
    toproceed = set([obs])
    # XXX know optimization available
    newer = set()
    while toproceed:
        current = toproceed.pop()
        if current in repo._obsobjrels:
            toproceed.update(repo._obsobjrels[current])
        elif current is not None: # None is kill
            newer.add(current)
    return sorted(newer)


### repo subclassing
#############################

def reposetup(ui, repo):

    if not repo.local():
        return

    opull = repo.pull
    opush = repo.push
    orollback = repo.rollback
    o_writejournal = repo._writejournal
    ocancopy = repo.cancopy

    class obsoletingrepo(repo.__class__):

        ### Public method
        def obsoletedby(self, node):
            """return the set of node that make <node> obsolete (obj)"""
            return self._obsobjrels.get(node, set())

        def obsolete(self, node):
            """return the set of node that <node> make obsolete (sub)"""
            return self._obssubrels.get(node, set())

        def addobsolete(self, sub, obj):
            """Add a relation marking that node <sub> is a new version of <obj>"""
            if sub == nullid:
                sub = None
            self._obssubrels.setdefault(sub, set()).add(obj)
            self._obsobjrels.setdefault(obj, set()).add(sub)
            try:
                if not self.nodestate(obj).mutable:
                    if sub is None:
                        self.ui.warn(
                            _("trying to kill immutable changeset %(obj)s\n")
                            % {'obj': short(obj)})
                    if sub is not None:
                        self.ui.warn(
                            _("%(sub)s try to obsolete immutable changeset %(obj)s\n")
                            % {'sub': short(sub), 'obj': short(obj)})
                self.changelog.hiddenrevs.add(repo[obj].rev())
            except (error.RepoLookupError, error.LookupError):
                pass #unknow revision (but keep propagating the data
            self._writeobsrels()

        ### obsolete storage
        @util.propertycache
        def _obsobjrels(self):
            """{<old-node> -> set(<new-node>)}

            also compute hidden revision"""
            #reverse sub -> objs mapping
            objrels = {}
            for sub, objs in self._obssubrels.iteritems():
                for obj in objs:
                    objrels.setdefault(obj, set()).add(sub)
            return objrels

        @util.propertycache
        def _obssubrels(self):
            """{<new-node> -> set(<old-node>)}"""
            return self._readobsrels()




        ### Disk IO
        def _readobsrels(self):
            """Write obsolete relation on disk"""
            # XXX handle lock
            try:
                f = self.opener('obsolete-relations')
                try:
                    return _obsdeserialise(f)
                finally:
                    f.close()
            except IOError:
                return {}

        def _writeobsrels(self):
            """Write obsolete relation on disk"""
            # XXX handle lock
            f = self.opener('obsolete-relations', 'w', atomictemp=True)
            try:
                _obsserialise(self._obssubrels, f)
                try:
                    f.rename()
                except AttributeError: # old version
                    f.close()
            finally:
                f.close()

        ### local clone support

        def cancopy(self):
            """wrapper on cancopy that deny copy if there is obsolete relation"""
            return ocancopy() and not bool(self._obsobjrels)  # you can't copy if there is obsolete

        ### pull // push support

        def pull(self, remote, *args, **kwargs):
            """wrapper around push that push obsolete relation"""
            result = opull(remote, *args, **kwargs)
            if 'obsolete' in remote.listkeys('namespaces'):
                tmp = StringIO()
                rels = remote.listkeys('obsolete')['relations']
                tmp.write(base64.b64decode(rels))
                tmp.seek(0)
                obsrels = _obsdeserialise(tmp)
                for sub, objs in obsrels.iteritems():
                    for obj in objs:
                        self.addobsolete(sub, obj)
            return result

        def push(self, remote, *args, **opts):
            """wrapper around pull that pull obsolete relation"""
            result = opush(remote, *args, **opts)
            if 'obsolete' in remote.listkeys('namespaces'):
                tmp = StringIO()
                _obsserialise(self._obssubrels, tmp)
                remote.pushkey('obsolete', 'relations', '', tmp.getvalue())

            return result



        ### rollback support

        def _writejournal(self, desc):
            """wrapped version of _writejournal that save obsolete data"""
            entries = list(o_writejournal(desc))
            filename = 'obsolete-relations'
            filepath = self.join(filename)
            if  os.path.exists(filepath):
                journalname = 'journal.' + filename
                journalpath = self.join(journalname)
                util.copyfile(filepath, journalpath)
                entries.append(journalpath)
            return tuple(entries)

        def rollback(self, dryrun=False):
            """wrapped version of rollback that restore obsolete data"""
            wlock = lock = None
            try:
                wlock = self.wlock()
                lock = self.lock()
                ret = orollback(dryrun)
                if not (ret or dryrun): #rollback did not failed
                    src = self.join('undo.obsolete-relations')
                    dst = self.join('obsolete-relations')
                    if os.path.exists(src):
                        util.rename(src, dst)
                    elif os.path.exists(dst): #unlink in any case
                        os.unlink(dst)
                    # invalidate cache
                    self.__dict__.pop('_obssubrels', None)
                    self.__dict__.pop('_obsobjrels', None)
                return ret
            finally:
                release(lock, wlock)

    repo.__class__ = obsoletingrepo