### Install Invoke Development Dependencies Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/development.rst After cloning the Invoke project repository, use this command to install all necessary development dependencies listed in `dev-requirements.txt` using pip. ```Shell pip install -r dev-requirements.txt ``` -------------------------------- ### List Available Invoke Tasks Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst Explains how to use the `invoke --list` command to display all tasks defined in the `tasks.py` file. This command also shows the first line of each task's docstring, providing a quick overview of available functionalities. ```bash $ invoke --list Available tasks: build ``` -------------------------------- ### PyInvoke Sphinx Docs Setup - Hardcoded Paths Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Initial example of Sphinx documentation tasks (`clean`, `build`) with hardcoded paths for build directories. This serves as a starting point before introducing more flexible configuration methods. ```python from invoke import task @task def clean(c): c.run("rm -rf docs/_build") @task def build(c): c.run("sphinx-build docs docs/_build") ``` -------------------------------- ### Creating Nested Namespaces with PyInvoke Collection Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst This example illustrates how to organize tasks into a hierarchical namespace using Invoke's Collection class. It demonstrates binding a 'deploy' task and an entire 'docs' module into a single root namespace, improving project task organization. ```python from invoke import Collection, task import docs @task def deploy(c): c.run("python setup.py sdist") c.run("twine upload dist/*") namespace = Collection(docs, deploy) ``` -------------------------------- ### Define and Run Basic Invoke Task Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst Demonstrates the simplest way to define an Invoke task using the `@task` decorator in a `tasks.py` file. It shows how to create a basic Python function that takes a context argument and how to execute it from the command line using the `invoke` CLI tool. ```python from invoke import task @task def build(c): print("Building!") ``` ```bash $ invoke build Building! ``` -------------------------------- ### Add Metadata and Help to Invoke Tasks Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst Shows how to enhance Invoke tasks with metadata using the `@task` decorator's `help` parameter and docstrings. This metadata provides useful descriptions for task arguments and the task itself, which are displayed when `invoke --help` is used. ```python @task(help={'name': "Name of the person to say hi to."}) def hi(c, name): """ Say hi to someone. """ print("Hi {}!".format(name)) ``` ```bash $ invoke --help hi Usage: inv[oke] [--core-opts] hi [--options] [other tasks here ...] Docstring: Say hi to someone. Options: -n STRING, --name=STRING Name of the person to say hi to. ``` -------------------------------- ### Listing PyInvoke Tasks with Namespaces Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst This snippet shows the command-line output of 'invoke --list' after defining a nested namespace. It demonstrates how Invoke displays the hierarchical structure of tasks, including top-level tasks and tasks within modules. ```shell $ invoke --list Available tasks: deploy docs.build docs.clean ``` -------------------------------- ### PyInvoke Sphinx Docs Setup - Collection Configuration Start Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Beginning the refactoring of Sphinx documentation tasks to leverage `Collection`-based configuration, introducing an explicit namespace object for defining shared settings. ```python from invoke import Collection, task default_target = "docs/_build" @task def clean(c, target=default_target): ``` -------------------------------- ### Run Shell Commands in Invoke Tasks Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst Demonstrates how to execute local shell commands within an Invoke task using the `Context.run` method. This method captures and displays the command's output, making it suitable for automating build processes or other shell-based operations. ```python from invoke import task @task def build(c): c.run("sphinx-build docs docs/_build") ``` ```bash $ invoke build Running Sphinx v1.1.3 loading pickled environment... done ... build succeeded, 2 warnings. ``` -------------------------------- ### Start Nesting Collections Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Introduces the concept of nesting collections by showing the beginning of a task definition intended for a sub-namespace, demonstrating how to create additional `Collection` instances. ```Python @task def build_docs(c): ``` -------------------------------- ### Define Release Task in `tasks/release.py` Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Example content for `tasks/release.py`, defining a `release` task that handles package distribution using `setuptools`. ```python from invoke import task @task def release(c): c.run("python setup.py sdist register upload") ``` -------------------------------- ### Define Invoke Tasks with Parameters Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst Illustrates how to add parameters to Invoke task functions, which automatically map to CLI flags. It covers boolean flags for toggling behavior and string arguments that can be passed positionally or via named flags, demonstrating various invocation methods. ```python @task def build(c, clean=False): if clean: print("Cleaning!") print("Building!") ``` ```bash $ invoke build -c $ invoke build --clean ``` ```python @task def hi(c, name): print("Hi {}!".format(name)) ``` ```bash $ invoke hi Name $ invoke hi --name Name $ invoke hi --name=Name $ invoke hi -n Name $ invoke hi -nName ``` -------------------------------- ### Example: --complete with Empty Input Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Demonstrates using the --complete option with no specific task or option input, resulting in a list of available task names. ```bash $ inv --complete -- foo bar ``` -------------------------------- ### Build Invoke Project Documentation and Website Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/development.rst Commands to build the Invoke project's public website (`www`) and its API documentation (`docs`). The `docs.browse` subtask allows for easy viewing of the generated documentation. ```Shell inv www inv docs inv docs.browse ``` -------------------------------- ### Defining Pre-Tasks in PyInvoke Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/getting-started.rst This snippet demonstrates how to define tasks that automatically execute before another task using Invoke's @task decorator. It shows a 'clean' task running prior to a 'build' task, ensuring necessary cleanup is performed before building documentation. ```python from invoke import task @task def clean(c): c.run("rm -rf docs/_build") @task(clean) def build(c): c.run("sphinx-build docs docs/_build") ``` -------------------------------- ### Getting Help for a Specific Task Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst Illustrates how to retrieve help documentation for a specific Invoke task, showing its docstring and available options/flags. ```bash $ inv --help build # or invoke build --help Docstring: none Options for 'build': -f STRING, --format=STRING Which build format type to use ``` -------------------------------- ### Define Build and Clean Docs Tasks in `tasks/docs.py` Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Example content for `tasks/docs.py`, defining `build` and `clean` tasks for Sphinx documentation, demonstrating task organization within a module. ```python from invoke import task @task def build(c): c.run("sphinx-build docs docs/_build") @task def clean(c): c.run("rm -rf docs/_build") ``` -------------------------------- ### Example: --complete with Partial Task Input Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Shows how --complete behaves when given a partial command line that does not end with a dash, still listing task names. ```bash $ inv --complete -- foo --foo-arg foo bar ``` -------------------------------- ### PyInvoke Sphinx Docs Setup - Runtime Parameterization Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Enhancing the Sphinx documentation tasks to accept a `target` parameter with a default value, allowing runtime customization of the build directory. ```python default_target = "docs/_build" @task def clean(c, target=default_target): c.run("rm -rf {}".format(target)) @task def build(c, target=default_target): c.run("sphinx-build docs {}".format(target)) ``` -------------------------------- ### Task Parameterization: Old CLI Invocation Example Source: https://github.com/pyinvoke/invoke/blob/main/THOUGHTS.rst An older example demonstrating how tasks could be invoked multiple times with different parameters directly from the command line, showing a pattern of repeated invocation for different modules. This highlights a previous approach to task parameterization. ```bash $ invoke test --module=foo test --module=bar Cleaning Testing foo Cleaning Testing bar ``` -------------------------------- ### Define Default Subcollections Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Comprehensive example demonstrating how to define nested collections with default tasks, and then set a subcollection as the default for the parent collection using `default=True` in `add_collection`. ```python from invoke import Collection, task @task(default=True) def build_all(c): print("build ALL THE THINGS!") @task def build_wheel(c): print("Just the wheel") build = Collection(all=build_all, wheel=build_wheel) @task(default=True) def build_docs(c): print("Code without docs is no code at all") docs = Collection(build_docs) ns = Collection() ns.add_collection(build, default=True) ns.add_collection(docs) ``` -------------------------------- ### Task Parameterization: Library-Level Executor Example Source: https://github.com/pyinvoke/invoke/blob/main/THOUGHTS.rst An example of a `ParameterizedExecutor` class, illustrating how task parameterization might be handled at the library level within Invoke. This approach suggests that complex, multi-dimensional parameterization is better managed programmatically rather than via CLI. ```Python @task def stuff(var): print(var) # NOTE: may need to be part of base executor since Collection has to know # to pass the parameterization option/values into Executor().execute()? class ParameterizedExecutor(Executor): # NOTE: assumes single dimension of parameterization. # Realistically would want e.g. {'name': [values], ...} structure and # then do cross product or something ``` -------------------------------- ### Update Documentation for Customizing Config Subclassing Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/changelog.rst The documentation example related to subclassing 'invoke.config.Config' has been updated. This ensures that users have accurate and helpful guidance when customizing configuration defaults through subclassing. ```APIDOC Documentation Update: Topic: Subclassing invoke.config.Config Reference: doc/example (customizing-config-defaults) ``` -------------------------------- ### Example Interactive Program Prompt Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/watchers.rst Demonstrates a command-line program that prompts the user for input, specifically a yes/no question, and shows the expected interactive exchange. ```Shell $ excitable-program When you give the OK, I'm going to do the things. All of them!! Are you ready? [Y/n] y OK! I just did all sorts of neat stuff. You're welcome! Bye! ``` -------------------------------- ### Run Invoke Project Test Suites Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/development.rst These commands execute the primary unit tests (`test`) and the integration tests (`integration`) for the Invoke project. The integration suite is primarily used by continuous integration systems. ```Shell inv test inv integration ``` -------------------------------- ### List Available Invoke Management Tasks Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/development.rst To see a comprehensive list of all project management tasks defined within the Invoke project, execute this command. Invoke uses itself for its internal task automation. ```Shell inv --list ``` -------------------------------- ### Initializing an Invoke Program object Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/library.rst This snippet demonstrates how to import the `Program` class from Invoke and initialize a `program` object. This `Program` instance will handle the core CLI functionality, starting with a specified version number. ```python from invoke import Program program = Program(version='0.1.0') ``` -------------------------------- ### PyInvoke Sphinx Docs Setup - Refactored Target Variable Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Refactoring the Sphinx documentation tasks to use a shared `target` variable for the build directory, improving maintainability compared to hardcoded paths. ```python target = "docs/_build" @task def clean(c): c.run("rm -rf {}".format(target)) @task def build(c): c.run("sphinx-build docs {}".format(target)) ``` -------------------------------- ### Example CLI output for configured Invoke Program Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/library.rst This shows the command-line output after the custom Invoke `Program` has been configured with a task namespace. The `tester` CLI now correctly lists `unit` and `integration` as subcommands and executes them as expected. ```shell $ tester --version Tester 0.1.0 $ tester --help Usage: tester [--core-opts] [--subcommand-opts] ... Core options: ... core options here, minus task-related ones ... Subcommands: unit integration $ tester --list No idea what '--list' is! $ tester unit Running unit tests! ``` -------------------------------- ### Example: --complete for Flag Names Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Illustrates using --complete when the input ends with a dash, causing it to list flag names relevant to the current context (e.g., for task 'foo'). ```bash $ inv --complete -- foo - --foo-arg --foo-arg-2 ``` -------------------------------- ### Invoking Tasks from the Command Line Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/index.rst These examples demonstrate how to execute Invoke tasks directly from the command line. They show various ways to pass boolean flags and string arguments, including long-form (`--docs`), short-form (`-d`), and combined short-form flags (`-db`). ```bash invoke clean build invoke clean --docs --bytecode build --docs --extra='**/*.pyo' invoke clean -d -b build --docs -e '**/*.pyo' invoke clean -db build -de '**/*.pyo' ``` -------------------------------- ### Invoking Task with Flag Arguments Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst Examples of invoking a task with flag arguments, demonstrating both long-form (--format=html) and short-form (-f pdf) syntax, with and without equals signs. ```bash $ inv build --format=html $ inv build --format html $ inv build -f pdf $ inv build -f=pdf ``` -------------------------------- ### Test Invoke task with .MockContext and Mock assertions Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/testing.rst This example shows how to test the `replace` task using `.MockContext` when its methods are wrapped by the `mock` library. It demonstrates setting up `MockContext.run` to respond to multiple commands using a dictionary and asserting calls with `Mock.assert_called_with`. ```python from invoke import MockContext, Result from mytasks import replace def test_regular_sed(): expected_sed = "sed -e s/foo/bar/g file.txt" c = MockContext(run={ "which gsed": Result(exited=1), expected_sed: Result(), }) replace(c, 'file.txt', 'foo', 'bar') c.run.assert_called_with(expected_sed) def test_homebrew_gsed(): expected_sed = "gsed -e s/foo/bar/g file.txt" c = MockContext(run={ "which gsed": Result(exited=0), expected_sed: Result(), }) replace(c, 'file.txt', 'foo', 'bar') c.run.assert_called_with(expected_sed) ``` -------------------------------- ### PyInvoke Collection-based Configuration Example Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Demonstrates how `Collection` objects can be used to define and merge configuration settings. It shows an inner collection with a default value and an outer collection overriding that value, illustrating the 'downwards' merging behavior where outer namespaces win. ```python from invoke import Collection, task # This task & collection could just as easily come from # another module somewhere. @task def mytask(c): print(c['conflicted']) inner = Collection('inner', mytask) inner.configure({'conflicted': 'default value'}) # Our project's root namespace. ns = Collection(inner) ns.configure({'conflicted': 'override value'}) ``` -------------------------------- ### CLI Option: --prompt-for-sudo-password Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Prompts for the 'sudo.password' configuration value at the start of the session, allowing users to provide sensitive information via input rather than storing it in config files or environment variables. ```APIDOC --prompt-for-sudo-password Prompt at the start of the session (before executing any tasks) for the ``sudo.password`` configuration value. This allows users who don't want to keep sensitive material in the config system or their shell environment to rely on user input, without otherwise interrupting the flow of the program. ``` -------------------------------- ### Configure Invoke Settings Across Multiple File Formats Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/configuration.rst Demonstrates how to configure common Invoke settings, specifically enabling debug output and run echoing, using YAML, JSON, and Python configuration files. All three examples achieve the equivalent configuration of `{'debug': True, 'run': {'echo': True}}`. ```yaml debug: true run: echo: true ``` ```javascript { "debug": true, "run": { "echo": true } } ``` ```python debug = True run = { "echo": True } ``` -------------------------------- ### Invoking Multiple Tasks from the Command Line Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/prior-art.rst This example illustrates Invoke's unique capability to run multiple tasks sequentially from a single command-line invocation, allowing each task to have its own set of specific options. This contrasts with many other Python command-line libraries that do not support such complex multi-task execution patterns. ```Shell runner --core-opts task1 --task1-opts task2 --task2-opts ``` -------------------------------- ### Example CLI output for unconfigured Invoke Program Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/library.rst This shows the command-line output when a custom Invoke `Program` is run without any specific tasks or namespaces configured. It behaves like the default Invoke CLI but with the custom binary name and version. ```shell $ tester --version Tester 0.1.0 $ tester --help Usage: tester [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts] Core options: ... core Invoke options here ... $ tester --list Can't find any collection named 'tasks'! ``` -------------------------------- ### Test Invoke task with .MockContext for c.run results Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/testing.rst This example shows how to test the `get_platform` task by injecting a `.MockContext` instance. The `MockContext` is initialized with `Result` objects to simulate the output of `c.run`, allowing assertions on the task's return value. ```python from invoke import MockContext, Result from mytasks import get_platform def test_get_platform_on_mac(): c = MockContext(run=Result("Darwin\n")) assert "Apple" in get_platform(c) def test_get_platform_on_linux(): c = MockContext(run=Result("Linux\n")) assert "desktop" in get_platform(c) ``` -------------------------------- ### Execute Invoke Task with Pre-Task Example Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst This shell command shows the execution of the `build` Invoke task from the command line. When executed, it triggers its defined pre-task (`clean`) before running the `build` logic, demonstrating the task dependency flow. ```shell $ inv build ``` -------------------------------- ### Customizing Invoke Config File and Env Var Prefixes Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/library.rst This Python example shows how to customize the default configuration file prefix and environment variable prefix for Invoke's configuration system. By subclassing `invoke.Config` and setting the `prefix` attribute, users can change the expected config filenames (e.g., `tester.yaml`) and environment variable prefixes (e.g., `TESTER_RUN_ECHO`). This is crucial for redistributing Invoke-based applications with custom branding. ```python from invoke import Config class TesterConfig(Config): prefix = 'tester' ``` -------------------------------- ### Understand Recursive and Chained Pre/Post Task Execution in Invoke Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst Explains how Invoke handles nested pre- and post-tasks recursively in a depth-first manner. This example showcases a complex task dependency graph and the resulting execution order, demonstrating robust task orchestration. ```python @task def clean_html(c): print("Cleaning HTML") @task def clean_tgz(c): print("Cleaning .tar.gz files") @task(clean_html, clean_tgz) def clean(c): print("Cleaned everything") @task def makedirs(c): print("Making directories") @task(clean, makedirs) def build(c): print("Building") @task(build) def deploy(c): print("Deploying") ``` ```bash $ inv deploy Cleaning HTML Cleaning .tar.gz files Cleaned everything Making directories Building Deploying ``` -------------------------------- ### Configure Invoke Shell Completion for Zsh Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst These commands demonstrate the process of generating and activating the Invoke shell completion script specifically for Zsh. The first command outputs the completion script to a file, which is then sourced by the second command to enable tab completion in the shell environment. This setup is typically added to a shell startup file like ~/.zshrc for persistence. ```shell $ inv --print-completion-script zsh > ~/.invoke-completion.sh ``` ```shell source ~/.invoke-completion.sh ``` -------------------------------- ### Configuring setup.py for a custom Invoke CLI Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/library.rst This snippet shows how to configure your `setup.py` file to create a custom command-line entry point for your Python package, using Invoke under the hood. It defines a `console_scripts` entry point that maps the `tester` command to `tester.main:program.run`. ```python setup( name='tester', version='0.1.0', packages=['tester'], install_requires=['invoke'], entry_points={ 'console_scripts': ['tester = tester.main:program.run'] } ) ``` -------------------------------- ### Test Invoke task with .MockContext using boolean results Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/testing.rst This example refines the previous test by using `True` or `False` as shorthand for `Result` objects with exit codes 0 or 1 respectively. This simplifies the `MockContext` setup for commands where only a boolean success/failure is relevant. ```python from invoke import MockContext, Result from mytasks import replace def test_regular_sed(): expected_sed = "sed -e s/foo/bar/g file.txt" c = MockContext(run={ "which gsed": False, expected_sed: True, }) replace(c, 'file.txt', 'foo', 'bar') c.run.assert_called_with(expected_sed) def test_homebrew_gsed(): expected_sed = "gsed -e s/foo/bar/g file.txt" c = MockContext(run={ "which gsed": True, expected_sed: True, }) replace(c, 'file.txt', 'foo', 'bar') ``` -------------------------------- ### Initialize Namespace from Modules using `Collection.from_module` Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Shows how to create a root `Collection` (`ns`) and populate it by importing other modules as collections using `Collection.from_module`, which scans modules for `Task` instances. ```python from invoke import Collection import release, docs ns = Collection() ns.add_collection(Collection.from_module(release)) ns.add_collection(Collection.from_module(docs)) ``` -------------------------------- ### Install Invoke via pip Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/installing.rst This command installs the latest stable release of the Invoke library using the pip package manager. Invoke supports Python 3.6+ and is pure-Python, vendorizing its few dependencies, meaning no other external dependencies are required. ```bash $ pip install invoke ``` -------------------------------- ### Initialize an Invoke Collection Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Demonstrates how to create a new, explicit Collection instance, which serves as the root for organizing tasks, instead of relying on Invoke's default behavior. ```Python from invoke import Collection ns = Collection() # or: namespace = Collection() ``` -------------------------------- ### List Available Tasks Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Illustrates the output of the `invoke --list` command after adding a task, showing how Invoke displays the available tasks in the current namespace. ```CLI $ invoke --list Available tasks: release ``` -------------------------------- ### Initialize Namespace from Modules using `add_collection` Shortcut Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Demonstrates a shorthand for populating a root `Collection` (`ns`) by directly passing module objects to `add_collection`, which internally calls `Collection.from_module`. ```python ns = Collection() ns.add_collection(release) ns.add_collection(docs) ``` -------------------------------- ### Fix `namespace` Argument in `Collection` Documentation Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/changelog.rst Corrected the documentation example for the explicit `namespace=` argument to accurately show wrapping an imported task module in a `invoke.collection.Collection`. ```APIDOC namespace=` argument `invoke.collection.Collection` ``` -------------------------------- ### Disable Auto-Dash Naming in Configuration Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Provides an example of how to configure Invoke to prevent automatic conversion of underscores to dashes in task names by setting `tasks.auto_dash_names` to `false` in a configuration file. ```YAML tasks: auto_dash_names: false ``` -------------------------------- ### Create and Populate an Invoke Collection Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Demonstrates how to create a new `Collection` object and add existing tasks to it with specific names, effectively grouping related tasks. ```python docs = Collection('docs') docs.add_task(build_docs, 'build') docs.add_task(clean_docs, 'clean') ``` -------------------------------- ### Invoke Command Line Usage Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Illustrates the general structure of an Invoke command, showing how core options, task names, and task-specific options are arranged. ```bash $ inv[oke] [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts] ``` -------------------------------- ### Fix six.moves Import in invoke.util Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/changelog.rst Resolves an 'ImportError' within 'invoke.util' caused by a broken 'six.moves' import, which occurred in environments without an external 'six' package installed. ```Python # Fix for ImportError in invoke.util due to six.moves # Ensures compatibility in environments without external 'six' package. ``` -------------------------------- ### API Documentation for invoke.util Module and ExceptionWrapper Class Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/api/util.rst Provides API documentation for the `invoke.util` module, which contains various utility components. It also documents the `invoke.util.ExceptionWrapper` class separately, noting that its members are not explicitly listed in this documentation block. ```APIDOC Module: invoke.util Description: This module contains utility functions and classes for the Invoke project. Excluded Members: ExceptionWrapper Class: invoke.util.ExceptionWrapper Description: A wrapper class for exceptions. Members: Not explicitly listed (due to :no-members: directive) ``` -------------------------------- ### Defining Invoke Tasks in Python Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/index.rst This Python code demonstrates how to define tasks using the `@task` decorator in an Invoke `tasks.py` file. It includes `clean` and `build` tasks, showing how to accept arguments, handle conditional logic, and execute shell commands using the context object `c.run()`. ```python from invoke import task @task def clean(c, docs=False, bytecode=False, extra=''): patterns = ['build'] if docs: patterns.append('docs/_build') if bytecode: patterns.append('**/*.pyc') if extra: patterns.append(extra) for pattern in patterns: c.run("rm -rf {}".format(pattern)) @task def build(c, docs=False): c.run("python setup.py build") if docs: c.run("sphinx-build docs docs/_build") ``` -------------------------------- ### List Tasks for Module-Based Collections Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Illustrates the `invoke --list` output when tasks are organized into module-based collections, showing the fully qualified task names. ```bash $ invoke --list Available tasks: release.release docs.build docs.clean ``` -------------------------------- ### List Tasks After Adding Collection Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Illustrates the output of `invoke --list` after adding a `docs` collection to the root namespace, showing the hierarchical task structure. ```bash $ invoke --list Available tasks: release docs.build docs.clean ``` -------------------------------- ### Invoke Config and Program Initialization API Changes Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/changelog.rst Documents backwards incompatible changes to `Config.__init__` and `Program.__init__`. `Config.__init__` now expects `overrides` as the first positional argument and `env_prefix` is a class attribute. `Program.__init__` no longer directly handles `env_prefix`, requiring `Config` subclassing instead. ```APIDOC invoke.config.Config.__init__(overrides: dict, defaults: dict, ...) - overrides: dict, now first positional argument - defaults: dict, now second positional argument - env_prefix: (formerly kwarg) now a class attribute (Config.prefix or Config.env_prefix) invoke.program.Program.__init__(...) - env_prefix: (formerly kwarg/attribute) now configured via subclassing Config and using its env_prefix attribute ``` -------------------------------- ### Define Invoke Task with Parameterized Pre-Task Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst This Python snippet demonstrates how to define an Invoke task (`build`) that executes a pre-task (`clean`) using `call`. The `call` function allows passing arguments to the pre-task, such as 'all' in this example, for more flexible task orchestration. ```python @task(pre=[call(clean, which='all')]) # or call(clean, 'all') def build(c): print("Building") ``` -------------------------------- ### Sphinx Automodule Directive for Invoke Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/api/__init__.rst This reStructuredText directive instructs Sphinx to automatically generate comprehensive API documentation for the specified Python module, `invoke`. It's commonly used in Sphinx projects to pull in docstrings and signatures from Python code, creating detailed reference pages for classes, functions, and methods within the module. ```reStructuredText .. automodule:: invoke ``` -------------------------------- ### CLI Option: --config Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Specifies a runtime configuration file to load. This option takes precedence over the INVOKE_RUNTIME_CONFIG environment variable if both are provided. ```APIDOC -f, --config Specify a runtime configuration file to load. Note that you may instead use the ``INVOKE_RUNTIME_CONFIG`` environment variable in place of this option. If both are given, the CLI option will win out. ``` -------------------------------- ### Illustrate Invoke Task Deduplication Behavior Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst This Python code defines a series of Invoke tasks (`clean`, `build`, `package`) where `build` depends on `clean` and `package` depends on `build`. It serves as an example to demonstrate how Invoke's default deduplication prevents `build` from running twice when both `build` and `package` are invoked in the same session. ```python @task def clean(c): print("Cleaning") @task(clean) def build(c): print("Building") @task(build) def package(c): print("Packaging") ``` -------------------------------- ### Basic Invoke CLI Layout Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst Demonstrates the general structure for invoking tasks from the command line, including core options and task-specific options. ```bash $ inv [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts] ``` -------------------------------- ### PyInvoke OhGodExecutor for Parameterized Pre-tasks Source: https://github.com/pyinvoke/invoke/blob/main/THOUGHTS.rst This Python example showcases a custom PyInvoke Executor, OhGodExecutor, designed to manage tasks with pre-tasks, especially when the main task is parameterized. It ensures that pre-tasks are executed only once before the main task is run for each parameter value, preventing redundant executions of prerequisites. ```python @task def setup(): print("Yay") @task(pre=[setup]) def build(): print("Woo") class OhGodExecutor(Executor): def execute(self, task, args, kwargs, parameter, values): # assume always parameterized meh # Run pretasks once only, instead of once per parameter value for pre in task.pre: self.execute(self.collection[pre]) for value in values: my_kwargs = dict(kwargs) my_kwargs[parameter] = value super(self, OhGodExecutor).execute(task, kwargs=my_kwargs) ``` -------------------------------- ### Invoke Default Subcollection Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Shows the output when `invoke` is run without arguments, triggering the default task of the default subcollection, demonstrating the highest level of default task resolution. ```bash $ invoke build ALL THE THINGS! ``` -------------------------------- ### Execute Invoke Tasks with Deduplication Disabled Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst This shell command shows how to explicitly disable Invoke's task deduplication feature using the `--no-dedupe` CLI option. When this option is used, tasks like `build` (from the example) will run every time they are referenced, even if it means multiple executions within the same session. ```shell $ inv --no-dedupe build package ``` -------------------------------- ### Invoke Core Command-Line Interface Options Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/invoke.rst Documentation for various core command-line options available in Invoke. These options control behavior such as displaying help for tasks, listing available tasks, using a pseudo-terminal for shell commands, changing the task module search root, setting command execution timeouts, showing the version, and handling shell command failures as warnings. ```APIDOC -h STRING, --help=STRING: When given without any task names, displays core help; when given with a task name (may come before or after the task name) displays help for that particular task. -l, --list=STRING: List available tasks. Shows all tasks by default; may give an explicit namespace to 'root' the displayed task tree to only that namespace. (This argument may contain periods, as with task names, so it's possible to show only a small, deep portion of the overall tree if desired.) -p, --pty: Use a pty when executing shell commands. -r STRING, --search-root=STRING: Change root directory used for finding task modules. -T INT, --command-timeout=INT: Set a default command execution timeout of INT seconds. Maps to the timeouts.command config setting. -V, --version: Show version and exit. -w, --warn-only: Warn, instead of failing, when shell commands fail. ``` -------------------------------- ### Define and Use Incrementable CLI Arguments in Invoke Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/invoking-tasks.rst Demonstrates how to define an 'incrementable' argument using the `@task` decorator in Invoke, allowing a CLI flag to increment an integer value with each occurrence. This is useful for verbosity levels. The example shows the Python task definition and its command-line usage, illustrating how multiple flag occurrences increment the associated integer. ```python @task(incrementable=['verbose']) def mytask(c, verbose=0): print(verbose) ``` ```bash $ inv mytask 0 $ inv mytask --verbose 1 $ inv mytask -v 1 $inv mytask -vvv 3 ``` -------------------------------- ### Add Collection with Custom Name Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Demonstrates how to add a `Collection` to the root namespace using a different name (`sphinx`) than its original definition, allowing for flexible naming in the CLI. ```python ns.add_collection(docs, 'sphinx') ``` -------------------------------- ### Automating Program Response with Invoke Responder Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/watchers.rst Shows how to use Invoke's `.Responder` class with `c.run` to automatically answer a yes/no prompt from an external program. It configures a regular expression pattern to match the prompt and provides the 'y\n' response to simulate user input. ```Python @task def always_ready(c): responder = Responder( pattern=r"Are you ready? \[Y/n\] ", response="y\n" ) c.run("excitable-program", watchers=[responder]) ``` -------------------------------- ### Embedding Invoke in Python Code Source: https://github.com/pyinvoke/invoke/blob/main/sites/www/index.rst This Python snippet illustrates how Invoke can be used programmatically within your own Python code or a REPL. It demonstrates using `invoke.run()` to execute a shell command, suppressing output (`hide=True`), handling warnings (`warn=True`), and inspecting the `Result` object for success and stdout. ```python from invoke import run cmd = "pip install -r requirements.txt" result = run(cmd, hide=True, warn=True) print(result.ok) print(result.stdout.splitlines()[-1]) ``` -------------------------------- ### Invoke Task with Dashes Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Demonstrates invoking a task defined with underscores using its automatically converted dashed name on the command line. ```CLI $ inv --list Available tasks: my-awesome-task $ inv my-awesome-task Awesome! ``` -------------------------------- ### Add Collection to Root Namespace Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Shows how to add a previously defined `Collection` object to the root namespace (`ns`), making its tasks available via dot notation (e.g., `docs.build`). ```python ns.add_collection(docs) ``` -------------------------------- ### Naming Tasks with Keyword Arguments in PyInvoke Collection Constructor Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Shows how to use keyword arguments in the `Collection` constructor to assign custom names to tasks when adding them to the namespace, providing an alternative to the `name` argument in `add_*` methods. ```python ns = Collection(docs, deploy=release.release) ``` ```bash $ invoke --list Available tasks: deploy docs.build docs.clean ``` -------------------------------- ### List Tasks with Default Task Indication Source: https://github.com/pyinvoke/invoke/blob/main/sites/docs/concepts/namespaces.rst Displays the `invoke --list` output when a default task is defined, showing the collection name in parentheses next to the default task, indicating it can be invoked directly. ```bash $ invoke --list Available tasks: release.release docs.build (docs) docs.clean ```