pax_global_header 0000666 0000000 0000000 00000000064 14343327243 0014517 g ustar 00root root 0000000 0000000 52 comment=3f809699d7025bd57541971854fa1d74ec50ef8e
rich-click-1.6.0/ 0000775 0000000 0000000 00000000000 14343327243 0013533 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/.flake8 0000664 0000000 0000000 00000000166 14343327243 0014711 0 ustar 00root root 0000000 0000000 [flake8]
# Default ignores that we can extend
ignore=D100,D102,D205,E203,E231,E731,W504,I001,W503
max-line-length=120
rich-click-1.6.0/.github/ 0000775 0000000 0000000 00000000000 14343327243 0015073 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14343327243 0017130 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/.github/workflows/deploy-pypi.yml 0000664 0000000 0000000 00000001352 14343327243 0022127 0 ustar 00root root 0000000 0000000 name: Publish rich-click to PyPI
on:
release:
types: [published]
jobs:
build-n-publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
name: Check out source-code repository
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: "3.8"
- name: Install python dependencies
run: |
python -m pip install --upgrade pip setuptools wheel build
- name: Build the distribution
run: python -m build
- name: Publish to PyPI
if: github.repository == 'ewels/rich-click'
uses: pypa/gh-action-pypi-publish@master
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
rich-click-1.6.0/.github/workflows/pre-commit.yml 0000664 0000000 0000000 00000000326 14343327243 0021730 0 ustar 00root root 0000000 0000000 name: Lint code
on:
push:
pull_request:
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
- uses: pre-commit/action@v2.0.3
rich-click-1.6.0/.github/workflows/rich-codex.yml 0000664 0000000 0000000 00000000745 14343327243 0021706 0 ustar 00root root 0000000 0000000 name: Rich-codex
on:
workflow_dispatch:
jobs:
rich_codex:
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
- name: Install your custom tools
run: pip install .
- name: Generate terminal images with rich-codex
uses: ewels/rich-codex@v1
with:
commit_changes: "true"
clean_img_paths: docs/images/*.svg
rich-click-1.6.0/.github/workflows/test-examples.yml 0000664 0000000 0000000 00000000732 14343327243 0022450 0 ustar 00root root 0000000 0000000 name: Test Examples
on: [push, pull_request]
jobs:
test_examples:
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
- name: Install rich-click
run: pip install .
- name: Test examples
run: |
for f in examples/*py
do
echo -e "\n\n$f"
python $f --help || exit 1;
done
rich-click-1.6.0/.gitignore 0000664 0000000 0000000 00000033263 14343327243 0015532 0 ustar 00root root 0000000 0000000
# Created by https://www.toptal.com/developers/gitignore/api/macos,linux,windows,pycharm+all,visualstudio,intellij+all,python
# Edit at https://www.toptal.com/developers/gitignore?templates=macos,linux,windows,pycharm+all,visualstudio,intellij+all,python
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
!.idea/codeStyles
!.idea/runConfigurations
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### PyCharm+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
# AWS User-specific
# Generated files
# Sensitive or high-churn files
# Gradle
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
# Mongo Explorer plugin
# File-based project format
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Cursive Clojure plugin
# SonarLint plugin
# Crashlytics plugin (for Android Studio and IntelliJ)
# Editor-based Rest Client
# Android studio 3.1+ serialized cache file
### PyCharm+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
# JetBrains Rider
*.sln.iml
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/macos,linux,windows,pycharm+all,visualstudio,intellij+all,python rich-click-1.6.0/.pre-commit-config.yaml 0000664 0000000 0000000 00000003363 14343327243 0020021 0 ustar 00root root 0000000 0000000 # This file contains the [pre-commit](https://pre-commit.com/) configuration of this repository.
# More on which specific pre-commit hooks we use can be found in README.md.
---
minimum_pre_commit_version: "2.9.2"
repos:
- repo: meta
hooks:
- id: identity
- id: check-hooks-apply
- repo: https://github.com/pre-commit/mirrors-prettier
rev: "" # Can not be removed, so leave this empty.
hooks:
- id: prettier
- repo: local
hooks:
- id: isort
name: iSort - Sorts imports.
description: Sorts your import for you.
entry: isort
language: python
types: [python]
require_serial: true
additional_dependencies:
- isort
- id: black
name: Black - Auto-formatter.
description: Black is the uncompromising Python code formatter. Writing to files.
entry: black
language: python
types: [python]
require_serial: true
additional_dependencies:
- black
- id: flake8
name: Flake8 - Enforce code style and doc.
description: A command-line utility for enforcing style consistency across Python projects.
entry: flake8
args: ["--config=.flake8"]
language: python
types: [python]
exclude: ^examples/
require_serial: true
additional_dependencies:
- flake8
- flake8-docstrings
- id: mypy
name: mypy - Static type checking
description: Mypy helps ensure that we use our functions and variables correctly by checking the types.
entry: mypy
language: python
types: [python]
exclude: ^examples/
require_serial: true
additional_dependencies:
- mypy
rich-click-1.6.0/.prettierrc.yaml 0000664 0000000 0000000 00000000000 14343327243 0016646 0 ustar 00root root 0000000 0000000 rich-click-1.6.0/CHANGELOG.md 0000664 0000000 0000000 00000021635 14343327243 0015353 0 ustar 00root root 0000000 0000000 # Changelog: rich-click
## Version 1.6.0 (2022-12-05)
- ⚠️ Removed support for Typer ⚠️
- Please use the [native Typer functionality](https://typer.tiangolo.com/tutorial/options/help/#cli-options-help-panels) instead.
- Added self-updating automated readme screengrabs using [rich-codex](https://github.com/ewels/rich-codex)
- Fix `AssertionError` when using click command call [#94](https://github.com/ewels/rich-click/issues/94)
## Version 1.5.2 (2022-08-01)
> ⚠️ Important notice! ⚠️
>
> As of [Typer v0.6.0](https://typer.tiangolo.com/release-notes/#060), Typer now supports rich help text natively.
> Support for Typer in rich-click is now depreciated and will be removed in a future release.
- Pin Typer version to `<0.6`
- Improve support for arguments [[#82](https://github.com/ewels/rich-click/pull/82)]
- Fixes error with Typer arguments [[#59](https://github.com/ewels/rich-click/issues/59)]
- Adds new style option `STYLE_ARGUMENT`
- Don't show env vars if `None` [[#84](https://github.com/ewels/rich-click/issues/84)]
- Specify `__all__` for type checkers [[#83](https://github.com/ewels/rich-click/pull/83)]
## Version 1.5.1 (2022-06-22)
- Updated pip release build CI [#78](https://github.com/ewels/rich-click/pull/78)
- Added missed occurence of return values when `standalone_mode` set [#79](https://github.com/ewels/rich-click/pull/79)
## Version 1.5 (2022-06-21)
- Add new `FORCE_TERMINAL` config flag to force colours even when help output is piped
- Can also be enabled by setting environment variables `GITHUB_ACTIONS`, `FORCE_COLOR` or `PY_COLORS`
- Add new `OPTION_ENVVAR_FIRST` config flag to print environment variables before option help texts instead of after (nice for alignment if all options have an env var).
- Refactor config flag `MAX_WIDTH` to set the console `width` and not individual panels
- Can now also be set with environment variable `TERMINAL_WIDTH`
- Fix package syntax in `setup.py` for `py.typed` [#75](https://github.com/ewels/rich-click/pull/75)
- Fix printing of return values when `standalone_mode` set [#76](https://github.com/ewels/rich-click/pull/76)
## Version 1.4 (2022-05-17)
- Added support for styling the tables that options and commands are displayed in [[#69](https://github.com/ewels/rich-click/issues/69)]
- Fixed `AttributeError` from `envvar` code in some Typer usage [[#70](https://github.com/ewels/rich-click/pull/70)]
## Version 1.3.2 (2022-05-16)
- Fix missed indentation issue in subcommand help text with `inspect.cleandoc` [[#67](https://github.com/ewels/rich-click/pull/67)]
- Add support for showing Click / Typer `envvar` environment variables [[#36](https://github.com/ewels/rich-click/issues/36)]
## Version 1.3.1 (2022-05-15)
- Bumped minimum version of `rich` from `10` to `10.7.0` (when `Group` was introduced)
- Refactored CLI's patching functionality to support `from rich_click.cli import patch` [[#53](https://github.com/ewels/rich-click/issues/53)]
- Make `_make_rich_rext` remove text indentations using `inspect.cleandoc` [[#55](https://github.com/ewels/rich-click/issues/55)]
- Import `rich_click` into main namespace for Pylance [[#64](https://github.com/ewels/rich-click/issues/64)]
- Add support of new click `hidden` command parameter [[#62](https://github.com/ewels/rich-click/pull/62)]
- Don't show Typer positional arguments unless `SHOW_ARGUMENTS` is specified [[#59](https://github.com/ewels/rich-click/issues/59)]
- Fix `\f` escape marker for new versions of Click, including in markdown [[#60](https://github.com/ewels/rich-click/issues/60)]
## Version 1.3.0 (2022-03-29)
- Added initial support for [Typer](https://typer.tiangolo.com/) [[#26](https://github.com/ewels/rich-click/pull/26)]
- Mark PEP 561 Compatibility [[#41](https://github.com/ewels/rich-click/pull/41)]
- Distribution now available via MacPorts [[#42](https://github.com/ewels/rich-click/pull/42)]
- Add typing information [[#39](https://github.com/ewels/rich-click/pull/39)]
- Refactor `RichCommand` and `RichGroup` out of `rich_click` [[#38](https://github.com/ewels/rich-click/pull/39)]
- Change metavar overflow to `fold`, so that large numbers of choices flow onto new lines instead of being truncated with an ellipsis [[#33](https://github.com/ewels/rich-click/issues/33)]
- Make metavar separators dim (`[]`,`<>`) (customise with `STYLE_METAVAR_SEPARATOR`)
- Add pre-commit config and a lot more linters (iSort, mypy, Flake8) [[#40](https://github.com/ewels/rich-click/pull/40)]
- Monkey-patch `RichCommand` and `RichGroup` in CLI code for better `rich-click` compatibility with more tools [[#43](https://github.com/ewels/rich-click/pull/43)]
- Parse emoji shortcodes `:partying_face:` [[#51](https://github.com/ewels/rich-click/pull/51)]
- Pushed minimum version of Python up to 3.7, in line with [Click v8.1](https://click.palletsprojects.com/en/8.1.x/changes/#version-8-1-0)
- Fixed bug where `--no-myflag` wasn't showing in the help [[#45](https://github.com/ewels/rich-click/issues/45)]
## Version 1.2.1 (2022-03-02)
- Support the command `short_help` argument [[#28](https://github.com/ewels/rich-click/issues/28)]
- Added `USE_CLICK_SHORT_HELP` global to enable default click shortening of help messages [[#28](https://github.com/ewels/rich-click/issues/28)]
- Avoid `AttributeError` exceptions when using custom exception classes based on click that don't have `ctx` [[#27](https://github.com/ewels/rich-click/issues/27)]
- Fix bug in inverted secondary options [[#31](https://github.com/ewels/rich-click/issues/31)]
- Refactor printing options to handle arbitrary numbers of flags [[#32](https://github.com/ewels/rich-click/issues/32)]
## Version 1.2.0 (2022-02-28)
- New CLI functionality to richifiy via prefix any other tool using click, by @pawamoy [[#13](https://github.com/ewels/rich-click/pull/13)]
- Distribution now available via conda-forge
## Version 1.1.1 (2022-02-28)
Hotfix patch release to remove an accidental `from turtle import st` that crept in due to a pesky VSCode plugin.
Many thanks to [@ashb](httpsd://github.com/ashb) for spotting.
## Version 1.1.0 (2022-02-28)
- Added support for `HEADER_TEXT` and `FOOTER_TEXT` to go before and after help output
- Catch Abort exceptions from `cmd+c` and print nicely using `ABORTED_TEXT`
- Handle missing `click.types._NumberRangeBase` in click 7x [[#16](https://github.com/ewels/rich-click/issues/16)]
- Fix compatibility issue for rich 10.6 (`group` vs `render_group` import) [[#16](https://github.com/ewels/rich-click/issues/16)]
- Require at least click v7.0 (released 2018) [[#16](https://github.com/ewels/rich-click/issues/16)]
- Require at least rich v10 (released March 2021) [[#16](https://github.com/ewels/rich-click/issues/16)]
- Unwrap single newlines in option and group-command help texts [[#23](https://github.com/ewels/rich-click/issues/23)]
- Add click `\b` escape marker functionality into help text rendering [[#24](https://github.com/ewels/rich-click/issues/24)]
- Fix syntax in example in README file by @fridex [[#15](https://github.com/ewels/rich-click/pull/15)]
## Version 1.0.0 (2022-02-18)
- _**Major change:**_ New usage, so that we can avoid having to do monkey patching [[#10](https://github.com/ewels/rich-click/pull/10).]
- Now use with `import rich_click as click`
- Add ability to create groups of options with separate panels
- Show positional arguments in their own panel by default
- Add config `GROUP_ARGUMENTS_OPTIONS` option to group with options
- Improve handing of metavars, give option to show appended instead of in column
- Add `COLOR_SYSTEM` option to add ability to disable colours
- Add options to customise error message help texts
- Add support for printing errors nicely
- A lot of additional testing and tweaking
## Version 0.3.0 (2022-02-13)
- Add ability to create groups of commands with separate panels
- Add support for rich console markup or Markdown in help texts
- Set default for `MAX_WIDTH` to `None` instead of `100`
- Switch boolean option `SKIP_ARGUMENTS` to `SHOW_ARGUMENTS`
- Improve regular expression for flags like `-bg`
- Use click's string for default value, instead of the value directly
- Show some previously missed metavar types (eg. choice and range options)
- Stripped required-asterisk column from options table if none are required
## Version 0.2.0 (2022-02-10)
- Made most styling decisions configurable
- Added support for more click parameters
- Showing default values, showing if required, showing if deprecated, epilog
- Option now hidden if set in click
## Version 0.1.2 (2022-02-10)
- Seems to work fine on Python 3.6, so dropped the requirement down to this instead of Python 3.7
## Version 0.1.1 (2022-02-10)
- Fix a bug in `setup.cfg` that broke installation
## Version 0.1.0 (2022-02-09)
Initial development version of `rich-click`, mostly as a proof of concept.
Supports basic generic functionality for printing help from click commands and groups.
Code was initially written by [@willmcgugan](https://github.com/willmcgugan) for `rich-cli`
and then further developed by [@ewels](http://github.com/ewels/).
rich-click-1.6.0/LICENSE 0000664 0000000 0000000 00000002053 14343327243 0014540 0 ustar 00root root 0000000 0000000 MIT License
Copyright (c) 2022 Phil Ewels
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
rich-click-1.6.0/README.md 0000664 0000000 0000000 00000041434 14343327243 0015020 0 ustar 00root root 0000000 0000000 # rich-click
**Format [click](https://click.palletsprojects.com/) help output nicely with [Rich](https://github.com/Textualize/rich).**
- Click is a _"Python package for creating beautiful command line interfaces"_.
- Rich is a _"Python library for rich text and beautiful formatting in the terminal"_.
The intention of `rich-click` is to provide attractive help output from
click, formatted with rich, with minimal customisation required.
## Features
- 🌈 Rich command-line formatting of click help and error messages
- 💫 Nice styles be default, usage is simply `import rich_click as click`
- 💻 CLI tool to run on _other people's_ tools (prefix the command with `rich-click`)
- 🎁 Group commands and options into named panels
- ❌ Well formatted error messages
- 🔢 Easily give custom sort order for options and commands
- 🎨 Extensive customisation of styling and behaviour possible

_Screenshot from [`examples/03_groups_sorting.py`](examples/03_groups_sorting.py)_
## Installation
You can install `rich-click` from the [Python Package Index (PyPI)](https://pypi.org/project/rich-click/) with `pip` or equivalent.
```bash
python -m pip install rich-click
```
Conda users can find `rich-click` on [conda forge](https://anaconda.org/conda-forge/rich-click).
Just set up conda to use conda-forge (see [docs](https://conda-forge.org/docs/user/introduction.html#how-can-i-install-packages-from-conda-forge)) then run:
```bash
conda install rich-click
```
Users on macOS can install `rich-click` via [MacPorts](https://ports.macports.org/port/py-rich-click/).
```bash
sudo port install py-rich-click
```
Note that rich-click requires `click>=7` but formatted subcommands (groups) only work with `click>=8`. With v7 the output simply reverts to default click output.
## Usage
### Import as click
To use `rich-click`, switch out your normal `click` import with `rich-click`, using the same namespace:
```python
import rich_click as click
```
That's it ✨ Then continue to use `click` as you would normally.
> See [`examples/01_simple.py`](examples/01_simple.py) for an example.
The intention is to maintain most / all of the normal click functionality and arguments.
If you spot something that breaks or is missing once you start using the plugin, please create an issue about it.
### Declarative
If you prefer, you can `RichGroup` or `RichCommand` with the `cls` argument in your click usage instead.
This means that you can continue to use the unmodified `click` package in parallel.
> See [`examples/02_declarative.py`](examples/02_declarative.py) for an example.
### Command-line usage
`rich-click` comes with a CLI tool that allows you to format the click help output from _any_ package.
As long as that tool is using click and isn't already passing custom `cls` objects, it should work.
However, please consider it an experimental feature at this point.
To use, simply prefix to your normal command.
For example, to get richified click help text from a package called `awesometool`, you could run:
```console
$ rich-click awesometool --help
Usage: awesometool [OPTIONS]
..more richified output below..
```
### Patching
In some situations, you might be registering a command from another Click CLI that does not use Rich-Click:
```python
import rich_click as click
from some_library import another_cli
@click.group("my-cli")
def cli():
pass
# `another_cli` will NOT have Rich-Click markup. :(
cli.add_command(another_cli)
```
In this situation, `another_cli` retains its original behavior. In order to make `another_cli` work with Rich-Click, you need to patch `click` before you import `another_cli`. You can patch Click with `rich_click.cli.patch` like this:
```python
import rich_click as click
from rich_click.cli import patch
patch()
from some_library import another_cli # noqa: E402
@click.group("my-cli")
def cli():
pass
# `another_cli` will have Rich-Click markup. :)
cli.add_command(another_cli)
```
## Customisation
There are a large number of customisation options in rich-click.
These can be modified by changing variables in the `click.rich_click` namespace.
Note that most normal click options should still work, such as `show_default=True`, `required=True` and `hidden=True`.
> Note: All images below are auto-generated using another side-project of mine: [rich-codex](https://github.com/ewels/rich-codex). Pretty cool!
### Using rich markup
In order to be as widely compatible as possible with a simple import, rich-click does _not_ parse rich formatting markup (eg. `[red]`) by default. You need to opt-in to this behaviour.
To use rich markup in your help texts, add the following:
```python
click.rich_click.USE_RICH_MARKUP = True
```
Remember that you'll need to escape any regular square brackets using a back slash in your help texts,
for example: `[dim]\[my-default: foo][\]`

> See [`examples/04_rich_markup.py`](examples/04_rich_markup.py) for an example.
### Using Markdown
If you prefer, you can use Markdown text.
You must choose either Markdown or rich markup. If you specify both, Markdown takes preference.
```python
click.rich_click.USE_MARKDOWN = True
```

> See [`examples/05_markdown.py`](examples/05_markdown.py) for an example.
### Positional arguments
The default click behaviour is to only show positional arguments in the top usage string,
and not in the list below with the options.
If you prefer, you can tell rich-click to show arguments with `SHOW_ARGUMENTS`.
By default, they will get their own panel but you can tell rich-click to bundle them together with `GROUP_ARGUMENTS_OPTIONS`:
```python
click.rich_click.SHOW_ARGUMENTS = True
click.rich_click.GROUP_ARGUMENTS_OPTIONS = True
```

> See [`examples/06_arguments.py`](examples/06_arguments.py) for an example.
### Metavars and option choices
Metavars are click's way of showing expected input types.
For example, if you have an option that must be an integer, the metavar is `INTEGER`.
If you have a choice, the metavar is a list of the possible values.
By default, rich-click shows metavars in their own column.
However, if you have a long list of choices, this column can be quite wide and result in a lot of white space:

It may look better to show metavars appended to the help text, instead of in their own column.
For this, use the following:
```python
click.rich_click.SHOW_METAVARS_COLUMN = False
click.rich_click.APPEND_METAVARS_HELP = True
```

> See [`examples/08_metavars.py`](examples/08_metavars.py) for an example.
### Error messages
By default, rich-click gives some nice formatting to error messages:

You can customise the _Try 'command --help' for help._ message with `ERRORS_SUGGESTION`
using rich-click though, and add some text after the error with `ERRORS_EPILOGUE`.
For example, from [`examples/07_custom_errors.py`](examples/07_custom_errors.py):
```python
click.rich_click.STYLE_ERRORS_SUGGESTION = "magenta italic"
click.rich_click.ERRORS_SUGGESTION = "Try running the '--help' flag for more information."
click.rich_click.ERRORS_EPILOGUE = "To find out more, visit [link=https://mytool.com]https://mytool.com[/link]"
```

> See [`examples/07_custom_errors.py`](examples/07_custom_errors.py) for an example.
### Help width
The default behaviour of rich-click is to use the full width of the terminal for output.
However, if you've carefully crafted your help texts for the default narrow click output, you may find that you now have a lot of whitespace at the side of the panels.
To limit the maximum width of the help output, set `MAX_WIDTH` in characters, as follows:
```python
click.rich_click.MAX_WIDTH = 100
```
### Styling
Most aspects of rich-click formatting can be customised, from colours to alignment.
For example, to print the option flags in a different colour, you can use:
```python
click.rich_click.STYLE_OPTION = "magenta"
```
To add a blank line between rows of options, you can use:
```python
click.rich_click.STYLE_OPTIONS_TABLE_LEADING = 1
click.rich_click.STYLE_OPTIONS_TABLE_BOX = "SIMPLE"
```
You can make some really ~horrible~ _colourful_ solutions using these styles if you wish:

> See [`examples/10_table_styles.py`](examples/10_table_styles.py) for an example.
See the [_Configuration options_](#configuration-options) section below for the full list of available options.
## Groups and sorting
`rich-click` gives functionality to list options and subcommands in groups, printed as separate panels.
It accepts a list of options / commands which means you can also choose a custom sorting order.
- For options (flags), set `click.rich_click.OPTION_GROUPS`
- For subcommands (groups), set `click.rich_click.COMMAND_GROUPS`

> See [`examples/03_groups_sorting.py`](examples/03_groups_sorting.py) for a full example.
### Options
To group option flags into two sections with custom names, see the following example:
```python
click.rich_click.OPTION_GROUPS = {
"mytool": [
{
"name": "Simple options",
"options": ["--name", "--description", "--version", "--help"],
},
{
"name": "Advanced options",
"options": ["--force", "--yes", "--delete"],
},
]
}
```
If you omit `name` it will use `Commands` (can be configured with `OPTIONS_PANEL_TITLE`).
### Commands
Here we create two groups of commands for the base command of `mytool`.
Any subcommands not listed will automatically be printed in a panel at the end labelled "Commands" as usual.
```python
click.rich_click.COMMAND_GROUPS = {
"mytool": [
{
"name": "Commands for uploading",
"commands": ["sync", "upload"],
},
{
"name": "Download data",
"commands": ["get", "fetch", "download"],
},
]
}
```
If you omit `name` it will use `Commands` (can be configured with `COMMANDS_PANEL_TITLE`).
### Multiple commands
If you use multiple nested subcommands, you can specify their commands using the top-level dictionary keys:
```python
click.rich_click.COMMAND_GROUPS = {
"mytool": [{"commands": ["sync", "auth"]}],
"mytool sync": [
{
"name": "Commands for uploading",
"commands": ["sync", "upload"],
},
{
"name": "Download data",
"commands": ["get", "fetch", "download"],
},
],
"mytool auth":[{"commands": ["login", "logout"]}],
}
```
### Table styling
Typically you would style the option / command tables using the global config options.
However, if you wish you may style tables on a per-group basis using the `table_styles` key:
```python
click.rich_click.COMMAND_GROUPS = {
"mytool": [
{
"commands": ["sync", "auth"],
"table_styles": {
"show_lines": True,
"row_styles": ["magenta", "yellow", "cyan", "green"],
"border_style": "red",
"box": "DOUBLE",
},
},
],
}
```
The available keys are: `show_lines`, `leading`, `box`, `border_style`, `row_styles`, `pad_edge`, `padding`.
## Configuration options
Here is the full list of config options:
```python
# Default styles
STYLE_OPTION = "bold cyan"
STYLE_ARGUMENT = "bold cyan"
STYLE_SWITCH = "bold green"
STYLE_METAVAR = "bold yellow"
STYLE_METAVAR_APPEND = "dim yellow"
STYLE_METAVAR_SEPARATOR = "dim"
STYLE_HEADER_TEXT = ""
STYLE_FOOTER_TEXT = ""
STYLE_USAGE = "yellow"
STYLE_USAGE_COMMAND = "bold"
STYLE_DEPRECATED = "red"
STYLE_HELPTEXT_FIRST_LINE = ""
STYLE_HELPTEXT = "dim"
STYLE_OPTION_HELP = ""
STYLE_OPTION_DEFAULT = "dim"
STYLE_OPTION_ENVVAR = "dim yellow"
STYLE_REQUIRED_SHORT = "red"
STYLE_REQUIRED_LONG = "dim red"
STYLE_OPTIONS_PANEL_BORDER = "dim"
ALIGN_OPTIONS_PANEL = "left"
STYLE_OPTIONS_TABLE_SHOW_LINES = False
STYLE_OPTIONS_TABLE_LEADING = 0
STYLE_OPTIONS_TABLE_PAD_EDGE = False
STYLE_OPTIONS_TABLE_PADDING = (0, 1)
STYLE_OPTIONS_TABLE_BOX = ""
STYLE_OPTIONS_TABLE_ROW_STYLES = None
STYLE_OPTIONS_TABLE_BORDER_STYLE = None
STYLE_COMMANDS_PANEL_BORDER = "dim"
ALIGN_COMMANDS_PANEL = "left"
STYLE_COMMANDS_TABLE_SHOW_LINES = False
STYLE_COMMANDS_TABLE_LEADING = 0
STYLE_COMMANDS_TABLE_PAD_EDGE = False
STYLE_COMMANDS_TABLE_PADDING = (0, 1)
STYLE_COMMANDS_TABLE_BOX = ""
STYLE_COMMANDS_TABLE_ROW_STYLES = None
STYLE_COMMANDS_TABLE_BORDER_STYLE = None
STYLE_ERRORS_PANEL_BORDER = "red"
ALIGN_ERRORS_PANEL = "left"
STYLE_ERRORS_SUGGESTION = "dim"
STYLE_ABORTED = "red"
MAX_WIDTH = None # Set to an int to limit to that many characters
COLOR_SYSTEM = "auto" # Set to None to disable colors
# Fixed strings
HEADER_TEXT = None
FOOTER_TEXT = None
DEPRECATED_STRING = "(Deprecated) "
DEFAULT_STRING = "[default: {}]"
ENVVAR_STRING = "[env var: {}]"
REQUIRED_SHORT_STRING = "*"
REQUIRED_LONG_STRING = "[required]"
RANGE_STRING = " [{}]"
APPEND_METAVARS_HELP_STRING = "({})"
ARGUMENTS_PANEL_TITLE = "Arguments"
OPTIONS_PANEL_TITLE = "Options"
COMMANDS_PANEL_TITLE = "Commands"
ERRORS_PANEL_TITLE = "Error"
ERRORS_SUGGESTION = None # Default: Try 'cmd -h' for help. Set to False to disable.
ERRORS_EPILOGUE = None
ABORTED_TEXT = "Aborted."
# Behaviours
SHOW_ARGUMENTS = False # Show positional arguments
SHOW_METAVARS_COLUMN = True # Show a column with the option metavar (eg. INTEGER)
APPEND_METAVARS_HELP = False # Append metavar (eg. [TEXT]) after the help text
GROUP_ARGUMENTS_OPTIONS = False # Show arguments with options instead of in own panel
USE_MARKDOWN = False # Parse help strings as markdown
USE_MARKDOWN_EMOJI = True # Parse emoji codes in markdown :smile:
USE_RICH_MARKUP = False # Parse help strings for rich markup (eg. [red]my text[/])
COMMAND_GROUPS = {} # Define sorted groups of panels to display subcommands
OPTION_GROUPS = {} # Define sorted groups of panels to display options and arguments
USE_CLICK_SHORT_HELP = False # Use click's default function to truncate help text
```
## Contributing
Contributions and suggestions for new features are welcome, as are bug reports!
Please create a new [issue](https://github.com/ewels/rich-click/issues)
or better still, dive right in with a pull-request.
### Local setup
1. Create a new venv with a python3.7+ interpreter using `python3 -m venv venv`
2. Activate the venv with `source venv/bin/activate`
3. Install our the package as an editable including all dev dependencies with `pip3 install -e ."[dev]"`
4. Install pre-commit with `pre-commit install`
#### Pre-commit
Our pre-commit hooks contain the following hooks:
- [Prettier](https://prettier.io/): formats our markdown and yaml files nicely.
- no relative imports: prevents you from using relative imports.
- [iSort](https://pycqa.github.io/isort/): will automatically sort the imports alphabetically.
- [black](https://black.readthedocs.io/): will automatically format your code to be according to standardized python format.
- [flake8](https://flake8.pycqa.org/): will do linting checks to make sure all your code is correctly styled and used.
- [mypy](http://mypy-lang.org/): static type checker which verifies you are not using objects incorrectly.
As mentioned, some of these tools automatically fix your code while other only highlight potential issues.
Sometimes it will be enough to try to commit a second time and it will pass, while other times it may require
manual changes to your code.
In rare cases it may be difficult or undesirable to change to code to pass the linting rules.
If this happens, it's ok to add a flake8 `# noqa` or mypy `# type: ignore` comment to skip that line.
For details of how to do this, please see the [flake8 docs](https://flake8.pycqa.org/en/3.1.1/user/ignoring-errors.html#in-line-ignoring-errors)
and [mypy docs](https://mypy.readthedocs.io/en/stable/common_issues.html#spurious-errors-and-locally-silencing-the-checker).
## Credits
This package was written by Phil Ewels ([@ewels](http://github.com/ewels/)),
based on initial code by Will McGugan ([@willmcgugan](https://github.com/willmcgugan)).
Furthermore, these contributors helped make the package what it is today:
- [@harens](http://github.com/harens/)
- [@fridex](http://github.com/fridex/)
- [@pawamoy](http://github.com/pawamoy/)
- [@jorrick](http://github.com/harens/)
rich-click-1.6.0/docs/ 0000775 0000000 0000000 00000000000 14343327243 0014463 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/docs/images/ 0000775 0000000 0000000 00000000000 14343327243 0015730 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/docs/images/arguments.svg 0000664 0000000 0000000 00000037455 14343327243 0020474 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/command_groups.svg 0000664 0000000 0000000 00000055555 14343327243 0021505 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/custom_error.svg 0000664 0000000 0000000 00000022137 14343327243 0021201 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/error.svg 0000664 0000000 0000000 00000022071 14343327243 0017604 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/markdown.svg 0000664 0000000 0000000 00000057722 14343327243 0020310 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/metavars_appended.svg 0000664 0000000 0000000 00000035262 14343327243 0022143 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/metavars_default.svg 0000664 0000000 0000000 00000060105 14343327243 0022001 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/rich_markup.svg 0000664 0000000 0000000 00000037521 14343327243 0020765 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/docs/images/style_tables.svg 0000664 0000000 0000000 00000166571 14343327243 0021163 0 ustar 00root root 0000000 0000000
rich-click-1.6.0/examples/ 0000775 0000000 0000000 00000000000 14343327243 0015351 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/examples/01_simple.py 0000664 0000000 0000000 00000003145 14343327243 0017517 0 ustar 00root root 0000000 0000000 import rich_click as click
@click.group()
@click.option(
"--debug/--no-debug",
"-d/-n",
default=False,
help="""Enable debug mode.
Newlines are removed by default.
Double newlines are preserved.""",
)
def cli(debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
@cli.command()
@click.option(
"--type",
required=True,
default="files",
show_default=True,
help="Type of file to sync",
)
@click.option("--all", is_flag=True)
def sync(type, all):
"""Synchronise all your files between two places.
Example command that doesn't do much except print to the terminal."""
print("Syncing")
@cli.command(short_help="Optionally use short-help for the group help text")
@click.option("--all", is_flag=True, help="Get everything")
def download(all):
"""
Pretend to download some files from
somewhere. Multi-line help strings are unwrapped
until you use a double newline.
Only the first paragraph is used in group help texts.
Don't forget you can opt-in to rich and markdown formatting!
\b
Click escape markers should still work.
* So you
* Can keep
* Your newlines
And this is a paragraph
that will be rewrapped again.
\f
Also if you want to write function help text that won't
be rendered to the terminal.
"""
print("Downloading")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/02_declarative.py 0000664 0000000 0000000 00000001150 14343327243 0020504 0 ustar 00root root 0000000 0000000 import click
from rich_click import RichCommand, RichGroup
@click.group(cls=RichGroup)
@click.option("--debug/--no-debug", default=False)
def cli(debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
click.echo(f"Debug mode is {'on' if debug else 'off'}")
@cli.command(cls=RichCommand)
def sync():
"""Synchronise all your files between two places."""
click.echo("Syncing")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/03_groups_sorting.py 0000664 0000000 0000000 00000004770 14343327243 0021321 0 ustar 00root root 0000000 0000000 import rich_click as click
click.rich_click.OPTION_GROUPS = {
"03_groups_sorting.py": [
{
"name": "Basic usage",
"options": ["--type", "--output"],
},
{
"name": "Advanced options",
"options": ["--help", "--version", "--debug"],
# You can also set table styles at group-level instead of using globals if you want
"table_styles": {
"row_styles": ["bold", "yellow", "cyan"],
},
},
],
"03_groups_sorting.py sync": [
{
"name": "Inputs and outputs",
"options": ["--input", "--output"],
},
{
"name": "Advanced usage",
"options": ["--overwrite", "--all", "--help"],
},
],
}
click.rich_click.COMMAND_GROUPS = {
"03_groups_sorting.py": [
{
"name": "Main usage",
"commands": ["sync", "download"],
},
{
"name": "Configuration",
"commands": ["config", "auth"],
},
]
}
@click.group(context_settings=dict(help_option_names=["-h", "--help"]))
@click.option(
"--type",
default="files",
show_default=True,
required=True,
help="Type of file to sync",
)
@click.option(
"--debug/--no-debug",
"-d/-n",
default=False,
show_default=True,
help="Show the debug log messages",
)
@click.version_option("1.23", prog_name="mytool")
def cli(type, debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
@cli.command()
@click.option("--input", "-i", required=True, help="Input path")
@click.option("--output", "-o", help="Output path")
@click.option("--all", is_flag=True, help="Sync all the things?")
@click.option("--overwrite", is_flag=True, help="Overwrite local files")
def sync(input, output, all, overwrite):
"""Synchronise all your files between two places."""
print("Syncing")
@cli.command()
@click.option("--all", is_flag=True, help="Get everything")
def download(all):
"""Pretend to download some files from somewhere."""
print("Downloading")
@cli.command()
def auth():
"""Authenticate the app."""
print("Downloading")
@cli.command()
def config():
"""Set up the configuration."""
print("Downloading")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/04_rich_markup.py 0000664 0000000 0000000 00000001670 14343327243 0020536 0 ustar 00root root 0000000 0000000 import rich_click as click
# Use Rich markup
click.rich_click.USE_RICH_MARKUP = True
@click.command()
@click.option(
"--input",
type=click.Path(),
help="Input [magenta bold]file[/]. [dim]\[default: a custom default][/]",
)
@click.option(
"--type",
default="files",
show_default=True,
help="Type of file to sync",
)
@click.option("--all", is_flag=True, help="Sync all the things?")
@click.option("--debug", is_flag=True, help="Enable :point_right: [yellow]debug mode[/] :point_left:")
def cli(input, type, all, debug):
"""
My amazing tool does [black on blue] all the things [/].
This is a [u]minimal example[/] based on documentation
from the [link=https://click.palletsprojects.com/]'click' package[/].
[i]You can try using --help at the top level and also for
specific group subcommands.[/]
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/05_markdown.py 0000664 0000000 0000000 00000001637 14343327243 0020060 0 ustar 00root root 0000000 0000000 import rich_click as click
# Use Markdown (bit of a ridiculous example!)
click.rich_click.USE_MARKDOWN = True
@click.command()
@click.option(
"--input",
type=click.Path(),
help="Input **file**. _[default: a custom default]_",
)
@click.option(
"--type",
default="files",
show_default=True,
help="Type of file to sync",
)
@click.option("--all", is_flag=True, help="Sync\n 1. all\n 2. the\n 3. things?")
@click.option("--debug", is_flag=True, help="# Enable `debug mode`")
def cli(input, type, all, debug):
"""
My amazing tool does _**all the things**_.
This is a `minimal example` based on documentation from the [_click_ package](https://click.palletsprojects.com/).
> Remember:
> - You can try using --help at the top level
> - Also for specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/06_arguments.py 0000664 0000000 0000000 00000001602 14343327243 0020234 0 ustar 00root root 0000000 0000000 import rich_click as click
# Show the positional arguments
click.rich_click.SHOW_ARGUMENTS = True
# Uncomment this line to group the arguments together with the options
# click.rich_click.GROUP_ARGUMENTS_OPTIONS = True
@click.command()
@click.argument("input", type=click.Path(), required=True)
@click.option(
"--type",
default="files",
show_default=True,
help="Type of file to sync",
)
@click.option("--all", is_flag=True, help="Sync all the things?")
@click.option("--debug", is_flag=True, help="Enable debug mode")
def cli(input, type, all, debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/07_custom_errors.py 0000664 0000000 0000000 00000001765 14343327243 0021150 0 ustar 00root root 0000000 0000000 import rich_click as click
# Show custom error messages
click.rich_click.STYLE_ERRORS_SUGGESTION = "magenta italic"
click.rich_click.ERRORS_SUGGESTION = "Try running the '--help' flag for more information."
click.rich_click.ERRORS_EPILOGUE = "To find out more, visit [link=https://mytool.com]https://mytool.com[/link]"
@click.command()
@click.argument("input", type=click.Path(), required=True)
@click.option(
"--type",
default="files",
show_default=True,
help="Type of file to sync",
)
@click.option("--all", is_flag=True, help="Sync all the things?")
@click.option("--debug", is_flag=True, default=False, help="Enable debug mode")
def cli(input, type, all, debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/08_metavars.py 0000664 0000000 0000000 00000002602 14343327243 0020054 0 ustar 00root root 0000000 0000000 import rich_click as click
click.rich_click.SHOW_METAVARS_COLUMN = False
click.rich_click.APPEND_METAVARS_HELP = True
@click.command()
@click.option("--debug", is_flag=True, help="Enable debug mode.")
@click.option(
"--number",
type=click.Choice(
[
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
"twenty-one",
"twenty-two",
"twenty-three",
"twenty-four",
"twenty-five",
"twenty-six",
"twenty-seven",
"twenty-eight",
"twenty-nine",
"thirty",
]
),
show_default=True,
help="This click choice has loads of options.",
)
def cli(debug, number):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/08_metavars_default.py 0000664 0000000 0000000 00000002446 14343327243 0021566 0 ustar 00root root 0000000 0000000 import rich_click as click
@click.command()
@click.option("--debug", is_flag=True, help="Enable debug mode.")
@click.option(
"--number",
type=click.Choice(
[
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
"twenty-one",
"twenty-two",
"twenty-three",
"twenty-four",
"twenty-five",
"twenty-six",
"twenty-seven",
"twenty-eight",
"twenty-nine",
"thirty",
]
),
show_default=True,
help="This click choice has loads of options.",
)
def cli(debug, number):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
if __name__ == "__main__":
cli()
rich-click-1.6.0/examples/09_envvar.py 0000664 0000000 0000000 00000001700 14343327243 0017532 0 ustar 00root root 0000000 0000000 import rich_click as click
# import click
# Example test usage:
# GREETER_DEBUG=1 GREETER_GREET_USERNAME="test" EMAIL_ADDRESS="foo@bar.com" python examples/09_envvar.py greet
@click.group()
@click.option("--debug/--no-debug")
def cli(debug):
click.echo(f"Debug mode is {'on' if debug else 'off'}")
@cli.command()
@click.option("--username", help="This can be set via env var GREETER_GREET_USERNAME", show_envvar=True)
@click.option(
"--nickname",
envvar="NICKNAME",
show_envvar=True,
show_default=True,
help="This can be set via env var NICKNAME",
)
@click.option(
"--email",
envvar=["EMAIL", "EMAIL_ADDRESS"],
show_envvar=True,
default="foo@bar.com",
show_default=True,
help="This can be set via env var EMAIL or EMAIL_ADDRESS",
)
def greet(username, nickname, email):
click.echo(f"Hello {username} ({nickname}) with email {email}!")
if __name__ == "__main__":
cli(auto_envvar_prefix="GREETER")
rich-click-1.6.0/examples/10_table_styles.py 0000664 0000000 0000000 00000013013 14343327243 0020713 0 ustar 00root root 0000000 0000000 import rich_click as click
click.rich_click.STYLE_OPTIONS_TABLE_LEADING = 1
click.rich_click.STYLE_OPTIONS_TABLE_BOX = "SIMPLE"
click.rich_click.STYLE_OPTIONS_TABLE_ROW_STYLES = ["bold", ""]
click.rich_click.STYLE_COMMANDS_TABLE_SHOW_LINES = True
click.rich_click.STYLE_COMMANDS_TABLE_PAD_EDGE = True
click.rich_click.STYLE_COMMANDS_TABLE_BOX = "DOUBLE"
click.rich_click.STYLE_COMMANDS_TABLE_BORDER_STYLE = "red"
click.rich_click.STYLE_COMMANDS_TABLE_ROW_STYLES = ["magenta", "yellow", "cyan", "green"]
@click.group()
@click.option(
"--type",
default="files",
help="""
Type of file to sync.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed sed mauris euismod, semper leo quis, sodales augue.
Donec posuere nulla quis egestas ornare.
Nam efficitur ex quis diam tempus, nec euismod diam consectetur.
Etiam vitae nisi at odio hendrerit dictum in at dui.
Aliquam nulla lacus, pellentesque id ultricies sit amet, mollis nec tellus.
Aenean arcu justo, pellentesque viverra justo eget, tempus tincidunt lectus.
Maecenas porttitor risus vitae libero dapibus ullamcorper.
Cras faucibus euismod erat in porta.
Phasellus cursus gravida ante vel aliquet.
In accumsan enim nec ullamcorper gravida.
Donec malesuada dui ac metus tristique cursus.
Sed gravida condimentum fermentum.
Ut sit amet nulla commodo, iaculis tellus vitae, accumsan enim.
Curabitur mollis semper velit a suscipit.
""",
)
@click.option(
"--debug/--no-debug",
"-d/-n",
default=False,
help="""
Show the debug log messages.
Suspendisse dictum hendrerit turpis eu rutrum.
Vivamus magna ex, elementum sit amet sapien laoreet, tempor consequat eros.
Morbi semper feugiat nisi eget sodales.
Pellentesque et turpis erat.
Donec ac aliquam risus.
Nam leo tellus, rutrum et scelerisque vitae, ultrices sed metus.
Ut sollicitudin convallis turpis, sit amet sollicitudin felis semper feugiat.
In sapien dui, aliquam eget dui quis, auctor maximus nibh.
Suspendisse maximus sem arcu.
Pellentesque sit amet semper est.
Cras pulvinar ut tellus a semper.
In facilisis tellus odio, non porta nisl accumsan nec.
Pellentesque sollicitudin quam ac felis congue, ac congue enim tempor.
""",
)
@click.version_option("1.23", prog_name="mytool")
def cli(type, debug):
"""
My amazing tool does all the things.
This is a minimal example based on documentation
from the 'click' package.
You can try using --help at the top level and also for
specific group subcommands.
"""
print(f"Debug mode is {'on' if debug else 'off'}")
@cli.command()
@click.option("--input", "-i", required=True, help="Input path")
@click.option("--output", "-o", help="Output path")
@click.option("--all", is_flag=True, help="Sync all the things?")
@click.option("--overwrite", is_flag=True, help="Overwrite local files")
def sync(input, output, all, overwrite):
"""
Synchronise all your files between two places.
Curabitur congue eget lorem in lacinia.
Praesent tempus nunc nec nulla dignissim, et lacinia ipsum accumsan.
Duis sodales, sapien at fermentum condimentum, diam metus porttitor lacus, nec gravida mi diam eget ligula.
Pellentesque elementum at justo a luctus.
Mauris a interdum odio.
Maecenas in consectetur velit.
Ut tristique congue felis at tempus.
Donec pulvinar tortor ut odio posuere imperdiet.
Fusce lacinia iaculis diam in scelerisque.
Pellentesque in lorem est.
Nulla efficitur luctus lacus, auctor auctor dui hendrerit a.
Ut nec iaculis dolor.
Morbi metus lectus, aliquet et sapien nec, congue euismod lorem.
Pellentesque tristique tempus augue at convallis.
"""
print("Syncing")
@cli.command()
@click.option("--all", is_flag=True, help="Get everything")
def download(all):
"""
Pretend to download some files from somewhere.
Integer bibendum libero nunc, sed aliquet ex tincidunt vel.
Duis vitae sem vel odio luctus suscipit nec vitae enim.
Curabitur vel lectus nec quam maximus dapibus.
Phasellus eros velit, maximus non hendrerit nec, tempor fringilla urna.
Vivamus vel nibh quis sapien consectetur fermentum.
Curabitur at ultrices quam, vel molestie justo.
Nunc lobortis orci vel nibh sagittis pretium.
Morbi rhoncus sapien luctus, ultrices urna vel, convallis tortor.
"""
print("Downloading")
@cli.command()
def auth():
"""
Authenticate the app.
Duis lacus nibh, feugiat a nibh a, commodo dictum libero.
Ut ac nulla tincidunt, bibendum nisi vitae, sodales ex.
Vestibulum efficitur, lectus quis venenatis porta, dolor elit varius mauris, consequat interdum lectus est quis mi.
Vestibulum imperdiet sed dolor eget semper.
Cras ut mauris ac libero hendrerit congue.
Vivamus pretium nunc turpis, eget imperdiet sapien tempor auctor.
Phasellus risus nisi, laoreet in posuere sit amet, sodales non diam.
Aliquam non malesuada urna, a faucibus risus.
"""
print("Downloading")
@cli.command()
def config():
"""
Set up the configuration.
Sed accumsan ornare odio dictum aliquam.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Curabitur in pellentesque mauris.
Nulla mollis dui finibus, dictum neque id, suscipit nisl.
Nunc mauris ex, laoreet nec tincidunt ut, pellentesque ut tortor.
Mauris fermentum diam at porttitor tempor.
Aliquam euismod nisi massa, nec placerat ante euismod quis.
"""
print("Downloading")
if __name__ == "__main__":
cli()
rich-click-1.6.0/pyproject.toml 0000664 0000000 0000000 00000000653 14343327243 0016453 0 ustar 00root root 0000000 0000000 [tool.black]
line-length=120
target-version=['py37']
[tool.isort]
line_length = 120
multi_line_output = 3
force_alphabetical_sort_within_sections = "True"
force_sort_within_sections = "False"
known_richclick = ["rich_click"]
sections=["FUTURE", "STDLIB", "THIRDPARTY", "FIRSTPARTY", "LOCALFOLDER", "RICHCLICK"]
profile = "black"
[tool.mypy]
python_version = "3.7"
ignore_missing_imports = "True"
scripts_are_modules = "True"
rich-click-1.6.0/setup.cfg 0000664 0000000 0000000 00000002125 14343327243 0015354 0 ustar 00root root 0000000 0000000 [metadata]
name = rich-click
version = attr: rich_click.__version__
url = https://github.com/ewels/rich-click
project_urls =
Documentation = https://github.com/ewels/rich-click
Source Code = https://github.com/ewels/rich-click
Issue Tracker = https://github.com/ewels/rich-click/issues/
license = MIT
license_files = LICENSE
author = Phil Ewels
author_email = phil@ewels.co.uk
maintainer = Phil Ewels
maintainer_email = phil@ewels.co.uk
description = Format click help output nicely with rich
long_description = file: README.md
long_description_content_type = text/markdown
classifiers =
Development Status :: 3 - Alpha
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python
[options]
packages = find:
package_dir =
=src
include_package_data = True
python_requires = >= 3.7
[options.entry_points]
console_scripts =
rich-click = rich_click.cli:main
[options.packages.find]
where = src
[options.package_data]
* = py.typed
# Dependencies are in setup.py for GitHub's dependency graph.
rich-click-1.6.0/setup.py 0000664 0000000 0000000 00000000340 14343327243 0015242 0 ustar 00root root 0000000 0000000 from setuptools import setup
setup(
install_requires=[
"click>=7",
"rich>=10.7.0",
"importlib-metadata; python_version < '3.8'",
],
extras_require={
"dev": "pre-commit",
},
)
rich-click-1.6.0/src/ 0000775 0000000 0000000 00000000000 14343327243 0014322 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/src/rich_click/ 0000775 0000000 0000000 00000000000 14343327243 0016414 5 ustar 00root root 0000000 0000000 rich-click-1.6.0/src/rich_click/__init__.py 0000664 0000000 0000000 00000003150 14343327243 0020524 0 ustar 00root root 0000000 0000000 """
rich-click is a minimal Python module to combine the efforts of the excellent packages 'rich' and 'click'.
The intention is to provide attractive help output from click, formatted with rich, with minimal
customisation required.
"""
__version__ = "1.6.0"
from typing import TYPE_CHECKING
from click import * # noqa: F401, F403
from click import command as click_command
from click import group as click_group
from . import rich_click # noqa: F401
from rich_click.rich_command import RichCommand
from rich_click.rich_group import RichGroup
# MyPy does not like star imports. Therefore when we are type checking, we import each individual module
# from click here. This way MyPy will recognize the import and not throw any errors. Furthermore, because of
# the TYPE_CHECKING check, it does not influence the start routine at all.
if TYPE_CHECKING:
from click import argument, Choice, option, Path, version_option # noqa: F401
__all__ = [
"argument",
"Choice",
"option",
"Path",
"version_option",
"group",
"command",
]
def group(*args, cls=RichGroup, **kwargs):
"""
Group decorator function.
Defines the group() function so that it uses the RichGroup class by default.
"""
return click_group(*args, cls=cls, **kwargs)
def command(name=None, cls=RichCommand, **attrs):
"""
Command decorator function.
Defines the command() function so that it uses the RichCommand class by default.
"""
if callable(name) and cls:
return click_command(cls=cls, **attrs)(name)
return click_command(name, cls=cls, **attrs)
rich-click-1.6.0/src/rich_click/__main__.py 0000664 0000000 0000000 00000000640 14343327243 0020506 0 ustar 00root root 0000000 0000000 """
Entry-point module for the command line prefixer, called in case you use `python -m rich_click`.
Why does this file exist, and why `__main__`? For more info, read:
- https://www.python.org/dev/peps/pep-0338/
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
from rich_click.cli import main
if __name__ == "__main__":
# main will run a Click command which will either exit or raise
main()
rich-click-1.6.0/src/rich_click/cli.py 0000664 0000000 0000000 00000010300 14343327243 0017527 0 ustar 00root root 0000000 0000000 """The command line interface."""
import sys
from importlib import import_module
from textwrap import dedent
from typing import Any, List, Optional
try:
from importlib.metadata import entry_points
except ImportError:
# Support Python <3.8
from importlib_metadata import entry_points
import click
from rich.console import Console
from rich.padding import Padding
from rich.panel import Panel
from rich.text import Text
from rich_click import command as rich_command
from rich_click import group as rich_group
from rich_click import RichCommand, RichGroup
from rich_click.rich_click import (
ALIGN_ERRORS_PANEL,
ERRORS_PANEL_TITLE,
STYLE_ERRORS_PANEL_BORDER,
STYLE_HELPTEXT,
STYLE_HELPTEXT_FIRST_LINE,
STYLE_USAGE,
STYLE_USAGE_COMMAND,
)
console = Console()
def _print_usage() -> None:
console.print(
Padding(
Text.from_markup(f"[{STYLE_USAGE}]Usage[/]: rich-click [SCRIPT | MODULE:FUNCTION] [-- SCRIPT_ARGS...]"),
1,
),
style=STYLE_USAGE_COMMAND,
)
def _print_help() -> None:
help_paragraphs = dedent(main.__doc__ or "").split("\n\n")
help_paragraphs = [x.replace("\n", " ").strip() for x in help_paragraphs]
console.print(
Padding(
Text.from_markup(help_paragraphs[0].strip()),
(0, 1),
),
style=STYLE_HELPTEXT_FIRST_LINE,
)
console.print(
Padding(
Text.from_markup("\n\n".join(help_paragraphs[1:]).strip()),
(0, 1),
),
style=STYLE_HELPTEXT,
)
def patch() -> None:
"""Patch Click internals to use Rich-Click types."""
click.group = rich_group
click.command = rich_command
click.Group = RichGroup
click.Command = RichCommand
def main(args: Optional[List[str]] = None) -> Any:
"""
The [link=https://github.com/ewels/rich-click]rich-click[/] CLI provides attractive help output from any
tool using [link=https://click.palletsprojects.com/]click[/], formatted with
[link=https://github.com/Textualize/rich]rich[/].
The rich-click command line tool can be prepended before any Python package
using native click to provide attractive richified click help output.
For example, if you have a package called [blue]my_package[/] that uses click,
you can run:
[blue] rich-click my_package --help [/]
It only works if the package is using vanilla click without customised [cyan]group()[/]
or [cyan]command()[/] classes.
If in doubt, please suggest to the authors that they use rich_click within their
tool natively - this will always give a better experience.
""" # noqa: D400, D401
args = args or sys.argv[1:]
if not args or args == ["--help"]:
# Print usage if we got no args, or only --help
_print_usage()
_print_help()
sys.exit(0)
else:
script_name = args[0]
scripts = {script.name: script for script in entry_points().get("console_scripts")}
if script_name in scripts:
# a valid script was passed
script = scripts[script_name]
module_path, function_name = script.value.split(":", 1)
prog = script_name
elif ":" in script_name:
# the path to a function was passed
module_path, function_name = args[0].split(":", 1)
prog = module_path.split(".", 1)[0]
else:
_print_usage()
console.print(
Panel(
Text.from_markup(f"No such script: [bold]{script_name}[/]"),
border_style=STYLE_ERRORS_PANEL_BORDER,
title=ERRORS_PANEL_TITLE,
title_align=ALIGN_ERRORS_PANEL,
)
)
console.print(
Padding(
"Please run [yellow bold]rich-click --help[/] for usage information.",
(0, 1),
),
style="dim",
)
sys.exit(1)
if len(args) > 1:
if args[1] == "--":
del args[1]
sys.argv = [prog, *args[1:]]
# patch click before importing the program function
patch()
# import the program function
module = import_module(module_path)
function = getattr(module, function_name)
# simply run it: it should be patched as well
return function()
rich-click-1.6.0/src/rich_click/py.typed 0000664 0000000 0000000 00000000071 14343327243 0020111 0 ustar 00root root 0000000 0000000 # Marker file for PEP 561. rich-click uses inline types.
rich-click-1.6.0/src/rich_click/rich_click.py 0000664 0000000 0000000 00000061117 14343327243 0021066 0 ustar 00root root 0000000 0000000 import inspect
import re
from os import getenv
from typing import Dict, List, Optional, Union
import click
import rich.markdown
from rich import box
from rich.align import Align
from rich.columns import Columns
from rich.console import Console
from rich.emoji import Emoji
from rich.highlighter import RegexHighlighter
from rich.markdown import Markdown
from rich.padding import Padding
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich.theme import Theme
# Support rich <= 10.6.0
try:
from rich.console import group
except ImportError:
from rich.console import render_group as group
# Default styles
STYLE_OPTION = "bold cyan"
STYLE_ARGUMENT = "bold cyan"
STYLE_SWITCH = "bold green"
STYLE_METAVAR = "bold yellow"
STYLE_METAVAR_APPEND = "dim yellow"
STYLE_METAVAR_SEPARATOR = "dim"
STYLE_HEADER_TEXT = ""
STYLE_FOOTER_TEXT = ""
STYLE_USAGE = "yellow"
STYLE_USAGE_COMMAND = "bold"
STYLE_DEPRECATED = "red"
STYLE_HELPTEXT_FIRST_LINE = ""
STYLE_HELPTEXT = "dim"
STYLE_OPTION_HELP = ""
STYLE_OPTION_DEFAULT = "dim"
STYLE_OPTION_ENVVAR = "dim yellow"
STYLE_REQUIRED_SHORT = "red"
STYLE_REQUIRED_LONG = "dim red"
STYLE_OPTIONS_PANEL_BORDER = "dim"
ALIGN_OPTIONS_PANEL = "left"
STYLE_OPTIONS_TABLE_SHOW_LINES = False
STYLE_OPTIONS_TABLE_LEADING = 0
STYLE_OPTIONS_TABLE_PAD_EDGE = False
STYLE_OPTIONS_TABLE_PADDING = (0, 1)
STYLE_OPTIONS_TABLE_BOX = ""
STYLE_OPTIONS_TABLE_ROW_STYLES = None
STYLE_OPTIONS_TABLE_BORDER_STYLE = None
STYLE_COMMANDS_PANEL_BORDER = "dim"
ALIGN_COMMANDS_PANEL = "left"
STYLE_COMMANDS_TABLE_SHOW_LINES = False
STYLE_COMMANDS_TABLE_LEADING = 0
STYLE_COMMANDS_TABLE_PAD_EDGE = False
STYLE_COMMANDS_TABLE_PADDING = (0, 1)
STYLE_COMMANDS_TABLE_BOX = ""
STYLE_COMMANDS_TABLE_ROW_STYLES = None
STYLE_COMMANDS_TABLE_BORDER_STYLE = None
STYLE_ERRORS_PANEL_BORDER = "red"
ALIGN_ERRORS_PANEL = "left"
STYLE_ERRORS_SUGGESTION = "dim"
STYLE_ABORTED = "red"
MAX_WIDTH = int(getenv("TERMINAL_WIDTH")) if getenv("TERMINAL_WIDTH") else None # type: ignore
COLOR_SYSTEM = "auto" # Set to None to disable colors
FORCE_TERMINAL = True if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS") else None
# Fixed strings
HEADER_TEXT: Optional[str] = None
FOOTER_TEXT: Optional[str] = None
DEPRECATED_STRING = "(Deprecated) "
DEFAULT_STRING = "[default: {}]"
ENVVAR_STRING = "[env var: {}]"
REQUIRED_SHORT_STRING = "*"
REQUIRED_LONG_STRING = "[required]"
RANGE_STRING = " [{}]"
APPEND_METAVARS_HELP_STRING = "({})"
ARGUMENTS_PANEL_TITLE = "Arguments"
OPTIONS_PANEL_TITLE = "Options"
COMMANDS_PANEL_TITLE = "Commands"
ERRORS_PANEL_TITLE = "Error"
ERRORS_SUGGESTION: Optional[str] = None # Default: Try 'cmd -h' for help. Set to False to disable.
ERRORS_EPILOGUE: Optional[str] = None
ABORTED_TEXT = "Aborted."
# Behaviours
SHOW_ARGUMENTS = False # Show positional arguments
SHOW_METAVARS_COLUMN = True # Show a column with the option metavar (eg. INTEGER)
APPEND_METAVARS_HELP = False # Append metavar (eg. [TEXT]) after the help text
GROUP_ARGUMENTS_OPTIONS = False # Show arguments with options instead of in own panel
OPTION_ENVVAR_FIRST = False # Show env vars before option help text instead of avert
USE_MARKDOWN = False # Parse help strings as markdown
USE_MARKDOWN_EMOJI = True # Parse emoji codes in markdown :smile:
USE_RICH_MARKUP = False # Parse help strings for rich markup (eg. [red]my text[/])
# Define sorted groups of panels to display subcommands
COMMAND_GROUPS: Dict[str, List[Dict[str, Union[str, List[str]]]]] = {}
# Define sorted groups of panels to display options and arguments
OPTION_GROUPS: Dict[str, List[Dict[str, Union[str, List[str]]]]] = {}
USE_CLICK_SHORT_HELP = False # Use click's default function to truncate help text
# Rich regex highlighter
class OptionHighlighter(RegexHighlighter):
"""Highlights our special options."""
highlights = [
r"(^|\W)(?P\-\w+)(?![a-zA-Z0-9])",
r"(^|\W)(?P