Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 1 | """text_file |
| 2 | |
| 3 | provides the TextFile class, which gives an interface to text files |
| 4 | that (optionally) takes care of stripping comments, ignoring blank |
| 5 | lines, and joining lines with backslashes.""" |
| 6 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 7 | __revision__ = "$Id$" |
| 8 | |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 9 | import sys |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 10 | |
| 11 | |
| 12 | class TextFile: |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 13 | |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 14 | """Provides a file-like object that takes care of all the things you |
| 15 | commonly want to do when processing a text file that has some |
Greg Ward | 60cd286 | 2000-09-16 18:04:55 +0000 | [diff] [blame] | 16 | line-by-line syntax: strip comments (as long as "#" is your |
| 17 | comment character), skip blank lines, join adjacent lines by |
| 18 | escaping the newline (ie. backslash at end of line), strip |
| 19 | leading and/or trailing whitespace. All of these are optional |
| 20 | and independently controllable. |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 21 | |
| 22 | Provides a 'warn()' method so you can generate warning messages that |
| 23 | report physical line number, even if the logical line in question |
| 24 | spans multiple physical lines. Also provides 'unreadline()' for |
| 25 | implementing line-at-a-time lookahead. |
| 26 | |
| 27 | Constructor is called as: |
| 28 | |
| 29 | TextFile (filename=None, file=None, **options) |
| 30 | |
| 31 | It bombs (RuntimeError) if both 'filename' and 'file' are None; |
| 32 | 'filename' should be a string, and 'file' a file object (or |
| 33 | something that provides 'readline()' and 'close()' methods). It is |
| 34 | recommended that you supply at least 'filename', so that TextFile |
| 35 | can include it in warning messages. If 'file' is not supplied, |
| 36 | TextFile creates its own using the 'open()' builtin. |
| 37 | |
| 38 | The options are all boolean, and affect the value returned by |
| 39 | 'readline()': |
| 40 | strip_comments [default: true] |
| 41 | strip from "#" to end-of-line, as well as any whitespace |
| 42 | leading up to the "#" -- unless it is escaped by a backslash |
| 43 | lstrip_ws [default: false] |
| 44 | strip leading whitespace from each line before returning it |
| 45 | rstrip_ws [default: true] |
| 46 | strip trailing whitespace (including line terminator!) from |
| 47 | each line before returning it |
| 48 | skip_blanks [default: true} |
| 49 | skip lines that are empty *after* stripping comments and |
Greg Ward | 60cd286 | 2000-09-16 18:04:55 +0000 | [diff] [blame] | 50 | whitespace. (If both lstrip_ws and rstrip_ws are false, |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 51 | then some lines may consist of solely whitespace: these will |
| 52 | *not* be skipped, even if 'skip_blanks' is true.) |
| 53 | join_lines [default: false] |
| 54 | if a backslash is the last non-newline character on a line |
| 55 | after stripping comments and whitespace, join the following line |
| 56 | to it to form one "logical line"; if N consecutive lines end |
| 57 | with a backslash, then N+1 physical lines will be joined to |
| 58 | form one logical line. |
Greg Ward | 60cd286 | 2000-09-16 18:04:55 +0000 | [diff] [blame] | 59 | collapse_join [default: false] |
| 60 | strip leading whitespace from lines that are joined to their |
| 61 | predecessor; only matters if (join_lines and not lstrip_ws) |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 62 | |
| 63 | Note that since 'rstrip_ws' can strip the trailing newline, the |
| 64 | semantics of 'readline()' must differ from those of the builtin file |
| 65 | object's 'readline()' method! In particular, 'readline()' returns |
| 66 | None for end-of-file: an empty string might just be a blank line (or |
| 67 | an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is |
| 68 | not.""" |
| 69 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 70 | default_options = { 'strip_comments': 1, |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 71 | 'skip_blanks': 1, |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 72 | 'lstrip_ws': 0, |
| 73 | 'rstrip_ws': 1, |
Greg Ward | 60cd286 | 2000-09-16 18:04:55 +0000 | [diff] [blame] | 74 | 'join_lines': 0, |
| 75 | 'collapse_join': 0, |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 76 | } |
| 77 | |
Greg Ward | 782cdfe | 1999-03-23 14:00:06 +0000 | [diff] [blame] | 78 | def __init__ (self, filename=None, file=None, **options): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 79 | """Construct a new TextFile object. At least one of 'filename' |
| 80 | (a string) and 'file' (a file-like object) must be supplied. |
| 81 | They keyword argument options are described above and affect |
| 82 | the values returned by 'readline()'.""" |
Greg Ward | 782cdfe | 1999-03-23 14:00:06 +0000 | [diff] [blame] | 83 | |
| 84 | if filename is None and file is None: |
| 85 | raise RuntimeError, \ |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 86 | "you must supply either or both of 'filename' and 'file'" |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 87 | |
| 88 | # set values for all options -- either from client option hash |
| 89 | # or fallback to default_options |
| 90 | for opt in self.default_options.keys(): |
Guido van Rossum | 8bc0965 | 2008-02-21 18:18:37 +0000 | [diff] [blame] | 91 | if opt in options: |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 92 | setattr (self, opt, options[opt]) |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 93 | |
| 94 | else: |
| 95 | setattr (self, opt, self.default_options[opt]) |
| 96 | |
| 97 | # sanity check client option hash |
| 98 | for opt in options.keys(): |
Guido van Rossum | 8bc0965 | 2008-02-21 18:18:37 +0000 | [diff] [blame] | 99 | if opt not in self.default_options: |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 100 | raise KeyError, "invalid TextFile option '%s'" % opt |
| 101 | |
Greg Ward | 782cdfe | 1999-03-23 14:00:06 +0000 | [diff] [blame] | 102 | if file is None: |
| 103 | self.open (filename) |
| 104 | else: |
| 105 | self.filename = filename |
| 106 | self.file = file |
| 107 | self.current_line = 0 # assuming that file is at BOF! |
Greg Ward | 787451b | 1999-03-26 21:48:59 +0000 | [diff] [blame] | 108 | |
Greg Ward | 91c488c | 1999-03-29 18:01:49 +0000 | [diff] [blame] | 109 | # 'linebuf' is a stack of lines that will be emptied before we |
| 110 | # actually read from the file; it's only populated by an |
| 111 | # 'unreadline()' operation |
| 112 | self.linebuf = [] |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 113 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 114 | |
Greg Ward | 782cdfe | 1999-03-23 14:00:06 +0000 | [diff] [blame] | 115 | def open (self, filename): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 116 | """Open a new file named 'filename'. This overrides both the |
| 117 | 'filename' and 'file' arguments to the constructor.""" |
| 118 | |
Greg Ward | 782cdfe | 1999-03-23 14:00:06 +0000 | [diff] [blame] | 119 | self.filename = filename |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 120 | self.file = open (self.filename, 'r') |
| 121 | self.current_line = 0 |
| 122 | |
| 123 | |
| 124 | def close (self): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 125 | """Close the current file and forget everything we know about it |
| 126 | (filename, current line number).""" |
Serhiy Storchaka | 1aa2c0f | 2015-04-10 13:24:10 +0300 | [diff] [blame] | 127 | file = self.file |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 128 | self.file = None |
| 129 | self.filename = None |
| 130 | self.current_line = None |
Serhiy Storchaka | 1aa2c0f | 2015-04-10 13:24:10 +0300 | [diff] [blame] | 131 | file.close() |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 132 | |
| 133 | |
Greg Ward | f11296b | 2000-09-16 18:06:31 +0000 | [diff] [blame] | 134 | def gen_error (self, msg, line=None): |
| 135 | outmsg = [] |
| 136 | if line is None: |
| 137 | line = self.current_line |
| 138 | outmsg.append(self.filename + ", ") |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 139 | if isinstance(line, (list, tuple)): |
Greg Ward | f11296b | 2000-09-16 18:06:31 +0000 | [diff] [blame] | 140 | outmsg.append("lines %d-%d: " % tuple (line)) |
| 141 | else: |
| 142 | outmsg.append("line %d: " % line) |
| 143 | outmsg.append(str(msg)) |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 144 | return ''.join(outmsg) |
Greg Ward | f11296b | 2000-09-16 18:06:31 +0000 | [diff] [blame] | 145 | |
| 146 | |
| 147 | def error (self, msg, line=None): |
| 148 | raise ValueError, "error: " + self.gen_error(msg, line) |
| 149 | |
Greg Ward | 4e5a7c7 | 1999-04-15 17:50:19 +0000 | [diff] [blame] | 150 | def warn (self, msg, line=None): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 151 | """Print (to stderr) a warning message tied to the current logical |
| 152 | line in the current file. If the current logical line in the |
| 153 | file spans multiple physical lines, the warning refers to the |
| 154 | whole range, eg. "lines 3-5". If 'line' supplied, it overrides |
| 155 | the current line number; it may be a list or tuple to indicate a |
| 156 | range of physical lines, or an integer for a single physical |
| 157 | line.""" |
Greg Ward | f11296b | 2000-09-16 18:06:31 +0000 | [diff] [blame] | 158 | sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n") |
Greg Ward | f6cdcd5 | 1999-01-18 17:08:16 +0000 | [diff] [blame] | 159 | |
| 160 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 161 | def readline (self): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 162 | """Read and return a single logical line from the current file (or |
| 163 | from an internal buffer if lines have previously been "unread" |
| 164 | with 'unreadline()'). If the 'join_lines' option is true, this |
| 165 | may involve reading multiple physical lines concatenated into a |
| 166 | single string. Updates the current line number, so calling |
| 167 | 'warn()' after 'readline()' emits a warning about the physical |
| 168 | line(s) just read. Returns None on end-of-file, since the empty |
| 169 | string can occur if 'rstrip_ws' is true but 'strip_blanks' is |
| 170 | not.""" |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 171 | |
Greg Ward | 91c488c | 1999-03-29 18:01:49 +0000 | [diff] [blame] | 172 | # If any "unread" lines waiting in 'linebuf', return the top |
| 173 | # one. (We don't actually buffer read-ahead data -- lines only |
| 174 | # get put in 'linebuf' if the client explicitly does an |
| 175 | # 'unreadline()'. |
| 176 | if self.linebuf: |
| 177 | line = self.linebuf[-1] |
| 178 | del self.linebuf[-1] |
| 179 | return line |
| 180 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 181 | buildup_line = '' |
| 182 | |
| 183 | while 1: |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 184 | # read the line, make it None if EOF |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 185 | line = self.file.readline() |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 186 | if line == '': line = None |
| 187 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 188 | if self.strip_comments and line: |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 189 | |
| 190 | # Look for the first "#" in the line. If none, never |
| 191 | # mind. If we find one and it's the first character, or |
| 192 | # is not preceded by "\", then it starts a comment -- |
| 193 | # strip the comment, strip whitespace before it, and |
| 194 | # carry on. Otherwise, it's just an escaped "#", so |
| 195 | # unescape it (and any other escaped "#"'s that might be |
| 196 | # lurking in there) and otherwise leave the line alone. |
| 197 | |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 198 | pos = line.find("#") |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 199 | if pos == -1: # no "#" -- no comments |
| 200 | pass |
Greg Ward | acff0b3 | 2000-09-16 18:33:36 +0000 | [diff] [blame] | 201 | |
| 202 | # It's definitely a comment -- either "#" is the first |
| 203 | # character, or it's elsewhere and unescaped. |
| 204 | elif pos == 0 or line[pos-1] != "\\": |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 205 | # Have to preserve the trailing newline, because it's |
| 206 | # the job of a later step (rstrip_ws) to remove it -- |
| 207 | # and if rstrip_ws is false, we'd better preserve it! |
| 208 | # (NB. this means that if the final line is all comment |
| 209 | # and has no trailing newline, we will think that it's |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 210 | # EOF; I think that's OK.) |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 211 | eol = (line[-1] == '\n') and '\n' or '' |
| 212 | line = line[0:pos] + eol |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 213 | |
Greg Ward | acff0b3 | 2000-09-16 18:33:36 +0000 | [diff] [blame] | 214 | # If all that's left is whitespace, then skip line |
| 215 | # *now*, before we try to join it to 'buildup_line' -- |
| 216 | # that way constructs like |
| 217 | # hello \\ |
| 218 | # # comment that should be ignored |
| 219 | # there |
| 220 | # result in "hello there". |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 221 | if line.strip() == "": |
Greg Ward | acff0b3 | 2000-09-16 18:33:36 +0000 | [diff] [blame] | 222 | continue |
| 223 | |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 224 | else: # it's an escaped "#" |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 225 | line = line.replace("\\#", "#") |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 226 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 227 | |
| 228 | # did previous line end with a backslash? then accumulate |
| 229 | if self.join_lines and buildup_line: |
| 230 | # oops: end of file |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 231 | if line is None: |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 232 | self.warn ("continuation line immediately precedes " |
| 233 | "end-of-file") |
| 234 | return buildup_line |
| 235 | |
Greg Ward | 60cd286 | 2000-09-16 18:04:55 +0000 | [diff] [blame] | 236 | if self.collapse_join: |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 237 | line = line.lstrip() |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 238 | line = buildup_line + line |
| 239 | |
| 240 | # careful: pay attention to line number when incrementing it |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 241 | if isinstance(self.current_line, list): |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 242 | self.current_line[1] = self.current_line[1] + 1 |
| 243 | else: |
Greg Ward | acff0b3 | 2000-09-16 18:33:36 +0000 | [diff] [blame] | 244 | self.current_line = [self.current_line, |
| 245 | self.current_line+1] |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 246 | # just an ordinary line, read it as usual |
| 247 | else: |
Greg Ward | abc2f96 | 1999-08-10 20:09:38 +0000 | [diff] [blame] | 248 | if line is None: # eof |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 249 | return None |
| 250 | |
| 251 | # still have to be careful about incrementing the line number! |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 252 | if isinstance(self.current_line, list): |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 253 | self.current_line = self.current_line[1] + 1 |
| 254 | else: |
| 255 | self.current_line = self.current_line + 1 |
Fred Drake | b94b849 | 2001-12-06 20:51:35 +0000 | [diff] [blame] | 256 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 257 | |
| 258 | # strip whitespace however the client wants (leading and |
| 259 | # trailing, or one or the other, or neither) |
| 260 | if self.lstrip_ws and self.rstrip_ws: |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 261 | line = line.strip() |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 262 | elif self.lstrip_ws: |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 263 | line = line.lstrip() |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 264 | elif self.rstrip_ws: |
Tarek Ziadé | 2b66da7 | 2009-12-21 01:22:46 +0000 | [diff] [blame] | 265 | line = line.rstrip() |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 266 | |
| 267 | # blank line (whether we rstrip'ed or not)? skip to next line |
| 268 | # if appropriate |
Greg Ward | 3d05c16 | 2000-09-16 18:09:22 +0000 | [diff] [blame] | 269 | if (line == '' or line == '\n') and self.skip_blanks: |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 270 | continue |
| 271 | |
| 272 | if self.join_lines: |
| 273 | if line[-1] == '\\': |
| 274 | buildup_line = line[:-1] |
| 275 | continue |
| 276 | |
| 277 | if line[-2:] == '\\\n': |
| 278 | buildup_line = line[0:-2] + '\n' |
| 279 | continue |
| 280 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 281 | # well, I guess there's some actual content there: return it |
| 282 | return line |
| 283 | |
Greg Ward | acff0b3 | 2000-09-16 18:33:36 +0000 | [diff] [blame] | 284 | # readline () |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 285 | |
| 286 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 287 | def readlines (self): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 288 | """Read and return the list of all logical lines remaining in the |
| 289 | current file.""" |
| 290 | |
Greg Ward | d1dc475 | 1999-01-13 16:12:04 +0000 | [diff] [blame] | 291 | lines = [] |
| 292 | while 1: |
| 293 | line = self.readline() |
| 294 | if line is None: |
| 295 | return lines |
| 296 | lines.append (line) |
| 297 | |
| 298 | |
Greg Ward | 91c488c | 1999-03-29 18:01:49 +0000 | [diff] [blame] | 299 | def unreadline (self, line): |
Greg Ward | 274ad9d | 1999-09-29 13:03:32 +0000 | [diff] [blame] | 300 | """Push 'line' (a string) onto an internal buffer that will be |
| 301 | checked by future 'readline()' calls. Handy for implementing |
| 302 | a parser with line-at-a-time lookahead.""" |
| 303 | |
Greg Ward | 91c488c | 1999-03-29 18:01:49 +0000 | [diff] [blame] | 304 | self.linebuf.append (line) |