add_c_file.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. Example usage:
  6. % add_c_file.py ./src/feature/dirauth/ocelot.c
  7. """
  8. import os
  9. import re
  10. import time
  11. def topdir_file(name):
  12. """Strip opening "src" from a filename"""
  13. if name.startswith("src/"):
  14. name = name[4:]
  15. return name
  16. def guard_macro(name):
  17. """Return the guard macro that should be used for the header file 'name'.
  18. """
  19. td = topdir_file(name).replace(".", "_").replace("/", "_").upper()
  20. return "TOR_{}".format(td)
  21. def makeext(name, new_extension):
  22. """Replace the extension for the file called 'name' with 'new_extension'.
  23. """
  24. base = os.path.splitext(name)[0]
  25. return base + "." + new_extension
  26. def instantiate_template(template, output_fname):
  27. """
  28. Fill in a template with string using the fields that should be used
  29. for 'output_fname'.
  30. """
  31. names = {
  32. # The relative location of the header file.
  33. 'header_path' : makeext(topdir_file(output_fname), "h"),
  34. # The relative location of the C file file.
  35. 'c_file_path' : makeext(topdir_file(output_fname), "c"),
  36. # The truncated name of the file.
  37. 'short_name' : os.path.basename(output_fname),
  38. # The current year, for the copyright notice
  39. 'this_year' : time.localtime().tm_year,
  40. # An appropriate guard macro, for the header.
  41. 'guard_macro' : guard_macro(output_fname),
  42. }
  43. return template.format(**names)
  44. HEADER_TEMPLATE = """\
  45. /* Copyright (c) 2001 Matej Pfajfar.
  46. * Copyright (c) 2001-2004, Roger Dingledine.
  47. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  48. * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
  49. /* See LICENSE for licensing information */
  50. /**
  51. * @file {short_name}
  52. * @brief Header for {c_file_path}
  53. **/
  54. #ifndef {guard_macro}
  55. #define {guard_macro}
  56. #endif /* !defined({guard_macro}) */
  57. """
  58. C_FILE_TEMPLATE = """\
  59. /* Copyright (c) 2001 Matej Pfajfar.
  60. * Copyright (c) 2001-2004, Roger Dingledine.
  61. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  62. * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
  63. /* See LICENSE for licensing information */
  64. /**
  65. * @file {short_name}
  66. * @brief DOCDOC
  67. **/
  68. #include "orconfig.h"
  69. #include "{header_path}"
  70. """
  71. class AutomakeChunk:
  72. """
  73. Represents part of an automake file. If it is decorated with
  74. an ADD_C_FILE comment, it has a "kind" based on what to add to it.
  75. Otherwise, it only has a bunch of lines in it.
  76. """
  77. pat = re.compile(r'# ADD_C_FILE: INSERT (\S*) HERE', re.I)
  78. def __init__(self):
  79. self.lines = []
  80. self.kind = ""
  81. def addLine(self, line):
  82. """
  83. Insert a line into this chunk while parsing the automake file.
  84. """
  85. m = self.pat.match(line)
  86. if m:
  87. if self.lines:
  88. raise ValueError("control line not preceded by a blank line")
  89. self.kind = m.group(1)
  90. self.lines.append(line)
  91. if line.strip() == "":
  92. return True
  93. return False
  94. def insertMember(self, member):
  95. """
  96. Add a new member to this chunk. Try to insert it in alphabetical
  97. order with matching indentation, but don't freak out too much if the
  98. source isn't consistent.
  99. Assumes that this chunk is of the form:
  100. FOOBAR = \
  101. X \
  102. Y \
  103. Z
  104. """
  105. prespace = "\t"
  106. postspace = "\t\t"
  107. for lineno, line in enumerate(self.lines):
  108. m = re.match(r'(\s+)(\S+)(\s+)\\', line)
  109. if not m:
  110. continue
  111. prespace, fname, postspace = m.groups()
  112. if fname > member:
  113. self.insert_before(lineno, member, prespace, postspace)
  114. return
  115. self.insert_at_end(member, prespace, postspace)
  116. def insert_before(self, lineno, member, prespace, postspace):
  117. self.lines.insert(lineno,
  118. "{}{}{}\\\n".format(prespace, member, postspace))
  119. def insert_at_end(self, member, prespace, postspace):
  120. lastline = self.lines[-1]
  121. self.lines[-1] += '{}\\\n'.format(postspace)
  122. self.lines.append("{}{}\n".format(prespace, member))
  123. def dump(self, f):
  124. """Write all the lines in this chunk to the file 'f'."""
  125. for line in self.lines:
  126. f.write(line)
  127. if not line.endswith("\n"):
  128. f.write("\n")
  129. class ParsedAutomake:
  130. """A sort-of-parsed automake file, with identified chunks into which
  131. headers and c files can be inserted.
  132. """
  133. def __init__(self):
  134. self.chunks = []
  135. self.by_type = {}
  136. def addChunk(self, chunk):
  137. """Add a newly parsed AutomakeChunk to this file."""
  138. self.chunks.append(chunk)
  139. self.by_type[chunk.kind.lower()] = chunk
  140. def add_file(self, fname, kind):
  141. """Insert a file of kind 'kind' to the appropriate section of this
  142. file. Return True if we added it.
  143. """
  144. if kind.lower() in self.by_type:
  145. self.by_type[kind.lower()].insertMember(fname)
  146. return True
  147. else:
  148. return False
  149. def dump(self, f):
  150. """Write this file into a file 'f'."""
  151. for chunk in self.chunks:
  152. chunk.dump(f)
  153. def get_include_am_location(fname):
  154. """Find the right include.am file for introducing a new file. Return None
  155. if we can't guess one.
  156. Note that this function is imperfect because our include.am layout is
  157. not (yet) consistent.
  158. """
  159. td = topdir_file(fname)
  160. m = re.match(r'^lib/([a-z0-9_]*)/', td)
  161. if m:
  162. return "src/lib/{}/include.am".format(m.group(1))
  163. if re.match(r'^(core|feature|app)/', td):
  164. return "src/core/include.am"
  165. if re.match(r'^test/', td):
  166. return "src/test/include.am"
  167. return None
  168. def run(fn):
  169. """
  170. Create a new C file and H file corresponding to the filename "fn", and
  171. add them to include.am.
  172. """
  173. cf = makeext(fn, "c")
  174. hf = makeext(fn, "h")
  175. if os.path.exists(cf):
  176. print("{} already exists".format(cf))
  177. return 1
  178. if os.path.exists(hf):
  179. print("{} already exists".format(hf))
  180. return 1
  181. with open(cf, 'w') as f:
  182. f.write(instantiate_template(C_FILE_TEMPLATE, cf))
  183. with open(hf, 'w') as f:
  184. f.write(instantiate_template(HEADER_TEMPLATE, hf))
  185. iam = get_include_am_location(cf)
  186. if iam is None or not os.path.exists(iam):
  187. print("Made files successfully but couldn't identify include.am for {}"
  188. .format(cf))
  189. return 1
  190. amfile = ParsedAutomake()
  191. cur_chunk = AutomakeChunk()
  192. with open(iam) as f:
  193. for line in f:
  194. if cur_chunk.addLine(line):
  195. amfile.addChunk(cur_chunk)
  196. cur_chunk = AutomakeChunk()
  197. amfile.addChunk(cur_chunk)
  198. amfile.add_file(cf, "sources")
  199. amfile.add_file(hf, "headers")
  200. with open(iam+".tmp", 'w') as f:
  201. amfile.dump(f)
  202. os.rename(iam+".tmp", iam)
  203. if __name__ == '__main__':
  204. import sys
  205. sys.exit(run(sys.argv[1]))