text_file.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """text_file
  2. provides the TextFile class, which gives an interface to text files
  3. that (optionally) takes care of stripping comments, ignoring blank
  4. lines, and joining lines with backslashes."""
  5. __revision__ = "$Id$"
  6. import sys
  7. class TextFile:
  8. """Provides a file-like object that takes care of all the things you
  9. commonly want to do when processing a text file that has some
  10. line-by-line syntax: strip comments (as long as "#" is your
  11. comment character), skip blank lines, join adjacent lines by
  12. escaping the newline (ie. backslash at end of line), strip
  13. leading and/or trailing whitespace. All of these are optional
  14. and independently controllable.
  15. Provides a 'warn()' method so you can generate warning messages that
  16. report physical line number, even if the logical line in question
  17. spans multiple physical lines. Also provides 'unreadline()' for
  18. implementing line-at-a-time lookahead.
  19. Constructor is called as:
  20. TextFile (filename=None, file=None, **options)
  21. It bombs (RuntimeError) if both 'filename' and 'file' are None;
  22. 'filename' should be a string, and 'file' a file object (or
  23. something that provides 'readline()' and 'close()' methods). It is
  24. recommended that you supply at least 'filename', so that TextFile
  25. can include it in warning messages. If 'file' is not supplied,
  26. TextFile creates its own using the 'open()' builtin.
  27. The options are all boolean, and affect the value returned by
  28. 'readline()':
  29. strip_comments [default: true]
  30. strip from "#" to end-of-line, as well as any whitespace
  31. leading up to the "#" -- unless it is escaped by a backslash
  32. lstrip_ws [default: false]
  33. strip leading whitespace from each line before returning it
  34. rstrip_ws [default: true]
  35. strip trailing whitespace (including line terminator!) from
  36. each line before returning it
  37. skip_blanks [default: true}
  38. skip lines that are empty *after* stripping comments and
  39. whitespace. (If both lstrip_ws and rstrip_ws are false,
  40. then some lines may consist of solely whitespace: these will
  41. *not* be skipped, even if 'skip_blanks' is true.)
  42. join_lines [default: false]
  43. if a backslash is the last non-newline character on a line
  44. after stripping comments and whitespace, join the following line
  45. to it to form one "logical line"; if N consecutive lines end
  46. with a backslash, then N+1 physical lines will be joined to
  47. form one logical line.
  48. collapse_join [default: false]
  49. strip leading whitespace from lines that are joined to their
  50. predecessor; only matters if (join_lines and not lstrip_ws)
  51. Note that since 'rstrip_ws' can strip the trailing newline, the
  52. semantics of 'readline()' must differ from those of the builtin file
  53. object's 'readline()' method! In particular, 'readline()' returns
  54. None for end-of-file: an empty string might just be a blank line (or
  55. an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
  56. not."""
  57. default_options = { 'strip_comments': 1,
  58. 'skip_blanks': 1,
  59. 'lstrip_ws': 0,
  60. 'rstrip_ws': 1,
  61. 'join_lines': 0,
  62. 'collapse_join': 0,
  63. }
  64. def __init__ (self, filename=None, file=None, **options):
  65. """Construct a new TextFile object. At least one of 'filename'
  66. (a string) and 'file' (a file-like object) must be supplied.
  67. They keyword argument options are described above and affect
  68. the values returned by 'readline()'."""
  69. if filename is None and file is None:
  70. raise RuntimeError, \
  71. "you must supply either or both of 'filename' and 'file'"
  72. # set values for all options -- either from client option hash
  73. # or fallback to default_options
  74. for opt in self.default_options.keys():
  75. if opt in options:
  76. setattr (self, opt, options[opt])
  77. else:
  78. setattr (self, opt, self.default_options[opt])
  79. # sanity check client option hash
  80. for opt in options.keys():
  81. if opt not in self.default_options:
  82. raise KeyError, "invalid TextFile option '%s'" % opt
  83. if file is None:
  84. self.open (filename)
  85. else:
  86. self.filename = filename
  87. self.file = file
  88. self.current_line = 0 # assuming that file is at BOF!
  89. # 'linebuf' is a stack of lines that will be emptied before we
  90. # actually read from the file; it's only populated by an
  91. # 'unreadline()' operation
  92. self.linebuf = []
  93. def open (self, filename):
  94. """Open a new file named 'filename'. This overrides both the
  95. 'filename' and 'file' arguments to the constructor."""
  96. self.filename = filename
  97. self.file = open (self.filename, 'r')
  98. self.current_line = 0
  99. def close (self):
  100. """Close the current file and forget everything we know about it
  101. (filename, current line number)."""
  102. file = self.file
  103. self.file = None
  104. self.filename = None
  105. self.current_line = None
  106. file.close()
  107. def gen_error (self, msg, line=None):
  108. outmsg = []
  109. if line is None:
  110. line = self.current_line
  111. outmsg.append(self.filename + ", ")
  112. if isinstance(line, (list, tuple)):
  113. outmsg.append("lines %d-%d: " % tuple (line))
  114. else:
  115. outmsg.append("line %d: " % line)
  116. outmsg.append(str(msg))
  117. return ''.join(outmsg)
  118. def error (self, msg, line=None):
  119. raise ValueError, "error: " + self.gen_error(msg, line)
  120. def warn (self, msg, line=None):
  121. """Print (to stderr) a warning message tied to the current logical
  122. line in the current file. If the current logical line in the
  123. file spans multiple physical lines, the warning refers to the
  124. whole range, eg. "lines 3-5". If 'line' supplied, it overrides
  125. the current line number; it may be a list or tuple to indicate a
  126. range of physical lines, or an integer for a single physical
  127. line."""
  128. sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
  129. def readline (self):
  130. """Read and return a single logical line from the current file (or
  131. from an internal buffer if lines have previously been "unread"
  132. with 'unreadline()'). If the 'join_lines' option is true, this
  133. may involve reading multiple physical lines concatenated into a
  134. single string. Updates the current line number, so calling
  135. 'warn()' after 'readline()' emits a warning about the physical
  136. line(s) just read. Returns None on end-of-file, since the empty
  137. string can occur if 'rstrip_ws' is true but 'strip_blanks' is
  138. not."""
  139. # If any "unread" lines waiting in 'linebuf', return the top
  140. # one. (We don't actually buffer read-ahead data -- lines only
  141. # get put in 'linebuf' if the client explicitly does an
  142. # 'unreadline()'.
  143. if self.linebuf:
  144. line = self.linebuf[-1]
  145. del self.linebuf[-1]
  146. return line
  147. buildup_line = ''
  148. while 1:
  149. # read the line, make it None if EOF
  150. line = self.file.readline()
  151. if line == '': line = None
  152. if self.strip_comments and line:
  153. # Look for the first "#" in the line. If none, never
  154. # mind. If we find one and it's the first character, or
  155. # is not preceded by "\", then it starts a comment --
  156. # strip the comment, strip whitespace before it, and
  157. # carry on. Otherwise, it's just an escaped "#", so
  158. # unescape it (and any other escaped "#"'s that might be
  159. # lurking in there) and otherwise leave the line alone.
  160. pos = line.find("#")
  161. if pos == -1: # no "#" -- no comments
  162. pass
  163. # It's definitely a comment -- either "#" is the first
  164. # character, or it's elsewhere and unescaped.
  165. elif pos == 0 or line[pos-1] != "\\":
  166. # Have to preserve the trailing newline, because it's
  167. # the job of a later step (rstrip_ws) to remove it --
  168. # and if rstrip_ws is false, we'd better preserve it!
  169. # (NB. this means that if the final line is all comment
  170. # and has no trailing newline, we will think that it's
  171. # EOF; I think that's OK.)
  172. eol = (line[-1] == '\n') and '\n' or ''
  173. line = line[0:pos] + eol
  174. # If all that's left is whitespace, then skip line
  175. # *now*, before we try to join it to 'buildup_line' --
  176. # that way constructs like
  177. # hello \\
  178. # # comment that should be ignored
  179. # there
  180. # result in "hello there".
  181. if line.strip() == "":
  182. continue
  183. else: # it's an escaped "#"
  184. line = line.replace("\\#", "#")
  185. # did previous line end with a backslash? then accumulate
  186. if self.join_lines and buildup_line:
  187. # oops: end of file
  188. if line is None:
  189. self.warn ("continuation line immediately precedes "
  190. "end-of-file")
  191. return buildup_line
  192. if self.collapse_join:
  193. line = line.lstrip()
  194. line = buildup_line + line
  195. # careful: pay attention to line number when incrementing it
  196. if isinstance(self.current_line, list):
  197. self.current_line[1] = self.current_line[1] + 1
  198. else:
  199. self.current_line = [self.current_line,
  200. self.current_line+1]
  201. # just an ordinary line, read it as usual
  202. else:
  203. if line is None: # eof
  204. return None
  205. # still have to be careful about incrementing the line number!
  206. if isinstance(self.current_line, list):
  207. self.current_line = self.current_line[1] + 1
  208. else:
  209. self.current_line = self.current_line + 1
  210. # strip whitespace however the client wants (leading and
  211. # trailing, or one or the other, or neither)
  212. if self.lstrip_ws and self.rstrip_ws:
  213. line = line.strip()
  214. elif self.lstrip_ws:
  215. line = line.lstrip()
  216. elif self.rstrip_ws:
  217. line = line.rstrip()
  218. # blank line (whether we rstrip'ed or not)? skip to next line
  219. # if appropriate
  220. if (line == '' or line == '\n') and self.skip_blanks:
  221. continue
  222. if self.join_lines:
  223. if line[-1] == '\\':
  224. buildup_line = line[:-1]
  225. continue
  226. if line[-2:] == '\\\n':
  227. buildup_line = line[0:-2] + '\n'
  228. continue
  229. # well, I guess there's some actual content there: return it
  230. return line
  231. # readline ()
  232. def readlines (self):
  233. """Read and return the list of all logical lines remaining in the
  234. current file."""
  235. lines = []
  236. while 1:
  237. line = self.readline()
  238. if line is None:
  239. return lines
  240. lines.append (line)
  241. def unreadline (self, line):
  242. """Push 'line' (a string) onto an internal buffer that will be
  243. checked by future 'readline()' calls. Handy for implementing
  244. a parser with line-at-a-time lookahead."""
  245. self.linebuf.append (line)