blob: 9e1a73b79890c532c1984356e56db6a4695e2461 [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:
16 filename = None
17 file = None
18 current_line = None
19
20 default_options = { 'strip_comments': 1,
21 'comment_re': re.compile (r'\s*#.*'),
22 'skip_blanks': 1,
23 'join_lines': 0,
24 'lstrip_ws': 0,
25 'rstrip_ws': 1,
26 }
27
28 def __init__ (self, filename=None, **options):
29
30 # set values for all options -- either from client option hash
31 # or fallback to default_options
32 for opt in self.default_options.keys():
33 if options.has_key (opt):
34 if opt == 'comment_re' and type (options[opt]) is StringType:
35 self.comment_re = re.compile (options[opt])
36 else:
37 setattr (self, opt, options[opt])
38
39 else:
40 setattr (self, opt, self.default_options[opt])
41
42 # sanity check client option hash
43 for opt in options.keys():
44 if not self.default_options.has_key (opt):
45 raise KeyError, "invalid TextFile option '%s'" % opt
46
47 self.filename = filename
48 if self.filename:
49 self.open ()
50
51
52 def open (self, filename=None):
53 if not self.filename:
54 if not filename:
55 raise RuntimeError, "must provide a filename somehow"
56
57 self.filename = filename
58
59 self.file = open (self.filename, 'r')
60 self.current_line = 0
61
62
63 def close (self):
64 self.file.close ()
65 self.file = None
66 self.filename = None
67 self.current_line = None
68
69
Greg Wardf6cdcd51999-01-18 17:08:16 +000070 def warn (self, msg):
71 sys.stderr.write (self.filename + ", ")
72 if type (self.current_line) is ListType:
73 sys.stderr.write ("lines %d-%d: " % tuple (self.current_line))
74 else:
75 sys.stderr.write ("line %d: " % self.current_line)
76 sys.stderr.write (msg + "\n")
77
78
Greg Wardd1dc4751999-01-13 16:12:04 +000079 def readline (self):
80
81 buildup_line = ''
82
83 while 1:
84 # read the line, optionally strip comments
85 line = self.file.readline()
86 if self.strip_comments and line:
87 line = self.comment_re.sub ('', line)
88
89 # did previous line end with a backslash? then accumulate
90 if self.join_lines and buildup_line:
91 # oops: end of file
92 if not line:
93 self.warn ("continuation line immediately precedes "
94 "end-of-file")
95 return buildup_line
96
97 line = buildup_line + line
98
99 # careful: pay attention to line number when incrementing it
100 if type (self.current_line) is ListType:
101 self.current_line[1] = self.current_line[1] + 1
102 else:
103 self.current_line = [self.current_line, self.current_line+1]
104 # just an ordinary line, read it as usual
105 else:
106 if not line:
107 return None
108
109 # still have to be careful about incrementing the line number!
110 if type (self.current_line) is ListType:
111 self.current_line = self.current_line[1] + 1
112 else:
113 self.current_line = self.current_line + 1
114
115
116 # strip whitespace however the client wants (leading and
117 # trailing, or one or the other, or neither)
118 if self.lstrip_ws and self.rstrip_ws:
119 line = string.strip (line)
120 else:
121 if self.lstrip_ws:
122 line = string.lstrip (line)
123 if self.rstrip_ws:
124 line = string.rstrip (line)
125
126 # blank line (whether we rstrip'ed or not)? skip to next line
127 # if appropriate
128 if line == '' or line == '\n' and self.skip_blanks:
129 continue
130
131 if self.join_lines:
132 if line[-1] == '\\':
133 buildup_line = line[:-1]
134 continue
135
136 if line[-2:] == '\\\n':
137 buildup_line = line[0:-2] + '\n'
138 continue
139
140 # well, I guess there's some actual content there: return it
141 return line
142
143 # end readline
144
145
146 def readlines (self):
147 lines = []
148 while 1:
149 line = self.readline()
150 if line is None:
151 return lines
152 lines.append (line)
153
154
155if __name__ == "__main__":
156 test_data = """# test file
157
158line 3 \\
159continues on next line
160"""
161
162 # result 1: no fancy options
163 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
164
165 # result 2: just strip comments
166 result2 = ["\n", "\n", "line 3 \\\n", "continues on next line\n"]
167
168 # result 3: just strip blank lines
169 result3 = ["# test file\n", "line 3 \\\n", "continues on next line\n"]
170
171 # result 4: default, strip comments, blank lines, and trailing whitespace
172 result4 = ["line 3 \\", "continues on next line"]
173
174 # result 5: full processing, strip comments and blanks, plus join lines
175 result5 = ["line 3 continues on next line"]
176
177 def test_input (count, description, file, expected_result):
178 result = file.readlines ()
179 # result = string.join (result, '')
180 if result == expected_result:
181 print "ok %d (%s)" % (count, description)
182 else:
183 print "not ok %d (%s):" % (count, description)
184 print "** expected:"
185 print expected_result
186 print "** received:"
187 print result
188
189
190 filename = "test.txt"
191 out_file = open (filename, "w")
192 out_file.write (test_data)
193 out_file.close ()
194
195 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
196 lstrip_ws=0, rstrip_ws=0)
197 test_input (1, "no processing", in_file, result1)
198
199 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
200 lstrip_ws=0, rstrip_ws=0)
201 test_input (2, "strip comments", in_file, result2)
202
203 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
204 lstrip_ws=0, rstrip_ws=0)
205 test_input (3, "strip blanks", in_file, result3)
206
207 in_file = TextFile (filename)
208 test_input (4, "default processing", in_file, result4)
209
210 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
211 join_lines=1, rstrip_ws=1)
212 test_input (5, "full processing", in_file, result5)
213
214 os.remove (filename)
215