Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
a committed Mar 1, 2024
1 parent 372897e commit b090435
Show file tree
Hide file tree
Showing 11 changed files with 252 additions and 35 deletions.
22 changes: 22 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# EditorConfig is awesome: https://EditorConfig.org

# this is the top-most EditorConfig file
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4

[*.{yml,json}]
indent_size = 2

[*.{md,markdown}]
# don't trim trailing spaces because markdown syntax allows that
trim_trailing_whitespace = false

[{makefile,Makefile,MAKEFILE}]
indent_style = tab
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
*.xsh text linguist-language=Python
myapp text linguist-language=Python
134 changes: 134 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
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/

# 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
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.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

# 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/

# xontrib is an implicit namespace package. DO NOT add an __init__.py file to this directory.
xontrib/__init__.py

# Copier
.copier-answers.yml

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) {% now 'local', '%Y' %}, {{ full_name }}

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.
36 changes: 19 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<p align="center">
Example of awesome cli app template for xonsh. Just fork it and add your commands.
Example of awesome CLI app template for xonsh. Just fork it and add your commands.
</p>

<p align="center">
Expand All @@ -10,10 +10,12 @@ If you like the idea of bar theme click ⭐ on the repo and <a href="https://twi
## Features

* Based on power and sugar from [click](https://click.palletsprojects.com).
* Setting up context and environment.
* Setting up context options and command arguments.
* Pip-installable as well as clone-and-run.
* Ability to grow your library.
* Ability to set up context and environment.
* Ability to set up context options and command arguments.
* Ability to use environment variables as replacement of options and arguments.
* Use `ctx.log` to different logging levels.
* Logging included.

## Usage

Expand All @@ -24,8 +26,8 @@ git clone https://github.com/anki-code/xonsh-awesome-cli-app
cd xonsh-awesome-cli-app
chmod +x myapp

./myapp
# Usage: myapp [OPTIONS] COMMAND [ARGS]...
./mycli
# Usage: mycli [OPTIONS] COMMAND [ARGS]...
#
# CLI management.
#
Expand All @@ -38,37 +40,37 @@ chmod +x myapp
# hello Say hello.
# context Show app context.

./myapp hello --help
# Usage: myapp hello [OPTIONS]
./mycli hello --help
# Usage: mycli hello [OPTIONS]
#
# Say hello.
#
# Options:
# --wait Command argument: wait before print.
# --help Show this message and exit.

./myapp hello
# Hello DefaultName
./mycli hello
# Hello Username

./myapp hello --wait
./mycli hello --wait
# Wait...
# Hello DefaultName
# Hello Username

./myapp --name Mike hello --wait
./mycli --name Mike hello --wait
# Wait...
# Hello Mike

$MYAPP_NAME = 'Alex'
./myapp hello
$MYCLI_NAME = 'Alex'
./mycli hello
# Hello Alex

./myapp context
./mycli context
# Environment:
# {'MYAPP_NAME': 'Alex'}
# Context:
# {'debug': False, 'log': <RootLogger root (INFO)>, 'name': 'Alex'}

./myapp --debug hello
./mycli --debug hello
# TRACE SUBPROC: (['echo', 'Hello', 'DefaultName'],)
# Hello DefaultName
# TRACE SUBPROC: (['echo', 'Here', 'is', 'debug', 'message', 'too', ''],)
Expand Down
7 changes: 7 additions & 0 deletions mycli
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env xonsh

# Fix https://github.com/xonsh/xonsh/issues/5291
__import__('sys').path.append('.')

from xonsh_awesome_cli_app.cli import cli
cli()
35 changes: 35 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python

import setuptools

try:
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
except (IOError, OSError):
long_description = ''

setuptools.setup(
name='xonsh-awesome-cli-app',
version='0.1.0',
license='BSD',
author='anki-code',
author_email='[email protected]',
description="Example of awesome CLI app template for xonsh.",
long_description=long_description,
long_description_content_type='text/markdown',
python_requires='>=3.6',
install_requires=['xonsh', 'click'],
scripts=['mycli'],
packages=setuptools.find_packages(),
package_data={'xonsh_awesome_cli_app': ['*.py', '*.xsh']},
platforms='any',
url='https://github.com/anki-code/xonsh-awesome-cli-app',
project_urls={
"Documentation": "https://github.com/anki-code/xonsh-awesome-cli-app/blob/master/README.md",
"Code": "https://github.com/anki-code/xonsh-awesome-cli-app",
"Issue tracker": "https://github.com/anki-code/xonsh-awesome-cli-app/issues",
},
classifiers=[
"License :: OSI Approved :: BSD License"
]
)
Empty file.
25 changes: 7 additions & 18 deletions myapp → xonsh_awesome_cli_app/cli.xsh
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,18 @@ xonsh-awesome-cli-app
"""

import os
import time
import click
import logging
import pprint
from pathlib import Path
from .lib.click import OrderCommands


# Set the prefix for environment variables. The app file name by default e.g. `./myapp.xsh` will be `MYAPP`.
# Usage: set `click.option(envvar)` and instead of passing `--name qwe` you can set `$MYAPP_NAME='qwe'`.
# Set the prefix for environment variables. The app file name by default e.g. `./mycli` will be `MYCLI`.
# Usage: set `click.option(envvar)` and instead of passing `--name qwe` you can set `$MYCLI_NAME='qwe'`.
_PFX = ''.join(e for e in Path(__file__).stem.upper() if e.isalnum())


class OrderCommands(click.Group):
"""Class to show `click` commands in declaration order."""
def list_commands(self, ctx: click.Context) -> list[str]:
return list(self.commands)


class CliCtx:
"""Class to prepare and store CLI context."""
def __init__(self, name, debug):
Expand All @@ -47,22 +41,17 @@ class CliCtx:


@click.group(cls=OrderCommands)
@click.option("--name", envvar=f'{_PFX}_NAME', default='DefaultName', help="Context option: name.")
@click.option("--name", envvar=f'{_PFX}_NAME', default='Username', help="Context option: name.")
@click.option("--debug", default=False, is_flag=True, envvar=f'{_PFX}_DEBUG', help="Context option: debug mode.")
@click.pass_context
def cli(ctx, name, debug):
"""
CLI management.
"""

# Check something and raise exception.
if False:
raise Exception('Exception!')
"""Xonsh CLI app."""

# Setting context object.
ctx.obj = CliCtx(name, debug)

# Setting up the environment variables.
$RAISE_SUBPROC_ERROR = True

if debug:
$XONSH_TRACE_SUBPROC = True
$XONSH_SHOW_TRACEBACK = True
Expand Down
Empty file.
6 changes: 6 additions & 0 deletions xonsh_awesome_cli_app/lib/click.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import click

class OrderCommands(click.Group):
"""Class to show `click` commands in declaration order."""
def list_commands(self, ctx: click.Context) -> list[str]:
return list(self.commands)

0 comments on commit b090435

Please sign in to comment.