1
# Copyright (C) 2005 Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
18
# XXX: Can we do any better about making interrupted commits change
 
 
19
# nothing?  Perhaps the best approach is to integrate commit of
 
 
20
# AtomicFiles with releasing the lock on the Branch.
 
 
22
# TODO: Separate 'prepare' phase where we find a list of potentially
 
 
23
# committed files.  We then can then pause the commit to prompt for a
 
 
24
# commit message, knowing the summary will be the same as what's
 
 
25
# actually used for the commit.  (But perhaps simpler to simply get
 
 
26
# the tree status, then use that for a selective commit?)
 
 
28
# The newly committed revision is going to have a shape corresponding
 
 
29
# to that of the working inventory.  Files that are not in the
 
 
30
# working tree and that were in the predecessor are reported as
 
 
31
# removed --- this can include files that were either removed from the
 
 
32
# inventory or deleted in the working tree.  If they were only
 
 
33
# deleted from disk, they are removed from the working inventory.
 
 
35
# We then consider the remaining entries, which will be in the new
 
 
36
# version.  Directory entries are simply copied across.  File entries
 
 
37
# must be checked to see if a new version of the file should be
 
 
38
# recorded.  For each parent revision inventory, we check to see what
 
 
39
# version of the file was present.  If the file was present in at
 
 
40
# least one tree, and if it was the same version in all the trees,
 
 
41
# then we can just refer to that version.  Otherwise, a new version
 
 
42
# representing the merger of the file versions must be added.
 
 
44
# TODO: Update hashcache before and after - or does the WorkingTree
 
 
47
# TODO: Rather than mashing together the ancestry and storing it back,
 
 
48
# perhaps the weave should have single method which does it all in one
 
 
49
# go, avoiding a lot of redundant work.
 
 
51
# TODO: Perhaps give a warning if one of the revisions marked as
 
 
52
# merged is already in the ancestry, and then don't record it as a
 
 
55
# TODO: If the file is newly merged but unchanged from the version it
 
 
56
# merges from, then it should still be reported as newly added
 
 
57
# relative to the basis revision.
 
 
59
# TODO: Do checks that the tree can be committed *before* running the 
 
 
60
# editor; this should include checks for a pointless commit and for 
 
 
61
# unknown or missing files.
 
 
63
# TODO: If commit fails, leave the message in a file somewhere.
 
 
72
from binascii import hexlify
 
 
73
from cStringIO import StringIO
 
 
75
from bzrlib.atomicfile import AtomicFile
 
 
76
from bzrlib.osutils import (local_time_offset,
 
 
77
                            rand_bytes, compact_date,
 
 
78
                            kind_marker, is_inside_any, quotefn,
 
 
79
                            sha_string, sha_strings, sha_file, isdir, isfile,
 
 
82
from bzrlib.errors import (BzrError, PointlessCommit,
 
 
87
import bzrlib.gpg as gpg
 
 
88
from bzrlib.revision import Revision
 
 
89
from bzrlib.testament import Testament
 
 
90
from bzrlib.trace import mutter, note, warning
 
 
91
from bzrlib.xml5 import serializer_v5
 
 
92
from bzrlib.inventory import Inventory, ROOT_ID
 
 
93
from bzrlib.weave import Weave
 
 
94
from bzrlib.weavefile import read_weave, write_weave_v5
 
 
95
from bzrlib.workingtree import WorkingTree
 
 
98
def commit(*args, **kwargs):
 
 
99
    """Commit a new revision to a branch.
 
 
101
    Function-style interface for convenience of old callers.
 
 
103
    New code should use the Commit class instead.
 
 
105
    ## XXX: Remove this in favor of Branch.commit?
 
 
106
    Commit().commit(*args, **kwargs)
 
 
109
class NullCommitReporter(object):
 
 
110
    """I report on progress of a commit."""
 
 
112
    def snapshot_change(self, change, path):
 
 
115
    def completed(self, revno, rev_id):
 
 
118
    def deleted(self, file_id):
 
 
121
    def escaped(self, escape_count, message):
 
 
124
    def missing(self, path):
 
 
128
class ReportCommitToLog(NullCommitReporter):
 
 
130
    def snapshot_change(self, change, path):
 
 
131
        note("%s %s", change, path)
 
 
133
    def completed(self, revno, rev_id):
 
 
134
        note('committed r%d {%s}', revno, rev_id)
 
 
136
    def deleted(self, file_id):
 
 
137
        note('deleted %s', file_id)
 
 
139
    def escaped(self, escape_count, message):
 
 
140
        note("replaced %d control characters in message", escape_count)
 
 
142
    def missing(self, path):
 
 
143
        note('missing %s', path)
 
 
146
class Commit(object):
 
 
147
    """Task of committing a new revision.
 
 
149
    This is a MethodObject: it accumulates state as the commit is
 
 
150
    prepared, and then it is discarded.  It doesn't represent
 
 
151
    historical revisions, just the act of recording a new one.
 
 
154
            Modified to hold a list of files that have been deleted from
 
 
155
            the working directory; these should be removed from the
 
 
161
        if reporter is not None:
 
 
162
            self.reporter = reporter
 
 
164
            self.reporter = NullCommitReporter()
 
 
165
        if config is not None:
 
 
177
               allow_pointless=True,
 
 
181
        """Commit working copy as a new revision.
 
 
183
        timestamp -- if not None, seconds-since-epoch for a
 
 
184
             postdated/predated commit.
 
 
186
        specific_files -- If true, commit only those files.
 
 
188
        rev_id -- If set, use this as the new revision id.
 
 
189
            Useful for test or import commands that need to tightly
 
 
190
            control what revisions are assigned.  If you duplicate
 
 
191
            a revision id that exists elsewhere it is your own fault.
 
 
192
            If null (default), a time/random revision id is generated.
 
 
194
        allow_pointless -- If true (default), commit even if nothing
 
 
195
            has changed and no merges are recorded.
 
 
197
        strict -- If true, don't allow a commit if the working tree
 
 
198
            contains unknown files.
 
 
200
        revprops -- Properties for new revision
 
 
202
        mutter('preparing to commit')
 
 
205
        self.weave_store = branch.weave_store
 
 
207
        self.specific_files = specific_files
 
 
208
        self.allow_pointless = allow_pointless
 
 
209
        self.revprops = {'branch-nick': branch.nick}
 
 
211
            self.revprops.update(revprops)
 
 
212
        self.work_tree = WorkingTree(branch.base, branch)
 
 
215
            # raise an exception as soon as we find a single unknown.
 
 
216
            for unknown in self.work_tree.unknowns():
 
 
217
                raise StrictCommitFailed()
 
 
219
        if timestamp is None:
 
 
220
            self.timestamp = time.time()
 
 
222
            self.timestamp = long(timestamp)
 
 
224
        if self.config is None:
 
 
225
            self.config = bzrlib.config.BranchConfig(self.branch)
 
 
228
            self.rev_id = _gen_revision_id(self.config, self.timestamp)
 
 
232
        if committer is None:
 
 
233
            self.committer = self.config.username()
 
 
235
            assert isinstance(committer, basestring), type(committer)
 
 
236
            self.committer = committer
 
 
239
            self.timezone = local_time_offset()
 
 
241
            self.timezone = int(timezone)
 
 
243
        if isinstance(message, str):
 
 
244
            message = message.decode(bzrlib.user_encoding)
 
 
245
        assert isinstance(message, unicode), type(message)
 
 
246
        self.message = message
 
 
247
        self._escape_commit_message()
 
 
249
        self.branch.lock_write()
 
 
251
            self.work_inv = self.work_tree.inventory
 
 
252
            self.basis_tree = self.branch.basis_tree()
 
 
253
            self.basis_inv = self.basis_tree.inventory
 
 
255
            self._gather_parents()
 
 
256
            if len(self.parents) > 1 and self.specific_files:
 
 
257
                raise NotImplementedError('selected-file commit of merges is not supported yet')
 
 
258
            self._check_parents_present()
 
 
260
            self._remove_deleted()
 
 
261
            self._populate_new_inv()
 
 
262
            self._store_snapshot()
 
 
263
            self._report_deletes()
 
 
265
            if not (self.allow_pointless
 
 
266
                    or len(self.parents) > 1
 
 
267
                    or self.new_inv != self.basis_inv):
 
 
268
                raise PointlessCommit()
 
 
270
            if len(list(self.work_tree.iter_conflicts()))>0:
 
 
271
                raise ConflictsInTree
 
 
273
            self._record_inventory()
 
 
274
            self._make_revision()
 
 
275
            self.work_tree.set_pending_merges([])
 
 
276
            self.branch.append_revision(self.rev_id)
 
 
277
            self.reporter.completed(self.branch.revno()+1, self.rev_id)
 
 
278
            if self.config.post_commit() is not None:
 
 
279
                hooks = self.config.post_commit().split(' ')
 
 
280
                # this would be nicer with twisted.python.reflect.namedAny
 
 
282
                    result = eval(hook + '(branch, rev_id)',
 
 
283
                                  {'branch':self.branch,
 
 
285
                                   'rev_id':self.rev_id})
 
 
289
    def _record_inventory(self):
 
 
290
        """Store the inventory for the new revision."""
 
 
291
        inv_text = serializer_v5.write_inventory_to_string(self.new_inv)
 
 
292
        self.inv_sha1 = sha_string(inv_text)
 
 
293
        s = self.branch.control_weaves
 
 
294
        s.add_text('inventory', self.rev_id,
 
 
295
                   split_lines(inv_text), self.present_parents,
 
 
296
                   self.branch.get_transaction())
 
 
298
    def _escape_commit_message(self):
 
 
299
        """Replace xml-incompatible control characters."""
 
 
300
        # Python strings can include characters that can't be
 
 
301
        # represented in well-formed XML; escape characters that
 
 
302
        # aren't listed in the XML specification
 
 
303
        # (http://www.w3.org/TR/REC-xml/#NT-Char).
 
 
304
        self.message, escape_count = re.subn(
 
 
305
            u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
 
 
306
            lambda match: match.group(0).encode('unicode_escape'),
 
 
309
            self.reporter.escaped(escape_count, self.message)
 
 
311
    def _gather_parents(self):
 
 
312
        """Record the parents of a merge for merge detection."""
 
 
313
        pending_merges = self.work_tree.pending_merges()
 
 
315
        self.parent_invs = []
 
 
316
        self.present_parents = []
 
 
317
        precursor_id = self.branch.last_revision()
 
 
319
            self.parents.append(precursor_id)
 
 
320
        self.parents += pending_merges
 
 
321
        for revision in self.parents:
 
 
322
            if self.branch.has_revision(revision):
 
 
323
                self.parent_invs.append(self.branch.get_inventory(revision))
 
 
324
                self.present_parents.append(revision)
 
 
326
    def _check_parents_present(self):
 
 
327
        for parent_id in self.parents:
 
 
328
            mutter('commit parent revision {%s}', parent_id)
 
 
329
            if not self.branch.has_revision(parent_id):
 
 
330
                if parent_id == self.branch.last_revision():
 
 
331
                    warning("parent is missing %r", parent_id)
 
 
332
                    raise HistoryMissing(self.branch, 'revision', parent_id)
 
 
334
                    mutter("commit will ghost revision %r", parent_id)
 
 
336
    def _make_revision(self):
 
 
337
        """Record a new revision object for this commit."""
 
 
338
        self.rev = Revision(timestamp=self.timestamp,
 
 
339
                            timezone=self.timezone,
 
 
340
                            committer=self.committer,
 
 
341
                            message=self.message,
 
 
342
                            inventory_sha1=self.inv_sha1,
 
 
343
                            revision_id=self.rev_id,
 
 
344
                            properties=self.revprops)
 
 
345
        self.rev.parent_ids = self.parents
 
 
347
        serializer_v5.write_revision(self.rev, rev_tmp)
 
 
349
        if self.config.signature_needed():
 
 
350
            plaintext = Testament(self.rev, self.new_inv).as_short_text()
 
 
351
            self.branch.store_revision_signature(gpg.GPGStrategy(self.config),
 
 
352
                                                 plaintext, self.rev_id)
 
 
353
        self.branch.revision_store.add(rev_tmp, self.rev_id)
 
 
354
        mutter('new revision_id is {%s}', self.rev_id)
 
 
356
    def _remove_deleted(self):
 
 
357
        """Remove deleted files from the working inventories.
 
 
359
        This is done prior to taking the working inventory as the
 
 
360
        basis for the new committed inventory.
 
 
362
        This returns true if any files
 
 
363
        *that existed in the basis inventory* were deleted.
 
 
364
        Files that were added and deleted
 
 
365
        in the working copy don't matter.
 
 
367
        specific = self.specific_files
 
 
369
        for path, ie in self.work_inv.iter_entries():
 
 
370
            if specific and not is_inside_any(specific, path):
 
 
372
            if not self.work_tree.has_filename(path):
 
 
373
                self.reporter.missing(path)
 
 
374
                deleted_ids.append((path, ie.file_id))
 
 
376
            deleted_ids.sort(reverse=True)
 
 
377
            for path, file_id in deleted_ids:
 
 
378
                del self.work_inv[file_id]
 
 
379
            self.work_tree._write_inventory(self.work_inv)
 
 
381
    def _store_snapshot(self):
 
 
382
        """Pass over inventory and record a snapshot.
 
 
384
        Entries get a new revision when they are modified in 
 
 
385
        any way, which includes a merge with a new set of
 
 
386
        parents that have the same entry. 
 
 
388
        # XXX: Need to think more here about when the user has
 
 
389
        # made a specific decision on a particular value -- c.f.
 
 
391
        for path, ie in self.new_inv.iter_entries():
 
 
392
            previous_entries = ie.find_previous_heads(
 
 
394
                self.weave_store.get_weave_or_empty(ie.file_id,
 
 
395
                    self.branch.get_transaction()))
 
 
396
            if ie.revision is None:
 
 
397
                change = ie.snapshot(self.rev_id, path, previous_entries,
 
 
398
                                     self.work_tree, self.weave_store,
 
 
399
                                     self.branch.get_transaction())
 
 
402
            self.reporter.snapshot_change(change, path)
 
 
404
    def _populate_new_inv(self):
 
 
405
        """Build revision inventory.
 
 
407
        This creates a new empty inventory. Depending on
 
 
408
        which files are selected for commit, and what is present in the
 
 
409
        current tree, the new inventory is populated. inventory entries 
 
 
410
        which are candidates for modification have their revision set to
 
 
411
        None; inventory entries that are carried over untouched have their
 
 
412
        revision set to their prior value.
 
 
414
        mutter("Selecting files for commit with filter %s", self.specific_files)
 
 
415
        self.new_inv = Inventory()
 
 
416
        for path, new_ie in self.work_inv.iter_entries():
 
 
417
            file_id = new_ie.file_id
 
 
418
            mutter('check %s {%s}', path, new_ie.file_id)
 
 
419
            if self.specific_files:
 
 
420
                if not is_inside_any(self.specific_files, path):
 
 
421
                    mutter('%s not selected for commit', path)
 
 
422
                    self._carry_entry(file_id)
 
 
425
                    # this is selected, ensure its parents are too.
 
 
426
                    parent_id = new_ie.parent_id
 
 
427
                    while parent_id != ROOT_ID:
 
 
428
                        if not self.new_inv.has_id(parent_id):
 
 
429
                            ie = self._select_entry(self.work_inv[parent_id])
 
 
430
                            mutter('%s selected for commit because of %s',
 
 
431
                                   self.new_inv.id2path(parent_id), path)
 
 
433
                        ie = self.new_inv[parent_id]
 
 
434
                        if ie.revision is not None:
 
 
436
                            mutter('%s selected for commit because of %s',
 
 
437
                                   self.new_inv.id2path(parent_id), path)
 
 
438
                        parent_id = ie.parent_id
 
 
439
            mutter('%s selected for commit', path)
 
 
440
            self._select_entry(new_ie)
 
 
442
    def _select_entry(self, new_ie):
 
 
443
        """Make new_ie be considered for committing."""
 
 
449
    def _carry_entry(self, file_id):
 
 
450
        """Carry the file unchanged from the basis revision."""
 
 
451
        if self.basis_inv.has_id(file_id):
 
 
452
            self.new_inv.add(self.basis_inv[file_id].copy())
 
 
454
    def _report_deletes(self):
 
 
455
        for file_id in self.basis_inv:
 
 
456
            if file_id not in self.new_inv:
 
 
457
                self.reporter.deleted(self.basis_inv.id2path(file_id))
 
 
459
def _gen_revision_id(config, when):
 
 
460
    """Return new revision-id."""
 
 
461
    s = '%s-%s-' % (config.user_email(), compact_date(when))
 
 
462
    s += hexlify(rand_bytes(8))