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

Migrate to pyproject + integrate ruff #69

Merged
merged 5 commits into from
Dec 11, 2024
Merged
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
15 changes: 15 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@ jobs:
- name: Run unit tests (via tox)
# Run tox using the version of Python in `PATH`
run: tox -e py
lint:
name: Run linters
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.13'
- name: Install dependencies
run: python -m pip install tox
- name: Run linters (via tox)
# Run tox using the version of Python in `PATH`
run: tox -e lint
release:
name: Upload release artifacts
runs-on: ubuntu-latest
Expand Down
20 changes: 20 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: mixed-line-ending
args: ['--fix', 'lf']
- id: check-byte-order-marker
- id: check-executables-have-shebangs
- id: check-merge-conflict
- id: debug-statements
- id: check-yaml
files: .*\.(yaml|yml)$
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.2
hooks:
- id: ruff
args: ['--fix']
- id: ruff-format
28 changes: 23 additions & 5 deletions click_man/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ def get_short_help_str(command, limit=45):
"""
Gets short help for the command or makes it by shortening the long help string.
"""
return command.short_help or command.help and click.utils.make_default_short_help(command.help, limit) or ''
return (
command.short_help
or command.help
and click.utils.make_default_short_help(command.help, limit)
or ''
)


def generate_man_page(ctx, version=None, date=None):
Expand All @@ -43,7 +48,11 @@ def generate_man_page(ctx, version=None, date=None):
man_page.short_help = get_short_help_str(ctx.command)
man_page.description = ctx.command.help
man_page.synopsis = ' '.join(ctx.command.collect_usage_pieces(ctx))
man_page.options = [x.get_help_record(ctx) for x in ctx.command.params if isinstance(x, click.Option) and not getattr(x, 'hidden', False)]
man_page.options = [
x.get_help_record(ctx)
for x in ctx.command.params
if isinstance(x, click.Option) and not getattr(x, 'hidden', False)
]

if date:
man_page.date = date
Expand All @@ -58,7 +67,12 @@ def generate_man_page(ctx, version=None, date=None):


def write_man_pages(
name, cli, parent_ctx=None, version=None, target_dir=None, date=None,
name,
cli,
parent_ctx=None,
version=None,
target_dir=None,
date=None,
):
"""
Generate man page files recursively
Expand Down Expand Up @@ -90,6 +104,10 @@ def write_man_pages(
continue

write_man_pages(
name, command, parent_ctx=ctx, version=version,
target_dir=target_dir, date=date,
name,
command,
parent_ctx=ctx,
version=version,
target_dir=target_dir,
date=date,
)
50 changes: 39 additions & 11 deletions click_man/man.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class ManPage(object):

:param str command: the name of the command
"""

TITLE_KEYWORD = '.TH'
SECTION_HEADING_KEYWORD = '.SH'
PARAGRAPH_KEYWORD = '.PP'
Expand Down Expand Up @@ -51,13 +52,17 @@ def __init__(self, command):
self.commands = []

#: Holds the date of the man page creation time.
self.date = time.strftime("%Y-%m-%d", time.gmtime(int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))))
self.date = time.strftime(
'%Y-%m-%d',
time.gmtime(int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))),
)

def replace_blank_lines(self, s):
''' Find any blank lines and replace them with .PP '''
"""Find any blank lines and replace them with .PP"""

lines = map(lambda l: self.PARAGRAPH_KEYWORD if l == '' else l,
s.split('\n'))
lines = map(
lambda x: self.PARAGRAPH_KEYWORD if x == '' else x, s.split('\n')
)
return '\n'.join(lines)

def __str__(self):
Expand All @@ -68,12 +73,23 @@ def __str__(self):
lines = []

# write title and footer
lines.append('{0} "{1}" "1" "{2}" "{3}" "{4} Manual"'.format(
self.TITLE_KEYWORD, self.command.upper(), self.date, self.version, self.command))
lines.append(
'{0} "{1}" "1" "{2}" "{3}" "{4} Manual"'.format(
self.TITLE_KEYWORD,
self.command.upper(),
self.date,
self.version,
self.command,
)
)

# write name section
lines.append('{0} NAME'.format(self.SECTION_HEADING_KEYWORD))
lines.append(r'{0} \- {1}'.format(self.command.replace(' ', r'\-'), self.short_help))
lines.append(
r'{0} \- {1}'.format(
self.command.replace(' ', r'\-'), self.short_help
)
)

# write synopsis
lines.append('{0} SYNOPSIS'.format(self.SECTION_HEADING_KEYWORD))
Expand All @@ -82,7 +98,9 @@ def __str__(self):

# write the description
if self.description:
lines.append('{0} DESCRIPTION'.format(self.SECTION_HEADING_KEYWORD))
lines.append(
'{0} DESCRIPTION'.format(self.SECTION_HEADING_KEYWORD)
)
lines.append(self.replace_blank_lines(self.description))

# write the options
Expand All @@ -91,7 +109,14 @@ def __str__(self):
for option, description in self.options:
lines.append(self.INDENT_KEYWORDD)
option_unpacked = option.replace('-', r'\-').split()
lines.append(r'\fB{0}\fP{1}'.format(option_unpacked[0], (' ' + ' '.join(option_unpacked[1:])) if len(option_unpacked) > 1 else ''))
lines.append(
r'\fB{0}\fP{1}'.format(
option_unpacked[0],
(' ' + ' '.join(option_unpacked[1:]))
if len(option_unpacked) > 1
else '',
)
)
lines.append(self.replace_blank_lines(description))

# write commands
Expand All @@ -101,8 +126,11 @@ def __str__(self):
lines.append(self.PARAGRAPH_KEYWORD)
lines.append(r'\fB{0}\fP'.format(name))
lines.append(' ' + self.replace_blank_lines(description))
lines.append(r' See \fB{0}-{1}(1)\fP for full documentation on the \fB{1}\fP command.'.format(
self.command, name))
lines.append(
r' See \fB{0}-{1}(1)\fP for full documentation on the \fB{1}\fP command.'.format(
self.command, name
)
)

man_page = '\n'.join(lines)

Expand Down
18 changes: 13 additions & 5 deletions click_man/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ def _get_entry_point(name: str) -> Optional[importlib.metadata.EntryPoint]:
)
else:
console_scripts = [
ep for ep in entry_points.get('console_scripts', [])
ep
for ep in entry_points.get('console_scripts', [])
if ep.name == name
]

Expand All @@ -41,9 +42,11 @@ def _get_entry_point(name: str) -> Optional[importlib.metadata.EntryPoint]:

@click.command(context_settings={'help_option_names': ['-h', '--help']})
@click.option(
'--target', '-t', default=os.path.join(os.getcwd(), 'man'),
'--target',
'-t',
default=os.path.join(os.getcwd(), 'man'),
type=click.Path(file_okay=False, dir_okay=True, resolve_path=True),
help='Target location for the man pages'
help='Target location for the man pages',
)
@click.option('--man-version', help='Version to use in generated man page(s)')
@click.option('--man-date', help='Date to use in generated man page(s)')
Expand Down Expand Up @@ -100,7 +103,8 @@ def cli(target, name, man_version, man_date):

ep_module = import_module(entry_point.module)
ep_members = getmembers(
ep_module, lambda x: isinstance(x, click.Command),
ep_module,
lambda x: isinstance(x, click.Command),
)

if len(ep_members) < 1:
Expand All @@ -115,5 +119,9 @@ def cli(target, name, man_version, man_date):

click.echo('Generate man pages for {0} in {1}'.format(name, target))
write_man_pages(
name, cli, version=man_version, target_dir=target, date=man_date,
name,
cli,
version=man_version,
target_dir=target,
date=man_date,
)
60 changes: 40 additions & 20 deletions examples/debian_pkg/repo/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Repo(object):

def __init__(self, home):
self.home = home
self.config = {}
Expand All @@ -25,12 +24,21 @@ def __repr__(self):


@click.group()
@click.option('--repo-home', envvar='REPO_HOME', default='.repo',
metavar='PATH', help='Changes the repository folder location.')
@click.option('--config', nargs=2, multiple=True,
metavar='KEY VALUE', help='Overrides a config key/value pair.')
@click.option('--verbose', '-v', is_flag=True,
help='Enables verbose mode.')
@click.option(
'--repo-home',
envvar='REPO_HOME',
default='.repo',
metavar='PATH',
help='Changes the repository folder location.',
)
@click.option(
'--config',
nargs=2,
multiple=True,
metavar='KEY VALUE',
help='Overrides a config key/value pair.',
)
@click.option('--verbose', '-v', is_flag=True, help='Enables verbose mode.')
@click.version_option('1.0')
@click.pass_context
def cli(ctx, repo_home, config, verbose):
Expand All @@ -52,10 +60,17 @@ def cli(ctx, repo_home, config, verbose):
@cli.command()
@click.argument('src')
@click.argument('dest', required=False)
@click.option('--shallow/--deep', default=False,
help='Makes a checkout shallow or deep. Deep by default.')
@click.option('--rev', '-r', default='HEAD',
help='Clone a specific revision instead of HEAD.')
@click.option(
'--shallow/--deep',
default=False,
help='Makes a checkout shallow or deep. Deep by default.',
)
@click.option(
'--rev',
'-r',
default='HEAD',
help='Clone a specific revision instead of HEAD.',
)
@pass_repo
def clone(repo, src, dest, shallow, rev):
"""Clones a repository.
Expand Down Expand Up @@ -86,10 +101,10 @@ def delete(repo):


@cli.command()
@click.option('--username', prompt=True,
help='The developer\'s shown username.')
@click.option('--email', prompt='E-Mail',
help='The developer\'s email address')
@click.option(
'--username', prompt=True, help="The developer's shown username."
)
@click.option('--email', prompt='E-Mail', help="The developer's email address")
@click.password_option(help='The login password.')
@pass_repo
def setuser(repo, username, email, password):
Expand All @@ -104,9 +119,13 @@ def setuser(repo, username, email, password):


@cli.command()
@click.option('--message', '-m', multiple=True,
help='The commit message. If provided multiple times each '
'argument gets converted into a new line.')
@click.option(
'--message',
'-m',
multiple=True,
help='The commit message. If provided multiple times each '
'argument gets converted into a new line.',
)
@click.argument('files', nargs=-1, type=click.Path())
@pass_repo
def commit(repo, files, message):
Expand Down Expand Up @@ -138,8 +157,9 @@ def commit(repo, files, message):


@cli.command(short_help='Copies files.')
@click.option('--force', is_flag=True,
help='forcibly copy over an existing managed file')
@click.option(
'--force', is_flag=True, help='forcibly copy over an existing managed file'
)
@click.argument('src', nargs=-1, type=click.Path())
@click.argument('dst', type=click.Path())
@pass_repo
Expand Down
2 changes: 1 addition & 1 deletion examples/debian_pkg/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
version='0.1.0',
install_requires=['click'],
packages=find_packages(),
entry_points={'console_scripts': ['repo = repo.__main__:cli']}
entry_points={'console_scripts': ['repo = repo.__main__:cli']},
)
Loading
Loading