Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add shell completions #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions gscholar/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,39 @@

import gscholar as gs

try:
import shtab
except ImportError:
from . import _shtab as shtab


logger = logging.getLogger('gscholar')
logging.basicConfig(
format='%(asctime)s %(levelname)s %(name)s %(message)s',
level=logging.WARNING
)

# https://github.com/iterative/shtab/blob/5358dda86e8ea98bf801a43a24ad73cd9f820c63/examples/customcomplete.py#L11-L22
PDF_FILE = {
"bash": "_shtab_greeter_compgen_pdf_files",
"zsh": "_files -g '*.pdf'",
"tcsh": "f:*.pdf"
}
PREAMBLE = {
"bash": """\
# $1=COMP_WORDS[1]
_shtab_greeter_compgen_pdf_files() {
compgen -d -- $1 # recurse into subdirs
compgen -f -X '!*?.pdf' -- $1
}
"""
}


def main():
usage = 'Usage: %prog [options] {pdf | "search terms"}'
parser = argparse.ArgumentParser(usage)
usage = 'Usage: %(prog)s [options] {pdf | "search terms"}'
parser = argparse.ArgumentParser('gscholar', usage)
shtab.add_argument_to(parser, preamble=PREAMBLE)
parser.add_argument(
"-a", "--all", action="store_true",
help="show all bibtex results"
Expand All @@ -41,7 +63,7 @@ def main():
'--version', action='version', version=gs.__VERSION__)
parser.add_argument(
'keyword', metavar='{pdf | "search terms"}',
help='pdf | "search terms"')
help='pdf | "search terms"').complete = PDF_FILE
args = parser.parse_args()
if args.debug is True:
logger.setLevel(logging.DEBUG)
Expand Down
38 changes: 38 additions & 0 deletions gscholar/_shtab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Fake shtab."""
from argparse import Action, ArgumentParser

FILE = None
DIRECTORY = DIR = None


class PrintCompletionAction(Action):
"""Print completion action."""

def __call__(self, parser, namespace, values, option_string=None):
"""Warn when shtab is not installed.

:param parser:
:param namespace:
:param values:
:param option_string:
"""
print("Please install shtab firstly!")
parser.exit(0)


def add_argument_to(parser: ArgumentParser, *args, **kwargs):
"""Add completion argument to parser.

:param parser:
:type parser: ArgumentParser
:param args:
:param kwargs:
"""
Action.complete = None # type: ignore
parser.add_argument(
"--print-completion",
choices=["bash", "zsh", "tcsh"],
action=PrintCompletionAction,
help="print shell completion script",
)
return parser
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
},
python_requires='>=3.7',
packages=['gscholar'],
extras_require={'completion': ['shtab']},
entry_points={
'console_scripts': [
'gscholar = gscholar.__main__:main'
Expand Down