I wrote a function to load a Git extension script in Python

Special features of Git

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.

I wrote it

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

I wrote a function to load a Git extension script in Python
I wrote a script to extract a web page link in Python
I wrote a script to get a popular site in Japan
To execute a Python enumerate function in JavaScript
I want to create a window in Python
I wrote a class in Python3 and Java
I wrote "Introduction to Effect Verification" in Python
I wrote a script to upload a WordPress plugin
I wrote a code to convert quaternions to z-y-x Euler angles in Python
[Python] I forcibly wrote a short Perlin noise generation function in Numpy.
I made a script in python to convert .md files to Scrapbox format
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I wrote python in Japanese
Create a function in Python
I want to write in Python! (2) Let's write a test
I made a script to put a snippet in README.md
I tried to implement a pseudo pachislot in Python
A memorandum to run a python script in a bat file
I want to randomly sample a file in Python
I want to work with a robot in python.
I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab
I tried to implement a one-dimensional cellular automaton in Python
I wrote a program quickly to study DI with Python ①
I tried "How to get a method decorated in Python"
I wrote an empty directory automatic creation script in Python
To return char * in a callback function using ctypes in Python
I tried to implement the mail sending function in Python
I wrote a script to combine the divided ts files
I tried to make a stopwatch using tkinter in python
I want to make input () a nice complement in python
I wrote a script that splits the image in two
I wrote Fizz Buzz in Python
I wrote the queue in Python
I wrote the stack in Python
I made a script in Python to convert a text file for JSON (for vscode user snippet)
I tried to create a Python script to get the value of a cell in Microsoft Excel
I also tried to imitate the function monad and State monad with a generator in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
How to pass arguments to a Python script in SPSS Modeler Batch
I wrote a script to get you started with AtCoder fast!
I wrote the code to write the code of Brainf * ck in python
I tried to implement a misunderstood prisoner's dilemma game in Python
I wrote a script to help goodnotes5 and Anki work together
I tried to implement permutation in Python
I want to print in a comprehension
I made a payroll program in Python!
Precautions when pickling a function in python
Pin current directory to script directory in Python
Sample script to trap signals in Python
I tried to implement PLSA in Python 2
I want to build a Python environment
A simple IDAPython script to name a function
Run the Python interpreter in a script
How to get a stacktrace in python
I tried to implement ADALINE in Python
I wanted to solve ABC159 in Python
I tried to implement PPO in Python
I made a script to display emoji
I created a password tool in Python.