### Setup and Teardown Actions Example Source: https://github.com/pydoit/doit/blob/master/doc/dependencies.md Illustrates how to define setup and teardown tasks for environment preparation and cleanup. Setup tasks run before the main task (if not up-to-date), and teardown tasks run after execution. ```python DOIT_CONFIG = {'verbosity': 2, 'default_tasks': ['withenvX', 'withenvY']} def start(name): print("start %s" % name) def stop(name): print("stop %s" % name) def task_setup_sample(): for name in ('setupX', 'setupY'): yield {'name': name, 'actions': [(start, (name,))], 'teardown': [(stop, (name,))], } def task_withenvX(): for fin in ('a','b','c'): yield {'name': fin, 'actions':['echo x %s' % fin], 'setup': ['setup_sample:setupX'], } def task_withenvY(): return {'actions':['echo y'], 'setup': ['setup_sample:setupY'], } ``` -------------------------------- ### Development Environment Setup Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Installs doit in editable mode with development dependencies. Ensure you are in a virtual environment. ```bash python -m venv .venv source .venv/bin/activate pip install --editable . pip install --requirement dev_requirements.txt ``` -------------------------------- ### Run and Clean Tasks with doit Source: https://github.com/pydoit/doit/blob/master/README.rst This console example demonstrates how to install doit, run tasks, observe incremental execution (when tasks are up-to-date), and clean generated files. It shows the typical workflow for using doit. ```console $ pip install doit $ doit . hello . shout $ doit # nothing to do - already up-to-date -- hello -- shout $ doit clean # remove generated files $ doit # runs again . hello . shout ``` -------------------------------- ### Using doit as an executable file with a hashbang Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Example of a hashbang line for making a doit script executable, assuming doit is installed in /usr/bin. ```bash #! /usr/bin/doit -f ``` -------------------------------- ### Python Script with On-the-Fly doit Installation Source: https://github.com/pydoit/doit/wiki/Standalone-script-(install-doit-on-the-fly) This script checks if 'doit' is installed and installs it if not. It then runs the defined 'doit' tasks. ```python #!/usr/bin/python3 import sys def import_or_install(modname, pip_name=None): """Import or install a package and allow the PIP package name to be different from the module we attempt to import. """ if modname in sys.modules: return sys.modules[modname] from importlib import import_module mod = None try: mod = import_module(modname) except ImportError: print("Attempting to install %s on the fly." % (pip_name or modname), file=sys.stderr) cmdline = ["install", "--upgrade", "--user"] try: from pip._internal import main as pipmain cmdline.append(pip_name or modname) pipmain(cmdline) mod = import_module(modname) except ImportError as exc: print("Could not install %s on the fly." % (pip_name or modname), file=sys.stderr) raise exc from None if mod is not None: globals()[modname] = mod return mod def task_hello(): """hello""" def python_hello(targets): with open(targets[0], "a") as output: output.write("Python says Hello World!!!\n") return { "actions": [python_hello], "targets": ["hello.txt"], } if __name__ == "__main__": import_or_install("doit") doit.run(globals()) ``` -------------------------------- ### Install and Run doit Source: https://github.com/pydoit/doit/blob/master/pypi_long_description.rst Install doit using pip and execute it from the command line to run defined tasks. Subsequent runs will be faster if no changes are detected. ```console $ pip install doit $ doit . hello . shout $ doit # nothing to do - already up-to-date -- hello -- shout ``` -------------------------------- ### Install doit from source using pip Source: https://github.com/pydoit/doit/blob/master/doc/install.md Install doit from its source code using pip. This is useful for development or when needing the latest unreleased version. ```bash $ pip install -e . ``` -------------------------------- ### Example: Configuring 'list' command options in doit.cfg Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Customize options for the 'list' command by defining a [list] section in doit.cfg. This example enables 'status' and 'subtasks' display. ```ini [list] status = True subtasks = True ``` -------------------------------- ### Install doit Source: https://github.com/pydoit/doit/blob/master/doc/index.md Install the doit package using pip. ```bash pip install doit ``` -------------------------------- ### Install doit using pip Source: https://github.com/pydoit/doit/blob/master/doc/install.md Install the latest stable version of doit using pip. Requires Python 3.10+. ```bash $ pip install doit ``` -------------------------------- ### Example: Configuring 'list' command options in pyproject.toml Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Customize options for the 'list' command by creating a [tool.doit.commands.list] section. This example enables 'status' and 'subtasks' display. ```toml [tool.doit.commands.list] status = true subtasks = true ``` -------------------------------- ### doit Environment Setup Class Source: https://github.com/pydoit/doit/blob/master/doc/presentation.rst Defines a class to manage environment setup and cleanup for tasks. The setup and cleanup methods can be used to start/stop services or reset states. ```python ### task setup env. good for functional tests! class SetupSample(object): def __init__(self, server): self.server = server def setup(self): # start server pass def cleanup(self): # stop server pass ``` -------------------------------- ### Example: Configuring doit behavior in dodo.py Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Set global doit configuration options directly within the dodo.py file using the DOIT_CONFIG dictionary. This example sets default tasks, enables continue mode, and specifies a JSON reporter. ```python DOIT_CONFIG = {'default_tasks': ['my_task_1', 'my_task_2'], 'continue': True, 'reporter': 'json'} ``` -------------------------------- ### doit Task with Environment Setup Source: https://github.com/pydoit/doit/blob/master/doc/presentation.rst Defines tasks that utilize environment setup objects. 'task_withenvX' yields multiple tasks, each with a shared setup object. 'task_withenvY' defines a single task with its own setup object. ```python setupX = SetupSample('x') setupY = SetupSample('y') def task_withenvX(): for fin in ('a','b','c'): yield {'name': fin, 'actions':['echo x'], 'setup': setupX} def task_withenvY(): return {'actions': ['echo x'], 'setup': setupY} ``` -------------------------------- ### Doit Command Line: Help and List Source: https://github.com/pydoit/doit/blob/master/doc/tutorial-1.md Shows how to get help for doit commands and list all available tasks. Task descriptions are derived from docstrings. ```console $ doit help $ doit help run $ doit help task ``` ```console $ doit list dot generate a graphviz's dot graph from module imports draw generate image from a dot file imports find imports from a python module ``` -------------------------------- ### Build Website Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Builds the project's website, including analytics tracking. This task is run after installing doit. ```bash doit website ``` -------------------------------- ### Example: Setting DB backend in doit.cfg Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Configure the DB backend globally using the 'backend' option within the [GLOBAL] section of a doit.cfg file. This affects commands that utilize a backend. ```ini [GLOBAL] backend = json ``` -------------------------------- ### Configuring DB backend and dep file Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Example of a Python dictionary DOIT_CONFIG to set the 'json' backend and specify a custom 'dep_file' name. ```python DOIT_CONFIG = { 'backend': 'json', 'dep_file': 'doit-db.json', } ``` -------------------------------- ### Task Groups Example Source: https://github.com/pydoit/doit/blob/master/doc/dependencies.md Shows how to define a group of tasks by setting their actions to None and listing them as dependencies of a group task. ```python def task_foo(): return {'actions': ["echo foo"]} def task_bar(): return {'actions': ["echo bar"]} def task_mygroup(): return {'actions': None, 'task_dep': ['foo', 'bar']} ``` -------------------------------- ### Example: Setting DB backend in pyproject.toml Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Configure the DB backend for doit commands by specifying the 'backend' option under the [tool.doit] section. This setting applies globally to commands like run, clean, and forget. ```toml [tool.doit] backend = "json" ``` -------------------------------- ### Example: Configuring task options in doit.cfg Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Set specific options for a task named 'make_cookies' by using the [task:make_cookies] section in doit.cfg. This allows for task-specific parameterization. ```ini [task:make_cookies] cookie_type = chocolate temp = 375F duration = 12 ``` -------------------------------- ### Task Dependencies Example Source: https://github.com/pydoit/doit/blob/master/doc/dependencies.md Demonstrates how to define task dependencies to ensure tasks are executed in the correct order. 'task_tar' depends on 'task_version'. ```python def task_tar(): return {'actions': ["tar -cf foo.tar *"], 'task_dep':['version'], 'targets':['foo.tar']} def task_version(): return {'actions': ["hg tip --template '{rev}' > revision.txt'"]} ``` -------------------------------- ### Custom doit Command for Project Scaffolding Source: https://github.com/pydoit/doit/blob/master/doc/extending.md Create a custom command by subclassing doit.cmd_base.Command. This example demonstrates a basic 'Init' command for scaffolding new projects, with placeholder logic for file creation. ```python from doit.cmd_base import Command class Init(Command): doc_purpose = 'create a project scaffolding' doc_usage = '' doc_description = """This is a multiline command description. It will be displayed on `doit help init`""" def execute(self, opt_values, pos_args): print("TODO: create some files for my project") ``` -------------------------------- ### Task Execution Order Based on Dependencies Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This example demonstrates how doit ensures correct execution order when the output of one task is the input for another. 'task_create' produces 'foo.txt', which is then used by 'task_modify'. ```python def task_modify(): return {'actions': ["echo bar > foo.txt"], 'file_dep': ["foo.txt"], } def task_create(): return {'actions': ["touch foo.txt"], 'targets': ["foo.txt"] } ``` -------------------------------- ### Doit Execution Order Example Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md Illustrates the console output when doit executes tasks in the correct order based on their dependencies. 'create' runs before 'modify' because 'modify' depends on 'create's output. ```console $ doit . create . modify ``` -------------------------------- ### Install Required Python Packages Source: https://github.com/pydoit/doit/blob/master/doc/tutorial-1.md Installs the necessary Python packages: doit, pygraphviz, and import_deps. On some Linux systems, you may need to install the graphviz-dev system package first. ```console $ pip install doit pygraphviz import_deps ``` -------------------------------- ### Define a Command Action Task Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This example defines a task that executes a shell command. The command is provided as a string and will be run in a subprocess. ```python def task_hello(): """hello cmd """ msg = 3 * "hi! " return { 'actions': ['echo %s ' % msg], } ``` -------------------------------- ### Example: Configuring task options in pyproject.toml Source: https://github.com/pydoit/doit/blob/master/doc/configuration.md Set specific options for a task named 'make_cookies' within the [tool.doit.tasks.make_cookies] section. This allows for task-specific parameterization. ```toml [tool.doit.tasks.make_cookies] cookie_type = "chocolate" temp = "375F" duration = 12 ``` -------------------------------- ### doit Task Grouping Example Source: https://github.com/pydoit/doit/blob/master/doc/presentation.rst Defines tasks 'foo' and 'bar', and then creates a group task 'mygroup' that depends on both 'foo' and 'bar'. ```python def task_foo(): return {'actions': ["echo foo"]} def task_bar(): return {'actions': ["echo bar"]} def task_mygroup(): return {'actions': None, 'dependencies': [':foo', ':bar']} ``` -------------------------------- ### Configuring output buffering for CmdAction Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Example of creating a CmdAction with custom buffering set to 1 (line-buffered) for controlling output streams. ```python from doit.action import CmdAction def task_progress(): return { 'actions': [CmdAction("progress_bar", buffering=1)], } ``` -------------------------------- ### Profile Doit Execution Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Profiles the execution of the 'doit list' command to analyze performance. Requires 'gprof2dot' and 'graphviz' to be installed. ```bash python -m cProfile -o output.pstats `which doit` list gprof2dot -f pstats output.pstats | dot -Tpng -o output.png ``` -------------------------------- ### Make Task Definition Example Source: https://github.com/pydoit/doit/blob/master/doc/presentation.rst A basic Make rule defining a target, its dependencies, and the commands to execute. Used for compiling C code. ```make helloworld: helloworld.o cc -o $@ $< helloworld.o: helloworld.c cc -c -o $@ $< .PHONY: clean clean: rm -f helloworld helloworld.o ``` -------------------------------- ### Define a Task with a Callable Command String Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This example demonstrates using CmdAction to execute a command string returned by a callable function. It also shows how to set verbosity. ```python from doit.action import CmdAction def task_hello(): """hello cmd """ def create_cmd_string(): return "echo hi" return { 'actions': [CmdAction(create_cmd_string)], 'verbosity': 2, } ``` -------------------------------- ### IPython doit Magic Function Examples Source: https://github.com/pydoit/doit/blob/master/doc/tools.md Demonstrates basic usage of the `%doit` magic function in IPython for showing help, defining tasks, listing discovered tasks, and running tasks. ```pycon >>> %doit --help ## Show help for options and arguments. >>> def task_foo(): return {'actions': ["echo hi IPython"], 'verbosity': 2} >>> %doit list ## List any tasks discovered. foo >>> %doit ## Run any tasks. . foo hi IPython ``` -------------------------------- ### Get initial working directory Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Use doit.get_initial_workdir() to retrieve the directory from which doit was invoked. This is useful for dynamically setting default tasks or paths. ```default ### README # Sample to test doit.get_initial_workdir # First create a folder named 'sub1'. # Invoking doit from the root folder will execute both tasks 'base' and 'sub1'. # Invoking 'doit -k' from path 'sub1' will execute only task 'sub1' ################## import os import doit DOIT_CONFIG = { 'verbosity': 2, 'default_tasks': None, # all by default } ``` -------------------------------- ### Define a Python Action Task with Arguments Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This example shows how to pass arguments to a Python action function. The arguments are provided as a list for positional arguments and a dictionary for keyword arguments within the task definition. ```python def task_hello(): """hello py """ def python_hello(times, text, targets): with open(targets[0], "a") as output: output.write(times * text) return {'actions': [(python_hello, [3, "py!\n"])], 'targets': ["hello.txt"], } ``` -------------------------------- ### Create Sub-tasks Using a Generator Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This example shows how a task creator can yield dictionaries to generate multiple sub-tasks, each requiring a unique 'name' field. ```python def task_create_file(): for i in range(3): filename = "file%d.txt" % i yield {'name': filename, 'actions': ["touch %s" % filename]} ``` -------------------------------- ### Compiling Source Files with Pathlib Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md Utilize Python's pathlib module to dynamically define compilation tasks. This example uses Path.glob to find source and header files, generating object files and specifying dependencies. ```python from pathlib import Path def task_compile(): working_directory = Path('.') # Path.glob returns an iterator so turn it into a list headers = list(working_directory.glob('*.h')) for source_file in working_directory.glob('*.c'): object_file = source_file.with_suffix('.o') yield { 'name': object_file.name, 'actions': [['cc', '-c', source_file]], 'file_dep': [source_file] + headers, 'targets': [object_file], } ``` -------------------------------- ### Doit Command Line: Running Tasks Source: https://github.com/pydoit/doit/blob/master/doc/tutorial-1.md Demonstrates running specific tasks and observing dependency execution. When a task is run, its dependencies are also executed if they are not up-to-date. ```console $ doit -- imports -- dot . draw ``` ```console $ doit imports -- imports ``` ```console $ doit imports dot -- imports -- dot ``` ```console $ doit dot -- imports -- dot ``` -------------------------------- ### List All Tasks Source: https://github.com/pydoit/doit/blob/master/doc/cmd-other.md Use the 'list' command to display all available tasks and their descriptions. Options like '--sort=definition', '-q', '--all', '-p', and '--deps' can modify the output. ```console $ doit list compile : compile C files install : install executable (TODO) link : create binary program ``` -------------------------------- ### Clone doit git repository Source: https://github.com/pydoit/doit/blob/master/doc/install.md Get the latest development version of doit by cloning the official git repository. ```bash $ git clone https://github.com/pydoit/doit.git ``` -------------------------------- ### Making a dodo file executable via API Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Shows how to make a dodo file executable by calling doit.run() with globals, enabling it to be run directly. ```python #! /usr/bin/env python3 def task_echo(): return { 'actions': ['echo hi'], 'verbosity': 2, } if __name__ == '__main__': import doit doit.run(globals()) ``` -------------------------------- ### Get Task Status Source: https://github.com/pydoit/doit/blob/master/doc/cmd-other.md The '--status' option with the 'list' command shows if a task will run ('R'), is up-to-date ('U'), or is ignored ('I'). ```console $ doit list -s compile : R install : U link : I ``` -------------------------------- ### Configure Zsh Completion Script Source: https://github.com/pydoit/doit/blob/master/doc/cmd-other.md This demonstrates how to set up zsh completion for doit. It involves adding a directory to your fpath and then copying the generated completion script into that directory. ```sh # add folder with completion scripts fpath=(~/.zsh/tabcompletion $fpath) # Use modern completion system autoload -Uz compinit compinit ``` ```console $ doit tabcompletion --shell zsh > _doit $ cp _doit ~/.zsh/tabcompletion/_doit ``` -------------------------------- ### Task Expiration with Timeout Source: https://github.com/pydoit/doit/blob/master/doc/uptodate.md Utilize timeout to set an expiration for a task, ensuring it re-runs only after a specified interval. The example uses a 5-minute timeout. ```python import datetime from doit.tools import timeout def task_expire(): return { 'actions': ['echo test expire; date'], 'uptodate': [timeout(datetime.timedelta(minutes=5))], 'verbosity': 2, } ``` -------------------------------- ### Basic doit command structure Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Illustrates the general syntax for the doit command, including sub-commands, options, task selection, and variables. ```console $ doit [run] [] [ ]* [] ``` -------------------------------- ### Create a file 'foo' Source: https://github.com/pydoit/doit/blob/master/doc/uptodate.md This task creates a file named 'foo' and sets its permissions. It serves as a prerequisite for other tasks that depend on 'foo'. ```python from doit.tools import check_timestamp_unchanged def task_create_foo(): return { 'actions': ['touch foo', 'chmod 750 foo'], 'targets': ['foo'], 'uptodate': [True], } ``` -------------------------------- ### Build and Upload Release Packages Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Builds source and wheel distribution packages for release and uploads them to PyPI using twine. Ensure version numbers are updated in relevant files. ```bash python -m build twine upload dist/doit-X.Y.Z.tar.gz twine upload dist/doit-X.Y.Z-py3-none-any.whl ``` -------------------------------- ### Clone the Requests Project Source: https://github.com/pydoit/doit/blob/master/doc/tutorial-1.md Clones the 'requests' project into a 'projects' directory for analysis. This step sets up the sample project structure. ```console $ mkdir projects $ cd projects $ git clone git@github.com:requests/requests.git $ cd .. ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Generates HTML documentation from ReST sources using Sphinx. This command should be run from the 'doc' directory. ```bash make html ``` -------------------------------- ### Select Tasks from Command Line Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md Execute specific tasks by providing their names as positional arguments on the command line. Multiple tasks can be specified. ```console $ doit t2 ``` ```console $ doit task1 ``` -------------------------------- ### Specifying a custom dodo file Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Demonstrates how to use the '-f' flag to specify a dodo file other than the default 'dodo.py'. ```console $ doit -f release.py ``` -------------------------------- ### Executing doit without the script Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Shows how to run doit using 'python -m doit', which is useful for testing with different Python versions. ```console $ python -m doit ``` -------------------------------- ### Automate Project Actions with Doit Source: https://github.com/pydoit/doit/blob/master/doc/usecases.md Define multiple project-related tasks in a dodo.py file for automated linting, testing, documentation generation, and packaging. This provides a unified way to perform common development actions. ```console $ doit list coverage show coverage for all modules including tests coverage_module show coverage for individual modules coverage_src show coverage for all modules (exclude tests) package create/upload package to pypi pyflakes pypi create/upload package to pypi spell spell checker for doc files sphinx build sphinx docs tutorial_check check tutorial sample are at least runnable without error ut run unit-tests website dodo file create website html files website_update update website on SITE_PATH ``` ```console $ doit spell ``` -------------------------------- ### Task Creation and Cleanup with Dependency Manager Source: https://github.com/pydoit/doit/blob/master/doc/globals.md Demonstrates how to use the dependency manager to store and retrieve task-specific data between action execution and cleanup phases. The `dep_manager` is accessible within task creation functions and action/clean functions. ```python import doit DOIT_CONFIG = dict( verbosity=2, ) def task_create(): # dependency manager is defined for all code inside the generator: dep_manager = doit.Globals.dep_manager def action(): # assume some involved logic to define ident: ident = 42 print('Created', ident) # store for clean: return dict(created=ident) def clean(task): result = dep_manager.get_result(task.name) if result: ident = result['created'] print('Deleted', ident) # possibly forget the task, after it was cleaned: dep_manager.remove(task.name) return dict( actions=[action], clean=[clean], ) ``` -------------------------------- ### Custom Task Loader with Pre-defined Task Source: https://github.com/pydoit/doit/blob/master/doc/extending.md Subclass TaskLoader2 to create a custom loader that defines tasks using dictionaries. This example shows a loader with a single pre-defined task, bypassing the need for a dodo.py file. ```python #! /usr/bin/env python3 import sys from doit.task import dict_to_task from doit.cmd_base import TaskLoader2 from doit.doit_cmd import DoitMain my_builtin_task = { 'name': 'sample_task', 'actions': ['echo hello from built in'], 'doc': 'sample doc', } class MyLoader(TaskLoader2): def setup(self, opt_values): pass def load_doit_config(self): return {'verbosity': 2} def load_tasks(self, cmd, pos_args): task_list = [dict_to_task(my_builtin_task)] return task_list if __name__ == "__main__": sys.exit(DoitMain(MyLoader()).run(sys.argv[1:])) ``` -------------------------------- ### Define Basic Tasks in dodo.py Source: https://github.com/pydoit/doit/blob/master/README.rst This snippet shows how to define two basic tasks, 'hello' and 'shout', in a dodo.py file. The 'hello' task creates a file with a greeting, and 'shout' converts its content to uppercase. Both tasks specify actions, targets, and cleaning behavior. ```python def task_hello(): """create a greeting file""" return { 'actions': ['echo "Hello from doit" > hello.txt'], 'targets': ['hello.txt'], 'clean': True, } def task_shout(): """convert greeting to uppercase""" return { 'actions': ['tr a-z A-Z < hello.txt > shout.txt'], 'file_dep': ['hello.txt'], 'targets': ['shout.txt'], 'clean': True, } ``` -------------------------------- ### Update Website Content Source: https://github.com/pydoit/doit/blob/master/DEV-README.rst Builds the site and synchronizes it to a local directory for deployment. This task is part of the website deployment process. ```bash doit website_update ``` -------------------------------- ### Reset Task Dependencies Source: https://github.com/pydoit/doit/blob/master/doc/cmd-other.md This command recomputes and saves file dependency information (like timestamps or md5sums) in the database without executing task actions. It's useful when targets already exist, you change the 'check_file_uptodate' setting, or start using doit with pre-computed data. Use with caution if tasks rely on more than just file status for up-to-date checks. ```console $ doit reset-dep ``` -------------------------------- ### Configure Command Plugin in TOML Source: https://github.com/pydoit/doit/blob/master/doc/extending.md Enable a command plugin by specifying its entry point in the [tool.doit.plugins.command] section of pyproject.toml. The value is a string in the format :. ```toml [tool.doit.plugins.command] foo = "my_plugins:FooCmd" ``` -------------------------------- ### Doit Command Line: Info Command Source: https://github.com/pydoit/doit/blob/master/doc/tutorial-1.md The 'info' command provides detailed metadata and status for a specific task, including its dependencies and targets. ```console $ doit info imports imports find imports from a python module status : up-to-date file_dep : - projects/requests/src/requests/models.py targets : - requests.models.deps ``` -------------------------------- ### Generating multiple tasks with yield Source: https://github.com/pydoit/doit/blob/master/doc/cmd-other.md Demonstrates how to generate multiple tasks dynamically using a yield statement. ```python def task_create_file(): for i in range(3): filename = "file%d.txt" % i yield {'name': filename, 'actions': ["touch %s" % filename]} ``` -------------------------------- ### Create Folder if Not Exists Source: https://github.com/pydoit/doit/blob/master/doc/tools.md Use `create_folder` to ensure a directory exists before performing actions that depend on it. It wraps `os.makedirs()`. ```default from doit.tools import create_folder BUILD_PATH = "_build" def task_build(): return {'actions': [(create_folder, [BUILD_PATH]), 'touch %(targets)s'], 'targets': ["%s/file.o" % BUILD_PATH] } ``` -------------------------------- ### Define a Python Task with a Simple Command Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md This snippet shows how to define a basic task that executes a command-line program. The command is provided as a list of strings. ```python def task_python_version(): return { 'actions': [['python', '--version']] } ``` -------------------------------- ### Task Creator with Parameters Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Demonstrates how to define parameters for a task creator function using the `@task_params` decorator. These parameters are used to generate subtasks. ```python from doit import task_params @task_params([{"name": "howmany", "default": 3, "type": int, "long": "howmany"}]) def task_subtasks(howmany): for i in range(howmany): yield {"name": i, "actions": [f"echo I can count to {howmany}: {i}"]} ``` -------------------------------- ### Dynamic Dependency Calculation with calculated-dependencies Source: https://github.com/pydoit/doit/blob/master/doc/dependencies.md Demonstrates how to use 'calc_dep' to delegate the calculation of dependencies to another task. The task calculating dependencies must return a dictionary containing dependency information. ```python DOIT_CONFIG = {'verbosity': 2} MOD_IMPORTS = {'a': ['b','c'], 'b': ['f','g'], 'c': [], 'f': ['a'], 'g': []} def print_deps(mod, dependencies): print("%s -> %s" % (mod, dependencies)) def task_mod_deps(): """task that depends on all direct imports""" for mod in MOD_IMPORTS.keys(): yield {'name': mod, 'actions': [(print_deps,(mod,))], 'file_dep': [mod], 'calc_dep': ["get_dep:%s" % mod], } def get_dep(mod): # fake implementation return {'file_dep': MOD_IMPORTS[mod]} def task_get_dep(): """get direct dependencies for each module""" for mod in MOD_IMPORTS.keys(): yield {'name': mod, 'actions':[(get_dep,[mod])], 'file_dep': [mod], } ``` -------------------------------- ### Configure Custom Loader in doit.cfg Source: https://github.com/pydoit/doit/blob/master/doc/extending.md Set up a custom loader and its corresponding plugin in the GLOBAL and LOADER sections of your doit.cfg file. ```ini [GLOBAL] loader = my_loader [LOADER] my_loader = my_plugins:MyLoader ``` -------------------------------- ### Execute Python Task with Parameters Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Demonstrates executing the 'py_params' task with custom values for 'param1' ('abc') and 'param2' (4) via the command line, overriding their default values. ```console $ doit py_params -p abc --param2 4 . py_params abc 9 ``` -------------------------------- ### doit Task Definitions: Download and ShrinkSafe Source: https://github.com/pydoit/doit/blob/master/doc/presentation.rst Defines tasks to download a JAR file using wget and then use it to compress a JavaScript file. Includes dependencies on the downloaded JAR. ```python URL = "http://svn.dojotoolkit.org/src/util/trunk/shrinksafe/shrinksafe.jar" shrinksafe = "shrinksafe.jar" jsFile = "file1.js" compFile = "compressed1.js" def task_shrink(): return {'actions': ['java -jar %s %s > %s'% (shrinksafe, jsFile, compFile)], 'dependencies': [shrinksafe] } def task_get_shrinksafe(): return {'actions': ["wget %s"% URL], 'targets': [shrinksafe], 'dependencies': [True] } ``` -------------------------------- ### Execute Command-Line Task with Parameter Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Demonstrates executing the 'cmd_params' task and passing a complex string value to the 'flag' parameter using the '-f' flag. ```console $ doit cmd_params -f "-c --other value" . cmd_params mycmd -c --other value xxx ``` -------------------------------- ### Listing Imported Tasks Source: https://github.com/pydoit/doit/blob/master/doc/task-creation.md After importing tasks, you can list them using the 'doit list' command. This confirms that the tasks from imported modules are recognized and available. ```console $ doit list echo hello sample ``` -------------------------------- ### Task with Command Line Variables Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Illustrates how to access variables passed from the command line using `doit.get_var`. These variables can be used to configure tasks or dodo.py itself. ```python from doit import get_var config = {"abc": get_var('abc', 'NO')} def task_echo(): return {'actions': ['echo hi %s' % config], 'verbosity': 2, } ``` ```console $ doit . echo hi {abc: NO} ``` ```console $ doit abc=xyz x=3 . echo hi {abc: xyz} ``` -------------------------------- ### Execute Python Task with Choice Parameter Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Demonstrates executing the 'py_params_choice' task and selecting 'that' for the 'choice' parameter using the '-c' flag. ```console $ doit py_params_choice -c that . py_params_choice that ``` -------------------------------- ### Configure Command Plugin in INI Source: https://github.com/pydoit/doit/blob/master/doc/extending.md Enable a command plugin by specifying its entry point in the [COMMAND] section of doit.cfg. The value is a string in the format :. ```ini [COMMAND] foo = my_plugins:FooCmd ``` -------------------------------- ### Select Tasks Using Wildcards Source: https://github.com/pydoit/doit/blob/master/doc/tasks.md Utilize glob-like syntax with a wildcard (*) on the command line to select multiple tasks that match a pattern. Ensure the pattern is quoted to prevent shell expansion. ```console $ doit "create_file:file*" ``` -------------------------------- ### Run Once Task for Downloads Source: https://github.com/pydoit/doit/blob/master/doc/uptodate.md Employ run_once to ensure a task executes only on its first successful run, ideal for one-time downloads. The task re-runs if the target file is removed. ```python from doit.tools import run_once def task_get_pylogo(): url = "http://python.org/images/python-logo.gif" return {'actions': ["wget %s" % url], 'targets': ["python-logo.gif"], 'uptodate': [run_once] } ``` -------------------------------- ### Continuing execution after task failure Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Demonstrates how to use the --continue or -c option to force doit to continue executing tasks even after a failure. ```console $ doit --continue ``` -------------------------------- ### Execute Python Task with List Parameter Source: https://github.com/pydoit/doit/blob/master/doc/task-args.md Demonstrates executing the 'py_params_list' task and providing multiple values ('milk', 'eggs', 'bread') for the 'list' parameter using the '-l' flag. ```console $ doit py_params_list -l milk -l eggs -l bread . py_params_list milk eggs bread ``` -------------------------------- ### Output results to a file Source: https://github.com/pydoit/doit/blob/master/doc/cmd-run.md Use the --output-file or -o option to redirect the command's output to a specified file. ```console $ doit --output-file result.txt ```