4 Add a C file with matching header to the Tor codebase. Creates
5 both files from templates, and adds them to the right include.am file.
7 This script takes paths relative to the top-level tor directory. It
8 expects to be run from that directory.
10 This script creates files, and inserts them into include.am, also
11 relative to the top-level tor directory.
13 But the template content in those files is relative to tor's src
14 directory. (This script strips "src" from the paths used to create
15 templated comments and macros.)
17 This script expects posix paths, so it should be run with a python
18 where os.path is posixpath. (Rather than ntpath.) This probably means
19 Linux, macOS, or BSD, although it might work on Windows if your python
20 was compiled with mingw, MSYS, or cygwin.
24 % add_c_file.py ./src/feature/dirauth/ocelot.c
27 # Future imports for Python 2.7, mandatory in 3.0
28 from __future__
import division
29 from __future__
import print_function
30 from __future__
import unicode_literals
36 def tordir_file(fname
):
37 """Make fname relative to the current directory, which should be the
38 top-level tor directory. Also performs basic path simplifications."""
39 return os
.path
.normpath(os
.path
.relpath(fname
))
41 def srcdir_file(tor_fname
):
42 """Make tor_fname relative to tor's "src" directory.
43 Also performs basic path simplifications.
44 (This function takes paths relative to the top-level tor directory,
45 but outputs a path that is relative to tor's src directory.)"""
46 return os
.path
.normpath(os
.path
.relpath(tor_fname
, 'src'))
48 def guard_macro(src_fname
):
49 """Return the guard macro that should be used for the header file
50 'src_fname'. This function takes paths relative to tor's src directory.
52 td
= src_fname
.replace(".", "_").replace("/", "_").upper()
53 return "TOR_{}".format(td
)
55 def makeext(fname
, new_extension
):
56 """Replace the extension for the file called 'fname' with 'new_extension'.
57 This function takes and returns paths relative to either the top-level
58 tor directory, or tor's src directory, and returns the same kind
61 base
= os
.path
.splitext(fname
)[0]
62 return base
+ "." + new_extension
64 def instantiate_template(template
, tor_fname
):
66 Fill in a template with string using the fields that should be used
69 This function takes paths relative to the top-level tor directory,
70 but the paths in the completed template are relative to tor's src
71 directory. (Except for one of the fields, which is just a basename).
73 src_fname
= srcdir_file(tor_fname
)
75 # The relative location of the header file.
76 'header_path' : makeext(src_fname
, "h"),
77 # The relative location of the C file file.
78 'c_file_path' : makeext(src_fname
, "c"),
79 # The truncated name of the file.
80 'short_name' : os
.path
.basename(src_fname
),
81 # The current year, for the copyright notice
82 'this_year' : time
.localtime().tm_year
,
83 # An appropriate guard macro, for the header.
84 'guard_macro' : guard_macro(src_fname
),
87 return template
.format(**names
)
89 # This template operates on paths relative to tor's src directory
90 HEADER_TEMPLATE
= """\
91 /* Copyright (c) 2001 Matej Pfajfar.
92 * Copyright (c) 2001-2004, Roger Dingledine.
93 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
94 * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
95 /* See LICENSE for licensing information */
99 * @brief Header for {c_file_path}
102 #ifndef {guard_macro}
103 #define {guard_macro}
105 #endif /* !defined({guard_macro}) */
108 # This template operates on paths relative to the tor's src directory
109 C_FILE_TEMPLATE
= """\
110 /* Copyright (c) 2001 Matej Pfajfar.
111 * Copyright (c) 2001-2004, Roger Dingledine.
112 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
113 * Copyright (c) 2007-{this_year}, The Tor Project, Inc. */
114 /* See LICENSE for licensing information */
121 #include "orconfig.h"
122 #include "{header_path}"
127 Represents part of an automake file. If it is decorated with
128 an ADD_C_FILE comment, it has a "kind" based on what to add to it.
129 Otherwise, it only has a bunch of lines in it.
131 This class operates on paths relative to the top-level tor directory.
133 pat
= re
.compile(r
'# ADD_C_FILE: INSERT (\S*) HERE', re
.I
)
138 self
.hasBlank
= False # true if we end with a blank line.
140 def addLine(self
, line
):
142 Insert a line into this chunk while parsing the automake file.
144 Return True if we have just read the last line in the chunk, and
147 m
= self
.pat
.match(line
)
150 raise ValueError("control line not preceded by a blank line")
151 self
.kind
= m
.group(1)
153 if line
.strip() == "":
157 self
.lines
.append(line
)
161 def insertMember(self
, new_tor_fname
):
163 Add a new file name new_tor_fname to this chunk. Try to insert it in
164 alphabetical order with matching indentation, but don't freak out too
165 much if the source isn't consistent.
167 Assumes that this chunk is of the form:
173 This function operates on paths relative to the top-level tor
178 for lineno
, line
in enumerate(self
.lines
):
179 m
= re
.match(r
'(\s+)(\S+)(\s+)\\', line
)
182 prespace
, cur_tor_fname
, postspace
= m
.groups()
183 if cur_tor_fname
> new_tor_fname
:
184 self
.insert_before(lineno
, new_tor_fname
, prespace
, postspace
)
186 self
.insert_at_end(new_tor_fname
, prespace
, postspace
)
188 def insert_before(self
, lineno
, new_tor_fname
, prespace
, postspace
):
189 self
.lines
.insert(lineno
,
190 "{}{}{}\\\n".format(prespace
, new_tor_fname
,
193 def insert_at_end(self
, new_tor_fname
, prespace
, postspace
):
194 lastline
= self
.lines
[-1].strip()
195 self
.lines
[-1] = '{}{}{}\\\n'.format(prespace
, lastline
, postspace
)
196 self
.lines
.append("{}{}\n".format(prespace
, new_tor_fname
))
199 """Write all the lines in this chunk to the file 'f'."""
200 for line
in self
.lines
:
202 if not line
.endswith("\n"):
208 class ParsedAutomake
:
209 """A sort-of-parsed automake file, with identified chunks into which
210 headers and c files can be inserted.
212 This class operates on paths relative to the top-level tor directory.
218 def addChunk(self
, chunk
):
219 """Add a newly parsed AutomakeChunk to this file."""
220 self
.chunks
.append(chunk
)
221 self
.by_type
[chunk
.kind
.lower()] = chunk
223 def add_file(self
, tor_fname
, kind
):
224 """Insert a file tor_fname of kind 'kind' to the appropriate
225 section of this file. Return True if we added it.
227 This function operates on paths relative to the top-level tor
230 if kind
.lower() in self
.by_type
:
231 self
.by_type
[kind
.lower()].insertMember(tor_fname
)
237 """Write this file into a file 'f'."""
238 for chunk
in self
.chunks
:
241 def get_include_am_location(tor_fname
):
242 """Find the right include.am file for introducing a new file
243 tor_fname. Return None if we can't guess one.
245 Note that this function is imperfect because our include.am layout is
246 not (yet) consistent.
248 This function operates on paths relative to the top-level tor directory.
250 # Strip src for pattern matching, but add it back when returning the path
251 src_fname
= srcdir_file(tor_fname
)
252 m
= re
.match(r
'^(lib|core|feature|app)/([a-z0-9_]*)/', src_fname
)
254 return "src/{}/{}/include.am".format(m
.group(1),m
.group(2))
256 if re
.match(r
'^test/', src_fname
):
257 return "src/test/include.am"
263 Create a new C file and H file corresponding to the filename "fname",
264 and add them to the corresponding include.am.
266 This function operates on paths relative to the top-level tor directory.
269 # Make sure we're in the top-level tor directory,
270 # which contains the src directory
271 if not os
.path
.isdir("src"):
272 raise RuntimeError("Could not find './src/'. "
273 "Run this script from the top-level tor source "
276 # And it looks like a tor/src directory
277 if not os
.path
.isfile("src/include.am"):
278 raise RuntimeError("Could not find './src/include.am'. "
279 "Run this script from the top-level tor source "
282 # Make the file name relative to the top-level tor directory
283 tor_fname
= tordir_file(fname
)
284 # And check that we're adding files to the "src" directory,
285 # with canonical paths
286 if tor_fname
[:4] != "src/":
287 raise ValueError("Requested file path '{}' canonicalized to '{}', "
288 "but the canonical path did not start with 'src/'. "
289 "Please add files to the src directory."
290 .format(fname
, tor_fname
))
292 c_tor_fname
= makeext(tor_fname
, "c")
293 h_tor_fname
= makeext(tor_fname
, "h")
295 if os
.path
.exists(c_tor_fname
):
296 print("{} already exists".format(c_tor_fname
))
298 if os
.path
.exists(h_tor_fname
):
299 print("{} already exists".format(h_tor_fname
))
302 with
open(c_tor_fname
, 'w') as f
:
303 f
.write(instantiate_template(C_FILE_TEMPLATE
, c_tor_fname
))
305 with
open(h_tor_fname
, 'w') as f
:
306 f
.write(instantiate_template(HEADER_TEMPLATE
, h_tor_fname
))
308 iam
= get_include_am_location(c_tor_fname
)
309 if iam
is None or not os
.path
.exists(iam
):
310 print("Made files successfully but couldn't identify include.am for {}"
311 .format(c_tor_fname
))
314 amfile
= ParsedAutomake()
315 cur_chunk
= AutomakeChunk()
318 if cur_chunk
.addLine(line
):
319 amfile
.addChunk(cur_chunk
)
320 cur_chunk
= AutomakeChunk()
321 amfile
.addChunk(cur_chunk
)
323 amfile
.add_file(c_tor_fname
, "sources")
324 amfile
.add_file(h_tor_fname
, "headers")
326 with
open(iam
+".tmp", 'w') as f
:
329 os
.rename(iam
+".tmp", iam
)
331 if __name__
== '__main__':
333 sys
.exit(run(sys
.argv
[1]))