blob: 97459fbf736ae3c42651c4e7132cbbd9122fb3b9 [file] [log] [blame]
Greg Wardd1dc4751999-01-13 16:12:04 +00001"""text_file
2
3provides the TextFile class, which gives an interface to text files
4that (optionally) takes care of stripping comments, ignoring blank
5lines, and joining lines with backslashes."""
6
Greg Wardd1dc4751999-01-13 16:12:04 +00007__revision__ = "$Id$"
8
Guido van Rossum63236cf2007-05-25 18:39:29 +00009import sys, os, io
Greg Wardd1dc4751999-01-13 16:12:04 +000010
11
12class TextFile:
Greg Ward274ad9d1999-09-29 13:03:32 +000013 """Provides a file-like object that takes care of all the things you
14 commonly want to do when processing a text file that has some
Greg Ward60cd2862000-09-16 18:04:55 +000015 line-by-line syntax: strip comments (as long as "#" is your
16 comment character), skip blank lines, join adjacent lines by
17 escaping the newline (ie. backslash at end of line), strip
18 leading and/or trailing whitespace. All of these are optional
19 and independently controllable.
Greg Ward274ad9d1999-09-29 13:03:32 +000020
21 Provides a 'warn()' method so you can generate warning messages that
22 report physical line number, even if the logical line in question
23 spans multiple physical lines. Also provides 'unreadline()' for
24 implementing line-at-a-time lookahead.
25
26 Constructor is called as:
27
28 TextFile (filename=None, file=None, **options)
29
30 It bombs (RuntimeError) if both 'filename' and 'file' are None;
31 'filename' should be a string, and 'file' a file object (or
32 something that provides 'readline()' and 'close()' methods). It is
33 recommended that you supply at least 'filename', so that TextFile
34 can include it in warning messages. If 'file' is not supplied,
Guido van Rossum63236cf2007-05-25 18:39:29 +000035 TextFile creates its own using 'io.open()'.
Greg Ward274ad9d1999-09-29 13:03:32 +000036
37 The options are all boolean, and affect the value returned by
38 'readline()':
39 strip_comments [default: true]
40 strip from "#" to end-of-line, as well as any whitespace
41 leading up to the "#" -- unless it is escaped by a backslash
42 lstrip_ws [default: false]
43 strip leading whitespace from each line before returning it
44 rstrip_ws [default: true]
45 strip trailing whitespace (including line terminator!) from
46 each line before returning it
47 skip_blanks [default: true}
48 skip lines that are empty *after* stripping comments and
Greg Ward60cd2862000-09-16 18:04:55 +000049 whitespace. (If both lstrip_ws and rstrip_ws are false,
Greg Ward274ad9d1999-09-29 13:03:32 +000050 then some lines may consist of solely whitespace: these will
51 *not* be skipped, even if 'skip_blanks' is true.)
52 join_lines [default: false]
53 if a backslash is the last non-newline character on a line
54 after stripping comments and whitespace, join the following line
55 to it to form one "logical line"; if N consecutive lines end
56 with a backslash, then N+1 physical lines will be joined to
57 form one logical line.
Greg Ward60cd2862000-09-16 18:04:55 +000058 collapse_join [default: false]
59 strip leading whitespace from lines that are joined to their
60 predecessor; only matters if (join_lines and not lstrip_ws)
Greg Ward274ad9d1999-09-29 13:03:32 +000061
62 Note that since 'rstrip_ws' can strip the trailing newline, the
63 semantics of 'readline()' must differ from those of the builtin file
64 object's 'readline()' method! In particular, 'readline()' returns
65 None for end-of-file: an empty string might just be a blank line (or
66 an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
67 not."""
68
Greg Wardd1dc4751999-01-13 16:12:04 +000069 default_options = { 'strip_comments': 1,
Greg Wardd1dc4751999-01-13 16:12:04 +000070 'skip_blanks': 1,
Greg Wardd1dc4751999-01-13 16:12:04 +000071 'lstrip_ws': 0,
72 'rstrip_ws': 1,
Greg Ward60cd2862000-09-16 18:04:55 +000073 'join_lines': 0,
74 'collapse_join': 0,
Greg Wardd1dc4751999-01-13 16:12:04 +000075 }
76
Collin Winter5b7e9d72007-08-30 03:52:21 +000077 def __init__(self, filename=None, file=None, **options):
Greg Ward274ad9d1999-09-29 13:03:32 +000078 """Construct a new TextFile object. At least one of 'filename'
79 (a string) and 'file' (a file-like object) must be supplied.
80 They keyword argument options are described above and affect
81 the values returned by 'readline()'."""
Greg Ward782cdfe1999-03-23 14:00:06 +000082 if filename is None and file is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +000083 raise RuntimeError("you must supply either or both of 'filename' and 'file'")
Greg Wardd1dc4751999-01-13 16:12:04 +000084
85 # set values for all options -- either from client option hash
86 # or fallback to default_options
87 for opt in self.default_options.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +000088 if opt in options:
Collin Winter5b7e9d72007-08-30 03:52:21 +000089 setattr(self, opt, options[opt])
Greg Wardd1dc4751999-01-13 16:12:04 +000090 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +000091 setattr(self, opt, self.default_options[opt])
Greg Wardd1dc4751999-01-13 16:12:04 +000092
93 # sanity check client option hash
94 for opt in options.keys():
Guido van Rossume2b70bc2006-08-18 22:13:04 +000095 if opt not in self.default_options:
Collin Winter5b7e9d72007-08-30 03:52:21 +000096 raise KeyError("invalid TextFile option '%s'" % opt)
Greg Wardd1dc4751999-01-13 16:12:04 +000097
Greg Ward782cdfe1999-03-23 14:00:06 +000098 if file is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +000099 self.open(filename)
Greg Ward782cdfe1999-03-23 14:00:06 +0000100 else:
101 self.filename = filename
102 self.file = file
103 self.current_line = 0 # assuming that file is at BOF!
Greg Ward787451b1999-03-26 21:48:59 +0000104
Greg Ward91c488c1999-03-29 18:01:49 +0000105 # 'linebuf' is a stack of lines that will be emptied before we
106 # actually read from the file; it's only populated by an
107 # 'unreadline()' operation
108 self.linebuf = []
Fred Drakeb94b8492001-12-06 20:51:35 +0000109
Collin Winter5b7e9d72007-08-30 03:52:21 +0000110 def open(self, filename):
Greg Ward274ad9d1999-09-29 13:03:32 +0000111 """Open a new file named 'filename'. This overrides both the
112 'filename' and 'file' arguments to the constructor."""
Greg Ward782cdfe1999-03-23 14:00:06 +0000113 self.filename = filename
Collin Winter5b7e9d72007-08-30 03:52:21 +0000114 self.file = io.open(self.filename, 'r')
Greg Wardd1dc4751999-01-13 16:12:04 +0000115 self.current_line = 0
116
Collin Winter5b7e9d72007-08-30 03:52:21 +0000117 def close(self):
Greg Ward274ad9d1999-09-29 13:03:32 +0000118 """Close the current file and forget everything we know about it
119 (filename, current line number)."""
Collin Winter5b7e9d72007-08-30 03:52:21 +0000120 self.file.close()
Greg Wardd1dc4751999-01-13 16:12:04 +0000121 self.file = None
122 self.filename = None
123 self.current_line = None
124
Collin Winter5b7e9d72007-08-30 03:52:21 +0000125 def gen_error(self, msg, line=None):
Greg Wardf11296b2000-09-16 18:06:31 +0000126 outmsg = []
127 if line is None:
128 line = self.current_line
129 outmsg.append(self.filename + ", ")
Collin Winter5b7e9d72007-08-30 03:52:21 +0000130 if isinstance(line, (list, tuple)):
131 outmsg.append("lines %d-%d: " % tuple(line))
Greg Wardf11296b2000-09-16 18:06:31 +0000132 else:
133 outmsg.append("line %d: " % line)
134 outmsg.append(str(msg))
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000135 return "".join(outmsg)
Greg Wardf11296b2000-09-16 18:06:31 +0000136
Collin Winter5b7e9d72007-08-30 03:52:21 +0000137 def error(self, msg, line=None):
138 raise ValueError("error: " + self.gen_error(msg, line))
Greg Wardf11296b2000-09-16 18:06:31 +0000139
Collin Winter5b7e9d72007-08-30 03:52:21 +0000140 def warn(self, msg, line=None):
Greg Ward274ad9d1999-09-29 13:03:32 +0000141 """Print (to stderr) a warning message tied to the current logical
142 line in the current file. If the current logical line in the
143 file spans multiple physical lines, the warning refers to the
144 whole range, eg. "lines 3-5". If 'line' supplied, it overrides
145 the current line number; it may be a list or tuple to indicate a
146 range of physical lines, or an integer for a single physical
147 line."""
Greg Wardf11296b2000-09-16 18:06:31 +0000148 sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
Greg Wardf6cdcd51999-01-18 17:08:16 +0000149
Collin Winter5b7e9d72007-08-30 03:52:21 +0000150 def readline(self):
Greg Ward274ad9d1999-09-29 13:03:32 +0000151 """Read and return a single logical line from the current file (or
152 from an internal buffer if lines have previously been "unread"
153 with 'unreadline()'). If the 'join_lines' option is true, this
154 may involve reading multiple physical lines concatenated into a
155 single string. Updates the current line number, so calling
156 'warn()' after 'readline()' emits a warning about the physical
157 line(s) just read. Returns None on end-of-file, since the empty
158 string can occur if 'rstrip_ws' is true but 'strip_blanks' is
159 not."""
Greg Ward91c488c1999-03-29 18:01:49 +0000160 # If any "unread" lines waiting in 'linebuf', return the top
161 # one. (We don't actually buffer read-ahead data -- lines only
162 # get put in 'linebuf' if the client explicitly does an
163 # 'unreadline()'.
164 if self.linebuf:
165 line = self.linebuf[-1]
166 del self.linebuf[-1]
167 return line
168
Greg Wardd1dc4751999-01-13 16:12:04 +0000169 buildup_line = ''
170
Collin Winter5b7e9d72007-08-30 03:52:21 +0000171 while True:
Greg Wardabc2f961999-08-10 20:09:38 +0000172 # read the line, make it None if EOF
Greg Wardd1dc4751999-01-13 16:12:04 +0000173 line = self.file.readline()
Collin Winter5b7e9d72007-08-30 03:52:21 +0000174 if line == '':
175 line = None
Greg Wardabc2f961999-08-10 20:09:38 +0000176
Greg Wardd1dc4751999-01-13 16:12:04 +0000177 if self.strip_comments and line:
Greg Wardabc2f961999-08-10 20:09:38 +0000178
179 # Look for the first "#" in the line. If none, never
180 # mind. If we find one and it's the first character, or
181 # is not preceded by "\", then it starts a comment --
182 # strip the comment, strip whitespace before it, and
183 # carry on. Otherwise, it's just an escaped "#", so
184 # unescape it (and any other escaped "#"'s that might be
185 # lurking in there) and otherwise leave the line alone.
186
Collin Winter5b7e9d72007-08-30 03:52:21 +0000187 pos = line.find("#")
188 if pos == -1: # no "#" -- no comments
Greg Wardabc2f961999-08-10 20:09:38 +0000189 pass
Greg Wardacff0b32000-09-16 18:33:36 +0000190
191 # It's definitely a comment -- either "#" is the first
192 # character, or it's elsewhere and unescaped.
193 elif pos == 0 or line[pos-1] != "\\":
Greg Ward274ad9d1999-09-29 13:03:32 +0000194 # Have to preserve the trailing newline, because it's
195 # the job of a later step (rstrip_ws) to remove it --
196 # and if rstrip_ws is false, we'd better preserve it!
197 # (NB. this means that if the final line is all comment
198 # and has no trailing newline, we will think that it's
Greg Wardabc2f961999-08-10 20:09:38 +0000199 # EOF; I think that's OK.)
Greg Ward274ad9d1999-09-29 13:03:32 +0000200 eol = (line[-1] == '\n') and '\n' or ''
201 line = line[0:pos] + eol
Fred Drakeb94b8492001-12-06 20:51:35 +0000202
Greg Wardacff0b32000-09-16 18:33:36 +0000203 # If all that's left is whitespace, then skip line
204 # *now*, before we try to join it to 'buildup_line' --
205 # that way constructs like
206 # hello \\
207 # # comment that should be ignored
208 # there
209 # result in "hello there".
Collin Winter5b7e9d72007-08-30 03:52:21 +0000210 if line.strip() == "":
Greg Wardacff0b32000-09-16 18:33:36 +0000211 continue
Collin Winter5b7e9d72007-08-30 03:52:21 +0000212 else: # it's an escaped "#"
Neal Norwitz9d72bb42007-04-17 08:48:32 +0000213 line = line.replace("\\#", "#")
Fred Drakeb94b8492001-12-06 20:51:35 +0000214
Greg Wardd1dc4751999-01-13 16:12:04 +0000215 # did previous line end with a backslash? then accumulate
216 if self.join_lines and buildup_line:
217 # oops: end of file
Greg Wardabc2f961999-08-10 20:09:38 +0000218 if line is None:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000219 self.warn("continuation line immediately precedes "
220 "end-of-file")
Greg Wardd1dc4751999-01-13 16:12:04 +0000221 return buildup_line
222
Greg Ward60cd2862000-09-16 18:04:55 +0000223 if self.collapse_join:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000224 line = line.lstrip()
Greg Wardd1dc4751999-01-13 16:12:04 +0000225 line = buildup_line + line
226
227 # careful: pay attention to line number when incrementing it
Collin Winter5b7e9d72007-08-30 03:52:21 +0000228 if isinstance(self.current_line, list):
Greg Wardd1dc4751999-01-13 16:12:04 +0000229 self.current_line[1] = self.current_line[1] + 1
230 else:
Greg Wardacff0b32000-09-16 18:33:36 +0000231 self.current_line = [self.current_line,
Collin Winter5b7e9d72007-08-30 03:52:21 +0000232 self.current_line + 1]
Greg Wardd1dc4751999-01-13 16:12:04 +0000233 # just an ordinary line, read it as usual
234 else:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000235 if line is None: # eof
Greg Wardd1dc4751999-01-13 16:12:04 +0000236 return None
237
238 # still have to be careful about incrementing the line number!
Collin Winter5b7e9d72007-08-30 03:52:21 +0000239 if isinstance(self.current_line, list):
Greg Wardd1dc4751999-01-13 16:12:04 +0000240 self.current_line = self.current_line[1] + 1
241 else:
242 self.current_line = self.current_line + 1
Fred Drakeb94b8492001-12-06 20:51:35 +0000243
Greg Wardd1dc4751999-01-13 16:12:04 +0000244 # strip whitespace however the client wants (leading and
245 # trailing, or one or the other, or neither)
246 if self.lstrip_ws and self.rstrip_ws:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000247 line = line.strip()
Greg Ward274ad9d1999-09-29 13:03:32 +0000248 elif self.lstrip_ws:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000249 line = line.lstrip()
Greg Ward274ad9d1999-09-29 13:03:32 +0000250 elif self.rstrip_ws:
Collin Winter5b7e9d72007-08-30 03:52:21 +0000251 line = line.rstrip()
Greg Wardd1dc4751999-01-13 16:12:04 +0000252
253 # blank line (whether we rstrip'ed or not)? skip to next line
254 # if appropriate
Greg Ward3d05c162000-09-16 18:09:22 +0000255 if (line == '' or line == '\n') and self.skip_blanks:
Greg Wardd1dc4751999-01-13 16:12:04 +0000256 continue
257
258 if self.join_lines:
259 if line[-1] == '\\':
260 buildup_line = line[:-1]
261 continue
262
263 if line[-2:] == '\\\n':
264 buildup_line = line[0:-2] + '\n'
265 continue
266
Greg Wardd1dc4751999-01-13 16:12:04 +0000267 # well, I guess there's some actual content there: return it
268 return line
269
Collin Winter5b7e9d72007-08-30 03:52:21 +0000270 def readlines(self):
Greg Ward274ad9d1999-09-29 13:03:32 +0000271 """Read and return the list of all logical lines remaining in the
272 current file."""
Greg Wardd1dc4751999-01-13 16:12:04 +0000273 lines = []
Collin Winter5b7e9d72007-08-30 03:52:21 +0000274 while True:
Greg Wardd1dc4751999-01-13 16:12:04 +0000275 line = self.readline()
276 if line is None:
277 return lines
Collin Winter5b7e9d72007-08-30 03:52:21 +0000278 lines.append(line)
Greg Wardd1dc4751999-01-13 16:12:04 +0000279
Collin Winter5b7e9d72007-08-30 03:52:21 +0000280 def unreadline(self, line):
Greg Ward274ad9d1999-09-29 13:03:32 +0000281 """Push 'line' (a string) onto an internal buffer that will be
282 checked by future 'readline()' calls. Handy for implementing
283 a parser with line-at-a-time lookahead."""
Collin Winter5b7e9d72007-08-30 03:52:21 +0000284 self.linebuf.append(line)