/Lib/distutils/text_file.py

http://unladen-swallow.googlecode.com/ · Python · 381 lines · 282 code · 49 blank · 50 comment · 51 complexity · ce486d337be73ac3f23701231821ea0d MD5 · raw file

  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: text_file.py 60923 2008-02-21 18:18:37Z guido.van.rossum $"
  6. import sys, os
  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. self.file.close ()
  103. self.file = None
  104. self.filename = None
  105. self.current_line = None
  106. def gen_error (self, msg, line=None):
  107. outmsg = []
  108. if line is None:
  109. line = self.current_line
  110. outmsg.append(self.filename + ", ")
  111. if type (line) in (list, tuple):
  112. outmsg.append("lines %d-%d: " % tuple (line))
  113. else:
  114. outmsg.append("line %d: " % line)
  115. outmsg.append(str(msg))
  116. return "".join(outmsg)
  117. def error (self, msg, line=None):
  118. raise ValueError, "error: " + self.gen_error(msg, line)
  119. def warn (self, msg, line=None):
  120. """Print (to stderr) a warning message tied to the current logical
  121. line in the current file. If the current logical line in the
  122. file spans multiple physical lines, the warning refers to the
  123. whole range, eg. "lines 3-5". If 'line' supplied, it overrides
  124. the current line number; it may be a list or tuple to indicate a
  125. range of physical lines, or an integer for a single physical
  126. line."""
  127. sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
  128. def readline (self):
  129. """Read and return a single logical line from the current file (or
  130. from an internal buffer if lines have previously been "unread"
  131. with 'unreadline()'). If the 'join_lines' option is true, this
  132. may involve reading multiple physical lines concatenated into a
  133. single string. Updates the current line number, so calling
  134. 'warn()' after 'readline()' emits a warning about the physical
  135. line(s) just read. Returns None on end-of-file, since the empty
  136. string can occur if 'rstrip_ws' is true but 'strip_blanks' is
  137. not."""
  138. # If any "unread" lines waiting in 'linebuf', return the top
  139. # one. (We don't actually buffer read-ahead data -- lines only
  140. # get put in 'linebuf' if the client explicitly does an
  141. # 'unreadline()'.
  142. if self.linebuf:
  143. line = self.linebuf[-1]
  144. del self.linebuf[-1]
  145. return line
  146. buildup_line = ''
  147. while 1:
  148. # read the line, make it None if EOF
  149. line = self.file.readline()
  150. if line == '': line = None
  151. if self.strip_comments and line:
  152. # Look for the first "#" in the line. If none, never
  153. # mind. If we find one and it's the first character, or
  154. # is not preceded by "\", then it starts a comment --
  155. # strip the comment, strip whitespace before it, and
  156. # carry on. Otherwise, it's just an escaped "#", so
  157. # unescape it (and any other escaped "#"'s that might be
  158. # lurking in there) and otherwise leave the line alone.
  159. pos = line.find("#")
  160. if pos == -1: # no "#" -- no comments
  161. pass
  162. # It's definitely a comment -- either "#" is the first
  163. # character, or it's elsewhere and unescaped.
  164. elif pos == 0 or line[pos-1] != "\\":
  165. # Have to preserve the trailing newline, because it's
  166. # the job of a later step (rstrip_ws) to remove it --
  167. # and if rstrip_ws is false, we'd better preserve it!
  168. # (NB. this means that if the final line is all comment
  169. # and has no trailing newline, we will think that it's
  170. # EOF; I think that's OK.)
  171. eol = (line[-1] == '\n') and '\n' or ''
  172. line = line[0:pos] + eol
  173. # If all that's left is whitespace, then skip line
  174. # *now*, before we try to join it to 'buildup_line' --
  175. # that way constructs like
  176. # hello \\
  177. # # comment that should be ignored
  178. # there
  179. # result in "hello there".
  180. if line.strip() == "":
  181. continue
  182. else: # it's an escaped "#"
  183. line = line.replace("\\#", "#")
  184. # did previous line end with a backslash? then accumulate
  185. if self.join_lines and buildup_line:
  186. # oops: end of file
  187. if line is None:
  188. self.warn ("continuation line immediately precedes "
  189. "end-of-file")
  190. return buildup_line
  191. if self.collapse_join:
  192. line = line.lstrip()
  193. line = buildup_line + line
  194. # careful: pay attention to line number when incrementing it
  195. if type (self.current_line) is list:
  196. self.current_line[1] = self.current_line[1] + 1
  197. else:
  198. self.current_line = [self.current_line,
  199. self.current_line+1]
  200. # just an ordinary line, read it as usual
  201. else:
  202. if line is None: # eof
  203. return None
  204. # still have to be careful about incrementing the line number!
  205. if type (self.current_line) is list:
  206. self.current_line = self.current_line[1] + 1
  207. else:
  208. self.current_line = self.current_line + 1
  209. # strip whitespace however the client wants (leading and
  210. # trailing, or one or the other, or neither)
  211. if self.lstrip_ws and self.rstrip_ws:
  212. line = line.strip()
  213. elif self.lstrip_ws:
  214. line = line.lstrip()
  215. elif self.rstrip_ws:
  216. line = line.rstrip()
  217. # blank line (whether we rstrip'ed or not)? skip to next line
  218. # if appropriate
  219. if (line == '' or line == '\n') and self.skip_blanks:
  220. continue
  221. if self.join_lines:
  222. if line[-1] == '\\':
  223. buildup_line = line[:-1]
  224. continue
  225. if line[-2:] == '\\\n':
  226. buildup_line = line[0:-2] + '\n'
  227. continue
  228. # well, I guess there's some actual content there: return it
  229. return line
  230. # readline ()
  231. def readlines (self):
  232. """Read and return the list of all logical lines remaining in the
  233. current file."""
  234. lines = []
  235. while 1:
  236. line = self.readline()
  237. if line is None:
  238. return lines
  239. lines.append (line)
  240. def unreadline (self, line):
  241. """Push 'line' (a string) onto an internal buffer that will be
  242. checked by future 'readline()' calls. Handy for implementing
  243. a parser with line-at-a-time lookahead."""
  244. self.linebuf.append (line)
  245. if __name__ == "__main__":
  246. test_data = """# test file
  247. line 3 \\
  248. # intervening comment
  249. continues on next line
  250. """
  251. # result 1: no fancy options
  252. result1 = map (lambda x: x + "\n", test_data.split("\n")[0:-1])
  253. # result 2: just strip comments
  254. result2 = ["\n",
  255. "line 3 \\\n",
  256. " continues on next line\n"]
  257. # result 3: just strip blank lines
  258. result3 = ["# test file\n",
  259. "line 3 \\\n",
  260. "# intervening comment\n",
  261. " continues on next line\n"]
  262. # result 4: default, strip comments, blank lines, and trailing whitespace
  263. result4 = ["line 3 \\",
  264. " continues on next line"]
  265. # result 5: strip comments and blanks, plus join lines (but don't
  266. # "collapse" joined lines
  267. result5 = ["line 3 continues on next line"]
  268. # result 6: strip comments and blanks, plus join lines (and
  269. # "collapse" joined lines
  270. result6 = ["line 3 continues on next line"]
  271. def test_input (count, description, file, expected_result):
  272. result = file.readlines ()
  273. # result = ''.join(result)
  274. if result == expected_result:
  275. print "ok %d (%s)" % (count, description)
  276. else:
  277. print "not ok %d (%s):" % (count, description)
  278. print "** expected:"
  279. print expected_result
  280. print "** received:"
  281. print result
  282. filename = "test.txt"
  283. out_file = open (filename, "w")
  284. out_file.write (test_data)
  285. out_file.close ()
  286. in_file = TextFile (filename, strip_comments=0, skip_blanks=0,
  287. lstrip_ws=0, rstrip_ws=0)
  288. test_input (1, "no processing", in_file, result1)
  289. in_file = TextFile (filename, strip_comments=1, skip_blanks=0,
  290. lstrip_ws=0, rstrip_ws=0)
  291. test_input (2, "strip comments", in_file, result2)
  292. in_file = TextFile (filename, strip_comments=0, skip_blanks=1,
  293. lstrip_ws=0, rstrip_ws=0)
  294. test_input (3, "strip blanks", in_file, result3)
  295. in_file = TextFile (filename)
  296. test_input (4, "default processing", in_file, result4)
  297. in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
  298. join_lines=1, rstrip_ws=1)
  299. test_input (5, "join lines without collapsing", in_file, result5)
  300. in_file = TextFile (filename, strip_comments=1, skip_blanks=1,
  301. join_lines=1, rstrip_ws=1, collapse_join=1)
  302. test_input (6, "join lines with collapsing", in_file, result6)
  303. os.remove (filename)