/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: 2018-07-26 19:15:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7055.
  • Revision ID: jelmer@jelmer.uk-20180726191527-wniq205k6tzfo1xx
Install fastimport from git.

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