|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import git |
| 6 | + |
| 7 | +def extract_gitrepo_sections(conf): |
| 8 | + return filter(lambda k: k.startswith('gitrepo'), conf.sections()) |
| 9 | + |
| 10 | +def extract_gitrepo_conf(gconf_old, gconf_new): |
| 11 | + if os.path.exists(gconf_new): |
| 12 | + return "✗ cannot execute, file already exists: {}".format(gconf_new) |
| 13 | + with git.config.GitConfigParser(gconf_old, read_only=False) as cold: |
| 14 | + with git.config.GitConfigParser(gconf_new, read_only=False) as cnew: |
| 15 | + sections = list(extract_gitrepo_sections(cold)) |
| 16 | + # copy the sections to the new configuration file |
| 17 | + cnew.update({s: {k:v for k,v in cold.items(s)} for s in sections}) |
| 18 | + cnew.write() |
| 19 | + # remove the sections from the old configuration file |
| 20 | + for section in sections: |
| 21 | + cold.remove_section(section) |
| 22 | + # insert path to the new config file in the old one |
| 23 | + cold.update({'include': {'path': os.path.abspath(gconf_new)}}) |
| 24 | + print("🍻 git-repo configuration extracted to new file: {}".format(gconf_new)) |
| 25 | + |
| 26 | +if __name__ == '__main__': |
| 27 | + if '-h' in sys.argv or '--help' in sys.argv: |
| 28 | + sys.exit('Usage: {} [.gitconfig-repos] [.gitconfig]'.format(sys.argv[0])) |
| 29 | + sys.exit(extract_gitrepo_conf( |
| 30 | + gconf_old=os.path.expanduser(len(sys.argv) >= 3 and sys.argv[2] or '~/.gitconfig'), |
| 31 | + gconf_new=os.path.expanduser(len(sys.argv) >= 2 and sys.argv[1] or '~/.gitconfig-repos') |
| 32 | + )) |
| 33 | + |
| 34 | + |
0 commit comments