Prodesire
The sample code and history articles involved have been synchronized to the HelloGithub-Team repository
One, foreword
In the previous five articles on Click, we got an overview of its power. By convention, we use click to implement git commands like argparse and docopt.
The focus of this article is not on how git’s various commands are implemented, but on how to use Click to build a useful command line program, and what the code structure is. Therefore, git related operations will be easily implemented using the GitPython library.
For those of you who have not read git commands implemented with XXX (XXX refers to argparse and docopt), we will provide a brief introduction to git commands and GitPython.
This series of articles uses Python 3 as the interpreter by default. If you are still using Python 2, be aware of the differences in syntax and library usageCopy the code
Git commands
When you have written a piece of code or added or deleted some files, you can check the status of the file with the following command:
git status
Copy the code
After confirming the file status, one or more files (folders) are added to the staging area with the following command:
git add [pathspec [pathspec ...]]
Copy the code
Then use the following command to submit the information:
git commit -m "your commit message"
Copy the code
Finally push the commit to the remote repository with the following command:
git push
Copy the code
We will use click and the GitPython library to implement these four subcommands.
About GitPython
Gitpython is a Python third-party library that interacts with git repositories. We’ll use its power to implement real Git logic.
Installation:
pip install gitpython
Copy the code
Four, thinking
Before implementing it, what features of Click will be used? What is the structure of the program?
click
Git’s four subcommands correspond to four functions, each decorated with Click’s command. Git add and Git commit need to be decorated with click.argument and click.option representing the parameters and options, respectively.
Program structure
Program structure:
- instantiation
Git
Object for global use - define
cli
Function as a command group, that is, the entry to the entire command program - Define the implementation functions corresponding to the four commands
status
,add
,commit
,push
The basic structure is as follows:
import os
import click
from git.cmd import Git
git = Git(os.getcwd())
@click.group()
def cli(a):
Git command line ""
pass
@cli.command()
def status(a):
""" Process the status command """
pass
@cli.command()
@click.argument('pathspec', nargs=-1)
def add(pathspec):
""" Processing the add command """
pass
@cli.command()
@click.option('-m', 'msg')
def commit(msg):
""" processing -m < MSG > command """
pass
@cli.command()
def push(a):
""" Processing the push command """
pass
if __name__ == '__main__':
cli()
Copy the code
Now we will implement our Git program step by step.
Five, the implementation
Suppose we implement our Git program in the click-git.py file.
5.1 Status subcommand
The status subcommand takes no arguments or options, so its implementation function just needs the cli.mand () decoration.
@cli.command()
def status(a):
""" Process the status command """
cmd = ['git'.'status']
output = git.execute(cmd)
click.echo(output)
Copy the code
As you can see, we ended up calling the real Git status and printing the output.
5.2 Add subcommand
The add subcommand needs to take any pathSpec argument as opposed to the status subcommand, so add a click.argument decorator, and add a pathSpec entry of the same name to the add function. The Click pathSpec is actually a tuple that needs to be converted to a list before being added to a list.
@cli.command()
@click.argument('pathspec', nargs=-1)
def add(pathspec):
""" Processing the add command """
cmd = ['git'.'add'] + list(pathspec)
output = git.execute(cmd)
click.echo(output)
Copy the code
When python3 click-git.py add –help, the result is as follows:
Usage: click-git.py add [OPTIONS] [PATHSPEC]... Process the add command Options: --help Show this message and exit.Copy the code
Git add can accept any number of pathSpecs, so it is more appropriate to change the parameter of add(pathSpec) to plural, but we want the help message to be singular.
@cli.command()
@click.argument('pathspecs', nargs=-1, metavar='[PATHSPEC]... ')
def add(pathspecs):
""" Processing the add command """
cmd = ['git'.'add'] + list(pathspecs)
output = git.execute(cmd)
click.echo(output)
Copy the code
5.3 Commit subcommand
The add subcommand needs to accept the -m option as opposed to the status subcommand, so add a click.option decorator, specify the option name MSG, and add an entry parameter of the same name to the commit function.
@cli.command()
@click.option('-m', 'msg')
def commit(msg):
""" processing -m < MSG > command """
cmd = ['git'.'commit'.'-m', msg]
output = git.execute(cmd)
click.echo(output)
Copy the code
5.4 Push subcommand
The push subcommand, like the status subcommand, does not take any arguments or options, so its implementation function needs only the cli.mand () decoration.
@cli.command()
def push(a):
""" Processing the push command """
cmd = ['git'.'push']
output = git.execute(cmd)
click.echo(output)
Copy the code
At this point, we have implemented a simple git command line to query project status using python click-git.py status.
Conveniently, the docString for each command function is used as the help for this command, so when python3 click-git.py –help is automatically generated:
Usage: click-git.py [OPTIONS] COMMAND [ARGS]... Git command line Options: --help Show this message and exit. Commands: Add Processing Add command commit processing -m < MSG > command push processing push command status Processing status commandCopy the code
To see the entire source code, poke click-git.py.
Six, the summary
This article briefly introduces the git commands commonly used in daily work, and then puts forward the idea of implementing it, and finally realizes the Git program step by step with Click and GitPython.
Compare the implementation versions of Argparse and Click, and you’ll find that using click becomes particularly easy:
- In contrast to
argparse
, child parsers, parameter types, and all that - In contrast to
docopt
Parameter parsing and command call processing are also not a concern
This is surely Click’s greatest strength.
Now that we’re done with Click, review the simplicity of Click and you’ll love it.
You have now learned to use the three command line parsing libraries. But do you think that’s enough? Click is simple enough, isn’t it? But it’s still not the easiest.
In the next article, I’ll introduce you to fire, a command line library from Google that is popular in Python.
“Explain Open Source Project series” — let the people who are interested in open source projects not be afraid, let the initiator of open source projects not be alone. Follow along as you discover the joys of programming, use, and how easy it is to get involved in open source projects. Welcome to leave a message to contact us, join us, let more people fall in love with open source, contribute to open source ~