add_c_file.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #!/usr/bin/env python3
  2. """
  3. Add a C file with matching header to the Tor codebase. Creates
  4. both files from templates, and adds them to the right include.am file.
  5. This script takes paths relative to the top-level tor directory. It
  6. expects to be run from that directory.
  7. This script creates files, and inserts them into include.am, also
  8. relative to the top-level tor directory.
  9. But the template content in those files is relative to tor's src
  10. directory. (This script strips "src" from the paths used to create
  11. templated comments and macros.)
  12. This script expects posix paths, so it should be run with a python
  13. where os.path is posixpath. (Rather than ntpath.) This probably means
  14. Linux, macOS, or BSD, although it might work on Windows if your python
  15. was compiled with mingw, MSYS, or cygwin.
  16. Example usage:
  17. % add_c_file.py ./src/feature/dirauth/ocelot.c
  18. """
  19. # Future imports for Python 2.7, mandatory in 3.0
  20. from __future__ import division
  21. from __future__ import print_function
  22. from __future__ import unicode_literals
  23. import os
  24. import re
  25. import time
  26. def tordir_file(fname):
  27. """Make fname relative to the current directory, which should be the
  28. top-level tor directory. Also performs basic path simplifications."""
  29. return os.path.normpath(os.path.relpath(fname))
  30. def srcdir_file(tor_fname):
  31. """Make tor_fname relative to tor's "src" directory.
  32. Also performs basic path simplifications.
  33. (This function takes paths relative to the top-level tor directory,
  34. but outputs a path that is relative to tor's src directory.)"""
  35. return os.path.normpath(os.path.relpath(tor_fname, 'src'))
  36. def guard_macro(src_fname):
  37. """Return the guard macro that should be used for the header file
  38. 'src_fname'. This function takes paths relative to tor's src directory.
  39. """
  40. td = src_fname.replace(".", "_").replace("/", "_").upper()
  41. return "TOR_{}".format(td)
  42. def makeext(fname, new_extension):
  43. """Replace the extension for the file called 'fname' with 'new_extension'.
  44. This function takes and returns paths relative to either the top-level
  45. tor directory, or tor's src directory, and returns the same kind
  46. of path.
  47. """
  48. base = os.path.splitext(fname)[0]
  49. return base + "." + new_extension
  50. def instantiate_template(template, tor_fname):
  51. """
  52. Fill in a template with string using the fields that should be used
  53. for 'tor_fname'.
  54. This function takes paths relative to the top-level tor directory,
  55. but the paths in the completed template are relative to tor's src
  56. directory. (Except for one of the fields, which is just a basename).
  57. """
  58. src_fname = srcdir_file(tor_fname)
  59. names = {
  60. # The relative location of the header file.
  61. 'header_path' : makeext(src_fname, "h"),
  62. # The relative location of the C file file.
  63. 'c_file_path' : makeext(src_fname, "c"),
  64. # The truncated name of the file.
  65. 'short_name' : os.path.basename(src_fname),
  66. # The current year, for the copyright notice
  67. 'this_year' : time.localtime().tm_year,
  68. # An appropriate guard macro, for the header.
  69. 'guard_macro' : guard_macro(src_fname),
  70. }
  71. return template.format(**names)
  72. # This template operates on paths relative to tor's src directory
  73. HEADER_TEMPLATE = """\
  74. /* Copyright (c) 2001 Matej Pfajfar.
  75. * Copyright (c) 2001-2004, Roger Dingledine.
  76. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  77. * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
  78. /* See LICENSE for licensing information */
  79. /**
  80. * @file {short_name}
  81. * @brief Header for {c_file_path}
  82. **/
  83. #ifndef {guard_macro}
  84. #define {guard_macro}
  85. #endif /* !defined({guard_macro}) */
  86. """
  87. # This template operates on paths relative to the tor's src directory
  88. C_FILE_TEMPLATE = """\
  89. /* Copyright (c) 2001 Matej Pfajfar.
  90. * Copyright (c) 2001-2004, Roger Dingledine.
  91. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  92. * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
  93. /* See LICENSE for licensing information */
  94. /**
  95. * @file {short_name}
  96. * @brief DOCDOC
  97. **/
  98. #include "orconfig.h"
  99. #include "{header_path}"
  100. """
  101. class AutomakeChunk:
  102. """
  103. Represents part of an automake file. If it is decorated with
  104. an ADD_C_FILE comment, it has a "kind" based on what to add to it.
  105. Otherwise, it only has a bunch of lines in it.
  106. This class operates on paths relative to the top-level tor directory.
  107. """
  108. pat = re.compile(r'# ADD_C_FILE: INSERT (\S*) HERE', re.I)
  109. def __init__(self):
  110. self.lines = []
  111. self.kind = ""
  112. self.hasBlank = False # true if we end with a blank line.
  113. def addLine(self, line):
  114. """
  115. Insert a line into this chunk while parsing the automake file.
  116. Return True if we have just read the last line in the chunk, and
  117. False otherwise.
  118. """
  119. m = self.pat.match(line)
  120. if m:
  121. if self.lines:
  122. raise ValueError("control line not preceded by a blank line")
  123. self.kind = m.group(1)
  124. if line.strip() == "":
  125. self.hasBlank = True
  126. return True
  127. self.lines.append(line)
  128. return False
  129. def insertMember(self, new_tor_fname):
  130. """
  131. Add a new file name new_tor_fname to this chunk. Try to insert it in
  132. alphabetical order with matching indentation, but don't freak out too
  133. much if the source isn't consistent.
  134. Assumes that this chunk is of the form:
  135. FOOBAR = \
  136. X \
  137. Y \
  138. Z
  139. This function operates on paths relative to the top-level tor
  140. directory.
  141. """
  142. prespace = "\t"
  143. postspace = "\t\t"
  144. for lineno, line in enumerate(self.lines):
  145. m = re.match(r'(\s+)(\S+)(\s+)\\', line)
  146. if not m:
  147. continue
  148. prespace, cur_tor_fname, postspace = m.groups()
  149. if cur_tor_fname > new_tor_fname:
  150. self.insert_before(lineno, new_tor_fname, prespace, postspace)
  151. return
  152. self.insert_at_end(new_tor_fname, prespace, postspace)
  153. def insert_before(self, lineno, new_tor_fname, prespace, postspace):
  154. self.lines.insert(lineno,
  155. "{}{}{}\\\n".format(prespace, new_tor_fname,
  156. postspace))
  157. def insert_at_end(self, new_tor_fname, prespace, postspace):
  158. lastline = self.lines[-1].strip()
  159. self.lines[-1] = '{}{}{}\\\n'.format(prespace, lastline, postspace)
  160. self.lines.append("{}{}\n".format(prespace, new_tor_fname))
  161. def dump(self, f):
  162. """Write all the lines in this chunk to the file 'f'."""
  163. for line in self.lines:
  164. f.write(line)
  165. if not line.endswith("\n"):
  166. f.write("\n")
  167. if self.hasBlank:
  168. f.write("\n")
  169. class ParsedAutomake:
  170. """A sort-of-parsed automake file, with identified chunks into which
  171. headers and c files can be inserted.
  172. This class operates on paths relative to the top-level tor directory.
  173. """
  174. def __init__(self):
  175. self.chunks = []
  176. self.by_type = {}
  177. def addChunk(self, chunk):
  178. """Add a newly parsed AutomakeChunk to this file."""
  179. self.chunks.append(chunk)
  180. self.by_type[chunk.kind.lower()] = chunk
  181. def add_file(self, tor_fname, kind):
  182. """Insert a file tor_fname of kind 'kind' to the appropriate
  183. section of this file. Return True if we added it.
  184. This function operates on paths relative to the top-level tor
  185. directory.
  186. """
  187. if kind.lower() in self.by_type:
  188. self.by_type[kind.lower()].insertMember(tor_fname)
  189. return True
  190. else:
  191. return False
  192. def dump(self, f):
  193. """Write this file into a file 'f'."""
  194. for chunk in self.chunks:
  195. chunk.dump(f)
  196. def get_include_am_location(tor_fname):
  197. """Find the right include.am file for introducing a new file
  198. tor_fname. Return None if we can't guess one.
  199. Note that this function is imperfect because our include.am layout is
  200. not (yet) consistent.
  201. This function operates on paths relative to the top-level tor directory.
  202. """
  203. # Strip src for pattern matching, but add it back when returning the path
  204. src_fname = srcdir_file(tor_fname)
  205. m = re.match(r'^(lib|core|feature|app)/([a-z0-9_]*)/', src_fname)
  206. if m:
  207. return "src/{}/{}/include.am".format(m.group(1),m.group(2))
  208. if re.match(r'^test/', src_fname):
  209. return "src/test/include.am"
  210. return None
  211. def run(fname):
  212. """
  213. Create a new C file and H file corresponding to the filename "fname",
  214. and add them to the corresponding include.am.
  215. This function operates on paths relative to the top-level tor directory.
  216. """
  217. # Make sure we're in the top-level tor directory,
  218. # which contains the src directory
  219. if not os.path.isdir("src"):
  220. raise RuntimeError("Could not find './src/'. "
  221. "Run this script from the top-level tor source "
  222. "directory.")
  223. # And it looks like a tor/src directory
  224. if not os.path.isfile("src/include.am"):
  225. raise RuntimeError("Could not find './src/include.am'. "
  226. "Run this script from the top-level tor source "
  227. "directory.")
  228. # Make the file name relative to the top-level tor directory
  229. tor_fname = tordir_file(fname)
  230. # And check that we're adding files to the "src" directory,
  231. # with canonical paths
  232. if tor_fname[:4] != "src/":
  233. raise ValueError("Requested file path '{}' canonicalized to '{}', "
  234. "but the canonical path did not start with 'src/'. "
  235. "Please add files to the src directory."
  236. .format(fname, tor_fname))
  237. c_tor_fname = makeext(tor_fname, "c")
  238. h_tor_fname = makeext(tor_fname, "h")
  239. if os.path.exists(c_tor_fname):
  240. print("{} already exists".format(c_tor_fname))
  241. return 1
  242. if os.path.exists(h_tor_fname):
  243. print("{} already exists".format(h_tor_fname))
  244. return 1
  245. with open(c_tor_fname, 'w') as f:
  246. f.write(instantiate_template(C_FILE_TEMPLATE, c_tor_fname))
  247. with open(h_tor_fname, 'w') as f:
  248. f.write(instantiate_template(HEADER_TEMPLATE, h_tor_fname))
  249. iam = get_include_am_location(c_tor_fname)
  250. if iam is None or not os.path.exists(iam):
  251. print("Made files successfully but couldn't identify include.am for {}"
  252. .format(c_tor_fname))
  253. return 1
  254. amfile = ParsedAutomake()
  255. cur_chunk = AutomakeChunk()
  256. with open(iam) as f:
  257. for line in f:
  258. if cur_chunk.addLine(line):
  259. amfile.addChunk(cur_chunk)
  260. cur_chunk = AutomakeChunk()
  261. amfile.addChunk(cur_chunk)
  262. amfile.add_file(c_tor_fname, "sources")
  263. amfile.add_file(h_tor_fname, "headers")
  264. with open(iam+".tmp", 'w') as f:
  265. amfile.dump(f)
  266. os.rename(iam+".tmp", iam)
  267. if __name__ == '__main__':
  268. import sys
  269. sys.exit(run(sys.argv[1]))