### Environment Setup Commands
Source: https://github.com/pawamoy/duty/blob/main/CONTRIBUTING.md
Commands to set up the development environment for the duty project. This includes navigating to the project directory, running the setup script, and optionally installing uv if the initial setup fails.
```bash
cd duty
make setup
```
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
```
```bash
make run duty [ARGS...]
```
```bash
make help
```
--------------------------------
### Install duty using uv
Source: https://github.com/pawamoy/duty/blob/main/README.md
Installs the duty task runner using uv, a fast Python package installer and resolver. This is an alternative installation method for users who prefer uv.
```bash
uv tool install duty
```
--------------------------------
### Install duty using pip
Source: https://github.com/pawamoy/duty/blob/main/README.md
Installs the duty task runner using pip, the standard package installer for Python. This command fetches and installs the latest version of duty from the Python Package Index.
```bash
pip install duty
```
--------------------------------
### Duty CLI Usage: Passing Options
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates how to use global and local options with the Duty CLI. Examples cover overriding options like capture mode and applying different options to multiple duties.
```bash
# Override global options
duty --capture=none --strict play this-file.mp4
# Local options for a specific duty
duty play -Zc none this-file.mp4
# Different options for multiple duties
duty -cboth format check test -cnone
# Passing additional CLI flags to a duty
duty docs -- -vs -f mkdocs.yml
```
--------------------------------
### Bash Shell Completion Setup
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Commands to enable auto-completion for the duty command in Bash. It creates the necessary directory and saves the completion script.
```bash
completions_dir="${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions"
mkdir -p "${completions_dir}"
duty --completion > "${completions_dir}/duty"
```
--------------------------------
### List Available Duties via CLI
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to list all defined duties from the command line interface using the `-l` or `--list` option. Includes an example of the output format, listing duty names and their brief descriptions.
```Console
$ duty --list
changelog Update the changelog in-place with latest commits.
check Check it all!
check-api Check for API breaking changes.
check-dependencies Check for vulnerabilities in dependencies.
check-docs Check if the documentation builds correctly.
check-quality Check the code quality.
check-types Check that the code is correctly typed.
clean Delete temporary files.
cov Report coverage as text and HTML.
docs Serve the documentation (localhost:8000).
docs-deploy Deploy the documentation on GitHub pages.
format Run formatting tools on the code.
release Release a new Python package.
test Run the test suite.
```
--------------------------------
### Duty CLI Usage: Passing Parameters
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows command-line examples for passing parameters to Duty functions. This includes boolean conversion rules, keyword arguments, positional arguments, and variadic arguments.
```bash
# Passing a boolean parameter
duty docs serve=yes
# Passing a custom type parameter
duty shoot point=5,15
# Passing a parameter as positional argument
duty shoot 5,15
# Passing variadic positional arguments
duty shout herbert marvin
```
--------------------------------
### Duty Decorator with Parameters
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates how to define a Duty function that accepts typed parameters, which can be passed from the command line. The example shows how the 'serve' parameter is converted to a boolean.
```python
from duty import duty
@duty
def docs(ctx, serve: bool = False):
command = "serve" if serve else "build"
ctx.run(f"mkdocs {command}")
```
--------------------------------
### Defining duties with pre and post execution hooks
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates the use of `pre` and `post` decorator options to define duties that execute other duties before and after their main task. This is useful for setup (like cleaning) and teardown/reporting (like coverage).
```python
import duty
@duty
def clean(ctx):
ctx.run("rm -rf tests/tmp")
@duty
def coverage(ctx):
ctx.run("coverage combine", nofail=True)
ctx.run("coverage report", capture=False)
@duty(pre=[clean], post=[coverage])
def test(ctx):
ctx.run("pytest tests")
```
--------------------------------
### Define a task with duty
Source: https://github.com/pawamoy/duty/blob/main/README.md
Example of defining a task function using the duty decorator in Python. It shows how to import duty and use the context object (ctx) to run external commands with optional titles.
```python
from duty import duty
@duty
def docs(ctx):
ctx.run("mkdocs build", title="Building documentation")
```
--------------------------------
### Python Duty Task with TAP Format
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Example of how to use the 'tap' output format within a Python duty task by passing the 'fmt' argument to ctx.run().
```python
# in the ctx.run() call
@duty
def task1(ctx):
ctx.run("echo failed && false", fmt="tap")
# or as a default duty option
@duty(fmt="tap")
def task2(ctx):
ctx.run("echo failed && false")
ctx.run("echo failed && false")
```
--------------------------------
### Define Duty with Silent Option
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows an example of using the `silent=True` option with `ctx.run` to prevent printing the command's output, even if it fails.
```python
@duty
def clean(ctx):
ctx.run("find . -type d -name __pycache__ | xargs rm -rf", silent=True)
```
--------------------------------
### Duty with Option Overrides
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Explains how to override default Duty options (like `capture` or `nofail`) using global or local CLI options. The example shows overriding the `capture` option for a specific Duty execution.
```python
from duty import duty
@duty(capture="both")
def play(ctx, file):
ctx.run(f"play {file}", nofail=True)
```
--------------------------------
### Duty CLI Help for 'release' command
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Provides detailed API-like documentation for the 'release' duty command. It includes usage syntax, parameter descriptions (like `ctx`, `version`), and a comprehensive list of command-line options with their short and long forms, capturing behavior, formatting, pseudo-terminal usage, progress display, verbosity, and failure handling.
```APIDOC
duty release
usage: duty release [-c {stdout,stderr,both,none}] [-f {pretty,tap}] [-y | -Y] [-p | -P] [-q | -Q] [-s | -S] [-z | -Z]
Release a new Python package.
Parameters:
ctx: The context instance (passed automatically).
version: The new version number to use.
options:
-c {stdout,stderr,both,none}, --capture {stdout,stderr,both,none}
Which output to capture. Colors are supported with 'both' only, unless the command has a 'force color' option.
-f {pretty,tap}, --fmt {pretty,tap}, --format {pretty,tap}
Output format. Pass your own Jinja2 template as a string with '-f custom=TEMPLATE'. Available variables: command, title (command or title passed with -t), code (exit status), success (boolean), failure (boolean), number (command number passed with -n), output (command output), nofail (boolean), quiet (boolean), silent (boolean).
Available filters: indent (textwrap.indent).
-y, --pty Enable the use of a pseudo-terminal. PTY doesn't allow programs to use standard input.
-Y, --no-pty Disable the use of a pseudo-terminal. PTY doesn't allow programs to use standard input.
-p, --progress Print progress while running a command.
-P, --no-progress Don't print progress while running a command.
-q, --quiet Don't print the command output, even if it failed.
-Q, --no-quiet Print the command output when it fails.
-s, --silent Don't print anything.
-S, --no-silent Print output as usual.
-z, --zero, --nofail Don't fail. Always return a success (0) exit code.
-Z, --no-zero, --strict
Return the original exit code.
```
--------------------------------
### Run Single Duty
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates the basic command to execute a single duty from the CLI. Also shows how to run duties when using package managers like Poetry or PDM.
```Bash
duty clean
```
```Bash
poetry run duty clean
```
```Bash
pdm run duty clean
```
--------------------------------
### Define Duty with Tool Callable
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates using `duty`'s provided tools to call popular Python tools, like `mkdocs.build`, with keyword arguments via `ctx.run`.
```python
from duty import duty, tools
@duty
def docs(ctx):
ctx.run(tool.mkdocs.build, kwargs={"strict": True}, title="Building documentation")
```
--------------------------------
### Define Duty with List Command
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to define a duty function that executes a command using `ctx.run` with a list of strings. This method avoids the overhead of an extra shell process.
```python
from duty import duty
@duty
def docs(ctx):
ctx.run(["mkdocs", "build"], title="Building documentation")
# avoid the overhead of an extra shell process
```
--------------------------------
### Immediate Directory Changes with ctx.cd() Context Manager
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Explains the use of `ctx.cd(directory)` as a context manager for immediate and nested directory changes. Unlike `ctx.options(workdir=...)`, `ctx.cd()` changes the actual working directory for all subsequent operations within its scope, including non-`ctx.run` calls.
```Python
import os
from duty import duty
@duty
def run_scripts(ctx):
ctx.run("echo in .") # run in ./
with ctx.cd("A"):
ctx.run("echo in A") # run in ./A
l = os.listdir() # run in ./A as well
with ctx.cd("B"):
ctx.run("echo in A/B") # run in ./A/B
ctx.run("echo in A/B/C", workdir="C") # run in ./A/B/C
ctx.run("echo in A") # back to ./A
ctx.run("echo in .") # back to ./
```
--------------------------------
### Bash Duty Command Line Options for Format
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates how to apply the 'tap' output format using the duty CLI, including global, local, and environment variable settings.
```bash
# or with the CLI global option
duty --format tap task1 task2
# or with a CLI local option
duty task1 -ftap task2
# or with an environment variable
FAILPRINT_FORMAT=tap duty task1 task2
```
--------------------------------
### Run Multiple Duties
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates how to execute multiple duties in a single command by listing them sequentially.
```Bash
duty clean docs
```
--------------------------------
### Makefile Integration for Duty
Source: https://github.com/pawamoy/duty/blob/main/docs/index.md
This Makefile snippet demonstrates how to integrate 'duty' tasks into a project managed by tools like Poetry or PDM. It defines a DUTY variable that automatically uses the project's virtual environment runner (e.g., 'pdm run') if available, simplifying the command to run duty tasks. This allows for shorter commands like 'make clean' instead of 'poetry run duty clean'.
```makefile
DUTY := $(if $(VIRTUAL_ENV),,pdm run) duty
clean:
@$(DUTY) clean
```
--------------------------------
### Changing Working Directory with ctx.run() and ctx.options()
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to specify a working directory for individual `ctx.run()` calls or for a group of calls using `ctx.options(workdir=...)`. The `workdir` option within `ctx.options` defers the directory change to each `run` call and is overridden by nested `workdir` options.
```Python
import os
from duty import duty
@duty
def run_scripts(ctx):
# Change working directory for a specific run
ctx.run("bash script3.sh", workdir="subfolder")
# Change working directory for a group of runs
ctx.run("echo in .")
ctx.run("ls")
with ctx.options(workdir="subfolder"):
ctx.run("echo in subfolder")
ctx.run("ls")
# Nested workdir overrides
ctx.run("echo in .") # run in ./
with ctx.options(workdir="A"):
ctx.run("echo in A") # run in ./A
with ctx.options(workdir="B"):
ctx.run("echo in...") # run in ./B, not ./A/B!
# Non-run instructions are unaffected by workdir option
ctx.run("echo in .") # run in ./
with ctx.options(workdir="A"):
ctx.run("echo in A") # run in ./A
l = os.listdir() # run in ./, not ./A!
```
--------------------------------
### Define Duty with Lazy Tool Callable
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Explains and shows how to use lazy callables for tools, allowing direct calls without `args` or `kwargs` parameters in `ctx.run`. This improves IDE integration and readability.
```python
from duty import duty, tools
@duty
def docs(ctx):
ctx.run(tools.mkdocs.build(strict=True), title="Building documentation")
```
--------------------------------
### Capturing Command Output with ctx.run() (Duty 0.7+)
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Details how `ctx.run()` in Duty version 0.7 and later captures and returns the output of executed commands, even when printed to standard output. This simplifies obtaining command results compared to older methods using `subprocess` directly.
```Python
import subprocess
from duty import duty
# Before Duty 0.7:
@duty
def action_old(ctx):
requirements = subprocess.run(
["pip", "freeze"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
).stdout # Note: .output was used in example, .stdout is more common for PIPE
...
# With Duty 0.7+:
@duty
def action_new(ctx):
requirements = ctx.run(["pip", "freeze"])
...
```
--------------------------------
### Run a duty task from the command line
Source: https://github.com/pawamoy/duty/blob/main/README.md
Executes a defined task named 'docs' using the duty command-line interface. This command invokes the Python function decorated with @duty.
```bash
duty docs
```
--------------------------------
### Define Duty with String Command
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates defining a duty function that executes a shell command using `ctx.run` with a string argument. The command is run in a shell process.
```python
from duty import duty
@duty
def docs(ctx):
ctx.run("mkdocs build", title="Building documentation")
```
--------------------------------
### TAP Jinja Output Format
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
A Jinja template for formatting command output in the Test Anything Protocol (TAP) style. It's useful for integrating with other testing tools.
```jinja
{% if failure %}not {% endif %}ok {{ number }} - {{ title or command }}
{% if failure and output %}
---
{{ ('command: ' + command + '\n ') if title else '' }}
output: |\n{{ output|indent(4 * ' ') }}
...{% endif %}
```
--------------------------------
### Custom Jinja Output Format via Environment Variable
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to define a custom Jinja output format by prefixing the value with 'custom=' in the FAILPRINT_FORMAT environment variable.
```bash
export FAILPRINT_FORMAT="custom={{output}}"
# always print the captured output, nothing else
duty task1 task2
```
--------------------------------
### Development Workflow Commands
Source: https://github.com/pawamoy/duty/blob/main/CONTRIBUTING.md
Essential commands for the development workflow, including creating branches, formatting code, running checks and tests, generating documentation, and managing commits for pull requests.
```git
git switch -c feature-or-bugfix-name
```
```bash
make format
make check
make test
```
```bash
make docs
```
```git
git commit --fixup=SHA
```
```git
git rebase -i --autosquash main
git push -f
```
--------------------------------
### Pretty Jinja Output Format
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
The default Jinja template for formatting command output in a human-readable, pretty style. It includes success/failure indicators, command titles, and indented output.
```jinja
{% if success %}✓
{% elif nofail %}✗
{% else %}✗{% endif %}
{{ title or command }}
{% if failure %} ({{ code }}){% endif %}
{% if failure and output and not quiet %}
{{ (' > ' + command + '\n') if title else '' }}
{{ output|indent(2 * ' ') }}{% endif %}
```
--------------------------------
### Temporary Option Changes with ctx.options()
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates using `ctx.options()` as a context manager to temporarily change options for a block of `ctx.run()` calls. These temporary changes stack and unstack as the `with` clauses are entered and exited, allowing for granular control over command execution behavior.
```Python
from duty import duty
@duty
def run_scripts(ctx):
# Default options
ctx.run("bash script0.sh")
with ctx.options(nofail=True):
# nofail=True
ctx.run("bash script1.sh")
with ctx.options(quiet=True):
# nofail=True, quiet=True
ctx.run("bash script2.sh")
with ctx.options(silent=True, nofail=False):
# nofail=False, quiet=True, silent=True
ctx.run("bash script3.sh")
# Back to nofail=True, quiet=True
ctx.run("bash script4.sh")
# Back to nofail=True
ctx.run("bash script5.sh")
# Back to defaults
ctx.run("bash script6.sh")
```
--------------------------------
### Running pre/post duties with unaltered context
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Explains how to ensure pre/post duties are executed with an unaltered context by using lambda functions. This is crucial when the main duty might modify the context in ways that should not affect its dependencies.
```python
import duty
@duty(nofail=True, capture=False)
def coverage(ctx):
ctx.run("coverage combine")
ctx.run("coverage report")
@duty(post=[lambda ctx: coverage.run()])
def test(ctx):
ctx.run("pytest tests")
```
--------------------------------
### Duty with Variadic Positional Arguments
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to define a Duty function that accepts an arbitrary number of positional arguments using `*names`. These arguments can be passed directly from the command line, useful for passing multiple values or CLI flags.
```python
from duty import duty
@duty
def shout(ctx, *names):
ctx.run(print, args=[f"{name.upper()}!" for name in names])
```
--------------------------------
### Passing stdin via shell pipe (Old Method)
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates the older method of passing standard input to a command using shell piping. This approach can lead to platform-dependent issues and difficulties in finding executables.
```python
import duty
@duty
def check_dependencies(ctx):
ctx.run(
"pdm export -f requirements --without-hashes | safety check --stdin --full-report",
title="Checking dependencies",
)
```
--------------------------------
### Defining a composite duty with pre-requisites
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Shows how to define a duty that automatically runs other specified duties before its own execution. This is achieved using the `pre` decorator argument, allowing for dependency management and task orchestration.
```python
import duty
@duty(pre=["check_quality", "check_types", "check_docs", "check_dependencies"])
def check(ctx):
"""Check it all!"""
```
--------------------------------
### Define Duty with Python Callable
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates defining a duty function that executes a Python callable directly using `ctx.run`. This avoids using a subprocess entirely.
```python
from duty import duty
from mkdocs import build, config
@duty
def docs(ctx):
ctx.run(build.build, args=[config.load_config()], title="Building documentation")
# avoid the overhead of an extra Python process
```
--------------------------------
### Generate Project Credits Script (Python)
Source: https://github.com/pawamoy/duty/blob/main/docs/credits.md
This Python script is executed to generate project credits. It utilizes an include directive to incorporate content from an external file, likely for dynamic credit generation.
```python
```python exec="yes"
--8<-- "scripts/gen_credits.py"
```
```
--------------------------------
### Passing stdin via variable (New Method)
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates the modern approach in duty 0.7+ for passing standard input. It involves capturing command output into a variable and then using that variable as stdin for subsequent commands, improving robustness and cross-platform compatibility.
```python
import duty
@duty
def check_dependencies(ctx):
requirements = ctx.run(
["pdm", "export", "-f", "requirements", "--without-hashes"],
title="Exporting dependencies as requirements",
allow_overrides=False,
)
ctx.run(
["safety", "check", "--stdin", "--full-report"],
title="Checking dependencies",
stdin=requirements,
)
ctx.run(
["other", "command", "using", "requirements"],
title="Checking one more thing",
stdin=requirements,
)
```
--------------------------------
### Duty with Variadic Arguments and CLI Flags
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates passing additional CLI flags to underlying commands or tools when using variadic arguments with Duty. The `--` separator is used to distinguish Duty's own options from the arguments intended for the executed command.
```python
from duty import duty, tools
@duty
def docs(ctx, *cli_args) -> None:
ctx.run(tools.mkdocs.serve().add_args(*cli_args), capture=False)
```
--------------------------------
### Define Duty with Lazy Function
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates creating custom lazy callables using `tools.lazy` for functions not provided by `duty`'s tools, such as `griffe.cli.check`.
```python
from duty import duty, tools
from griffe.cli import check
@duty
def check_api(ctx):
griffe_check = tools.lazy(check, name="griffe.check")
ctx.run(griffe_check("pkg"))
```
--------------------------------
### Defining custom aliases for duties
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates how to assign custom aliases to duties using the `aliases` decorator option. This allows duties to be invoked via shorter or alternative names, enhancing command-line usability.
```python
import duty
@duty(aliases=["start", "up"])
def start_backend(ctx):
ctx.run("docker-compose up")
```
--------------------------------
### Preventing CLI Option Overrides
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates how to prevent command-line options from overriding settings defined within `ctx.run()` or `ctx.options()`. Setting `allow_overrides=False` ensures that the specified options are strictly enforced.
```python
from duty import duty
@duty
def run_scripts(ctx):
# no option can be changed from the CLI for the following run
ctx.run("bash script1.sh", quiet=False, allow_overrides=False)
# not for these runs either
with ctx.options(nofail=True, allow_overrides=False):
ctx.run("bash script2.sh")
ctx.run("bash script3.sh")
```
--------------------------------
### Skip Duty with Python Decorator
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates how to use the `@duty` decorator in Python to skip a duty based on a condition, such as Python version. Includes the `skip_if` argument for conditional skipping and `skip_reason` for explaining the skip.
```Python
import sys
@duty(
skip_if=sys.version_info < (3, 8),
skip_reason="Building docs is not supported on Python 3.7",
)
def docs(ctx):
ctx.run("mkdocs build")
```
--------------------------------
### Commit Message Convention
Source: https://github.com/pawamoy/duty/blob/main/CONTRIBUTING.md
The standard format for commit messages, based on Angular or Karma conventions. It includes a type, optional scope, subject, and an optional body with trailers for issue and PR references.
```markdown
[(scope)]: Subject
[Body]
Issue #10: https://github.com/namespace/project/issues/10
Related to PR namespace/other-project#15: https://github.com/namespace/other-project/pull/15
```
--------------------------------
### Set Default Options in Duty Decorator
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Demonstrates setting default options, such as `silent=True`, directly within the `@duty` decorator. This applies the option to all `ctx.run()` calls within the decorated function, with the ability to override defaults in individual `ctx.run()` calls.
```Python
from duty import duty
@duty(silent=True)
def clean(ctx):
ctx.run("rm -rf .coverage*")
ctx.run("rm -rf .mypy_cache")
ctx.run("rm -rf .pytest_cache")
ctx.run("rm -rf build")
ctx.run("rm -rf dist")
ctx.run("rm -rf pip-wheel-metadata")
ctx.run("rm -rf site")
ctx.run("find . -type d -name __pycache__ | xargs rm -rf")
ctx.run("find . -name '*.rej' -delete")
@duty(capture=True)
def run_scripts(ctx):
ctx.run("bash script1.sh")
ctx.run("bash script2.sh")
ctx.run("bash script3.sh", capture=False) # Override default capture=True
```
--------------------------------
### Duty with Custom Type Parameters
Source: https://github.com/pawamoy/duty/blob/main/docs/usage.md
Illustrates using custom Python classes as parameter types for Duty functions. The 'Point' class is defined to parse a string into x and y coordinates, enabling structured data passing from the CLI.
```python
from duty import duty
class Point:
def __init__(self, xy: str):
self.x, self.y = xy.split(",")
@duty
def shoot(ctx, point: Point):
ctx.run(f"shoot -x {point.x} -y {point.y}")
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.