I feel like this question could be answered with one or two hyperlinks; I'm just not coming up with the right search terms to find those links myself...
I'm trying to make some minor changes to the git p4 subcommand, which is implemented as a 3797-line Python script named /usr/libexec/git-core/git-p4. Before wading into the code too much farther, I'd like to get a sense of how a Python git command is structured.
What information does the subcommand get from its caller? What environment variables can it rely on existing? How does it detect the configuration (from .git/config and/or ~/.gitconfig)? How are git command-line options passed down from git (in case there are command-line options common to many different subcommands and you want to make sure their handling is centralized)? What is the current working directory at the time the subcommand is launched? What happens if I change the cwd? How do I communicate back to git that it should change the repo (make commits, add or delete tags, rewrite history) as part of the functionality of my new subcommand? Can my command "work on" the index directly without making a working tree, and if so, how? How do I handle and report errors? How do I print usage information in a consistent way?
I assume there must be blog posts and things about this topic, but searching "write a git subcommand in python", "create new git subcommand", etc., just turns up ways to run existing git commands from Python and ways to create new git repos, respectively.