Skip to content

Instantly share code, notes, and snippets.

@garretfick
Created March 26, 2019 21:22
Show Gist options
  • Save garretfick/a9d6f12ba918f9d4021f847fb95928c9 to your computer and use it in GitHub Desktop.
Save garretfick/a9d6f12ba918f9d4021f847fb95928c9 to your computer and use it in GitHub Desktop.
Adds header guards to multiple files
import argparse
import glob
import logging
import os
import sys
logger = logging.getLogger(__name__)
def main(argv):
"""The main function for the script so it can be included if desired."""
# Setup a nice little command prompt for running the script.
parser = argparse.ArgumentParser(
description="Console tool for applying header guards automatically."
)
parser.add_argument("directory",
default=os.getcwd(),
help="The root path for constructing the guard name.")
parser.add_argument("-s", "--searchpos",
help="If specified, insert the guard after the " +
"specified search phrase.")
parser.add_argument("-d", "--dryrun",
help="If specified, don't actually modify files.")
parser.add_argument("-v", "--verbose",
help="Prints more information about the conversion.",
action="store_const",
dest="loglevel",
const=logging.INFO,
default=logging.WARNING)
args = parser.parse_args()
logging.basicConfig(level=args.loglevel)
directory = os.path.abspath(args.directory)
logger.info("Inserting guard after %s to files in directory %s",
args.searchpos, directory)
# Now get to work on adding the guards
search_path = os.path.join(directory, "**", "*.h")
for filename in glob.glob(search_path, recursive=True):
with open(filename, "r") as read_fp:
contents = read_fp.read()
split_index = contents.find(args.searchpos) + 3 if args.searchpos is not None else 0
before = contents[0:split_index]
after = contents[split_index:]
# If the file has a newline at the end, preserve it
if after[-1] == "\n":
after = after[:-1]
tail = "\n"
else:
tail = ""
# What is the guard we want to add? It depends on the path
guard_name = filename[len(directory) + 1:].replace("\\", "_"). \
replace("/", "_").replace(".", "_").upper()
logger.info("%s -> insert at %d guard %s", filename, split_index, guard_name)
guard = "\n#ifndef %s\n#define %s\n" % (guard_name, guard_name)
if not args.dryrun:
# Now construct the contents
contents = before + guard + after + "\n#endif" + tail
# And write to disk
with open(filename, "w") as write_fp:
write_fp.write(contents)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment