Skip to content

Instantly share code, notes, and snippets.

@ajdavis
Created November 14, 2019 21:26
Show Gist options
  • Save ajdavis/267e61d23c304ed4de9f447db2f34857 to your computer and use it in GitHub Desktop.
Save ajdavis/267e61d23c304ed4de9f447db2f34857 to your computer and use it in GitHub Desktop.
Script for CLion to switch between editing a C/C++ header and source file
#!/usr/bin/env python3
import os
import sys
if len(sys.argv) != 2:
print("Usage: %s FILE" % (sys.argv[0],))
sys.exit(1)
path = os.path.abspath(sys.argv[1])
basepath, ext = os.path.splitext(path)
h_exts = ('.h', '.hpp')
c_exts = ('.cpp', '.cxx', '.c')
def find_altpath(base, exts):
for ext in exts:
altpath = base + ext
if os.path.exists(altpath):
return altpath
candidates = [
os.path.join(os.path.dirname(base), filename)
for filename in os.listdir(os.path.dirname(base))
for ext in exts
if filename.endswith(ext)
]
if candidates:
def prefixlen(x):
return len(os.path.commonprefix([base, x]))
return sorted(candidates, key=prefixlen)[-1]
if ext in h_exts:
altpath = find_altpath(basepath, c_exts)
elif ext in c_exts:
altpath = find_altpath(basepath, h_exts)
else:
print("Unrecognized extension: %s" % (path,))
sys.exit(2)
if not altpath:
print("Could not find alternate file for %s" % (path,))
sys.exit(3)
else:
os.system('%s/bin/clion "%s"' % (os.path.expanduser('~'), altpath,))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment