Git has a special feature that if you have a script called git-xxx
(** with execution privileges and under your PATH **), you can run it in the form ** git xxx **. (The famous git-flow
also uses this feature to call git flow
)
Let's reinvent the wheel with Python for this feature.
mygit.py
# coding: utf-8
import os
import sys
from subprocess import call
class ExtensionLoader:
def __init__(self):
#Since the environment variable PATH is a string connected by a colon,
#Convert to an array by splitting with a colon
self.PATH = os.environ["PATH"].split(":")
def load(self, ext, args):
# ext: 'mygit init' -> 'init'
ext_absname = "mygit-{}".format(ext)
found_flag = None
extension = None
for directory in self.PATH:
# 'mygit-init'Is in the directory
if ext_absname in os.listdir(directory):
found_flag = True
extension = os.path.join(directory, ext_absname)
if found_flag:
# 'mygit-init'Run when you find
cmd = [extension]
cmd += args #Passing arguments to the extension script to be executed here
return call(cmd)
else:
raise IOError("Extension does not found: {}".format(ext))
if __name__ == "__main__":
if len(sys.argv) == 1:
print "usage: mygit {command}"
sys.exit(1)
extloader = ExtensionLoader()
# argv: ["mygit" "command", "arg1", "arg2", "arg3"]
command = sys.argv[1]
arguments = sys.argv[2:]
exit_status = extloader.load(command, arguments)
sys.exit(exit_status)
It was surprisingly easy.
The problem is that it can't be used with ** argparse **. argparse can parse subcommands, but if an unregistered command is entered, it will throw an error and it is not possible to register the extension script command in advance ...
Recommended Posts