blob: 1d579565d58d7bcc5a92c98a76496740046ae862 [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
56 # 'linestart' stores the file offset of the start of each logical
57 # line; it is used to back up the file pointer when the caller
58 # wants to "unread" a line
59 self.linestart = []
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
86 buildup_line = ''
87
88 while 1:
Greg Ward787451b1999-03-26 21:48:59 +000089 # record current file position; this will be appended to
90 # the linestart array *unless* we're accumulating a
91 # continued logical line
92 current_pos = self.file.tell()
93
Greg Wardd1dc4751999-01-13 16:12:04 +000094 # read the line, optionally strip comments
95 line = self.file.readline()
96 if self.strip_comments and line:
97 line = self.comment_re.sub ('', line)
98
99 # did previous line end with a backslash? then accumulate
100 if self.join_lines and buildup_line:
101 # oops: end of file
102 if not line:
103 self.warn ("continuation line immediately precedes "
104 "end-of-file")
105 return buildup_line
106
107 line = buildup_line + line
108
109 # careful: pay attention to line number when incrementing it
110 if type (self.current_line) is ListType:
111 self.current_line[1] = self.current_line[1] + 1
112 else:
113 self.current_line = [self.current_line, self.current_line+1]
Greg Ward787451b1999-03-26 21:48:59 +0000114
115 # Forget current position: don't want to save it in the
116 # middle of a logical line
117 current_pos = None
118
Greg Wardd1dc4751999-01-13 16:12:04 +0000119 # just an ordinary line, read it as usual
120 else:
121 if not line:
122 return None
123
124 # still have to be careful about incrementing the line number!
125 if type (self.current_line) is ListType:
126 self.current_line = self.current_line[1] + 1
127 else:
128 self.current_line = self.current_line + 1
Greg Ward787451b1999-03-26 21:48:59 +0000129
Greg Wardd1dc4751999-01-13 16:12:04 +0000130
131 # strip whitespace however the client wants (leading and
132 # trailing, or one or the other, or neither)
133 if self.lstrip_ws and self.rstrip_ws:
134 line = string.strip (line)
135 else:
136 if self.lstrip_ws:
137 line = string.lstrip (line)
138 if self.rstrip_ws:
139 line = string.rstrip (line)
140
141 # blank line (whether we rstrip'ed or not)? skip to next line
142 # if appropriate
143 if line == '' or line == '\n' and self.skip_blanks:
144 continue
145
Greg Ward787451b1999-03-26 21:48:59 +0000146 # if we're still here and have kept the current position,
147 # then this physical line starts a logical line; record its
148 # starting offset
149 if current_pos is not None:
150 self.linestart.append (current_pos)
151
Greg Wardd1dc4751999-01-13 16:12:04 +0000152 if self.join_lines:
153 if line[-1] == '\\':
154 buildup_line = line[:-1]
155 continue
156
157 if line[-2:] == '\\\n':
158 buildup_line = line[0:-2] + '\n'
159 continue
160
Greg Warddb75afe1999-03-08 21:46:11 +0000161 # collapse internal whitespace (*after* joining lines!)
162 if self.collapse_ws:
163 line = re.sub (r'(\S)\s+(\S)', r'\1 \2', line)
164
Greg Wardd1dc4751999-01-13 16:12:04 +0000165 # well, I guess there's some actual content there: return it
166 return line
167
168 # end readline
169
170
Greg Ward787451b1999-03-26 21:48:59 +0000171 def unreadline (self):
172 if not self.linestart:
173 raise IOError, "at beginning of file -- can't unreadline"
174 pos = self.linestart[-1]
175 del self.linestart[-1]
176 self.file.seek (pos)
177
178
Greg Wardd1dc4751999-01-13 16:12:04 +0000179 def readlines (self):
180 lines = []
181 while 1:
182 line = self.readline()
183 if line is None:
184 return lines
185 lines.append (line)
186
187
188if __name__ == "__main__":
189 test_data = """# test file
190
191line 3 \\
192continues on next line
193"""
194
195 # result 1: no fancy options
196 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
197
198 # result 2: just strip comments
199 result2 = ["\n", "\n", "line 3 \\\n", "continues on next line\n"]
200
201 # result 3: just strip blank lines
202 result3 = ["# test file\n", "line 3 \\\n", "continues on next line\n"]
203
204 # result 4: default, strip comments, blank lines, and trailing whitespace
205 result4 = ["line 3 \\", "continues on next line"]
206
207 # result 5: full processing, strip comments and blanks, plus join lines
208 result5 = ["line 3 continues on next line"]
209
210 def test_input (count, description, file, expected_result):
211 result = file.readlines ()
212 # result = string.join (result, '')
213 if result == expected_result:
214 print "ok %d (%s)" % (count, description)
215 else:
216 print "not ok %d (%s):" % (count, description)
217 print "** expected:"
218 print expected_result
219 print "** received:"
220 print result
221
222
223 filename = "test.txt"
224 out_file = open (filename, "w")
225 out_file.write (test_data)
226 out_file.close ()
227
228 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
229 lstrip_ws=0, rstrip_ws=0)
230 test_input (1, "no processing", in_file, result1)
231
232 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
233 lstrip_ws=0, rstrip_ws=0)
234 test_input (2, "strip comments", in_file, result2)
235
236 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
237 lstrip_ws=0, rstrip_ws=0)
238 test_input (3, "strip blanks", in_file, result3)
239
240 in_file = TextFile (filename)
241 test_input (4, "default processing", in_file, result4)
242
243 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
244 join_lines=1, rstrip_ws=1)
245 test_input (5, "full processing", in_file, result5)
246
247 os.remove (filename)
248