~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/add.py

ignore BRANCH-INFO file

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
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
 
"""Helper functions for adding files to working trees."""
18
 
 
19
 
import sys
20
 
import os
21
 
 
22
 
from bzrlib import (
23
 
    osutils,
24
 
    ui, 
25
 
    )
26
 
from bzrlib.i18n import gettext
27
 
 
28
 
class AddAction(object):
29
 
    """A class which defines what action to take when adding a file."""
30
 
 
31
 
    def __init__(self, to_file=None, should_print=None):
32
 
        """Initialize an action which prints added files to an output stream.
33
 
 
34
 
        :param to_file: The stream to write into. This is expected to take
35
 
            Unicode paths. If not supplied, it will default to ``sys.stdout``.
36
 
        :param should_print: If False, printing will be suppressed.
37
 
        """
38
 
        self._to_file = to_file
39
 
        if to_file is None:
40
 
            self._to_file = sys.stdout
41
 
        self.should_print = False
42
 
        if should_print is not None:
43
 
            self.should_print = should_print
44
 
 
45
 
    def __call__(self, inv, parent_ie, path, kind, _quote=osutils.quotefn):
46
 
        """Add path to inventory.
47
 
 
48
 
        The default action does nothing.
49
 
 
50
 
        :param inv: The inventory we are working with.
51
 
        :param path: The FastPath being added
52
 
        :param kind: The kind of the object being added.
53
 
        """
54
 
        if self.should_print:
55
 
            self._to_file.write('adding %s\n' % _quote(path))
56
 
        return None
57
 
 
58
 
    def skip_file(self, tree, path, kind, stat_value = None):
59
 
        """Test whether the given file should be skipped or not.
60
 
        
61
 
        The default action never skips. Note this is only called during
62
 
        recursive adds
63
 
        
64
 
        :param tree: The tree we are working in
65
 
        :param path: The path being added
66
 
        :param kind: The kind of object being added.
67
 
        :param stat: Stat result for this file, if available already
68
 
        :return bool. True if the file should be skipped (not added)
69
 
        """
70
 
        return False
71
 
 
72
 
 
73
 
class AddWithSkipLargeAction(AddAction):
74
 
    """A class that can decide to skip a file if it's considered too large"""
75
 
 
76
 
    # default 20 MB
77
 
    _DEFAULT_MAX_FILE_SIZE = 20000000
78
 
    _optionName = 'add.maximum_file_size'
79
 
    _maxSize = None
80
 
 
81
 
    def skip_file(self, tree, path, kind, stat_value = None):
82
 
        if kind != 'file':
83
 
            return False            
84
 
        if self._maxSize is None:
85
 
            config = tree.branch.get_config()
86
 
            self._maxSize = config.get_user_option_as_int_from_SI(
87
 
                self._optionName,  
88
 
                self._DEFAULT_MAX_FILE_SIZE)
89
 
        if stat_value is None:
90
 
            file_size = os.path.getsize(path);
91
 
        else:
92
 
            file_size = stat_value.st_size;
93
 
        if self._maxSize > 0 and file_size > self._maxSize:
94
 
            ui.ui_factory.show_warning(gettext(
95
 
                "skipping {0} (larger than {1} of {2} bytes)").format(
96
 
                path, self._optionName,  self._maxSize))
97
 
            return True
98
 
        return False
99
 
 
100
 
 
101
 
class AddFromBaseAction(AddAction):
102
 
    """This class will try to extract file ids from another tree."""
103
 
 
104
 
    def __init__(self, base_tree, base_path, to_file=None, should_print=None):
105
 
        super(AddFromBaseAction, self).__init__(to_file=to_file,
106
 
                                                should_print=should_print)
107
 
        self.base_tree = base_tree
108
 
        self.base_path = base_path
109
 
 
110
 
    def __call__(self, inv, parent_ie, path, kind):
111
 
        # Place the parent call
112
 
        # Now check to see if we can extract an id for this file
113
 
        file_id, base_path = self._get_base_file_id(path, parent_ie)
114
 
        if file_id is not None:
115
 
            if self.should_print:
116
 
                self._to_file.write('adding %s w/ file id from %s\n'
117
 
                                    % (path, base_path))
118
 
        else:
119
 
            # we aren't doing anything special, so let the default
120
 
            # reporter happen
121
 
            file_id = super(AddFromBaseAction, self).__call__(
122
 
                        inv, parent_ie, path, kind)
123
 
        return file_id
124
 
 
125
 
    def _get_base_file_id(self, path, parent_ie):
126
 
        """Look for a file id in the base branch.
127
 
 
128
 
        First, if the base tree has the parent directory,
129
 
        we look for a file with the same name in that directory.
130
 
        Else, we look for an entry in the base tree with the same path.
131
 
        """
132
 
 
133
 
        if self.base_tree.has_id(parent_ie.file_id):
134
 
            base_parent_ie = self.base_tree.inventory[parent_ie.file_id]
135
 
            base_child_ie = base_parent_ie.children.get(
136
 
                osutils.basename(path))
137
 
            if base_child_ie is not None:
138
 
                return (base_child_ie.file_id,
139
 
                        self.base_tree.id2path(base_child_ie.file_id))
140
 
        full_base_path = osutils.pathjoin(self.base_path, path)
141
 
        # This may return None, but it is our last attempt
142
 
        return self.base_tree.path2id(full_base_path), full_base_path
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
from os.path import dirname
 
18
 
 
19
import bzrlib.errors as errors
 
20
from bzrlib.inventory import InventoryEntry
 
21
from bzrlib.trace import mutter, note, warning
 
22
from bzrlib.errors import NotBranchError
 
23
from bzrlib.branch import is_control_file
 
24
import bzrlib.osutils
 
25
from bzrlib.workingtree import WorkingTree
 
26
 
 
27
def glob_expand_for_win32(file_list):
 
28
    if not file_list:
 
29
        return
 
30
    import glob
 
31
    expanded_file_list = []
 
32
    for possible_glob in file_list:
 
33
        glob_files = glob.glob(possible_glob)
 
34
       
 
35
        if glob_files == []:
 
36
            # special case to let the normal code path handle
 
37
            # files that do not exists
 
38
            expanded_file_list.append(possible_glob)
 
39
        else:
 
40
            expanded_file_list += glob_files
 
41
    return expanded_file_list
 
42
 
 
43
 
 
44
def add_reporter_null(path, kind, entry):
 
45
    """Absorb add reports and do nothing."""
 
46
    pass
 
47
 
 
48
 
 
49
def add_reporter_print(path, kind, entry):
 
50
    """Print a line to stdout for each file that's added."""
 
51
    print "added", bzrlib.osutils.quotefn(path)
 
52
 
 
53
 
 
54
def _prepare_file_list(file_list):
 
55
    """Prepare a file list for use by smart_add_*."""
 
56
    import sys
 
57
    if sys.platform == 'win32':
 
58
        file_list = glob_expand_for_win32(file_list)
 
59
    if not file_list:
 
60
        file_list = [u'.']
 
61
    file_list = list(file_list)
 
62
    return file_list
 
63
 
 
64
 
 
65
def smart_add(file_list, recurse=True, reporter=add_reporter_null):
 
66
    """Add files to version, optionally recursing into directories.
 
67
 
 
68
    This is designed more towards DWIM for humans than API simplicity.
 
69
    For the specific behaviour see the help for cmd_add().
 
70
 
 
71
    Returns the number of files added.
 
72
    """
 
73
    file_list = _prepare_file_list(file_list)
 
74
    tree = WorkingTree.open_containing(file_list[0])[0]
 
75
    return smart_add_tree(tree, file_list, recurse, reporter)
 
76
 
 
77
        
 
78
def smart_add_tree(tree, file_list, recurse=True, reporter=add_reporter_null):
 
79
    """Add files to version, optionally recursing into directories.
 
80
 
 
81
    This is designed more towards DWIM for humans than API simplicity.
 
82
    For the specific behaviour see the help for cmd_add().
 
83
 
 
84
    This calls reporter with each (path, kind, file_id) of added files.
 
85
 
 
86
    Returns the number of files added.
 
87
    """
 
88
    import os
 
89
    from bzrlib.errors import BadFileKindError, ForbiddenFileError
 
90
    assert isinstance(recurse, bool)
 
91
 
 
92
    file_list = _prepare_file_list(file_list)
 
93
    user_list = file_list[:]
 
94
    inv = tree.read_working_inventory()
 
95
    count = 0
 
96
 
 
97
    for f in file_list:
 
98
        rf = tree.relpath(f)
 
99
        af = tree.abspath(rf)
 
100
 
 
101
        kind = bzrlib.osutils.file_kind(af)
 
102
 
 
103
        if not InventoryEntry.versionable_kind(kind):
 
104
            if f in user_list:
 
105
                raise BadFileKindError("cannot add %s of type %s" % (f, kind))
 
106
            else:
 
107
                warning("skipping %s (can't add file of kind '%s')", f, kind)
 
108
                continue
 
109
 
 
110
        mutter("smart add of %r, abs=%r", f, af)
 
111
        
 
112
        if is_control_file(af):
 
113
            raise ForbiddenFileError('cannot add control file %s' % f)
 
114
            
 
115
        versioned = (inv.path2id(rf) != None)
 
116
 
 
117
        if kind == 'directory':
 
118
            try:
 
119
                sub_branch = WorkingTree(af)
 
120
                sub_tree = True
 
121
            except NotBranchError:
 
122
                sub_tree = False
 
123
            except errors.UnsupportedFormatError:
 
124
                sub_tree = True
 
125
        else:
 
126
            sub_tree = False
 
127
 
 
128
        if rf == '':
 
129
            mutter("tree root doesn't need to be added")
 
130
            sub_tree = False
 
131
        elif versioned:
 
132
            mutter("%r is already versioned", f)
 
133
        elif sub_tree:
 
134
            mutter("%r is a bzr tree", f)
 
135
        else:
 
136
            count += __add_one(tree, inv, rf, kind, reporter)
 
137
 
 
138
        if kind == 'directory' and recurse and not sub_tree:
 
139
            for subf in os.listdir(af):
 
140
                subp = os.path.join(rf, subf)
 
141
                if subf == bzrlib.BZRDIR:
 
142
                    mutter("skip control directory %r", subp)
 
143
                elif tree.is_ignored(subp):
 
144
                    mutter("skip ignored sub-file %r", subp)
 
145
                else:
 
146
                    mutter("queue to add sub-file %r", subp)
 
147
                    file_list.append(tree.abspath(subp))
 
148
 
 
149
 
 
150
    mutter('added %d entries', count)
 
151
    
 
152
    if count > 0:
 
153
        tree._write_inventory(inv)
 
154
 
 
155
    return count
 
156
 
 
157
def __add_one(tree, inv, path, kind, reporter):
 
158
    """Add a file or directory, automatically add unversioned parents."""
 
159
 
 
160
    # Nothing to do if path is already versioned.
 
161
    # This is safe from infinite recursion because the tree root is
 
162
    # always versioned.
 
163
    if inv.path2id(path) != None:
 
164
        return 0
 
165
 
 
166
    # add parent
 
167
    count = __add_one(tree, inv, dirname(path), 'directory', reporter)
 
168
 
 
169
    entry = inv.add_path(path, kind=kind)
 
170
    mutter("added %r kind %r file_id={%s}", path, kind, entry.file_id)
 
171
    reporter(path, kind, entry)
 
172
 
 
173
    return count + 1