/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/blackbox/test_commit.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-29 13:16:26 UTC
  • mto: This revision was merged to the branch mainline in revision 7376.
  • Revision ID: jelmer@jelmer.uk-20190629131626-qioafloyemhdbm4w
Remove Tree.get_root_id() in favour of Tree.path2id('').

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
"""Tests for the commit CLI of bzr."""
 
19
 
 
20
import doctest
 
21
import os
 
22
import re
 
23
import sys
 
24
 
 
25
from testtools.matchers import DocTestMatches
 
26
 
 
27
from ... import (
 
28
    config,
 
29
    osutils,
 
30
    ignores,
 
31
    msgeditor,
 
32
    )
 
33
from ...controldir import ControlDir
 
34
from ...sixish import PY3
 
35
from .. import (
 
36
    test_foreign,
 
37
    features,
 
38
    )
 
39
from .. import TestCaseWithTransport
 
40
from ..matchers import ContainsNoVfsCalls
 
41
from ..test_bedding import override_whoami
 
42
 
 
43
 
 
44
class TestCommit(TestCaseWithTransport):
 
45
 
 
46
    def test_05_empty_commit(self):
 
47
        """Commit of tree with no versioned files should fail"""
 
48
        # If forced, it should succeed, but this is not tested here.
 
49
        self.make_branch_and_tree('.')
 
50
        self.build_tree(['hello.txt'])
 
51
        out, err = self.run_bzr('commit -m empty', retcode=3)
 
52
        self.assertEqual('', out)
 
53
        # Two ugly bits here.
 
54
        # 1) We really don't want 'aborting commit write group' anymore.
 
55
        # 2) brz: ERROR: is a really long line, so we wrap it with '\'
 
56
        self.assertThat(
 
57
            err,
 
58
            DocTestMatches("""\
 
59
Committing to: ...
 
60
brz: ERROR: No changes to commit.\
 
61
 Please 'brz add' the files you want to commit,\
 
62
 or use --unchanged to force an empty commit.
 
63
""", flags=doctest.ELLIPSIS | doctest.REPORT_UDIFF))
 
64
 
 
65
    def test_commit_success(self):
 
66
        """Successful commit should not leave behind a bzr-commit-* file"""
 
67
        self.make_branch_and_tree('.')
 
68
        self.run_bzr('commit --unchanged -m message')
 
69
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
70
 
 
71
        # same for unicode messages
 
72
        self.run_bzr(["commit", "--unchanged", "-m", u'foo\xb5'])
 
73
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
74
 
 
75
    def test_commit_lossy_native(self):
 
76
        """A --lossy option to commit is supported."""
 
77
        self.make_branch_and_tree('.')
 
78
        self.run_bzr('commit --lossy --unchanged -m message')
 
79
        self.assertEqual('', self.run_bzr('unknowns')[0])
 
80
 
 
81
    def test_commit_lossy_foreign(self):
 
82
        test_foreign.register_dummy_foreign_for_test(self)
 
83
        self.make_branch_and_tree('.',
 
84
                                  format=test_foreign.DummyForeignVcsDirFormat())
 
85
        self.run_bzr('commit --lossy --unchanged -m message')
 
86
        output = self.run_bzr('revision-info')[0]
 
87
        self.assertTrue(output.startswith('1 dummy-'))
 
88
 
 
89
    def test_commit_with_path(self):
 
90
        """Commit tree with path of root specified"""
 
91
        a_tree = self.make_branch_and_tree('a')
 
92
        self.build_tree(['a/a_file'])
 
93
        a_tree.add('a_file')
 
94
        self.run_bzr(['commit', '-m', 'first commit', 'a'])
 
95
 
 
96
        b_tree = a_tree.controldir.sprout('b').open_workingtree()
 
97
        self.build_tree_contents([('b/a_file', b'changes in b')])
 
98
        self.run_bzr(['commit', '-m', 'first commit in b', 'b'])
 
99
 
 
100
        self.build_tree_contents([('a/a_file', b'new contents')])
 
101
        self.run_bzr(['commit', '-m', 'change in a', 'a'])
 
102
 
 
103
        b_tree.merge_from_branch(a_tree.branch)
 
104
        self.assertEqual(len(b_tree.conflicts()), 1)
 
105
        self.run_bzr('resolved b/a_file')
 
106
        self.run_bzr(['commit', '-m', 'merge into b', 'b'])
 
107
 
 
108
    def test_10_verbose_commit(self):
 
109
        """Add one file and examine verbose commit output"""
 
110
        tree = self.make_branch_and_tree('.')
 
111
        self.build_tree(['hello.txt'])
 
112
        tree.add("hello.txt")
 
113
        out, err = self.run_bzr('commit -m added')
 
114
        self.assertEqual('', out)
 
115
        self.assertContainsRe(err, '^Committing to: .*\n'
 
116
                              'added hello.txt\n'
 
117
                              'Committed revision 1.\n$',)
 
118
 
 
119
    def prepare_simple_history(self):
 
120
        """Prepare and return a working tree with one commit of one file"""
 
121
        # Commit with modified file should say so
 
122
        wt = ControlDir.create_standalone_workingtree('.')
 
123
        self.build_tree(['hello.txt', 'extra.txt'])
 
124
        wt.add(['hello.txt'])
 
125
        wt.commit(message='added')
 
126
        return wt
 
127
 
 
128
    def test_verbose_commit_modified(self):
 
129
        # Verbose commit of modified file should say so
 
130
        wt = self.prepare_simple_history()
 
131
        self.build_tree_contents([('hello.txt', b'new contents')])
 
132
        out, err = self.run_bzr('commit -m modified')
 
133
        self.assertEqual('', out)
 
134
        self.assertContainsRe(err, '^Committing to: .*\n'
 
135
                              'modified hello\\.txt\n'
 
136
                              'Committed revision 2\\.\n$')
 
137
 
 
138
    def test_unicode_commit_message_is_filename(self):
 
139
        """Unicode commit message same as a filename (Bug #563646).
 
140
        """
 
141
        self.requireFeature(features.UnicodeFilenameFeature)
 
142
        file_name = u'\N{euro sign}'
 
143
        self.run_bzr(['init'])
 
144
        with open(file_name, 'w') as f:
 
145
            f.write('hello world')
 
146
        self.run_bzr(['add'])
 
147
        out, err = self.run_bzr(['commit', '-m', file_name])
 
148
        reflags = re.MULTILINE | re.DOTALL | re.UNICODE
 
149
        te = osutils.get_terminal_encoding()
 
150
        self.assertContainsRe(err if PY3 else err.decode(te),
 
151
                              u'The commit message is a file name:',
 
152
                              flags=reflags)
 
153
 
 
154
        # Run same test with a filename that causes encode
 
155
        # error for the terminal encoding. We do this
 
156
        # by forcing terminal encoding of ascii for
 
157
        # osutils.get_terminal_encoding which is used
 
158
        # by ui.text.show_warning
 
159
        default_get_terminal_enc = osutils.get_terminal_encoding
 
160
        try:
 
161
            osutils.get_terminal_encoding = lambda trace=None: 'ascii'
 
162
            file_name = u'foo\u1234'
 
163
            with open(file_name, 'w') as f:
 
164
                f.write('hello world')
 
165
            self.run_bzr(['add'])
 
166
            out, err = self.run_bzr(['commit', '-m', file_name])
 
167
            reflags = re.MULTILINE | re.DOTALL | re.UNICODE
 
168
            te = osutils.get_terminal_encoding()
 
169
            self.assertContainsRe(err if PY3 else err.decode(te, 'replace'),
 
170
                                  u'The commit message is a file name:',
 
171
                                  flags=reflags)
 
172
        finally:
 
173
            osutils.get_terminal_encoding = default_get_terminal_enc
 
174
 
 
175
    def test_non_ascii_file_unversioned_utf8(self):
 
176
        self.requireFeature(features.UnicodeFilenameFeature)
 
177
        tree = self.make_branch_and_tree(".")
 
178
        self.build_tree(["f"])
 
179
        tree.add(["f"])
 
180
        out, err = self.run_bzr_raw(["commit", "-m", "Wrong filename", u"\xa7"],
 
181
                                    encoding="utf-8", retcode=3)
 
182
        self.assertContainsRe(err, b"(?m)not versioned: \"\xc2\xa7\"$")
 
183
 
 
184
    def test_non_ascii_file_unversioned_iso_8859_5(self):
 
185
        self.requireFeature(features.UnicodeFilenameFeature)
 
186
        tree = self.make_branch_and_tree(".")
 
187
        self.build_tree(["f"])
 
188
        tree.add(["f"])
 
189
        out, err = self.run_bzr_raw(["commit", "-m", "Wrong filename", u"\xa7"],
 
190
                                    encoding="iso-8859-5", retcode=3)
 
191
        if not PY3:
 
192
            self.expectFailure("Error messages are always written as UTF-8",
 
193
                               self.assertNotContainsString, err, b"\xc2\xa7")
 
194
        else:
 
195
            self.assertNotContainsString(err, b"\xc2\xa7")
 
196
        self.assertContainsRe(err, b"(?m)not versioned: \"\xfd\"$")
 
197
 
 
198
    def test_warn_about_forgotten_commit_message(self):
 
199
        """Test that the lack of -m parameter is caught"""
 
200
        wt = self.make_branch_and_tree('.')
 
201
        self.build_tree(['one', 'two'])
 
202
        wt.add(['two'])
 
203
        out, err = self.run_bzr('commit -m one two')
 
204
        self.assertContainsRe(err, "The commit message is a file name")
 
205
 
 
206
    def test_verbose_commit_renamed(self):
 
207
        # Verbose commit of renamed file should say so
 
208
        wt = self.prepare_simple_history()
 
209
        wt.rename_one('hello.txt', 'gutentag.txt')
 
210
        out, err = self.run_bzr('commit -m renamed')
 
211
        self.assertEqual('', out)
 
212
        self.assertContainsRe(err, '^Committing to: .*\n'
 
213
                              'renamed hello\\.txt => gutentag\\.txt\n'
 
214
                              'Committed revision 2\\.$\n')
 
215
 
 
216
    def test_verbose_commit_moved(self):
 
217
        # Verbose commit of file moved to new directory should say so
 
218
        wt = self.prepare_simple_history()
 
219
        os.mkdir('subdir')
 
220
        wt.add(['subdir'])
 
221
        wt.rename_one('hello.txt', 'subdir/hello.txt')
 
222
        out, err = self.run_bzr('commit -m renamed')
 
223
        self.assertEqual('', out)
 
224
        self.assertEqual({
 
225
            'Committing to: %s/' % osutils.getcwd(),
 
226
            'added subdir',
 
227
            'renamed hello.txt => subdir/hello.txt',
 
228
            'Committed revision 2.',
 
229
            '',
 
230
            }, set(err.split('\n')))
 
231
 
 
232
    def test_verbose_commit_with_unknown(self):
 
233
        """Unknown files should not be listed by default in verbose output"""
 
234
        # Is that really the best policy?
 
235
        wt = ControlDir.create_standalone_workingtree('.')
 
236
        self.build_tree(['hello.txt', 'extra.txt'])
 
237
        wt.add(['hello.txt'])
 
238
        out, err = self.run_bzr('commit -m added')
 
239
        self.assertEqual('', out)
 
240
        self.assertContainsRe(err, '^Committing to: .*\n'
 
241
                              'added hello\\.txt\n'
 
242
                              'Committed revision 1\\.\n$')
 
243
 
 
244
    def test_verbose_commit_with_unchanged(self):
 
245
        """Unchanged files should not be listed by default in verbose output"""
 
246
        tree = self.make_branch_and_tree('.')
 
247
        self.build_tree(['hello.txt', 'unchanged.txt'])
 
248
        tree.add('unchanged.txt')
 
249
        self.run_bzr('commit -m unchanged unchanged.txt')
 
250
        tree.add("hello.txt")
 
251
        out, err = self.run_bzr('commit -m added')
 
252
        self.assertEqual('', out)
 
253
        self.assertContainsRe(err, '^Committing to: .*\n'
 
254
                              'added hello\\.txt\n'
 
255
                              'Committed revision 2\\.$\n')
 
256
 
 
257
    def test_verbose_commit_includes_master_location(self):
 
258
        """Location of master is displayed when committing to bound branch"""
 
259
        a_tree = self.make_branch_and_tree('a')
 
260
        self.build_tree(['a/b'])
 
261
        a_tree.add('b')
 
262
        a_tree.commit(message='Initial message')
 
263
 
 
264
        b_tree = a_tree.branch.create_checkout('b')
 
265
        expected = "%s/" % (osutils.abspath('a'), )
 
266
        out, err = self.run_bzr('commit -m blah --unchanged', working_dir='b')
 
267
        self.assertEqual(err, 'Committing to: %s\n'
 
268
                         'Committed revision 2.\n' % expected)
 
269
 
 
270
    def test_commit_sanitizes_CR_in_message(self):
 
271
        # See bug #433779, basically Emacs likes to pass '\r\n' style line
 
272
        # endings to 'brz commit -m ""' which breaks because we don't allow
 
273
        # '\r' in commit messages. (Mostly because of issues where XML style
 
274
        # formats arbitrarily strip it out of the data while parsing.)
 
275
        # To make life easier for users, we just always translate '\r\n' =>
 
276
        # '\n'. And '\r' => '\n'.
 
277
        a_tree = self.make_branch_and_tree('a')
 
278
        self.build_tree(['a/b'])
 
279
        a_tree.add('b')
 
280
        self.run_bzr(['commit',
 
281
                      '-m', 'a string\r\n\r\nwith mixed\r\rendings\n'],
 
282
                     working_dir='a')
 
283
        rev_id = a_tree.branch.last_revision()
 
284
        rev = a_tree.branch.repository.get_revision(rev_id)
 
285
        self.assertEqualDiff('a string\n\nwith mixed\n\nendings\n',
 
286
                             rev.message)
 
287
 
 
288
    def test_commit_merge_reports_all_modified_files(self):
 
289
        # the commit command should show all the files that are shown by
 
290
        # brz diff or brz status when committing, even when they were not
 
291
        # changed by the user but rather through doing a merge.
 
292
        this_tree = self.make_branch_and_tree('this')
 
293
        # we need a bunch of files and dirs, to perform one action on each.
 
294
        self.build_tree([
 
295
            'this/dirtorename/',
 
296
            'this/dirtoreparent/',
 
297
            'this/dirtoleave/',
 
298
            'this/dirtoremove/',
 
299
            'this/filetoreparent',
 
300
            'this/filetorename',
 
301
            'this/filetomodify',
 
302
            'this/filetoremove',
 
303
            'this/filetoleave']
 
304
            )
 
305
        this_tree.add([
 
306
            'dirtorename',
 
307
            'dirtoreparent',
 
308
            'dirtoleave',
 
309
            'dirtoremove',
 
310
            'filetoreparent',
 
311
            'filetorename',
 
312
            'filetomodify',
 
313
            'filetoremove',
 
314
            'filetoleave']
 
315
            )
 
316
        this_tree.commit('create_files')
 
317
        other_dir = this_tree.controldir.sprout('other')
 
318
        other_tree = other_dir.open_workingtree()
 
319
        other_tree.lock_write()
 
320
        # perform the needed actions on the files and dirs.
 
321
        try:
 
322
            other_tree.rename_one('dirtorename', 'renameddir')
 
323
            other_tree.rename_one('dirtoreparent', 'renameddir/reparenteddir')
 
324
            other_tree.rename_one('filetorename', 'renamedfile')
 
325
            other_tree.rename_one('filetoreparent',
 
326
                                  'renameddir/reparentedfile')
 
327
            other_tree.remove(['dirtoremove', 'filetoremove'])
 
328
            self.build_tree_contents([
 
329
                ('other/newdir/',),
 
330
                ('other/filetomodify', b'new content'),
 
331
                ('other/newfile', b'new file content')])
 
332
            other_tree.add('newfile')
 
333
            other_tree.add('newdir/')
 
334
            other_tree.commit('modify all sample files and dirs.')
 
335
        finally:
 
336
            other_tree.unlock()
 
337
        this_tree.merge_from_branch(other_tree.branch)
 
338
        out, err = self.run_bzr('commit -m added', working_dir='this')
 
339
        self.assertEqual('', out)
 
340
        self.assertEqual({
 
341
            'Committing to: %s/' % osutils.pathjoin(osutils.getcwd(), 'this'),
 
342
            'modified filetomodify',
 
343
            'added newdir',
 
344
            'added newfile',
 
345
            'renamed dirtorename => renameddir',
 
346
            'renamed filetorename => renamedfile',
 
347
            'renamed dirtoreparent => renameddir/reparenteddir',
 
348
            'renamed filetoreparent => renameddir/reparentedfile',
 
349
            'deleted dirtoremove',
 
350
            'deleted filetoremove',
 
351
            'Committed revision 2.',
 
352
            ''
 
353
            }, set(err.split('\n')))
 
354
 
 
355
    def test_empty_commit_message(self):
 
356
        tree = self.make_branch_and_tree('.')
 
357
        self.build_tree_contents([('foo.c', b'int main() {}')])
 
358
        tree.add('foo.c')
 
359
        self.run_bzr('commit -m ""')
 
360
 
 
361
    def test_other_branch_commit(self):
 
362
        # this branch is to ensure consistent behaviour, whether we're run
 
363
        # inside a branch, or not.
 
364
        outer_tree = self.make_branch_and_tree('.')
 
365
        inner_tree = self.make_branch_and_tree('branch')
 
366
        self.build_tree_contents([
 
367
            ('branch/foo.c', b'int main() {}'),
 
368
            ('branch/bar.c', b'int main() {}')])
 
369
        inner_tree.add(['foo.c', 'bar.c'])
 
370
        # can't commit files in different trees; sane error
 
371
        self.run_bzr('commit -m newstuff branch/foo.c .', retcode=3)
 
372
        # can commit to branch - records foo.c only
 
373
        self.run_bzr('commit -m newstuff branch/foo.c')
 
374
        # can commit to branch - records bar.c
 
375
        self.run_bzr('commit -m newstuff branch')
 
376
        # No changes left
 
377
        self.run_bzr_error(["No changes to commit"],
 
378
                           'commit -m newstuff branch')
 
379
 
 
380
    def test_out_of_date_tree_commit(self):
 
381
        # check we get an error code and a clear message committing with an out
 
382
        # of date checkout
 
383
        tree = self.make_branch_and_tree('branch')
 
384
        # make a checkout
 
385
        checkout = tree.branch.create_checkout('checkout', lightweight=True)
 
386
        # commit to the original branch to make the checkout out of date
 
387
        tree.commit('message branch', allow_pointless=True)
 
388
        # now commit to the checkout should emit
 
389
        # ERROR: Out of date with the branch, 'brz update' is suggested
 
390
        output = self.run_bzr('commit --unchanged -m checkout_message '
 
391
                              'checkout', retcode=3)
 
392
        self.assertEqual(output,
 
393
                         ('',
 
394
                          "brz: ERROR: Working tree is out of date, please "
 
395
                          "run 'brz update'.\n"))
 
396
 
 
397
    def test_local_commit_unbound(self):
 
398
        # a --local commit on an unbound branch is an error
 
399
        self.make_branch_and_tree('.')
 
400
        out, err = self.run_bzr('commit --local', retcode=3)
 
401
        self.assertEqualDiff('', out)
 
402
        self.assertEqualDiff('brz: ERROR: Cannot perform local-only commits '
 
403
                             'on unbound branches.\n', err)
 
404
 
 
405
    def test_commit_a_text_merge_in_a_checkout(self):
 
406
        # checkouts perform multiple actions in a transaction across bond
 
407
        # branches and their master, and have been observed to fail in the
 
408
        # past. This is a user story reported to fail in bug #43959 where
 
409
        # a merge done in a checkout (using the update command) failed to
 
410
        # commit correctly.
 
411
        trunk = self.make_branch_and_tree('trunk')
 
412
 
 
413
        u1 = trunk.branch.create_checkout('u1')
 
414
        self.build_tree_contents([('u1/hosts', b'initial contents\n')])
 
415
        u1.add('hosts')
 
416
        self.run_bzr('commit -m add-hosts u1')
 
417
 
 
418
        u2 = trunk.branch.create_checkout('u2')
 
419
        self.build_tree_contents([('u2/hosts', b'altered in u2\n')])
 
420
        self.run_bzr('commit -m checkin-from-u2 u2')
 
421
 
 
422
        # make an offline commits
 
423
        self.build_tree_contents(
 
424
            [('u1/hosts', b'first offline change in u1\n')])
 
425
        self.run_bzr('commit -m checkin-offline --local u1')
 
426
 
 
427
        # now try to pull in online work from u2, and then commit our offline
 
428
        # work as a merge
 
429
        # retcode 1 as we expect a text conflict
 
430
        self.run_bzr('update u1', retcode=1)
 
431
        self.assertFileEqual(b'''\
 
432
<<<<<<< TREE
 
433
first offline change in u1
 
434
=======
 
435
altered in u2
 
436
>>>>>>> MERGE-SOURCE
 
437
''',
 
438
                             'u1/hosts')
 
439
 
 
440
        self.run_bzr('resolved u1/hosts')
 
441
        # add a text change here to represent resolving the merge conflicts in
 
442
        # favour of a new version of the file not identical to either the u1
 
443
        # version or the u2 version.
 
444
        self.build_tree_contents([('u1/hosts', b'merge resolution\n')])
 
445
        self.run_bzr('commit -m checkin-merge-of-the-offline-work-from-u1 u1')
 
446
 
 
447
    def test_commit_exclude_excludes_modified_files(self):
 
448
        """Commit -x foo should ignore changes to foo."""
 
449
        tree = self.make_branch_and_tree('.')
 
450
        self.build_tree(['a', 'b', 'c'])
 
451
        tree.smart_add(['.'])
 
452
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b'])
 
453
        self.assertFalse('added b' in out)
 
454
        self.assertFalse('added b' in err)
 
455
        # If b was excluded it will still be 'added' in status.
 
456
        out, err = self.run_bzr(['added'])
 
457
        self.assertEqual('b\n', out)
 
458
        self.assertEqual('', err)
 
459
 
 
460
    def test_commit_exclude_twice_uses_both_rules(self):
 
461
        """Commit -x foo -x bar should ignore changes to foo and bar."""
 
462
        tree = self.make_branch_and_tree('.')
 
463
        self.build_tree(['a', 'b', 'c'])
 
464
        tree.smart_add(['.'])
 
465
        out, err = self.run_bzr(['commit', '-m', 'test', '-x', 'b', '-x', 'c'])
 
466
        self.assertFalse('added b' in out)
 
467
        self.assertFalse('added c' in out)
 
468
        self.assertFalse('added b' in err)
 
469
        self.assertFalse('added c' in err)
 
470
        # If b was excluded it will still be 'added' in status.
 
471
        out, err = self.run_bzr(['added'])
 
472
        self.assertTrue('b\n' in out)
 
473
        self.assertTrue('c\n' in out)
 
474
        self.assertEqual('', err)
 
475
 
 
476
    def test_commit_respects_spec_for_removals(self):
 
477
        """Commit with a file spec should only commit removals that match"""
 
478
        t = self.make_branch_and_tree('.')
 
479
        self.build_tree(['file-a', 'dir-a/', 'dir-a/file-b'])
 
480
        t.add(['file-a', 'dir-a', 'dir-a/file-b'])
 
481
        t.commit('Create')
 
482
        t.remove(['file-a', 'dir-a/file-b'])
 
483
        result = self.run_bzr('commit . -m removed-file-b',
 
484
                              working_dir='dir-a')[1]
 
485
        self.assertNotContainsRe(result, 'file-a')
 
486
        result = self.run_bzr('status', working_dir='dir-a')[0]
 
487
        self.assertContainsRe(result, 'removed:\n  file-a')
 
488
 
 
489
    def test_strict_commit(self):
 
490
        """Commit with --strict works if everything is known"""
 
491
        ignores._set_user_ignores([])
 
492
        tree = self.make_branch_and_tree('tree')
 
493
        self.build_tree(['tree/a'])
 
494
        tree.add('a')
 
495
        # A simple change should just work
 
496
        self.run_bzr('commit --strict -m adding-a', working_dir='tree')
 
497
 
 
498
    def test_strict_commit_no_changes(self):
 
499
        """commit --strict gives "no changes" if there is nothing to commit"""
 
500
        tree = self.make_branch_and_tree('tree')
 
501
        self.build_tree(['tree/a'])
 
502
        tree.add('a')
 
503
        tree.commit('adding a')
 
504
 
 
505
        # With no changes, it should just be 'no changes'
 
506
        # Make sure that commit is failing because there is nothing to do
 
507
        self.run_bzr_error(['No changes to commit'],
 
508
                           'commit --strict -m no-changes',
 
509
                           working_dir='tree')
 
510
 
 
511
        # But --strict doesn't care if you supply --unchanged
 
512
        self.run_bzr('commit --strict --unchanged -m no-changes',
 
513
                     working_dir='tree')
 
514
 
 
515
    def test_strict_commit_unknown(self):
 
516
        """commit --strict fails if a file is unknown"""
 
517
        tree = self.make_branch_and_tree('tree')
 
518
        self.build_tree(['tree/a'])
 
519
        tree.add('a')
 
520
        tree.commit('adding a')
 
521
 
 
522
        # Add one file so there is a change, but forget the other
 
523
        self.build_tree(['tree/b', 'tree/c'])
 
524
        tree.add('b')
 
525
        self.run_bzr_error(['Commit refused because there are unknown files'],
 
526
                           'commit --strict -m add-b',
 
527
                           working_dir='tree')
 
528
 
 
529
        # --no-strict overrides --strict
 
530
        self.run_bzr('commit --strict -m add-b --no-strict',
 
531
                     working_dir='tree')
 
532
 
 
533
    def test_fixes_bug_output(self):
 
534
        """commit --fixes=lp:23452 succeeds without output."""
 
535
        tree = self.make_branch_and_tree('tree')
 
536
        self.build_tree(['tree/hello.txt'])
 
537
        tree.add('hello.txt')
 
538
        output, err = self.run_bzr(
 
539
            'commit -m hello --fixes=lp:23452 tree/hello.txt')
 
540
        self.assertEqual('', output)
 
541
        self.assertContainsRe(err, 'Committing to: .*\n'
 
542
                              'added hello\\.txt\n'
 
543
                              'Committed revision 1\\.\n')
 
544
 
 
545
    def test_fixes_bug_unicode(self):
 
546
        """commit --fixes=lp:unicode succeeds without output."""
 
547
        tree = self.make_branch_and_tree('tree')
 
548
        self.build_tree(['tree/hello.txt'])
 
549
        tree.add('hello.txt')
 
550
        output, err = self.run_bzr_raw(
 
551
            ['commit', '-m', 'hello',
 
552
             u'--fixes=generic:\u20ac', 'tree/hello.txt'],
 
553
            encoding='utf-8', retcode=3)
 
554
        self.assertEqual(b'', output)
 
555
        self.assertContainsRe(err,
 
556
                              b'brz: ERROR: Unrecognized bug generic:\xe2\x82\xac\\. Commit refused.\n')
 
557
 
 
558
    def test_no_bugs_no_properties(self):
 
559
        """If no bugs are fixed, the bugs property is not set.
 
560
 
 
561
        see https://beta.launchpad.net/bzr/+bug/109613
 
562
        """
 
563
        tree = self.make_branch_and_tree('tree')
 
564
        self.build_tree(['tree/hello.txt'])
 
565
        tree.add('hello.txt')
 
566
        self.run_bzr('commit -m hello tree/hello.txt')
 
567
        # Get the revision properties, ignoring the branch-nick property, which
 
568
        # we don't care about for this test.
 
569
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
570
        properties = dict(last_rev.properties)
 
571
        del properties['branch-nick']
 
572
        self.assertFalse('bugs' in properties)
 
573
 
 
574
    def test_bugs_sets_property(self):
 
575
        """commit --bugs=lp:234 sets the lp:234 revprop to 'related'."""
 
576
        tree = self.make_branch_and_tree('tree')
 
577
        self.build_tree(['tree/hello.txt'])
 
578
        tree.add('hello.txt')
 
579
        self.run_bzr('commit -m hello --bugs=lp:234 tree/hello.txt')
 
580
 
 
581
        # Get the revision properties, ignoring the branch-nick property, which
 
582
        # we don't care about for this test.
 
583
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
584
        properties = dict(last_rev.properties)
 
585
        del properties[u'branch-nick']
 
586
 
 
587
        self.assertEqual({u'bugs': 'https://launchpad.net/bugs/234 related'},
 
588
                         properties)
 
589
 
 
590
    def test_fixes_bug_sets_property(self):
 
591
        """commit --fixes=lp:234 sets the lp:234 revprop to 'fixed'."""
 
592
        tree = self.make_branch_and_tree('tree')
 
593
        self.build_tree(['tree/hello.txt'])
 
594
        tree.add('hello.txt')
 
595
        self.run_bzr('commit -m hello --fixes=lp:234 tree/hello.txt')
 
596
 
 
597
        # Get the revision properties, ignoring the branch-nick property, which
 
598
        # we don't care about for this test.
 
599
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
600
        properties = dict(last_rev.properties)
 
601
        del properties[u'branch-nick']
 
602
 
 
603
        self.assertEqual({u'bugs': 'https://launchpad.net/bugs/234 fixed'},
 
604
                         properties)
 
605
 
 
606
    def test_fixes_multiple_bugs_sets_properties(self):
 
607
        """--fixes can be used more than once to show that bugs are fixed."""
 
608
        tree = self.make_branch_and_tree('tree')
 
609
        self.build_tree(['tree/hello.txt'])
 
610
        tree.add('hello.txt')
 
611
        self.run_bzr('commit -m hello --fixes=lp:123 --fixes=lp:235'
 
612
                     ' tree/hello.txt')
 
613
 
 
614
        # Get the revision properties, ignoring the branch-nick property, which
 
615
        # we don't care about for this test.
 
616
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
617
        properties = dict(last_rev.properties)
 
618
        del properties['branch-nick']
 
619
 
 
620
        self.assertEqual(
 
621
            {u'bugs': 'https://launchpad.net/bugs/123 fixed\n'
 
622
             'https://launchpad.net/bugs/235 fixed'},
 
623
            properties)
 
624
 
 
625
    def test_fixes_bug_with_alternate_trackers(self):
 
626
        """--fixes can be used on a properly configured branch to mark bug
 
627
        fixes on multiple trackers.
 
628
        """
 
629
        tree = self.make_branch_and_tree('tree')
 
630
        tree.branch.get_config().set_user_option(
 
631
            'trac_twisted_url', 'http://twistedmatrix.com/trac')
 
632
        self.build_tree(['tree/hello.txt'])
 
633
        tree.add('hello.txt')
 
634
        self.run_bzr(
 
635
            'commit -m hello --fixes=lp:123 --fixes=twisted:235 tree/')
 
636
 
 
637
        # Get the revision properties, ignoring the branch-nick property, which
 
638
        # we don't care about for this test.
 
639
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
640
        properties = dict(last_rev.properties)
 
641
        del properties['branch-nick']
 
642
 
 
643
        self.assertEqual(
 
644
            {'bugs': 'https://launchpad.net/bugs/123 fixed\n'
 
645
                     'http://twistedmatrix.com/trac/ticket/235 fixed'},
 
646
            properties)
 
647
 
 
648
    def test_fixes_unknown_bug_prefix(self):
 
649
        tree = self.make_branch_and_tree('tree')
 
650
        self.build_tree(['tree/hello.txt'])
 
651
        tree.add('hello.txt')
 
652
        self.run_bzr_error(
 
653
            ["Unrecognized bug %s. Commit refused." % 'xxx:123'],
 
654
            'commit -m add-b --fixes=xxx:123',
 
655
            working_dir='tree')
 
656
 
 
657
    def test_fixes_bug_with_default_tracker(self):
 
658
        """commit --fixes=234 uses the default bug tracker."""
 
659
        tree = self.make_branch_and_tree('tree')
 
660
        self.build_tree(['tree/hello.txt'])
 
661
        tree.add('hello.txt')
 
662
        self.run_bzr_error(
 
663
            ["brz: ERROR: No tracker specified for bug 123. Use the form "
 
664
             "'tracker:id' or specify a default bug tracker using the "
 
665
             "`bugtracker` option.\n"
 
666
             "See \"brz help bugs\" for more information on this feature. "
 
667
             "Commit refused."],
 
668
            'commit -m add-b --fixes=123',
 
669
            working_dir='tree')
 
670
        tree.branch.get_config_stack().set("bugtracker", "lp")
 
671
        self.run_bzr('commit -m hello --fixes=234 tree/hello.txt')
 
672
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
673
        self.assertEqual('https://launchpad.net/bugs/234 fixed',
 
674
                         last_rev.properties['bugs'])
 
675
 
 
676
    def test_fixes_invalid_bug_number(self):
 
677
        tree = self.make_branch_and_tree('tree')
 
678
        self.build_tree(['tree/hello.txt'])
 
679
        tree.add('hello.txt')
 
680
        self.run_bzr_error(
 
681
            ["Did not understand bug identifier orange: Must be an integer. "
 
682
             "See \"brz help bugs\" for more information on this feature.\n"
 
683
             "Commit refused."],
 
684
            'commit -m add-b --fixes=lp:orange',
 
685
            working_dir='tree')
 
686
 
 
687
    def test_fixes_invalid_argument(self):
 
688
        """Raise an appropriate error when the fixes argument isn't tag:id."""
 
689
        tree = self.make_branch_and_tree('tree')
 
690
        self.build_tree(['tree/hello.txt'])
 
691
        tree.add('hello.txt')
 
692
        self.run_bzr_error(
 
693
            [r"Invalid bug orange:apples:bananas. Must be in the form of "
 
694
             r"'tracker:id'\. See \"brz help bugs\" for more information on "
 
695
             r"this feature.\nCommit refused\."],
 
696
            'commit -m add-b --fixes=orange:apples:bananas',
 
697
            working_dir='tree')
 
698
 
 
699
    def test_no_author(self):
 
700
        """If the author is not specified, the author property is not set."""
 
701
        tree = self.make_branch_and_tree('tree')
 
702
        self.build_tree(['tree/hello.txt'])
 
703
        tree.add('hello.txt')
 
704
        self.run_bzr('commit -m hello tree/hello.txt')
 
705
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
706
        properties = last_rev.properties
 
707
        self.assertFalse('author' in properties)
 
708
 
 
709
    def test_author_sets_property(self):
 
710
        """commit --author='John Doe <jdoe@example.com>' sets the author
 
711
           revprop.
 
712
        """
 
713
        tree = self.make_branch_and_tree('tree')
 
714
        self.build_tree(['tree/hello.txt'])
 
715
        tree.add('hello.txt')
 
716
        self.run_bzr(["commit", '-m', 'hello',
 
717
                      '--author', u'John D\xf6 <jdoe@example.com>',
 
718
                      "tree/hello.txt"])
 
719
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
720
        properties = last_rev.properties
 
721
        self.assertEqual(u'John D\xf6 <jdoe@example.com>',
 
722
                         properties['authors'])
 
723
 
 
724
    def test_author_no_email(self):
 
725
        """Author's name without an email address is allowed, too."""
 
726
        tree = self.make_branch_and_tree('tree')
 
727
        self.build_tree(['tree/hello.txt'])
 
728
        tree.add('hello.txt')
 
729
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
 
730
                                "tree/hello.txt")
 
731
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
732
        properties = last_rev.properties
 
733
        self.assertEqual('John Doe', properties['authors'])
 
734
 
 
735
    def test_multiple_authors(self):
 
736
        """Multiple authors can be specyfied, and all are stored."""
 
737
        tree = self.make_branch_and_tree('tree')
 
738
        self.build_tree(['tree/hello.txt'])
 
739
        tree.add('hello.txt')
 
740
        out, err = self.run_bzr("commit -m hello --author='John Doe' "
 
741
                                "--author='Jane Rey' tree/hello.txt")
 
742
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
743
        properties = last_rev.properties
 
744
        self.assertEqual('John Doe\nJane Rey', properties['authors'])
 
745
 
 
746
    def test_commit_time(self):
 
747
        tree = self.make_branch_and_tree('tree')
 
748
        self.build_tree(['tree/hello.txt'])
 
749
        tree.add('hello.txt')
 
750
        out, err = self.run_bzr("commit -m hello "
 
751
                                "--commit-time='2009-10-10 08:00:00 +0100' tree/hello.txt")
 
752
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
753
        self.assertEqual(
 
754
            'Sat 2009-10-10 08:00:00 +0100',
 
755
            osutils.format_date(last_rev.timestamp, last_rev.timezone))
 
756
 
 
757
    def test_commit_time_bad_time(self):
 
758
        tree = self.make_branch_and_tree('tree')
 
759
        self.build_tree(['tree/hello.txt'])
 
760
        tree.add('hello.txt')
 
761
        out, err = self.run_bzr("commit -m hello "
 
762
                                "--commit-time='NOT A TIME' tree/hello.txt", retcode=3)
 
763
        self.assertStartsWith(
 
764
            err, "brz: ERROR: Could not parse --commit-time:")
 
765
 
 
766
    def test_commit_time_missing_tz(self):
 
767
        tree = self.make_branch_and_tree('tree')
 
768
        self.build_tree(['tree/hello.txt'])
 
769
        tree.add('hello.txt')
 
770
        out, err = self.run_bzr("commit -m hello "
 
771
                                "--commit-time='2009-10-10 08:00:00' tree/hello.txt", retcode=3)
 
772
        self.assertStartsWith(
 
773
            err, "brz: ERROR: Could not parse --commit-time:")
 
774
        # Test that it is actually checking and does not simply crash with
 
775
        # some other exception
 
776
        self.assertContainsString(err, "missing a timezone offset")
 
777
 
 
778
    def test_partial_commit_with_renames_in_tree(self):
 
779
        # this test illustrates bug #140419
 
780
        t = self.make_branch_and_tree('.')
 
781
        self.build_tree(['dir/', 'dir/a', 'test'])
 
782
        t.add(['dir/', 'dir/a', 'test'])
 
783
        t.commit('initial commit')
 
784
        # important part: file dir/a should change parent
 
785
        # and should appear before old parent
 
786
        # then during partial commit we have error
 
787
        # parent_id {dir-XXX} not in inventory
 
788
        t.rename_one('dir/a', 'a')
 
789
        self.build_tree_contents([('test', b'changes in test')])
 
790
        # partial commit
 
791
        out, err = self.run_bzr('commit test -m "partial commit"')
 
792
        self.assertEqual('', out)
 
793
        self.assertContainsRe(err, r'modified test\nCommitted revision 2.')
 
794
 
 
795
    def test_commit_readonly_checkout(self):
 
796
        # https://bugs.launchpad.net/bzr/+bug/129701
 
797
        # "UnlockableTransport error trying to commit in checkout of readonly
 
798
        # branch"
 
799
        self.make_branch('master')
 
800
        master = ControlDir.open_from_transport(
 
801
            self.get_readonly_transport('master')).open_branch()
 
802
        master.create_checkout('checkout')
 
803
        out, err = self.run_bzr(['commit', '--unchanged', '-mfoo', 'checkout'],
 
804
                                retcode=3)
 
805
        self.assertContainsRe(err,
 
806
                              r'^brz: ERROR: Cannot lock.*readonly transport')
 
807
 
 
808
    def setup_editor(self):
 
809
        # Test that commit template hooks work
 
810
        if sys.platform == "win32":
 
811
            with open('fed.bat', 'w') as f:
 
812
                f.write('@rem dummy fed')
 
813
            self.overrideEnv('BRZ_EDITOR', "fed.bat")
 
814
        else:
 
815
            with open('fed.sh', 'wb') as f:
 
816
                f.write(b'#!/bin/sh\n')
 
817
            os.chmod('fed.sh', 0o755)
 
818
            self.overrideEnv('BRZ_EDITOR', "./fed.sh")
 
819
 
 
820
    def setup_commit_with_template(self):
 
821
        self.setup_editor()
 
822
        msgeditor.hooks.install_named_hook("commit_message_template",
 
823
                                           lambda commit_obj, msg: "save me some typing\n", None)
 
824
        tree = self.make_branch_and_tree('tree')
 
825
        self.build_tree(['tree/hello.txt'])
 
826
        tree.add('hello.txt')
 
827
        return tree
 
828
 
 
829
    def test_edit_empty_message(self):
 
830
        tree = self.make_branch_and_tree('tree')
 
831
        self.setup_editor()
 
832
        self.build_tree(['tree/hello.txt'])
 
833
        tree.add('hello.txt')
 
834
        out, err = self.run_bzr("commit tree/hello.txt", retcode=3,
 
835
                                stdin="y\n")
 
836
        self.assertContainsRe(err,
 
837
                              "brz: ERROR: Empty commit message specified")
 
838
 
 
839
    def test_commit_hook_template_accepted(self):
 
840
        tree = self.setup_commit_with_template()
 
841
        out, err = self.run_bzr("commit tree/hello.txt", stdin="y\n")
 
842
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
843
        self.assertEqual('save me some typing\n', last_rev.message)
 
844
 
 
845
    def test_commit_hook_template_rejected(self):
 
846
        tree = self.setup_commit_with_template()
 
847
        expected = tree.last_revision()
 
848
        out, err = self.run_bzr_error(["Empty commit message specified."
 
849
                                       " Please specify a commit message with either"
 
850
                                       " --message or --file or leave a blank message"
 
851
                                       " with --message \"\"."],
 
852
                                      "commit tree/hello.txt", stdin="n\n")
 
853
        self.assertEqual(expected, tree.last_revision())
 
854
 
 
855
    def test_set_commit_message(self):
 
856
        msgeditor.hooks.install_named_hook("set_commit_message",
 
857
                                           lambda commit_obj, msg: "save me some typing\n", None)
 
858
        tree = self.make_branch_and_tree('tree')
 
859
        self.build_tree(['tree/hello.txt'])
 
860
        tree.add('hello.txt')
 
861
        out, err = self.run_bzr("commit tree/hello.txt")
 
862
        last_rev = tree.branch.repository.get_revision(tree.last_revision())
 
863
        self.assertEqual('save me some typing\n', last_rev.message)
 
864
 
 
865
    def test_commit_without_username(self):
 
866
        """Ensure commit error if username is not set.
 
867
        """
 
868
        self.run_bzr(['init', 'foo'])
 
869
        with open('foo/foo.txt', 'w') as f:
 
870
            f.write('hello')
 
871
        self.run_bzr(['add'], working_dir='foo')
 
872
        override_whoami(self)
 
873
        self.run_bzr_error(
 
874
            ['Unable to determine your name'],
 
875
            ['commit', '-m', 'initial'], working_dir='foo')
 
876
 
 
877
    def test_commit_recursive_checkout(self):
 
878
        """Ensure that a commit to a recursive checkout fails cleanly.
 
879
        """
 
880
        self.run_bzr(['init', 'test_branch'])
 
881
        self.run_bzr(['checkout', 'test_branch', 'test_checkout'])
 
882
        # bind to self
 
883
        self.run_bzr(['bind', '.'], working_dir='test_checkout')
 
884
        with open('test_checkout/foo.txt', 'w') as f:
 
885
            f.write('hello')
 
886
        self.run_bzr(['add'], working_dir='test_checkout')
 
887
        out, err = self.run_bzr_error(
 
888
            ['Branch.*test_checkout.*appears to be bound to itself'],
 
889
            ['commit', '-m', 'addedfoo'], working_dir='test_checkout')
 
890
 
 
891
    def test_mv_dirs_non_ascii(self):
 
892
        """Move directory with non-ascii name and containing files.
 
893
 
 
894
        Regression test for bug 185211.
 
895
        """
 
896
        tree = self.make_branch_and_tree('.')
 
897
        self.build_tree([u'abc\xa7/', u'abc\xa7/foo'])
 
898
 
 
899
        tree.add([u'abc\xa7/', u'abc\xa7/foo'])
 
900
        tree.commit('checkin')
 
901
 
 
902
        tree.rename_one(u'abc\xa7', 'abc')
 
903
 
 
904
        self.run_bzr('ci -m "non-ascii mv"')
 
905
 
 
906
 
 
907
class TestSmartServerCommit(TestCaseWithTransport):
 
908
 
 
909
    def test_commit_to_lightweight(self):
 
910
        self.setup_smart_server_with_call_log()
 
911
        t = self.make_branch_and_tree('from')
 
912
        for count in range(9):
 
913
            t.commit(message='commit %d' % count)
 
914
        out, err = self.run_bzr(['checkout', '--lightweight', self.get_url('from'),
 
915
                                 'target'])
 
916
        self.reset_smart_call_log()
 
917
        self.build_tree(['target/afile'])
 
918
        self.run_bzr(['add', 'target/afile'])
 
919
        out, err = self.run_bzr(['commit', '-m', 'do something', 'target'])
 
920
        # This figure represent the amount of work to perform this use case. It
 
921
        # is entirely ok to reduce this number if a test fails due to rpc_count
 
922
        # being too low. If rpc_count increases, more network roundtrips have
 
923
        # become necessary for this use case. Please do not adjust this number
 
924
        # upwards without agreement from bzr's network support maintainers.
 
925
        self.assertLength(211, self.hpss_calls)
 
926
        self.assertLength(2, self.hpss_connections)
 
927
        self.expectFailure("commit still uses VFS calls",
 
928
                           self.assertThat, self.hpss_calls, ContainsNoVfsCalls)