blob: a27df06d45692dbb33cf55fbcfe3600c1e9dc81a [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 Ward4e5a7c71999-04-15 17:50:19 +000075 def warn (self, msg, line=None):
76 if line is None:
77 line = self.current_line
Greg Wardf6cdcd51999-01-18 17:08:16 +000078 sys.stderr.write (self.filename + ", ")
Greg Ward4e5a7c71999-04-15 17:50:19 +000079 if type (line) is ListType:
80 sys.stderr.write ("lines %d-%d: " % tuple (line))
Greg Wardf6cdcd51999-01-18 17:08:16 +000081 else:
Greg Ward4e5a7c71999-04-15 17:50:19 +000082 sys.stderr.write ("line %d: " % line)
Greg Wardf6cdcd51999-01-18 17:08:16 +000083 sys.stderr.write (msg + "\n")
84
85
Greg Wardd1dc4751999-01-13 16:12:04 +000086 def readline (self):
87
Greg Ward91c488c1999-03-29 18:01:49 +000088 # If any "unread" lines waiting in 'linebuf', return the top
89 # one. (We don't actually buffer read-ahead data -- lines only
90 # get put in 'linebuf' if the client explicitly does an
91 # 'unreadline()'.
92 if self.linebuf:
93 line = self.linebuf[-1]
94 del self.linebuf[-1]
95 return line
96
Greg Wardd1dc4751999-01-13 16:12:04 +000097 buildup_line = ''
98
99 while 1:
100 # read the line, optionally strip comments
101 line = self.file.readline()
102 if self.strip_comments and line:
103 line = self.comment_re.sub ('', line)
104
105 # did previous line end with a backslash? then accumulate
106 if self.join_lines and buildup_line:
107 # oops: end of file
108 if not line:
109 self.warn ("continuation line immediately precedes "
110 "end-of-file")
111 return buildup_line
112
113 line = buildup_line + line
114
115 # careful: pay attention to line number when incrementing it
116 if type (self.current_line) is ListType:
117 self.current_line[1] = self.current_line[1] + 1
118 else:
119 self.current_line = [self.current_line, self.current_line+1]
120 # just an ordinary line, read it as usual
121 else:
122 if not line:
123 return None
124
125 # still have to be careful about incrementing the line number!
126 if type (self.current_line) is ListType:
127 self.current_line = self.current_line[1] + 1
128 else:
129 self.current_line = self.current_line + 1
Greg Ward91c488c1999-03-29 18:01:49 +0000130
Greg Wardd1dc4751999-01-13 16:12:04 +0000131
132 # strip whitespace however the client wants (leading and
133 # trailing, or one or the other, or neither)
134 if self.lstrip_ws and self.rstrip_ws:
135 line = string.strip (line)
136 else:
137 if self.lstrip_ws:
138 line = string.lstrip (line)
139 if self.rstrip_ws:
140 line = string.rstrip (line)
141
142 # blank line (whether we rstrip'ed or not)? skip to next line
143 # if appropriate
144 if line == '' or line == '\n' and self.skip_blanks:
145 continue
146
147 if self.join_lines:
148 if line[-1] == '\\':
149 buildup_line = line[:-1]
150 continue
151
152 if line[-2:] == '\\\n':
153 buildup_line = line[0:-2] + '\n'
154 continue
155
Greg Warddb75afe1999-03-08 21:46:11 +0000156 # collapse internal whitespace (*after* joining lines!)
157 if self.collapse_ws:
158 line = re.sub (r'(\S)\s+(\S)', r'\1 \2', line)
159
Greg Wardd1dc4751999-01-13 16:12:04 +0000160 # well, I guess there's some actual content there: return it
161 return line
162
163 # end readline
164
165
Greg Wardd1dc4751999-01-13 16:12:04 +0000166 def readlines (self):
167 lines = []
168 while 1:
169 line = self.readline()
170 if line is None:
171 return lines
172 lines.append (line)
173
174
Greg Ward91c488c1999-03-29 18:01:49 +0000175 def unreadline (self, line):
176 self.linebuf.append (line)
177
178
Greg Wardd1dc4751999-01-13 16:12:04 +0000179if __name__ == "__main__":
180 test_data = """# test file
181
182line 3 \\
183continues on next line
184"""
185
186 # result 1: no fancy options
187 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
188
189 # result 2: just strip comments
190 result2 = ["\n", "\n", "line 3 \\\n", "continues on next line\n"]
191
192 # result 3: just strip blank lines
193 result3 = ["# test file\n", "line 3 \\\n", "continues on next line\n"]
194
195 # result 4: default, strip comments, blank lines, and trailing whitespace
196 result4 = ["line 3 \\", "continues on next line"]
197
198 # result 5: full processing, strip comments and blanks, plus join lines
199 result5 = ["line 3 continues on next line"]
200
201 def test_input (count, description, file, expected_result):
202 result = file.readlines ()
203 # result = string.join (result, '')
204 if result == expected_result:
205 print "ok %d (%s)" % (count, description)
206 else:
207 print "not ok %d (%s):" % (count, description)
208 print "** expected:"
209 print expected_result
210 print "** received:"
211 print result
212
213
214 filename = "test.txt"
215 out_file = open (filename, "w")
216 out_file.write (test_data)
217 out_file.close ()
218
219 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
220 lstrip_ws=0, rstrip_ws=0)
221 test_input (1, "no processing", in_file, result1)
222
223 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
224 lstrip_ws=0, rstrip_ws=0)
225 test_input (2, "strip comments", in_file, result2)
226
227 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
228 lstrip_ws=0, rstrip_ws=0)
229 test_input (3, "strip blanks", in_file, result3)
230
231 in_file = TextFile (filename)
232 test_input (4, "default processing", in_file, result4)
233
234 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
235 join_lines=1, rstrip_ws=1)
236 test_input (5, "full processing", in_file, result5)
237
238 os.remove (filename)
239