~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/ignores.py

  • Committer: Andrew Bennetts
  • Date: 2010-10-13 00:26:41 UTC
  • mto: This revision was merged to the branch mainline in revision 5498.
  • Revision ID: andrew.bennetts@canonical.com-20101013002641-9tlh9k89mlj1666m
Keep docs-plain working.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2010 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
"""Lists of ignore files, etc."""
 
18
 
 
19
import errno
 
20
import os
 
21
from cStringIO import StringIO
 
22
 
 
23
import bzrlib
 
24
from bzrlib import (
 
25
    atomicfile,
 
26
    config,
 
27
    globbing,
 
28
    )
 
29
 
 
30
from trace import warning
 
31
 
 
32
# ~/.bazaar/ignore will be filled out using
 
33
# this ignore list, if it does not exist
 
34
# please keep these sorted (in C locale order) to aid merging
 
35
USER_DEFAULTS = [
 
36
    '*.a',
 
37
    '*.o',
 
38
    '*.py[co]',
 
39
    '*.so',
 
40
    '*.sw[nop]',
 
41
    '*~',
 
42
    '.#*',
 
43
    '[#]*#',
 
44
    '__pycache__',
 
45
]
 
46
 
 
47
 
 
48
 
 
49
def parse_ignore_file(f):
 
50
    """Read in all of the lines in the file and turn it into an ignore list
 
51
    
 
52
    Continue in the case of utf8 decoding errors, and emit a warning when 
 
53
    such and error is found. Optimise for the common case -- no decoding 
 
54
    errors.
 
55
    """
 
56
    ignored = set()
 
57
    ignore_file = f.read()
 
58
    try:
 
59
        # Try and parse whole ignore file at once.
 
60
        unicode_lines = ignore_file.decode('utf8').split('\n')
 
61
    except UnicodeDecodeError:
 
62
        # Otherwise go though line by line and pick out the 'good'
 
63
        # decodable lines
 
64
        lines = ignore_file.split('\n')
 
65
        unicode_lines = []
 
66
        for line_number, line in enumerate(lines):
 
67
            try:
 
68
                unicode_lines.append(line.decode('utf-8'))
 
69
            except UnicodeDecodeError:
 
70
                # report error about line (idx+1)
 
71
                warning('.bzrignore: On Line #%d, malformed utf8 character. '
 
72
                        'Ignoring line.' % (line_number+1))
 
73
 
 
74
    # Append each line to ignore list if it's not a comment line
 
75
    for line in unicode_lines:
 
76
        line = line.rstrip('\r\n')
 
77
        if not line or line.startswith('#'):
 
78
            continue
 
79
        ignored.add(globbing.normalize_pattern(line))
 
80
    return ignored
 
81
 
 
82
 
 
83
def get_user_ignores():
 
84
    """Get the list of user ignored files, possibly creating it."""
 
85
    path = config.user_ignore_config_filename()
 
86
    patterns = set(USER_DEFAULTS)
 
87
    try:
 
88
        f = open(path, 'rb')
 
89
    except (IOError, OSError), e:
 
90
        # open() shouldn't return an IOError without errno, but just in case
 
91
        err = getattr(e, 'errno', None)
 
92
        if err not in (errno.ENOENT,):
 
93
            raise
 
94
        # Create the ignore file, and just return the default
 
95
        # We want to ignore if we can't write to the file
 
96
        # since get_* should be a safe operation
 
97
        try:
 
98
            _set_user_ignores(USER_DEFAULTS)
 
99
        except (IOError, OSError), e:
 
100
            if e.errno not in (errno.EPERM,):
 
101
                raise
 
102
        return patterns
 
103
 
 
104
    try:
 
105
        return parse_ignore_file(f)
 
106
    finally:
 
107
        f.close()
 
108
 
 
109
 
 
110
def _set_user_ignores(patterns):
 
111
    """Fill out the user ignore file with the given patterns
 
112
 
 
113
    This may raise an error if it doesn't have permission to
 
114
    write to the user ignore file.
 
115
    This is mostly used for testing, since it would be
 
116
    bad form to rewrite a user's ignore list.
 
117
    bzrlib only writes this file if it does not exist.
 
118
    """
 
119
    ignore_path = config.user_ignore_config_filename()
 
120
    config.ensure_config_dir_exists()
 
121
 
 
122
    # Create an empty file
 
123
    f = open(ignore_path, 'wb')
 
124
    try:
 
125
        for pattern in patterns:
 
126
            f.write(pattern.encode('utf8') + '\n')
 
127
    finally:
 
128
        f.close()
 
129
 
 
130
 
 
131
def add_unique_user_ignores(new_ignores):
 
132
    """Add entries to the user's ignore list if not present.
 
133
 
 
134
    :param new_ignores: A list of ignore patterns
 
135
    :return: The list of ignores that were added
 
136
    """
 
137
    ignored = get_user_ignores()
 
138
    to_add = []
 
139
    for ignore in new_ignores:
 
140
        ignore = globbing.normalize_pattern(ignore)
 
141
        if ignore not in ignored:
 
142
            ignored.add(ignore)
 
143
            to_add.append(ignore)
 
144
 
 
145
    if not to_add:
 
146
        return []
 
147
 
 
148
    f = open(config.user_ignore_config_filename(), 'ab')
 
149
    try:
 
150
        for pattern in to_add:
 
151
            f.write(pattern.encode('utf8') + '\n')
 
152
    finally:
 
153
        f.close()
 
154
 
 
155
    return to_add
 
156
 
 
157
 
 
158
_runtime_ignores = set()
 
159
 
 
160
 
 
161
def add_runtime_ignores(ignores):
 
162
    """Add some ignore patterns that only exists in memory.
 
163
 
 
164
    This is used by some plugins that want bzr to ignore files,
 
165
    but don't want to change a users ignore list.
 
166
    (Such as a conversion script that needs to ignore temporary files,
 
167
    but does not want to modify the project's ignore list.)
 
168
 
 
169
    :param ignores: A list or generator of ignore patterns.
 
170
    :return: None
 
171
    """
 
172
    global _runtime_ignores
 
173
    _runtime_ignores.update(set(ignores))
 
174
 
 
175
 
 
176
def get_runtime_ignores():
 
177
    """Get the current set of runtime ignores."""
 
178
    return _runtime_ignores
 
179
 
 
180
 
 
181
def tree_ignores_add_patterns(tree, name_pattern_list):
 
182
    """Add more ignore patterns to the ignore file in a tree.
 
183
    If ignore file does not exist then it will be created.
 
184
    The ignore file will be automatically added under version control.
 
185
 
 
186
    :param tree: Working tree to update the ignore list.
 
187
    :param name_pattern_list: List of ignore patterns.
 
188
    :return: None
 
189
    """
 
190
    # read in the existing ignores set
 
191
    ifn = tree.abspath(bzrlib.IGNORE_FILENAME)
 
192
    if tree.has_filename(ifn):
 
193
        f = open(ifn, 'rU')
 
194
        try:
 
195
            file_contents = f.read()
 
196
            # figure out what kind of line endings are used
 
197
            newline = getattr(f, 'newlines', None)
 
198
            if type(newline) is tuple:
 
199
                newline = newline[0]
 
200
            elif newline is None:
 
201
                newline = os.linesep
 
202
        finally:
 
203
            f.close()
 
204
    else:
 
205
        file_contents = ""
 
206
        newline = os.linesep
 
207
    
 
208
    sio = StringIO(file_contents)
 
209
    try:
 
210
        ignores = parse_ignore_file(sio)
 
211
    finally:
 
212
        sio.close()
 
213
    
 
214
    # write out the updated ignores set
 
215
    f = atomicfile.AtomicFile(ifn, 'wb')
 
216
    try:
 
217
        # write the original contents, preserving original line endings
 
218
        f.write(newline.join(file_contents.split('\n')))
 
219
        if len(file_contents) > 0 and not file_contents.endswith('\n'):
 
220
            f.write(newline)
 
221
        for pattern in name_pattern_list:
 
222
            if not pattern in ignores:
 
223
                f.write(pattern.encode('utf-8'))
 
224
                f.write(newline)
 
225
        f.commit()
 
226
    finally:
 
227
        f.close()
 
228
 
 
229
    if not tree.path2id(bzrlib.IGNORE_FILENAME):
 
230
        tree.add([bzrlib.IGNORE_FILENAME])