blob: 6153dea3df59d692a2c088b4a699f97c65923a7f [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 Wardd1dc4751999-01-13 16:12:04 +000055
56
Greg Ward782cdfe1999-03-23 14:00:06 +000057 def open (self, filename):
58 self.filename = filename
Greg Wardd1dc4751999-01-13 16:12:04 +000059 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
Greg Warddb75afe1999-03-08 21:46:11 +0000140 # collapse internal whitespace (*after* joining lines!)
141 if self.collapse_ws:
142 line = re.sub (r'(\S)\s+(\S)', r'\1 \2', line)
143
Greg Wardd1dc4751999-01-13 16:12:04 +0000144 # well, I guess there's some actual content there: return it
145 return line
146
147 # end readline
148
149
150 def readlines (self):
151 lines = []
152 while 1:
153 line = self.readline()
154 if line is None:
155 return lines
156 lines.append (line)
157
158
159if __name__ == "__main__":
160 test_data = """# test file
161
162line 3 \\
163continues on next line
164"""
165
166 # result 1: no fancy options
167 result1 = map (lambda x: x + "\n", string.split (test_data, "\n")[0:-1])
168
169 # result 2: just strip comments
170 result2 = ["\n", "\n", "line 3 \\\n", "continues on next line\n"]
171
172 # result 3: just strip blank lines
173 result3 = ["# test file\n", "line 3 \\\n", "continues on next line\n"]
174
175 # result 4: default, strip comments, blank lines, and trailing whitespace
176 result4 = ["line 3 \\", "continues on next line"]
177
178 # result 5: full processing, strip comments and blanks, plus join lines
179 result5 = ["line 3 continues on next line"]
180
181 def test_input (count, description, file, expected_result):
182 result = file.readlines ()
183 # result = string.join (result, '')
184 if result == expected_result:
185 print "ok %d (%s)" % (count, description)
186 else:
187 print "not ok %d (%s):" % (count, description)
188 print "** expected:"
189 print expected_result
190 print "** received:"
191 print result
192
193
194 filename = "test.txt"
195 out_file = open (filename, "w")
196 out_file.write (test_data)
197 out_file.close ()
198
199 in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
200 lstrip_ws=0, rstrip_ws=0)
201 test_input (1, "no processing", in_file, result1)
202
203 in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
204 lstrip_ws=0, rstrip_ws=0)
205 test_input (2, "strip comments", in_file, result2)
206
207 in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
208 lstrip_ws=0, rstrip_ws=0)
209 test_input (3, "strip blanks", in_file, result3)
210
211 in_file = TextFile (filename)
212 test_input (4, "default processing", in_file, result4)
213
214 in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
215 join_lines=1, rstrip_ws=1)
216 test_input (5, "full processing", in_file, result5)
217
218 os.remove (filename)
219