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