1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Helper functions for adding files to working trees."""
21
from os.path import dirname
25
import bzrlib.errors as errors
26
from bzrlib.errors import NotBranchError
27
from bzrlib.inventory import InventoryEntry
29
from bzrlib.symbol_versioning import *
30
from bzrlib.trace import mutter, note, warning
31
from bzrlib.workingtree import WorkingTree
34
class AddAction(object):
35
"""A class which defines what action to take when adding a file."""
37
def __init__(self, to_file=None, should_print=None):
38
"""Initialize an action which prints added files to an output stream.
40
:param to_file: The stream to write into. This is expected to take
41
Unicode paths. If not supplied, it will default to ``sys.stdout``.
42
:param should_print: If False, printing will be supressed.
44
self._to_file = to_file
46
self._to_file = sys.stdout
47
self.should_print = False
48
if should_print is not None:
49
self.should_print = should_print
51
def __call__(self, inv, parent_ie, path, kind, _quote=bzrlib.osutils.quotefn):
52
"""Add path to inventory.
54
The default action does nothing.
56
:param inv: The inventory we are working with.
57
:param path: The FastPath being added
58
:param kind: The kind of the object being added.
61
self._to_file.write('added %s\n' % _quote(path.raw_path))
65
class AddFromBaseAction(AddAction):
66
"""This class will try to extract file ids from another tree."""
68
def __init__(self, base_tree, base_path, to_file=None, should_print=None):
69
super(AddFromBaseAction, self).__init__(to_file=to_file,
70
should_print=should_print)
71
self.base_tree = base_tree
72
self.base_path = base_path
74
def __call__(self, inv, parent_ie, path, kind):
75
# Place the parent call
76
# Now check to see if we can extract an id for this file
77
file_id, base_path = self._get_base_file_id(path, parent_ie)
78
if file_id is not None:
80
self._to_file.write('added %s w/ file id from %s\n'
81
% (path.raw_path, base_path))
83
# we aren't doing anything special, so let the default
85
file_id = super(AddFromBaseAction, self).__call__(
86
inv, parent_ie, path, kind)
89
def _get_base_file_id(self, path, parent_ie):
90
"""Look for a file id in the base branch.
92
First, if the base tree has the parent directory,
93
we look for a file with the same name in that directory.
94
Else, we look for an entry in the base tree with the same path.
97
if (parent_ie.file_id in self.base_tree):
98
base_parent_ie = self.base_tree.inventory[parent_ie.file_id]
99
base_child_ie = base_parent_ie.children.get(path.base_path)
100
if base_child_ie is not None:
101
return (base_child_ie.file_id,
102
self.base_tree.id2path(base_child_ie.file_id))
103
full_base_path = bzrlib.osutils.pathjoin(self.base_path, path.raw_path)
104
# This may return None, but it is our last attempt
105
return self.base_tree.path2id(full_base_path), full_base_path
108
# TODO: jam 20050105 These could be used for compatibility
109
# however, they bind against the current stdout, not the
110
# one which exists at the time they are called, so they
111
# don't work for the test suite.
113
add_action_add = AddAction()
114
add_action_null = add_action_add
115
add_action_add_and_print = AddAction(should_print=True)
116
add_action_print = add_action_add_and_print
119
@deprecated_function(zero_eighteen)
120
def smart_add(file_list, recurse=True, action=None, save=True):
121
"""Add files to version, optionally recursing into directories.
123
This is designed more towards DWIM for humans than API simplicity.
124
For the specific behaviour see the help for cmd_add().
126
Returns the number of files added.
127
Please see smart_add_tree for more detail.
129
tree = WorkingTree.open_containing(file_list[0])[0]
130
return smart_add_tree(tree, file_list, recurse, action=action, save=save)
133
class FastPath(object):
134
"""A path object with fast accessors for things like basename."""
136
__slots__ = ['raw_path', 'base_path']
138
def __init__(self, path, base_path=None):
139
"""Construct a FastPath from path."""
140
if base_path is None:
141
self.base_path = bzrlib.osutils.basename(path)
143
self.base_path = base_path
146
def __cmp__(self, other):
147
return cmp(self.raw_path, other.raw_path)
150
return hash(self.raw_path)
153
def smart_add_tree(tree, file_list, recurse=True, action=None, save=True):
154
"""Add files to version, optionally recursing into directories.
156
This is designed more towards DWIM for humans than API simplicity.
157
For the specific behaviour see the help for cmd_add().
159
This calls reporter with each (path, kind, file_id) of added files.
161
Returns the number of files added.
163
:param save: Save the inventory after completing the adds. If False this
164
provides dry-run functionality by doing the add and not saving the
165
inventory. Note that the modified inventory is left in place, allowing
166
further dry-run tasks to take place. To restore the original inventory
167
call tree.read_working_inventory().
169
tree.lock_tree_write()
171
return _smart_add_tree(tree=tree, file_list=file_list, recurse=recurse,
172
action=action, save=save)
177
def _smart_add_tree(tree, file_list, recurse=True, action=None, save=True):
178
"""Helper for smart_add_tree.
180
The tree should be locked before entering this function. See smart_add_tree
181
for parameter definitions.
183
assert isinstance(recurse, bool)
188
# no paths supplied: add the entire tree.
190
mutter("smart add of %r")
191
inv = tree.read_working_inventory()
197
# validate user file paths and convert all paths to tree
198
# relative : its cheaper to make a tree relative path an abspath
199
# than to convert an abspath to tree relative.
200
for filepath in file_list:
201
rf = FastPath(tree.relpath(filepath))
202
# validate user parameters. Our recursive code avoids adding new files
203
# that need such validation
204
if tree.is_control_filename(rf.raw_path):
205
raise errors.ForbiddenControlFileError(filename=rf.raw_path)
207
abspath = tree.abspath(rf.raw_path)
208
kind = bzrlib.osutils.file_kind(abspath)
209
if kind == 'directory':
210
# schedule the dir for scanning
213
if not InventoryEntry.versionable_kind(kind):
214
raise errors.BadFileKindError(filename=abspath, kind=kind)
215
# ensure the named path is added, so that ignore rules in the later directory
217
# we dont have a parent ie known yet.: use the relatively slower inventory
219
versioned = inv.has_filename(rf.raw_path)
222
added.extend(__add_one_and_parent(tree, inv, None, rf, kind, action))
225
# no need to walk any directories at all.
226
if len(added) > 0 and save:
227
tree._write_inventory(inv)
228
return added, ignored
230
# only walk the minimal parents needed: we have user_dirs to override
234
is_inside = bzrlib.osutils.is_inside_or_parent_of_any
235
for path in sorted(user_dirs):
236
if (prev_dir is None or not is_inside([prev_dir], path.raw_path)):
237
dirs_to_add.append((path, None))
238
prev_dir = path.raw_path
240
# this will eventually be *just* directories, right now it starts off with
242
for directory, parent_ie in dirs_to_add:
243
# directory is tree-relative
244
abspath = tree.abspath(directory.raw_path)
246
# get the contents of this directory.
248
# find the kind of the path being added.
249
kind = bzrlib.osutils.file_kind(abspath)
251
if not InventoryEntry.versionable_kind(kind):
252
warning("skipping %s (can't add file of kind '%s')", abspath, kind)
255
if parent_ie is not None:
256
versioned = directory.base_path in parent_ie.children
258
# without the parent ie, use the relatively slower inventory
260
versioned = inv.has_filename(directory.raw_path)
262
if kind == 'directory':
264
sub_branch = bzrlib.bzrdir.BzrDir.open(abspath)
266
except NotBranchError:
268
except errors.UnsupportedFormatError:
273
if directory.raw_path == '':
274
# mutter("tree root doesn't need to be added")
278
# mutter("%r is already versioned", abspath)
280
# XXX: This is wrong; people *might* reasonably be trying to add
281
# subtrees as subtrees. This should probably only be done in formats
282
# which can represent subtrees, and even then perhaps only when
283
# the user asked to add subtrees. At the moment you can add them
284
# specially through 'join --reference', which is perhaps
285
# reasonable: adding a new reference is a special operation and
286
# can have a special behaviour. mbp 20070306
287
mutter("%r is a nested bzr tree", abspath)
289
__add_one(tree, inv, parent_ie, directory, kind, action)
290
added.append(directory.raw_path)
292
if kind == 'directory' and not sub_tree:
293
if parent_ie is not None:
295
this_ie = parent_ie.children[directory.base_path]
297
# without the parent ie, use the relatively slower inventory
299
this_id = inv.path2id(directory.raw_path)
303
this_ie = inv[this_id]
305
for subf in sorted(os.listdir(abspath)):
306
# here we could use TreeDirectory rather than
307
# string concatenation.
308
subp = bzrlib.osutils.pathjoin(directory.raw_path, subf)
309
# TODO: is_control_filename is very slow. Make it faster.
310
# TreeDirectory.is_control_filename could also make this
311
# faster - its impossible for a non root dir to have a
313
if tree.is_control_filename(subp):
314
mutter("skip control directory %r", subp)
315
elif subf in this_ie.children:
316
# recurse into this already versioned subdir.
317
dirs_to_add.append((FastPath(subp, subf), this_ie))
319
# user selection overrides ignoes
320
# ignore while selecting files - if we globbed in the
321
# outer loop we would ignore user files.
322
ignore_glob = tree.is_ignored(subp)
323
if ignore_glob is not None:
324
# mutter("skip ignored sub-file %r", subp)
325
ignored.setdefault(ignore_glob, []).append(subp)
327
#mutter("queue to add sub-file %r", subp)
328
dirs_to_add.append((FastPath(subp, subf), this_ie))
330
if len(added) > 0 and save:
331
tree._write_inventory(inv)
332
return added, ignored
335
def __add_one_and_parent(tree, inv, parent_ie, path, kind, action):
336
"""Add a new entry to the inventory and automatically add unversioned parents.
338
:param inv: Inventory which will receive the new entry.
339
:param parent_ie: Parent inventory entry if known, or None. If
340
None, the parent is looked up by name and used if present, otherwise it
341
is recursively added.
342
:param kind: Kind of new entry (file, directory, etc)
343
:param action: callback(inv, parent_ie, path, kind); return ignored.
344
:return: A list of paths which have been added.
346
# Nothing to do if path is already versioned.
347
# This is safe from infinite recursion because the tree root is
349
if parent_ie is not None:
350
# we have a parent ie already
353
# slower but does not need parent_ie
354
if inv.has_filename(path.raw_path):
356
# its really not there : add the parent
357
# note that the dirname use leads to some extra str copying etc but as
358
# there are a limited number of dirs we can be nested under, it should
359
# generally find it very fast and not recurse after that.
360
added = __add_one_and_parent(tree, inv, None, FastPath(dirname(path.raw_path)), 'directory', action)
361
parent_id = inv.path2id(dirname(path.raw_path))
362
parent_ie = inv[parent_id]
363
__add_one(tree, inv, parent_ie, path, kind, action)
364
return added + [path.raw_path]
367
def __add_one(tree, inv, parent_ie, path, kind, file_id_callback):
368
"""Add a new entry to the inventory.
370
:param inv: Inventory which will receive the new entry.
371
:param parent_ie: Parent inventory entry.
372
:param kind: Kind of new entry (file, directory, etc)
373
:param file_id_callback: callback(inv, parent_ie, path, kind); return a file_id
374
or None to generate a new file id
377
file_id = file_id_callback(inv, parent_ie, path, kind)
378
entry = bzrlib.inventory.make_entry(kind, path.base_path, parent_ie.file_id,