/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
1
# Copyright (C) 2008, 2009 Canonical Ltd
0.152.1 by Vincent Ladeuil
Empty shell
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
0.152.6 by Vincent Ladeuil
Really use the transports and test against all targeted protocols.
17
"""Upload a working tree, incrementally.
18
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
19
Quickstart
20
----------
21
22
To get started, it's as simple as running::
23
24
    bzr upload sftp://user@host/location/on/webserver
25
26
This will initially upload the whole working tree, and leave a file on the
27
remote location indicating the last revision that was uploaded
28
(.bzr-upload.revid), in order to avoid uploading unnecessary information the
29
next time.
30
31
If you would like to upload a specific revision, you just do:
32
33
    bzr upload -r X  sftp://user@host/location/on/webserver
34
35
bzr-upload, just as bzr does, will remember the location where you upload the 
36
first time, so you don't need to specify it every time.
37
38
If you need to re-upload the whole working tree for some reason, you can:
39
40
    bzr upload --full sftp://user@host/location/on/webserver
41
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
42
This command only works on the revision beening uploaded is a decendent of the
43
revision that was previously uploaded, and that they are hence from branches
44
that have not diverged. Branches are considered diverged if the destination
45
branch's most recent commit is one that has not been merged (directly or
46
indirectly) by the source branch.
47
48
If branches have diverged, you can use 'bzr upload --overwrite' to replace
49
the other branch completely, discarding its unmerged changes.
50
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
51
52
Automatically Uploading
53
-----------------------
54
55
bzr-upload comes with a hook that can be used to trigger an upload whenever
56
the tip of the branch changes, including on commit, push, uncommit etc. This
57
would allow you to keep the code on the target up to date automatically.
58
59
The easiest way to enable this is to run upload with the --auto option.
60
61
     bzr upload --auto
62
63
will enable the hook for this branch. If you were to do a commit in this branch
64
now you would see it trigger the upload automatically.
65
66
If you wish to disable this for a branch again then you can use the --no-auto
67
option.
68
69
     bzr upload --no-auto
70
71
will disable the feature for that branch.
72
73
Since the auto hook is triggered automatically, you can't use the --quiet
74
option available for the upload command. Instead, you can set the
75
'upload_auto_quiet' configuration variable to True or False in either
76
bazaar.conf, locations.conf or branch.conf.
77
78
79
Storing the '.bzr-upload.revid' file
80
------------------------------------
81
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
82
The only bzr-related info uploaded with the working tree is the corresponding
0.152.6 by Vincent Ladeuil
Really use the transports and test against all targeted protocols.
83
revision id. The uploaded working tree is not linked to any other bzr data.
84
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
85
If the layout of your remote server is such that you can't write in the
86
root directory but only in the directories inside that root, you will need
87
to use the 'upload_revid_location' configuration variable to specify the
88
relative path to be used. That configuration variable can be specified in
89
locations.conf or branch.conf.
90
91
For example, given the following layout:
92
93
  Project/
94
    private/
95
    public/
96
97
you may have write access in 'private' and 'public' but in 'Project'
98
itself. In that case, you can add the following in your locations.conf or
99
branch.conf file:
100
101
  upload_revid_location = private/.bzr-upload.revid
102
103
104
Upload from Remote Location
105
---------------------------
106
107
It is possible to upload to a remote location from another remote location by
108
specifying it with the --directory option:
109
110
    bzr upload ftp://public.example.com --directory sftp://private.example.com 
111
112
This, together with --auto, can be used to upload when you push to your
113
central branch, rather than when you commit to your local branch.
114
115
Note that you will consume more bandwith this way than uploading from a local
116
branch.
117
0.160.5 by Martin Albisetti
Add docs
118
Ignoring certain files
119
-----------------------
120
121
If you want to version a file, but not upload it, you can create a file called
122
.bzrignore-upload, which works in the same way as the regular .bzrignore file,
123
but only applies to bzr-upload.
124
125
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
126
Collaborating
127
-------------
128
129
While we don't have any platform setup, you can branch from trunk:
130
131
    bzr branch lp:bzr-upload
132
0.160.5 by Martin Albisetti
Add docs
133
And change anything you'd like, and file a merge proposal on Launchpad.
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
134
135
136
Known Issues
137
------------
138
139
 * Symlinks are not supported
140
141
0.152.6 by Vincent Ladeuil
Really use the transports and test against all targeted protocols.
142
"""
0.152.1 by Vincent Ladeuil
Empty shell
143
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
144
# TODO: the chmod bits *can* be supported via the upload protocols
145
# (i.e. poorly), but since the web developers use these protocols to upload
146
# manually, it is expected that the associated web server is coherent with
147
# their presence/absence. In other words, if a web hosting provider requires
148
# chmod bits but don't provide an ftp server that support them, well, better
149
# find another provider ;-)
150
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
151
# TODO: The message emitted in verbose mode displays local paths. That may be
152
# scary for the user when we say 'Deleting <path>' and are referring to
153
# remote files...
0.152.19 by Vincent Ladeuil
Handle kind_change. Trivial implementation, blocked by bug #205636.
154
0.152.3 by v.ladeuil+lp at free
Make the tests fail not error out.
155
from bzrlib import (
0.155.2 by James Westby
Add a post_change_branch_tip hook to upload.
156
    branch,
0.152.3 by v.ladeuil+lp at free
Make the tests fail not error out.
157
    commands,
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
158
    lazy_import,
0.152.3 by v.ladeuil+lp at free
Make the tests fail not error out.
159
    option,
160
    )
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
161
lazy_import.lazy_import(globals(), """
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
162
import stat
163
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
164
from bzrlib import (
0.158.1 by Gary van der Merwe
Don't require a working tree.
165
    bzrdir,
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
166
    errors,
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
167
    globbing,
0.160.3 by Martin Albisetti
Start implementing
168
    ignores,
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
169
    revisionspec,
170
    transport,
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
171
    osutils,
0.152.40 by Martin Albisetti
We need to import urlutils if we are going to use it
172
    urlutils,
0.152.27 by Martin Albisetti
* Added error message if the working tree has uncommited changes
173
    workingtree,
0.159.2 by Gary van der Merwe
If there has not been an upload, treat the uploaded revid as revision.NULL_REVISION. This enables this request to be cached.
174
    revision
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
175
    )
176
""")
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
177
0.152.54 by Vincent Ladeuil
Let's start dev for a 1.0.
178
version_info = (1, 0, 0, 'dev', 0)
0.152.23 by Martin Albisetti
Added version_info and plugin_name
179
plugin_name = 'upload'
180
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
181
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
182
def _get_branch_option(branch, option):
183
    return branch.get_config().get_user_option(option)
184
0.152.64 by Vincent Ladeuil
Fix compatibility with bzr.
185
# FIXME: Get rid of that as soon as we depend on a bzr API that includes
186
# get_user_option_as_bool
187
def _get_branch_bool_option(branch, option):
188
    conf = branch.get_config()
189
    if hasattr(conf, 'get_user_option_as_bool'):
190
        value = conf.get_user_option_as_bool(option)
191
    else:
192
        value = conf.get_user_option(option)
193
        if value is not None:
194
            if value.lower().strip() == 'true':
195
                value = True
196
            else:
197
                value = False
198
    return value
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
199
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
200
def _set_branch_option(branch, option, value):
201
    branch.get_config().set_user_option(option, value)
202
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
203
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
204
def get_upload_location(branch):
205
    return _get_branch_option(branch, 'upload_location')
206
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
207
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
208
def set_upload_location(branch, location):
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
209
    _set_branch_option(branch, 'upload_location', location)
210
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
211
0.152.62 by Vincent Ladeuil
Fix bug #423331 by adding a way to configure the path used to
212
# FIXME: Add more tests around invalid paths used here or relative paths that
213
# doesn't exist on remote (if only to get proper error messages)
214
def get_upload_revid_location(branch):
215
    loc =  _get_branch_option(branch, 'upload_revid_location')
216
    if loc is None:
217
        loc = '.bzr-upload.revid'
218
    return loc
219
220
221
def set_upload_revid_location(branch, location):
222
    _set_branch_option(branch, 'upload_revid_location', location)
223
224
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
225
def get_upload_auto(branch):
0.152.64 by Vincent Ladeuil
Fix compatibility with bzr.
226
    auto = _get_branch_bool_option(branch, 'upload_auto')
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
227
    if auto is None:
228
        auto = False # Default to False if not specified
229
    return auto
230
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
231
232
def set_upload_auto(branch, auto):
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
233
    # FIXME: What's the point in allowing a boolean here instead of requiring
234
    # the callers to use strings instead ?
0.155.3 by James Westby
Add some tests for the hook, rename the option to "upload_auto"
235
    if auto:
236
        auto_str = "True"
237
    else:
238
        auto_str = "False"
239
    _set_branch_option(branch, 'upload_auto', auto_str)
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
240
241
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
242
def get_upload_auto_quiet(branch):
0.152.64 by Vincent Ladeuil
Fix compatibility with bzr.
243
    quiet = _get_branch_bool_option(branch, 'upload_auto_quiet')
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
244
    if quiet is None:
245
        quiet = False # Default to False if not specified
246
    return quiet
247
248
249
def set_upload_auto_quiet(branch, quiet):
250
    _set_branch_option(branch, 'upload_auto_quiet', quiet)
251
252
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
253
class BzrUploader(object):
254
255
    def __init__(self, branch, to_transport, outf, tree, rev_id,
0.152.62 by Vincent Ladeuil
Fix bug #423331 by adding a way to configure the path used to
256
                 quiet=False):
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
257
        self.branch = branch
258
        self.to_transport = to_transport
259
        self.outf = outf
260
        self.tree = tree
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
261
        self.rev_id = rev_id
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
262
        self.quiet = quiet
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
263
        self._pending_deletions = []
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
264
        self._pending_renames = []
0.159.1 by Gary van der Merwe
Cache the uploaded_revid, so that we can query it more that once, with out having to worry about extra network calls.
265
        self._uploaded_revid = None
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
266
        self._ignored = None
0.152.12 by Vincent Ladeuil
Implement 'upload_location' in config files.
267
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
268
    def _up_stat(self, relpath):
269
        return self.to_transport.stat(urlutils.escape(relpath))
270
271
    def _up_rename(self, old_path, new_path):
272
        return self.to_transport.rename(urlutils.escape(old_path),
273
                                        urlutils.escape(new_path))
274
275
    def _up_delete(self, relpath):
276
        return self.to_transport.delete(urlutils.escape(relpath))
277
278
    def _up_delete_tree(self, relpath):
279
        return self.to_transport.delete_tree(urlutils.escape(relpath))
280
281
    def _up_mkdir(self, relpath, mode):
282
        return self.to_transport.mkdir(urlutils.escape(relpath), mode)
283
284
    def _up_rmdir(self, relpath):
285
        return self.to_transport.rmdir(urlutils.escape(relpath))
286
287
    def _up_put_bytes(self, relpath, bytes, mode):
288
        self.to_transport.put_bytes(urlutils.escape(relpath), bytes, mode)
289
290
    def _up_get_bytes(self, relpath):
291
        return self.to_transport.get_bytes(urlutils.escape(relpath))
292
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
293
    def set_uploaded_revid(self, rev_id):
0.152.10 by Vincent Ladeuil
Fix incremental upload cheat.
294
        # XXX: Add tests for concurrent updates, etc.
0.152.62 by Vincent Ladeuil
Fix bug #423331 by adding a way to configure the path used to
295
        revid_path = get_upload_revid_location(self.branch)
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
296
        self.to_transport.put_bytes(urlutils.escape(revid_path), rev_id)
0.159.1 by Gary van der Merwe
Cache the uploaded_revid, so that we can query it more that once, with out having to worry about extra network calls.
297
        self._uploaded_revid = rev_id
0.152.10 by Vincent Ladeuil
Fix incremental upload cheat.
298
299
    def get_uploaded_revid(self):
0.159.1 by Gary van der Merwe
Cache the uploaded_revid, so that we can query it more that once, with out having to worry about extra network calls.
300
        if self._uploaded_revid is None:
301
            revid_path = get_upload_revid_location(self.branch)
0.159.2 by Gary van der Merwe
If there has not been an upload, treat the uploaded revid as revision.NULL_REVISION. This enables this request to be cached.
302
            try:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
303
                self._uploaded_revid = self._up_get_bytes(revid_path)
0.159.2 by Gary van der Merwe
If there has not been an upload, treat the uploaded revid as revision.NULL_REVISION. This enables this request to be cached.
304
            except errors.NoSuchFile:
305
                # We have not upload to here.
306
                self._uploaded_revid = revision.NULL_REVISION
0.159.1 by Gary van der Merwe
Cache the uploaded_revid, so that we can query it more that once, with out having to worry about extra network calls.
307
        return self._uploaded_revid
0.152.7 by Vincent Ladeuil
Slight refactoring.
308
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
309
    def _get_ignored(self):
310
        if self._ignored is None:
311
            try:
312
                ignore_file = self.tree.get_file_by_path('.bzrignore-upload')
313
                ignored_patterns = ignores.parse_ignore_file(ignore_file)
314
            except errors.NoSuchId:
315
                ignored_patterns = []
316
            self._ignored = globbing.Globster(ignored_patterns)
317
        return self._ignored
318
319
    def is_ignored(self, relpath):
320
        glob = self._get_ignored()
321
        ignored = glob.match(relpath)
322
        import os
323
        if not ignored:
324
            # We still need to check that all parents are not ignored
325
            dir = os.path.dirname(relpath)
326
            while dir and not ignored:
327
                ignored = glob.match(dir)
328
                if not ignored:
329
                    dir = os.path.dirname(dir)
330
        return ignored
0.160.3 by Martin Albisetti
Start implementing
331
0.152.46 by Vincent Ladeuil
Handle x mode bit for files and provides default mode bits for
332
    def upload_file(self, relpath, id, mode=None):
0.161.5 by Vincent Ladeuil
Cleanup.
333
        if mode is None:
334
            if self.tree.is_executable(id):
335
                mode = 0775
336
            else:
337
                mode = 0664
338
        if not self.quiet:
339
            self.outf.write('Uploading %s\n' % relpath)
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
340
        self._up_put_bytes(relpath, self.tree.get_file_text(id), mode)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
341
0.152.46 by Vincent Ladeuil
Handle x mode bit for files and provides default mode bits for
342
    def upload_file_robustly(self, relpath, id, mode=None):
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
343
        """Upload a file, clearing the way on the remote side.
344
345
        When doing a full upload, it may happen that a directory exists where
346
        we want to put our file.
347
        """
348
        try:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
349
            st = self._up_stat(relpath)
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
350
            if stat.S_ISDIR(st.st_mode):
351
                # A simple rmdir may not be enough
352
                if not self.quiet:
353
                    self.outf.write('Clearing %s/%s\n' % (
354
                            self.to_transport.external_url(), relpath))
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
355
                self._up_delete_tree(relpath)
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
356
        except errors.PathError:
357
            pass
0.152.46 by Vincent Ladeuil
Handle x mode bit for files and provides default mode bits for
358
        self.upload_file(relpath, id, mode)
359
360
    def make_remote_dir(self, relpath, mode=None):
0.161.5 by Vincent Ladeuil
Cleanup.
361
        if mode is None:
362
            mode = 0775
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
363
        self._up_mkdir(relpath, mode)
0.152.46 by Vincent Ladeuil
Handle x mode bit for files and provides default mode bits for
364
365
    def make_remote_dir_robustly(self, relpath, mode=None):
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
366
        """Create a remote directory, clearing the way on the remote side.
367
368
        When doing a full upload, it may happen that a file exists where we
369
        want to create our directory.
370
        """
371
        try:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
372
            st = self._up_stat(relpath)
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
373
            if not stat.S_ISDIR(st.st_mode):
374
                if not self.quiet:
375
                    self.outf.write('Deleting %s/%s\n' % (
376
                            self.to_transport.external_url(), relpath))
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
377
                self._up_delete(relpath)
0.152.47 by Vincent Ladeuil
Don't fail a full upload on an already existing dir.
378
            else:
379
                # Ok the remote dir already exists, nothing to do
380
                return
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
381
        except errors.PathError:
382
            pass
0.152.46 by Vincent Ladeuil
Handle x mode bit for files and provides default mode bits for
383
        self.make_remote_dir(relpath, mode)
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
384
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
385
    def delete_remote_file(self, relpath):
0.161.5 by Vincent Ladeuil
Cleanup.
386
        if not self.quiet:
387
            self.outf.write('Deleting %s\n' % relpath)
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
388
        self._up_delete(relpath)
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
389
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
390
    def delete_remote_dir(self, relpath):
0.161.5 by Vincent Ladeuil
Cleanup.
391
        if not self.quiet:
392
            self.outf.write('Deleting %s\n' % relpath)
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
393
        self._up_rmdir(relpath)
0.161.5 by Vincent Ladeuil
Cleanup.
394
        # XXX: Add a test where a subdir is ignored but we still want to
395
        # delete the dir -- vila 100106
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
396
397
    def delete_remote_dir_maybe(self, relpath):
398
        """Try to delete relpath, keeping failures to retry later."""
399
        try:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
400
            self._up_rmdir(relpath)
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
401
        # any kind of PathError would be OK, though we normally expect
402
        # DirectoryNotEmpty
403
        except errors.PathError:
404
            self._pending_deletions.append(relpath)
405
406
    def finish_deletions(self):
407
        if self._pending_deletions:
408
            # Process the previously failed deletions in reverse order to
409
            # delete children before parents
410
            for relpath in reversed(self._pending_deletions):
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
411
                self._up_rmdir(relpath)
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
412
            # The following shouldn't be needed since we use it once per
413
            # upload, but better safe than sorry ;-)
414
            self._pending_deletions = []
415
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
416
    def rename_remote(self, old_relpath, new_relpath):
417
        """Rename a remote file or directory taking care of collisions.
418
419
        To avoid collisions during bulk renames, each renamed target is
420
        temporarily assigned a unique name. When all renames have been done,
421
        each target get its proper name.
422
        """
423
        # We generate a sufficiently random name to *assume* that
424
        # no collisions will occur and don't worry about it (nor
425
        # handle it).
426
        import os
427
        import random
428
        import time
429
430
        stamp = '.tmp.%.9f.%d.%d' % (time.time(),
431
                                     os.getpid(),
432
                                     random.randint(0,0x7FFFFFFF))
0.152.34 by Martin Albisetti
* Change the default behaviour to be more verbose
433
        if not self.quiet:
0.152.30 by Vincent Ladeuil
Comply to verbose.
434
            self.outf.write('Renaming %s to %s\n' % (old_relpath, new_relpath))
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
435
        self._up_rename(old_relpath, stamp)
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
436
        self._pending_renames.append((stamp, new_relpath))
437
438
    def finish_renames(self):
439
        for (stamp, new_path) in self._pending_renames:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
440
            self._up_rename(stamp, new_path)
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
441
        # The following shouldn't be needed since we use it once per upload,
442
        # but better safe than sorry ;-)
443
        self._pending_renames = []
444
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
445
    def upload_full_tree(self):
0.152.14 by Vincent Ladeuil
Handle renames (trivial implementation).
446
        self.to_transport.ensure_base() # XXX: Handle errors (add
447
                                        # --create-prefix option ?)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
448
        self.tree.lock_read()
449
        try:
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
450
            for relpath, ie in self.tree.inventory.iter_entries():
0.160.4 by Martin Albisetti
Test passes!
451
                if relpath in ('', '.bzrignore', '.bzrignore-upload'):
0.152.10 by Vincent Ladeuil
Fix incremental upload cheat.
452
                    # skip root ('')
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
453
                    # .bzrignore and .bzrignore-upload have no meaning outside
454
                    # a working tree so do not upload them
455
                    continue
456
                if self.is_ignored(relpath):
457
                    if not self.quiet:
458
                        self.outf.write('Ignoring %s\n' % relpath)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
459
                    continue
0.152.8 by Vincent Ladeuil
Handle uploading directories.
460
                if ie.kind == 'file':
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
461
                    self.upload_file_robustly(relpath, ie.file_id)
0.152.8 by Vincent Ladeuil
Handle uploading directories.
462
                elif ie.kind == 'directory':
0.152.44 by Vincent Ladeuil
More robust full upload (at least regarding files changed to dirs and vice-versa).
463
                    self.make_remote_dir_robustly(relpath)
0.152.8 by Vincent Ladeuil
Handle uploading directories.
464
                else:
465
                    raise NotImplementedError
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
466
            self.set_uploaded_revid(self.rev_id)
467
        finally:
468
            self.tree.unlock()
469
0.152.10 by Vincent Ladeuil
Fix incremental upload cheat.
470
    def upload_tree(self):
0.152.24 by Martin Albisetti
Changed the way we upload the full tree if its never been uploaded
471
        # If we can't find the revid file on the remote location, upload the
472
        # full tree instead
0.159.2 by Gary van der Merwe
If there has not been an upload, treat the uploaded revid as revision.NULL_REVISION. This enables this request to be cached.
473
        rev_id = self.get_uploaded_revid()
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
474
0.159.2 by Gary van der Merwe
If there has not been an upload, treat the uploaded revid as revision.NULL_REVISION. This enables this request to be cached.
475
        if rev_id == revision.NULL_REVISION:
0.152.34 by Martin Albisetti
* Change the default behaviour to be more verbose
476
            if not self.quiet:
0.152.29 by Vincent Ladeuil
Work around test fixture limitation regarding self.outf (cough). All tests passing again.
477
                self.outf.write('No uploaded revision id found,'
0.152.34 by Martin Albisetti
* Change the default behaviour to be more verbose
478
                                ' switching to full upload\n')
0.152.24 by Martin Albisetti
Changed the way we upload the full tree if its never been uploaded
479
            self.upload_full_tree()
0.152.29 by Vincent Ladeuil
Work around test fixture limitation regarding self.outf (cough). All tests passing again.
480
            # We're done
481
            return
0.152.24 by Martin Albisetti
Changed the way we upload the full tree if its never been uploaded
482
0.152.35 by Martin Albisetti
* Tell the user if the remote location is already up to date
483
        # Check if the revision hasn't already been uploaded
484
        if rev_id == self.rev_id:
485
            if not self.quiet:
486
                self.outf.write('Remote location already up to date\n')
487
0.152.10 by Vincent Ladeuil
Fix incremental upload cheat.
488
        # XXX: errors out if rev_id not in branch history (probably someone
489
        # uploaded from a different branch).
490
        from_tree = self.branch.repository.revision_tree(rev_id)
0.152.14 by Vincent Ladeuil
Handle renames (trivial implementation).
491
        self.to_transport.ensure_base() # XXX: Handle errors (add
492
                                        # --create-prefix option ?)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
493
        changes = self.tree.changes_from(from_tree)
494
        self.tree.lock_read()
495
        try:
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
496
            for (path, id, kind) in changes.removed:
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
497
                if self.is_ignored(path):
498
                    if not self.quiet:
499
                        self.outf.write('Ignoring %s\n' % path)
500
                    continue
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
501
                if kind is 'file':
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
502
                    self.delete_remote_file(path)
503
                elif kind is  'directory':
504
                    self.delete_remote_dir_maybe(path)
0.152.17 by Vincent Ladeuil
Handle deletes (trivial implementation).
505
                else:
506
                    raise NotImplementedError
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
507
0.152.14 by Vincent Ladeuil
Handle renames (trivial implementation).
508
            for (old_path, new_path, id, kind,
509
                 content_change, exec_change) in changes.renamed:
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
510
                if self.is_ignored(old_path) and self.is_ignored(new_path):
511
                    if not self.quiet:
512
                        self.outf.write('Ignoring %s\n' % old_path)
513
                        self.outf.write('Ignoring %s\n' % new_path)
514
                    continue
0.152.52 by Vincent Ladeuil
Fix bug #270219 by handling content changes during renames.
515
                if content_change:
516
                    # We update the old_path content because renames and
517
                    # deletions are differed.
518
                    self.upload_file(old_path, id)
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
519
                self.rename_remote(old_path, new_path)
520
            self.finish_renames()
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
521
            self.finish_deletions()
0.152.16 by Vincent Ladeuil
Handle renames. Robust implementation.
522
0.152.19 by Vincent Ladeuil
Handle kind_change. Trivial implementation, blocked by bug #205636.
523
            for (path, id, old_kind, new_kind) in changes.kind_changed:
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
524
                if self.is_ignored(path):
525
                    if not self.quiet:
526
                        self.outf.write('Ignoring %s\n' % path)
527
                    continue
0.152.19 by Vincent Ladeuil
Handle kind_change. Trivial implementation, blocked by bug #205636.
528
                if old_kind is 'file':
529
                    self.delete_remote_file(path)
530
                elif old_kind is  'directory':
531
                    self.delete_remote_dir(path)
532
                else:
533
                    raise NotImplementedError
534
535
                if new_kind is 'file':
536
                    self.upload_file(path, id)
537
                elif new_kind is 'directory':
538
                    self.make_remote_dir(path)
539
                else:
540
                    raise NotImplementedError
541
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
542
            for (path, id, kind) in changes.added:
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
543
                if self.is_ignored(path):
544
                    if not self.quiet:
545
                        self.outf.write('Ignoring %s\n' % path)
546
                    continue
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
547
                if kind is 'file':
0.152.7 by Vincent Ladeuil
Slight refactoring.
548
                    self.upload_file(path, id)
0.152.8 by Vincent Ladeuil
Handle uploading directories.
549
                elif kind is 'directory':
550
                    self.make_remote_dir(path)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
551
                else:
552
                    raise NotImplementedError
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
553
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
554
            # XXX: Add a test for exec_change
555
            for (path, id, kind,
556
                 content_change, exec_change) in changes.modified:
0.161.4 by Vincent Ladeuil
Handle regexps in .bzrignore-upload and take parents into account.
557
                if self.is_ignored(path):
558
                    if not self.quiet:
559
                        self.outf.write('Ignoring %s\n' % path)
560
                    continue
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
561
                if kind is 'file':
0.152.7 by Vincent Ladeuil
Slight refactoring.
562
                    self.upload_file(path, id)
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
563
                else:
564
                    raise NotImplementedError
0.152.18 by Vincent Ladeuil
Handle deletions. Robust implementation.
565
0.152.5 by v.ladeuil+lp at free
Partial incremental upload implementationm tests pass.
566
            self.set_uploaded_revid(self.rev_id)
567
        finally:
568
            self.tree.unlock()
0.152.4 by v.ladeuil+lp at free
Implement a trivial implementation to make one test pass.
569
0.152.57 by Vincent Ladeuil
Fix minor 2.4 compatibility bug.
570
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
571
class CannotUploadToWorkingTree(errors.BzrCommandError):
0.158.19 by Vincent Ladeuil
Bzr has facilities for exceptions, let's use them.
572
573
    _fmt = 'Cannot upload to a bzr managed working tree: %(url)s".'
574
0.152.1 by Vincent Ladeuil
Empty shell
575
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
576
class DivergedUploadedTree(errors.BzrCommandError):
577
578
    _fmt = ("Your branch (%(revid)s)"
579
            " and the uploaded tree (%(uploaded_revid)s) have diverged: ")
580
581
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
582
class cmd_upload(commands.Command):
583
    """Upload a working tree, as a whole or incrementally.
584
585
    If no destination is specified use the last one used.
586
    If no revision is specified upload the changes since the last upload.
0.152.56 by Vincent Ladeuil
Small tweaks including doc fix (#275538).
587
588
    Changes include files added, renamed, modified or removed.
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
589
    """
0.152.63 by Vincent Ladeuil
Make the doc more easily discoverable.
590
    _see_also = ['plugins/upload']
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
591
    takes_args = ['location?']
592
    takes_options = [
593
        'revision',
594
        'remember',
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
595
        'overwrite',
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
596
        option.Option('full', 'Upload the full working tree.'),
597
        option.Option('quiet', 'Do not output what is being done.',
598
                       short_name='q'),
599
        option.Option('directory',
600
                      help='Branch to upload from, '
601
                      'rather than the one containing the working directory.',
602
                      short_name='d',
603
                      type=unicode,
604
                      ),
0.155.5 by James Westby
Hook up the --upload option and document it.
605
        option.Option('auto',
606
                      'Trigger an upload from this branch whenever the tip '
607
                      'revision changes.')
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
608
       ]
609
610
    def run(self, location=None, full=False, revision=None, remember=None,
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
611
            directory=None, quiet=False, auto=None, overwrite=False
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
612
            ):
613
        if directory is None:
614
            directory = u'.'
0.158.7 by Gary van der Merwe
Clean up white space.
615
0.157.1 by James Westby
Don't try and register the hook if install_named_hook is not available
616
        if auto and not auto_hook_available:
617
            raise BzrCommandError("Your version of bzr does not have the "
618
                    "hooks necessary for --auto to work")
619
0.158.19 by Vincent Ladeuil
Bzr has facilities for exceptions, let's use them.
620
        (wt, branch,
621
         relpath) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
622
0.158.1 by Gary van der Merwe
Don't require a working tree.
623
        if wt:
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
624
            wt.lock_read()
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
625
            locked = wt
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
626
        else:
627
            branch.lock_read()
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
628
            locked = branch
0.158.9 by Gary van der Merwe
Add a check to make sure we are not uploading to an existing wt.
629
        try:
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
630
            if wt:
631
                changes = wt.changes_from(wt.basis_tree())
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
632
0.161.2 by Martin Albisetti
Remove commented lines for debugging
633
                if revision is None and  changes.has_changed():
634
                    raise errors.UncommittedChanges(wt)
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
635
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
636
            if location is None:
637
                stored_loc = get_upload_location(branch)
638
                if stored_loc is None:
639
                    raise errors.BzrCommandError('No upload location'
640
                                                 ' known or specified.')
641
                else:
642
                    # FIXME: Not currently tested
643
                    display_url = urlutils.unescape_for_display(stored_loc,
644
                            self.outf.encoding)
645
                    self.outf.write("Using saved location: %s\n" % display_url)
646
                    location = stored_loc
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
647
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
648
            to_transport = transport.get_transport(location)
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
649
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
650
            # Check that we are not uploading to a existing working tree.
651
            try:
652
                to_bzr_dir = bzrdir.BzrDir.open_from_transport(to_transport)
653
                has_wt = to_bzr_dir.has_workingtree()
654
            except errors.NotBranchError:
655
                has_wt = False
656
            except errors.NotLocalUrl:
657
                # The exception raised is a bit weird... but that's life.
658
                has_wt = True
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
659
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
660
            if has_wt:
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
661
                raise CannotUploadToWorkingTree(url=location)
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
662
            if revision is None:
663
                rev_id = branch.last_revision()
664
            else:
665
                if len(revision) != 1:
666
                    raise errors.BzrCommandError(
667
                        'bzr upload --revision takes exactly 1 argument')
668
                rev_id = revision[0].in_history(branch).rev_id
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
669
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
670
            tree = branch.repository.revision_tree(rev_id)
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
671
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
672
            uploader = BzrUploader(branch, to_transport, self.outf, tree,
673
                                   rev_id, quiet=quiet)
0.160.2 by Martin Albisetti
Clean up whitespace to appease the neurotic in me
674
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
675
            if not overwrite:
676
                prev_uploaded_rev_id = uploader.get_uploaded_revid()
677
                graph = branch.repository.get_graph()
678
                if not graph.is_ancestor(prev_uploaded_rev_id, rev_id):
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
679
                    raise DivergedUploadedTree(
680
                        revid=rev_id, uploaded_revid=prev_uploaded_rev_id)
0.159.4 by Gary van der Merwe
Check that the revision we are uploading is a descendent from the revision that was uploaded.
681
            if full:
682
                uploader.upload_full_tree()
683
            else:
684
                uploader.upload_tree()
685
        finally:
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
686
            locked.unlock()
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
687
688
        # We uploaded successfully, remember it
689
        if get_upload_location(branch) is None or remember:
0.152.70 by Vincent Ladeuil
Ensure we use the transport API correctly for unicode paths.
690
            set_upload_location(branch, urlutils.unescape(to_transport.base))
0.155.4 by James Westby
Add the groundwork for --auto that enables the hook for a branch.
691
        if auto is not None:
692
            set_upload_auto(branch, auto)
0.155.1 by James Westby
Switch most of the logic to a class outside of the command class.
693
694
0.152.1 by Vincent Ladeuil
Empty shell
695
commands.register_command(cmd_upload)
696
0.152.68 by Vincent Ladeuil
Cleanup some pending changes.
697
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
698
def install_auto_upload_hook():
699
    from bzrlib.plugins.upload import auto_upload_hook
0.157.1 by James Westby
Don't try and register the hook if install_named_hook is not available
700
    branch.Branch.hooks.install_named_hook('post_change_branch_tip',
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
701
            auto_upload_hook.auto_upload_hook,
0.157.1 by James Westby
Don't try and register the hook if install_named_hook is not available
702
            'Auto upload code from a branch when it is changed.')
0.152.61 by Vincent Ladeuil
Fix bug #312686 and add an 'upload_auto_quiet' config variable.
703
704
705
if hasattr(branch.Branch.hooks, "install_named_hook"):
706
    install_auto_upload_hook()
0.157.1 by James Westby
Don't try and register the hook if install_named_hook is not available
707
    auto_hook_available = True
708
else:
709
    auto_hook_available = False
0.155.2 by James Westby
Add a post_change_branch_tip hook to upload.
710
711
0.152.29 by Vincent Ladeuil
Work around test fixture limitation regarding self.outf (cough). All tests passing again.
712
def load_tests(basic_tests, module, loader):
0.153.1 by Vincent Ladeuil
Clean up references to verbose.
713
    # This module shouldn't define any tests but I don't know how to report
0.154.1 by Vincent Ladeuil
Create a simple setup.py and rework tests modules accordingly.
714
    # that. I prefer to update basic_tests with the other tests to detect
715
    # unwanted tests and I think that's sufficient.
0.152.1 by Vincent Ladeuil
Empty shell
716
717
    testmod_names = [
0.154.1 by Vincent Ladeuil
Create a simple setup.py and rework tests modules accordingly.
718
        'tests',
0.152.1 by Vincent Ladeuil
Empty shell
719
        ]
0.154.1 by Vincent Ladeuil
Create a simple setup.py and rework tests modules accordingly.
720
    basic_tests.addTest(loader.loadTestsFromModuleNames(
0.152.1 by Vincent Ladeuil
Empty shell
721
            ["%s.%s" % (__name__, tmn) for tmn in testmod_names]))
0.154.1 by Vincent Ladeuil
Create a simple setup.py and rework tests modules accordingly.
722
    return basic_tests