clang-format
is a great code formatter for C and C++ code, but using it can
be annoying due to the way the format file is specified. There is no option
to pick your format file explicitly. Instead, clang-format
will look for
a file called .clang-format
or _clang-format
in your working directory,
and then search recursively upward through the tree until it finds that
file.
That doesn't really work for me. I have a .clang-format
file I keep in
my dotfiles repo, and I'd like to use that for all of my code formatting.
Unfortunately this file won't get used unless there are no other .clang-format
files anywhere in the path from my code directory to my home directory root, and
that doesn't work for me. For reasons not worth getting into, I often find a
.clang-format
file in the way in the way.
Now certainly, you could fix this issue by symlinking my global .clang-format
into every code project directory, but that gets pretty annoying as well.
Instead, here's my solution. clang-format
offers a -style
option that lets
you specify a YAML dictionary of all your style options on the command line.
I made a script that acts as a wrapper around clang-format
. It parses whatever
.clang-format
file you want, formats it into a single arg, then calls
clang-format
passing your style information to the -style
argument.
Hope this helps anyone out there!
#!/usr/bin/env python3
# Note: depends on you having the pyyaml module installed.
import os
import yaml
import sys
import subprocess
p = os.path.expanduser("~/.clang-format")
clangf = open(p, 'r')
clangfc = clangf.read()
clangf.close()
yl = yaml.load(clangfc)
ret = subprocess.run(["clang-format-6.0", "-style", str(yl)] + sys.argv[1:])
sys.exit(ret.returncode)
Copyright © 2013 - 2018 Nate Craun.