blob: bc56a4906bc1160b0e63ef6cc263f01889740447 [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
7# created 1999/01/12, Greg Ward
8
9__revision__ = "$Id$"
10
11from types import *
Greg Wardf6cdcd51999-01-18 17:08:16 +000012import sys, os, string, re
Greg Wardd1dc4751999-01-13 16:12:04 +000013
14
15class TextFile:
Greg Wardd1dc4751999-01-13 16:12:04 +000016
17 default_options = { 'strip_comments': 1,
18 'comment_re': re.compile (r'\s*#.*'),
19 'skip_blanks': 1,
20 'join_lines': 0,
21 'lstrip_ws': 0,
22 'rstrip_ws': 1,
Greg Warddb75afe1999-03-08 21:46:11 +000023 'collapse_ws': 0,
Greg Wardd1dc4751999-01-13 16:12:04 +000024 }
25
Greg Ward782cdfe1999-03-23 14:00:06 +000026 def __init__ (self, filename=None, file=None, **options):
27
28 if filename is None and file is None:
29 raise RuntimeError, \
30 "you must supply either or both of 'filename' and 'file'"
Greg Wardd1dc4751999-01-13 16:12:04 +000031
32 # set values for all options -- either from client option hash
33 # or fallback to default_options
34 for opt in self.default_options.keys():
35 if options.has_key (opt):
36 if opt == 'comment_re' and type (options[opt]) is StringType:
37 self.comment_re = re.compile (options[opt])
38 else:
39 setattr (self, opt, options[opt])
40
41 else:
42 setattr (self, opt, self.default_options[opt])
43
44 # sanity check client option hash
45 for opt in options.keys():
46 if not self.default_options.has_key (opt):
47 raise KeyError, "invalid TextFile option '%s'" % opt
48
Greg Ward782cdfe1999-03-23 14:00:06 +000049 if file is None:
50 self.open (filename)
51 else:
52 self.filename = filename
53 self.file = file
54 self.current_line = 0 # assuming that file is at BOF!
Greg Ward787451b1999-03-26 21:48:59 +000055
Greg Ward91c488c1999-03-29 18:01:49 +000056 # 'linebuf' is a stack of lines that will be emptied before we
57 # actually read from the file; it's only populated by an
58 # 'unreadline()' operation
59 self.linebuf = []
Greg Wardd1dc4751999-01-13 16:12:04 +000060
61
Greg Ward782cdfe1999-03-23 14:00:06 +000062 def open (self, filename):
63 self.filename = filename
Greg Wardd1dc4751999-01-13 16:12:04 +000064 self.file = open (self.filename, 'r')
65 self.current_line = 0
66
67
68 def close (self):
69 self.file.close ()
70 self.file = None
71 self.filename = None
72 self.current_line = None
73
74
Greg Wardf6cdcd51999-01-18 17:08:16 +000075 def warn (self, msg):
76 sys.stderr.write (self.filename + ", ")
77 if type (self.current_line) is ListType:
78 sys.stderr.write ("lines %d-%d: " % tuple (self.current_line))
79 else:
80 sys.stderr.write ("line %d: " % self.current_line)
81 sys.stderr.write (msg + "\n")
82
83
Greg Wardd1dc4751999-01-13 16:12:04 +000084 def readline (self):
85
Greg Ward91c488c1999-03-29 18:01:49 +000086 # If any "unread" lines waiting in 'linebuf', return the top
87 # one. (We don't actually buffer read-ahead data -- lines only
88 # get put in 'linebuf' if the client explicitly does an
89 # 'unreadline()'.
90 if self.linebuf:
91 line = self.linebuf[-1]
92 del self.linebuf[-1]
93 return line
94
Greg Wardd1dc4751999-01-13 16:12:04 +000095 buildup_line = ''
96
97 while 1:
98 # read the line, optionally strip comments
99 line = self.file.readline()
100 if self.strip_comments and line:
101 line = self.comment_re.sub ('', line)
102
103 # did previous line end with a backslash? then accumulate
104 if self.join_lines and buildup_line:
105 # oops: end of file
106 if not line:
107 self.warn ("continuation line immediately precedes "
108 "end-of-file")
109 return buildup_line
110
111 line = buildup_line + line
112
113 # careful: pay attention to line number when incrementing it
114 if type (self.current_line) is ListType:
115 self.current_line[1] = self.current_line[1] + 1
116 else:
117 self.current_line = [self.current_line, self.current_line+1]
118 # just an ordinary line, read it as usual
119 else:
120 if not line:
121 return None
122
123 # still have to be careful about incrementing the line number!
124 if type (self.current_line) is ListType:
125 self.current_line = self.current_line[1] + 1
126 else:
127 self.current_line = self.current_line + 1
Greg Ward91c488c1999-03-29 18:01:49 +0000128
Greg Wardd1dc4751999-01-13 16:12:04 +0000129
130 # strip whitespace however the client wants (leading and
131 # trailing, or one or the other, or neither)
132 if self.lstrip_ws and self.rstrip_ws:
133 line = string.strip (line)
134 else:
135 if self.lstrip_ws:
136 line = string.lstrip (line)
137 if self.rstrip_ws:
138 line = string.rstrip (line)
139
140 # blank line (whether we rstrip'ed or not)? skip to next line
141 # if appropriate
142 if line == '' or line == '\n' and self.skip_blanks:
143 continue
144
145 if self.join_lines:
146 if line[-1] == '\\':
147 buildup_line = line[:-1]
148 continue
149
150 if line[-2:] == '\\\n':
151 buildup_line = line[0:-2] + '\n'
152 continue
153
Greg Warddb75afe1999-03-08 21:46:11 +0000154 # collapse internal whitespace (*after* joining lines!)
155 if self.collapse_ws:
156 line = re.sub (r'(\S)\s+(\S)', r'\1 \2', line)
157
Greg Wardd1dc4751999-01-13 16:12:04 +0000158 # well, I guess there's some actual content there: return it
159 return line
160
161 # end readline
162
163
Greg Wardd1dc4751999-01-13 16:12:04 +0000164 def readlines (self):
165 lines = []
166 while 1:
167 line = self.readline()
168 if line is None:
169 return lines
170 lines.append (line)
171
172
Greg Ward91c488c1999-03-29 18:01:49 +0000173 def unreadline (self, line):
174 self.linebuf.append (line)
175
176
Greg Wardd1dc4751999-01-13 16:12:04 +0000177if __name__ == "__main__":
178 test_data = """# test file
179
180line 3 \\
181continues on next line
182"""
183
184 # result 1: no fancy options
185 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
186
187 # result 2: just strip comments
188 result2 = ["\n", "\n", "line 3 \\\n", "continues on next line\n"]
189
190 # result 3: just strip blank lines
191 result3 = ["# test file\n", "line 3 \\\n", "continues on next line\n"]
192
193 # result 4: default, strip comments, blank lines, and trailing whitespace
194 result4 = ["line 3 \\", "continues on next line"]
195
196 # result 5: full processing, strip comments and blanks, plus join lines
197 result5 = ["line 3 continues on next line"]
198
199 def test_input (count, description, file, expected_result):
200 result = file.readlines ()
201 # result = string.join (result, '')
202 if result == expected_result:
203 print "ok %d (%s)" % (count, description)
204 else:
205 print "not ok %d (%s):" % (count, description)
206 print "** expected:"
207 print expected_result
208 print "** received:"
209 print result
210
211
212 filename = "test.txt"
213 out_file = open (filename, "w")
214 out_file.write (test_data)
215 out_file.close ()
216
217 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
218 lstrip_ws=0, rstrip_ws=0)
219 test_input (1, "no processing", in_file, result1)
220
221 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
222 lstrip_ws=0, rstrip_ws=0)
223 test_input (2, "strip comments", in_file, result2)
224
225 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
226 lstrip_ws=0, rstrip_ws=0)
227 test_input (3, "strip blanks", in_file, result3)
228
229 in_file = TextFile (filename)
230 test_input (4, "default processing", in_file, result4)
231
232 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
233 join_lines=1, rstrip_ws=1)
234 test_input (5, "full processing", in_file, result5)
235
236 os.remove (filename)
237