### Install Frontend Libraries Source: https://github.com/inventree/plugin-creator/blob/main/plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/README.md Installs the necessary frontend libraries for the plugin. Run this command in the `frontend` directory. ```bash npm install ``` -------------------------------- ### Conditional Frontend Setup Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Create plugins with or without frontend components based on configuration. This example shows how to disable frontend entirely or enable a minimal version with specific features. ```python from plugin_creator.cli import default_values, cleanup from plugin_creator.frontend import define_frontend, update_frontend from cookiecutter.main import cookiecutter import os def create_plugin_without_frontend(): """Create plugin without frontend components.""" context = default_values() context['plugin_mixins']['mixin_list'].remove('UserInterfaceMixin') context['frontend'] = define_frontend(enabled=False) # Generate src_path = 'plugin_creator/template' output_dir = '/tmp/plugins' cookiecutter(src_path, no_input=True, output_dir=output_dir, extra_context=context) # Cleanup (removes frontend entirely) plugin_path = os.path.join(output_dir, context['plugin_name']) cleanup(plugin_path, context) return plugin_path def create_plugin_with_minimal_frontend(): """Create plugin with only dashboard and settings features.""" context = default_values() context['frontend'] = define_frontend(enabled=True, defaults=True) # Disable some features context['frontend']['features']['panel'] = False context['frontend']['features']['spotlight'] = False context['frontend']['translation'] = False # Generate and cleanup plugin_path = create_and_cleanup(context) return plugin_path ``` -------------------------------- ### Automated CI/CD Setup Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Automatically create plugins with specific CI/CD configuration by passing the desired CI system to a helper function. This example generates plugins for GitHub, GitLab, and no CI. ```python from plugin_creator.cli import default_values, cleanup from plugin_creator.devops import cleanup_devops_files from cookiecutter.main import cookiecutter import os def create_plugin_with_ci(ci_system='github'): """Create plugin with specific CI/CD configuration.""" context = default_values() context['ci_support'] = ci_system # 'github', 'gitlab', or 'none' # Generate plugin src_path = 'plugin_creator/template' output_dir = '/tmp/plugins' cookiecutter( src_path, no_input=True, output_dir=output_dir, extra_context=context, ) # Cleanup files plugin_path = os.path.join(output_dir, context['plugin_name']) cleanup_devops_files(ci_system, plugin_path) return plugin_path # Create plugins for different CI systems github_plugin = create_plugin_with_ci('github') gitlab_plugin = create_plugin_with_ci('gitlab') no_ci_plugin = create_plugin_with_ci('none') ``` -------------------------------- ### Install and Build Frontend Code for UI Plugins Source: https://github.com/inventree/plugin-creator/blob/main/README.md For plugins with frontend features, navigate to the frontend directory, install dependencies, and build the code. This must be done before packaging the plugin. ```bash cd /frontend npm install npm run build ``` -------------------------------- ### Naming Convention Examples Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/types.md Illustrates how plugin names are derived through various stages, from user input to distribution name. ```text Stage | Example Value | Rules |-------|---------------|-------| | User input (plugin_title) | "My Custom Plugin" | Human-readable, max 50 chars, alphanumeric + spaces, no Python keywords | | plugin_name | "MyCustomPlugin" | Spaces removed, used as Python class name | | plugin_slug | "my-custom-plugin" | Lowercase, hyphens instead of spaces, URL-safe | | package_name | "my_custom_plugin" | Underscores instead of hyphens, Python import-safe | | distribution_name | "inventree-my-custom-plugin" | Prefixed with "inventree-" (if not already), matches package_name but with hyphens ``` -------------------------------- ### Example Plugin View Mixin Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/mixins.md Demonstrates a basic mixin for creating plugin views. This example shows how to extend the base mixin to add custom view logic. ```python class MyPluginViewMixin(BaseViewMixin): """A basic mixin for plugin views.""" def get_context_data(self, **kwargs) -> dict: """Get context data for the view.""" context = super().get_context_data(**kwargs) context['my_custom_data'] = 'Hello from MyPluginViewMixin!' return context def get_template_names(self) -> list[str]: """Get template names for the view.""" return ['my_plugin/my_template.html'] ``` -------------------------------- ### Install Plugin via Pip Source: https://github.com/inventree/plugin-creator/blob/main/plugin_creator/template/{{ cookiecutter.plugin_name }}/README.md Use this command to install the plugin manually from the command line. ```bash pip install inventree-{{ cookiecutter.plugin_slug }} ``` -------------------------------- ### Initialize Git Repository and Pre-commit Hooks Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/devops.md Initializes a new Git repository in the specified plugin directory and installs pre-commit hooks. This function executes `git init`, `pip install pre-commit`, and `pre-commit install` commands. It will raise a `subprocess.CalledProcessError` if any of these commands fail. ```python import subprocess from plugin_creator.devops import git_init plugin_dir = '/path/to/generated/plugin' try: git_init(plugin_dir) except subprocess.CalledProcessError as e: print(f'Failed to initialize git: {e}') ``` -------------------------------- ### Python ProjectNameValidator Usage Example Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/validators.md Shows how to use the ProjectNameValidator with a questionary text prompt for entering a plugin name. Includes examples of valid and invalid inputs based on the defined rules. ```python from plugin_creator.validators import ProjectNameValidator import questionary validator = ProjectNameValidator() name = questionary.text( 'Enter plugin name', default='My Plugin', validate=validator ).ask() # Valid: "My Plugin", "MyPlugin", "_Plugin", "Plugin1" # Invalid: "", "class", "123Plugin", "My-Plugin", "My.Plugin" ``` -------------------------------- ### Combine CLI Arguments Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Use multiple command-line arguments together to configure plugin creation. This example uses defaults and specifies an output directory. ```bash $ create-inventree-plugin --default --output /tmp/plugins ``` -------------------------------- ### Install InvenTree Plugin Creator Source: https://github.com/inventree/plugin-creator/blob/main/README.md Install the plugin creator tool using pip. This command ensures you have the latest version. ```bash pip install -U inventree-plugin-creator ``` -------------------------------- ### Programmatic Plugin Creation Setup Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/README.md This Python snippet demonstrates how to load default values, merge with user configuration, and gather necessary information programmatically for plugin creation. ```python from plugin_creator.cli import main, default_values, gather_info from plugin_creator.config import load_config, save_config from plugin_creator.mixins import get_mixins from plugin_creator.devops import get_devops_mode # Load defaults and user config context = default_values() context.update(load_config()) # Gather user input context = gather_info(context) # Save config for next time save_config(context) ``` -------------------------------- ### Create a New InvenTree Plugin Source: https://github.com/inventree/plugin-creator/blob/main/README.md Run this command to start the plugin creation process. It will prompt for necessary information. ```bash create-inventree-plugin ``` -------------------------------- ### Command-Line Usage Examples Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/overview.md Demonstrates various ways to invoke the create-inventree-plugin command, including interactive mode, using defaults, specifying an output directory, and displaying the version. ```bash # Interactive mode create-inventree-plugin ``` ```bash # Non-interactive with defaults create-inventree-plugin --default ``` ```bash # Custom output directory create-inventree-plugin --output /path/to/plugins ``` ```bash # Display version create-inventree-plugin --version ``` -------------------------------- ### Create Plugin Interactively (CLI) Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Use the command-line tool and respond to prompts to create a new plugin. This method guides you through all necessary configuration steps. ```bash $ create-inventree-plugin InvenTree Plugin Creator Tool Enter project information: Enter plugin name: My Custom Plugin Enter plugin description: A plugin for custom functionality Author name: John Doe Author email: john@example.com Project URL: https://github.com/johndoe/my-plugin Select a license: MIT Select plugin mixins: [X] SettingsMixin [X] UserInterfaceMixin [X] ReportMixin Select frontend features to enable: [X] Custom dashboard items [X] Custom panel items Enable translation support? [Y/n]: y Enable Git integration? [Y/n]: y DevOps support (CI/CD)?: GitHub Actions - output: /current/directory/MyCustomPlugin Git repository initialized and pre-commit hooks installed. Plugin created -> '/current/directory/MyCustomPlugin' ``` -------------------------------- ### Python NotEmptyValidator Usage Example Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/validators.md Demonstrates how to instantiate and use the NotEmptyValidator with a questionary text prompt. Ensures the user provides some input. ```python from plugin_creator.validators import NotEmptyValidator import questionary validator = NotEmptyValidator() text = questionary.text( 'Enter something', validate=validator ).ask() ``` -------------------------------- ### Create Plugin with Defaults (CLI) Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Generate a plugin using all default values specified in the configuration. This is useful for quick setup without manual input. ```bash $ create-inventree-plugin --default InvenTree Plugin Creator Tool - Using default values for all prompts - output: /current/directory/MyCustomPlugin Plugin created -> '/current/directory/MyCustomPlugin' ``` -------------------------------- ### Initialize Git Repository and Hooks Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Programmatically initialize a Git repository in a specified plugin directory and install pre-commit hooks. Includes error handling for potential subprocess failures. ```python from plugin_creator.devops import git_init import subprocess plugin_dir = '/path/to/generated/plugin' try: git_init(plugin_dir) # Creates .git directory with main branch # Installs pre-commit hooks except subprocess.CalledProcessError as e: print(f'Git initialization failed: {e}') print(f'Command: {e.cmd}') print(f'Return code: {e.returncode}') ``` -------------------------------- ### plugin_creator.devops Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Handles DevOps related functionalities such as Git initialization and CI/CD pipeline setup. ```APIDOC ## get_devops_options ### Description List available CI/CD options. ### Signature `() -> list` ## get_devops_mode ### Description Prompt for CI/CD selection. ### Signature `() -> str` ## cleanup_devops_files ### Description Remove unneeded CI/CD files. ### Signature `(devops_mode: str, plugin_dir: str) -> None` ## git_init ### Description Init git repo and pre-commit hooks. ### Signature `(plugin_dir: str) -> None` ``` -------------------------------- ### Run Inventree Plugin Creator CLI Interactively Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/README.md Use this command to start the plugin creation process in interactive mode, where you will be prompted for necessary information. ```bash # Interactive mode create-inventree-plugin ``` -------------------------------- ### Basic Programmatic Plugin Creation Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Programmatically create a plugin using default settings and user input gathering. This example shows the core steps involved in the CLI's main function. ```python from plugin_creator.cli import main, default_values, gather_info, cleanup from plugin_creator.config import load_config, save_config from plugin_creator.helpers import info, success import os import json # Load defaults and existing config context = default_values() context.update(load_config()) # Gather user input (or use the context as-is for non-interactive) context = gather_info(context) # Save config for next time save_config(context) # Run cookiecutter (simplified example - actual implementation uses cookiecutter.main) # ... template rendering happens here ... # Perform cleanup plugin_dir = '/path/to/generated/plugin' cleanup(plugin_dir, context) success(f'Plugin created at {plugin_dir}') ``` -------------------------------- ### Get Default Plugin Creation Values Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/cli.md Retrieves default configuration values for plugin creation from the cookiecutter template. Use this to get a base dictionary of settings before user interaction. ```python from plugin_creator.cli import default_values defaults = default_values() print(defaults['plugin_title']) # "My Custom Plugin" ``` -------------------------------- ### Run Frontend Development Server Source: https://github.com/inventree/plugin-creator/blob/main/plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/README.md Starts a development server with automatic reloading for frontend code changes. Requires the InvenTree frontend dev server to also be running. ```bash npm run dev ``` -------------------------------- ### Batch Plugin Creation Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Create multiple plugins with different configurations by iterating over a list of plugin definitions. This example uses cookiecutter to generate plugins based on a template and custom context. ```python from plugin_creator.cli import default_values, cleanup from plugin_creator.config import load_config, save_config from cookiecutter.main import cookiecutter import os plugins = [ { 'title': 'API Plugin', 'description': 'External API integration', 'author': 'Team A', }, { 'title': 'Report Plugin', 'description': 'Advanced reporting', 'author': 'Team B', }, ] output_dir = '/tmp/plugin-batch' for plugin in plugins: # Create context context = default_values() context.update(load_config()) context['plugin_title'] = plugin['title'] context['plugin_description'] = plugin['description'] context['author_name'] = plugin['author'] context['plugin_name'] = plugin['title'].replace(' ', '') context['package_name'] = plugin['title'].lower().replace(' ', '_') # Save and generate save_config(context) src_path = 'plugin_creator/template' # Path to cookiecutter template cookiecutter( src_path, no_input=True, output_dir=output_dir, extra_context=context, ) # Cleanup plugin_path = os.path.join(output_dir, context['plugin_name']) cleanup(plugin_path, context) ``` -------------------------------- ### Show Inventree Plugin Creator CLI Version Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/README.md Display the installed version of the Inventree Plugin Creator using the --version flag. ```bash # Show version create-inventree-plugin --version ``` -------------------------------- ### Typical Developer Workflow Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md This bash script outlines the standard steps for developing an Inventree plugin. It covers interactive creation, directory navigation, frontend building, installation, testing, and version control operations. ```bash # 1. Create plugin interactively $ create-inventree-plugin --output ~/plugins # 2. Navigate to plugin directory $ cd ~/plugins/MyPlugin # 3. Build frontend (if enabled) $ cd frontend $ npm install $ npm run build $ cd .. # 4. Install in development mode $ pip install -e . # 5. Run tests $ pytest # 6. Push to repository $ git add . $ git commit -m "Initial plugin structure" $ git push origin main ``` -------------------------------- ### Get All Frontend Features Enabled Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Returns a dictionary with all frontend features set to True. Use this to ensure all features are enabled by default. ```python from plugin_creator.frontend import all_features features = all_features() # {'dashboard': True, 'panel': True, 'settings': True, 'spotlight': True} ``` -------------------------------- ### Get Plugin Creator Config File Path Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Returns the full path to the main configuration file (config.json). Use this to directly access or reference the configuration file. ```python from plugin_creator.config import config_file config_path = config_file() print(config_path) # e.g., '/home/user/.config/inventree-plugin-creator/config.json' ``` -------------------------------- ### Get Available DevOps Options Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/devops.md Retrieves a list of supported DevOps and CI/CD options for plugin configuration. Use this to display available choices to the user. ```python from plugin_creator.devops import get_devops_options options = get_devops_options() print(options) # ['None', 'GitHub Actions', 'GitLab CI/CD'] ``` -------------------------------- ### Get Frontend Feature Descriptions Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Retrieves a dictionary mapping frontend feature keys to their human-readable descriptions. Useful for displaying available features to the user. ```python from plugin_creator.frontend import frontend_features features = frontend_features() print(features['dashboard']) # "Custom dashboard items" print(features.keys()) # dict_keys(['dashboard', 'panel', 'settings', 'spotlight']) ``` -------------------------------- ### Handle DevOps Configuration Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Display available CI/CD systems (None, GitHub Actions, GitLab CI/CD), get the user's selection, and provide a function to clean up unneeded DevOps files based on the selected mode. ```python from plugin_creator.devops import ( get_devops_options, get_devops_mode, cleanup_devops_files ) # Show available options options = get_devops_options() print("Available CI/CD systems:") for option in options: print(f" - {option}") # Output: None, GitHub Actions, GitLab CI/CD # Get user selection mode = get_devops_mode() print(f"Selected: {mode}") # Returns: 'none', 'github', or 'gitlab' # Later, clean up unneeded files plugin_dir = '/path/to/generated/plugin' cleanup_devops_files(mode, plugin_dir) # Removes .github/ if not 'github' # Removes .gitlab-ci.yml if not 'gitlab' ``` -------------------------------- ### Handling File System Errors Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Catch and handle file operation failures during plugin cleanup. This example demonstrates how to manage `PermissionError` and general `OSError` exceptions. ```python from plugin_creator.cli import cleanup from plugin_creator.helpers import error import os plugin_dir = '/path/to/plugin' context = { 'frontend': {'enabled': True}, 'ci_support': 'github', 'git_support': True, 'plugin_mixins': {'mixin_list': ['SettingsMixin']}, } try: cleanup(plugin_dir, context) except PermissionError: error(f'Permission denied: cannot write to {plugin_dir}', exit=True) except OSError as e: error(f'File system error: {e}', exit=True) ``` -------------------------------- ### Get Plugin Creator Config Directory Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Returns the platform-specific directory path where plugin creator configuration is stored. This is useful for locating or creating configuration files. ```python from plugin_creator.config import config_dir config_location = config_dir() print(config_location) # e.g., '/home/user/.config/inventree-plugin-creator' ``` -------------------------------- ### Execute package entry point Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Demonstrates how to run the plugin creator package from the command line using its entry point. ```bash create-inventree-plugin # Calls plugin_creator.cli:main ``` -------------------------------- ### View Plugin Creator Options Source: https://github.com/inventree/plugin-creator/blob/main/README.md Use the --help flag to see all available command-line options for the plugin creator. ```bash create-inventree-plugin --help ``` -------------------------------- ### Configure Frontend Options Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Programmatically define frontend settings, including enabling it with all features, allowing user selection, or disabling it entirely. Also shows how to check available features. ```python from plugin_creator.frontend import ( define_frontend, frontend_features, all_features, no_features ) # Enable frontend with all features frontend_config = define_frontend(enabled=True, defaults=True) # Returns: all libraries and all features enabled # Enable frontend but let user select features frontend_config = define_frontend(enabled=True, defaults=False) # User is prompted for feature selection and translation # Disable frontend entirely frontend_config = define_frontend(enabled=False) # Returns: all features disabled, frontend.enabled=False # Check available features print(frontend_features()) # Shows all feature keys and descriptions ``` -------------------------------- ### Get All Frontend Features Disabled Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Returns a dictionary with all frontend features set to False. Use this to ensure all features are disabled by default. ```python from plugin_creator.frontend import no_features features = no_features() # {'dashboard': False, 'panel': False, 'settings': False, 'spotlight': False} ``` -------------------------------- ### git_init Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/devops.md Initializes a new git repository in the specified plugin directory and sets up pre-commit hooks. ```APIDOC ## git_init ### Description Initializes a git repository in the plugin directory and installs pre-commit hooks. ### Method POST (or equivalent for SDK, as it performs an action) ### Endpoint /git/init ### Parameters #### Query Parameters - **plugin_dir** (str) - Required - Absolute path to the generated plugin directory where git repository will be initialized. ### Response #### Success Response (200) (No content returned, operation is performed) ### Response Example (No response body for success) ### Error Handling - **subprocess.CalledProcessError**: If any subprocess command fails (git init, pip install, pre-commit install). ``` -------------------------------- ### Get Available Mixin Classes Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/mixins.md Retrieves a list of all available mixin classes that can be included in a plugin. This is useful for displaying options to the user or for introspection. ```python from plugin_creator.mixins import available_mixins mixins = available_mixins() print(mixins) # ['AppMixin', 'CurrencyExchangeMixin', 'EventMixin', ...] ``` -------------------------------- ### Get Persisted Config Keys Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Retrieves the list of configuration keys that are actively saved and loaded from the configuration file. Only these keys are considered persistent. ```python from plugin_creator.config import config_keys keys = config_keys() print(keys) # ['author_name', 'author_email', 'license_key', 'ci_support'] ``` -------------------------------- ### Get Selected DevOps Mode Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/devops.md Prompts the user to interactively select a DevOps mode. The function normalizes the selection to a lowercase string representing the mode. ```python from plugin_creator.devops import get_devops_mode mode = get_devops_mode() # User selects from: None, GitHub Actions, GitLab CI/CD # Returns: 'none', 'github', or 'gitlab' print(mode) ``` -------------------------------- ### CLI Entry Point Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Defines the entry point for the create-inventree-plugin command-line script. ```python console_scripts: create-inventree-plugin = plugin_creator.cli:main ``` -------------------------------- ### Load and Modify Configuration Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Load existing configuration, print its values, modify specific settings, and save the updated configuration. ```python config = load_config() print(f"Author: {config.get('author_name')}") # "John Doe" print(f"Email: {config.get('author_email')}") # "john@example.com" print(f"License: {config.get('license_key')}") # "MIT" # Modify configuration config['author_email'] = 'newemail@example.com' config['license_key'] = 'Apache-2.0' config['ci_support'] = 'gitlab' # Save modified configuration save_config(config) ``` -------------------------------- ### Specify Output Directory (CLI) Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Create a plugin in a custom directory by using the --output argument. The plugin will be generated within the specified path. ```bash $ create-inventree-plugin --output /home/projects/plugins InvenTree Plugin Creator Tool [...prompts...] - output: /home/projects/plugins/MyCustomPlugin Plugin created -> '/home/projects/plugins/MyCustomPlugin' ``` -------------------------------- ### Run InvenTree Plugin Scaffolding Tool Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/overview.md This is the main entry point for the InvenTree Plugin Creator CLI. It orchestrates the interactive plugin scaffolding process. ```python from plugin_creator.cli import main main() # Runs the interactive plugin scaffolding tool ``` -------------------------------- ### Run Frontend Translations Source: https://github.com/inventree/plugin-creator/blob/main/plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/README.md Generates or updates translation files if translation support is enabled. Execute this command within the `frontend` directory. ```bash npm run translate ``` -------------------------------- ### Gather Plugin Information Interactively Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/cli.md Prompts the user for plugin details and validates inputs to generate naming conventions. Pass a context dictionary with default values to pre-fill prompts. ```python from plugin_creator.cli import gather_info context = { 'plugin_title': 'Default Plugin', 'plugin_description': 'A plugin', 'author_name': 'Jane Doe', 'author_email': 'jane@example.com', 'project_url': 'https://example.com', 'git_support': True, 'license_key': 'MIT' } result = gather_info(context) # User is prompted interactively for information # Returns updated context with user input ``` -------------------------------- ### Handling Validation Errors Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Gracefully handle user input validation failures during plugin creation. This example uses a try-except block to catch potential errors during the `gather_info` process. ```python from plugin_creator.cli import gather_info from plugin_creator.helpers import error context = { 'plugin_title': 'My Plugin', 'plugin_description': '', # Will fail validation # ... other fields ... } try: context = gather_info(context) except KeyboardInterrupt: error('Plugin creation cancelled by user', exit=True) except Exception as e: error(f'Unexpected error during input: {e}', exit=True) ``` -------------------------------- ### Import a single function from cli Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Demonstrates how to import and call a single function from the cli module. ```python from plugin_creator.cli import main main() ``` -------------------------------- ### Load Plugin Creator Configuration Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Loads configuration settings from the JSON file. Creates the config directory if it doesn't exist and returns an empty dictionary if the file is not found or contains no recognized keys. ```python from plugin_creator.config import load_config config = load_config() print(config.get('author_name')) # e.g., 'John Doe' print(config.get('author_email')) # e.g., 'john@example.com' ``` -------------------------------- ### Handle CalledProcessError during Git Initialization Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/errors.md This snippet demonstrates how to catch and handle `subprocess.CalledProcessError` which can occur during git initialization or pre-commit setup. It prints detailed error information if the process fails. ```python from plugin_creator.devops import git_init import subprocess try: git_init('/path/to/plugin') except subprocess.CalledProcessError as e: print(f'Failed to initialize git: {e}') print(f'Return code: {e.returncode}') print(f'Command: {e.cmd}') ``` -------------------------------- ### Select Mixins for Plugin Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Display available mixins and allow the user to select which ones to enable for the plugin. The selection is then used in the plugin's context. ```python from plugin_creator.mixins import get_mixins, available_mixins # Show available mixins print("Available mixins:") for mixin in available_mixins(): print(f" - {mixin}") # Get user selection selected_mixins = get_mixins() print(f"Selected mixins: {selected_mixins}") # Use in context context = { 'plugin_mixins': {'mixin_list': selected_mixins}, # ... other context keys ... } ``` -------------------------------- ### load_config Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Loads the plugin creator configuration from disk. If the configuration file does not exist, it returns an empty dictionary. The configuration directory is created if it does not exist. ```APIDOC ## load_config ### Description Loads the plugin creator configuration from disk. Creates the config directory if it does not exist. Returns an empty dictionary if the config file does not exist. ### Returns - `dict`: Dictionary containing configuration values from the config file. Only includes keys returned by `config_keys()`. Empty dictionary if file does not exist or no recognized keys are found. ### Behavior 1. Creates config directory using `os.makedirs()` with `exist_ok=True` 2. Checks if config file exists 3. If file exists, reads JSON and extracts keys from `config_keys()` 4. Returns filtered dictionary with only recognized keys ### Example ```python from plugin_creator.config import load_config config = load_config() print(config.get('author_name')) # e.g., 'John Doe' print(config.get('author_email')) # e.g., 'john@example.com' ``` ``` -------------------------------- ### Validate Plugin Names Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Use ProjectNameValidator to check if plugin names are valid according to defined rules, such as avoiding reserved keywords, starting with numbers, or containing hyphens. Handles ValidationError for invalid names. ```python from plugin_creator.validators import ProjectNameValidator from questionary import ValidationError validator = ProjectNameValidator() # Create a mock document for testing class Document: def __init__(self, text): self.text = text test_names = [ 'My Plugin', # Valid 'MyPlugin', # Valid 'My_Plugin', # Valid '_Plugin', # Valid 'class', # Invalid - reserved keyword '123Plugin', # Invalid - starts with number 'My-Plugin', # Invalid - contains hyphen ] for name in test_names: doc = Document(name) try: validator.validate(doc) print(f"✓ '{name}' is valid") except ValidationError as e: print(f"✗ '{name}': {e.message}") ``` -------------------------------- ### Manual Context Building for Programmatic Creation Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md Manually construct the context dictionary for full control over plugin generation parameters. This bypasses interactive prompts and default loading. ```python from plugin_creator.frontend import define_frontend, all_features from plugin_creator.mixins import available_mixins from plugin_creator.devops import get_devops_options # Build custom context context = { 'plugin_title': 'API Integration Plugin', 'plugin_name': 'APIIntegrationPlugin', 'plugin_slug': 'api-integration-plugin', 'package_name': 'api_integration_plugin', 'distribution_name': 'inventree-api-integration-plugin', 'plugin_description': 'Integrate external APIs with InvenTree', 'plugin_version': '1.0.0', 'author_name': 'Developer Team', 'author_email': 'dev@company.com', 'project_url': 'https://github.com/company/inventree-api-plugin', 'license_key': 'Apache-2.0', 'plugin_mixins': {'mixin_list': ['UrlsMixin', 'SettingsMixin']}, 'frontend': define_frontend(enabled=False), # No UI 'git_support': True, 'ci_support': 'github' } # Use context with cookiecutter... ``` -------------------------------- ### DevOps Options Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/types.md Lists available DevOps and CI/CD systems supported by the plugin creator. ```python ['None', 'GitHub Actions', 'GitLab CI/CD'] ``` -------------------------------- ### Handling Validation in Prompts with Questionary Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/errors.md This example shows how the questionary library automatically handles validation errors for user input. The `ProjectNameValidator` ensures that the entered plugin name meets specific criteria, and the prompt automatically re-prompts the user upon validation failure. ```python from plugin_creator.validators import ProjectNameValidator import questionary name = questionary.text( 'Enter plugin name', validate=ProjectNameValidator ).ask() # User sees error message if validation fails # Prompt repeats until valid input provided ``` -------------------------------- ### Run Inventree Plugin Creator CLI with Defaults Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/README.md Execute the CLI with the --default flag to use all default values and skip interactive prompts. ```bash # Non-interactive with defaults create-inventree-plugin --default ``` -------------------------------- ### plugin_creator.helpers Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Provides utility functions for colored output, file operations, and user feedback. ```APIDOC ## pretty_print ### Description Print colored message. ### Signature `(*args, color='green') -> None` ## error ### Description Print error in red, optionally exit. ### Signature `(*args, exit=True) -> None` ## warning ### Description Print warning in yellow. ### Signature `(*args) -> None` ## success ### Description Print success in green. ### Signature `(*args) -> None` ## info ### Description Print info in blue. ### Signature `(*args) -> None` ## remove_file ### Description Delete a file if exists. ### Signature `(*args) -> None` ## remove_dir ### Description Delete directory recursively if exists. ### Signature `(*args) -> None` ``` -------------------------------- ### Import multiple functions from devops and frontend Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Shows how to import multiple functions from different modules within the plugin_creator package. ```python from plugin_creator.devops import get_devops_options, get_devops_mode from plugin_creator.frontend import define_frontend ``` -------------------------------- ### Handle Git Initialization Errors Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/usage-examples.md This Python snippet demonstrates how to catch and manage subprocess errors during git initialization for a plugin. It provides specific warnings for 'git' or 'pre-commit' command failures, offering manual alternatives or skipping steps as appropriate. ```python from plugin_creator.devops import git_init from plugin_creator.helpers import error, warning import subprocess plugin_dir = '/path/to/plugin' try: git_init(plugin_dir) except subprocess.CalledProcessError as e: if 'git' in str(e.cmd): warning('Git not found - initializing git repository manually') warning('Run: git init -b main') elif 'pre-commit' in str(e.cmd): warning('Pre-commit installation failed - skipping hooks') else: error(f'Command failed: {e.cmd}', exit=True) ``` -------------------------------- ### Display Tool Version Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/configuration.md Use the --version flag to display the current version of the create-inventree-plugin tool and exit the application. ```bash create-inventree-plugin --version ``` -------------------------------- ### Build Frontend Code Source: https://github.com/inventree/plugin-creator/blob/main/plugin_creator/template/{{ cookiecutter.plugin_name }}/frontend/README.md Compiles the frontend code into the static directory for distribution. The output is placed outside the `frontend` directory to be included in the Python package. ```bash npm run build ``` -------------------------------- ### Import an entire module using an alias Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Illustrates importing an entire module and assigning it an alias for easier access to its functions. ```python import plugin_creator.config as config config_data = config.load_config() ``` -------------------------------- ### Define Frontend Configuration Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Defines frontend configuration options based on whether frontend support is enabled and user preferences. Use this to set up React, Mantine, Lingui, and Vite versions, along with feature and translation settings. ```python from plugin_creator.frontend import define_frontend # Frontend disabled - no prompts config = define_frontend(enabled=False) # Returns: {'react_version': '19.2.4', 'mantine_version': '9.2.1', 'lingui_version': '5.9.2', 'vite_version': '6.4.2', 'enabled': False, 'translation': False, 'features': {...all False...}} # Frontend enabled with defaults config = define_frontend(enabled=True, defaults=True) # Returns: {..., 'enabled': True, 'translation': True, 'features': {...all True...}} # Frontend enabled with user prompts config = define_frontend(enabled=True, defaults=False) # User is prompted for feature selection and translation preference ``` -------------------------------- ### Specify Output Directory Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/configuration.md Use the --output flag to specify a custom directory for the generated plugin. The plugin will be created in a subdirectory named after the plugin_name within the specified output path. ```bash create-inventree-plugin --output /tmp/plugins # Creates: /tmp/plugins// ``` -------------------------------- ### define_frontend Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Defines frontend configuration options based on whether frontend support is enabled and user preferences. It returns a dictionary containing version information and, if enabled, feature and translation settings. ```APIDOC ## define_frontend ### Description Defines frontend configuration options based on whether frontend support is enabled and user preferences. ### Method ```python def define_frontend(enabled: bool, defaults: bool = False) -> dict ``` ### Parameters #### Arguments - **enabled** (bool) - Required - Whether frontend support is enabled for the plugin. - **defaults** (bool) - Optional - Whether to use default values (True) or prompt user (False) for feature and translation selection. Defaults to `False`. ### Returns #### Return Value - `dict` - Frontend configuration dictionary. ### Return Structure **Always included:** - `react_version`: string (e.g., "19.2.4") - `mantine_version`: string (e.g., "9.2.1") - `lingui_version`: string (e.g., "5.9.2") - `vite_version`: string (e.g., "6.4.2") **When enabled=True:** - `enabled`: `True` - `features`: dict from `all_features()` (if defaults=True) or `select_features()` (if defaults=False) - `translation`: `True` (if defaults=True) or result of `enable_translation()` (if defaults=False) **When enabled=False:** - `enabled`: `False` - `translation`: `False` - `features`: dict from `no_features()` ### Example ```python from plugin_creator.frontend import define_frontend # Frontend disabled - no prompts config = define_frontend(enabled=False) # Returns: {'react_version': '19.2.4', 'mantine_version': '9.2.1', 'lingui_version': '5.9.2', 'vite_version': '6.4.2', 'enabled': False, 'translation': False, 'features': {...all False...}} # Frontend enabled with defaults config = define_frontend(enabled=True, defaults=True) # Returns: {..., 'enabled': True, 'translation': True, 'features': {...all True...}} # Frontend enabled with user prompts config = define_frontend(enabled=True, defaults=False) # User is prompted for feature selection and translation preference ``` ``` -------------------------------- ### Config Module Imports Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Imports standard libraries for configuration management. ```python import json import os import appdirs ``` -------------------------------- ### Generated Plugin Structure Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/overview.md Illustrates the typical directory and file layout of a plugin generated by the tool, including Python package structure, frontend assets, CI/CD configuration, and project metadata files. ```text / ├── / # Python package │ ├── __init__.py │ ├── core.py # Main plugin class (always) │ ├── apps.py # (if AppMixin) │ ├── models.py # (if AppMixin) │ ├── admin.py # (if AppMixin) │ ├── views.py # (if UrlsMixin) │ ├── serializers.py # (if UrlsMixin) │ └── migrations/ # (if AppMixin) ├── frontend/ # (if frontend enabled) │ ├── src/ │ │ ├── Dashboard.tsx # (if dashboard feature) │ │ ├── Panel.tsx # (if panel feature) │ │ ├── Settings.tsx # (if settings feature) │ │ ├── Spotlight.tsx # (if spotlight feature) │ │ └── locales/ # (if translation enabled) │ ├── package.json │ └── vite.config.ts ├── .github/ │ └── workflows/ # (if GitHub Actions) ├── .gitlab-ci.yml # (if GitLab CI/CD) ├── pyproject.toml ├── setup.py ├── README.md └── .pre-commit-config.yaml # (if git_support=true) ``` -------------------------------- ### plugin_creator.config Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/module-index.md Manages configuration loading, saving, and directory paths for the plugin creator. ```APIDOC ## config_dir ### Description Get config directory path. ### Signature `() -> str` ## config_file ### Description Get config file path. ### Signature `() -> str` ## config_keys ### Description List persisted config keys. ### Signature `() -> list` ## load_config ### Description Load saved configuration. ### Signature `() -> dict` ## save_config ### Description Save configuration to disk. ### Signature `(data: dict) -> None` ``` -------------------------------- ### Prompt User to Select Frontend Features Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Presents an interactive checkbox interface for the user to select frontend features. Returns a dictionary of selected features. ```python from plugin_creator.frontend import select_features features = select_features() # User sees checkbox list and can check/uncheck features # Returns: {'dashboard': True, 'panel': False, 'settings': True, 'spotlight': False} ``` -------------------------------- ### Complete Context Dictionary Structure Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/types.md This is the full structure of the context dictionary used for plugin creation. It includes naming, metadata, author, license, mixins, frontend, and DevOps configurations. ```python { # Plugin naming information 'plugin_title': str, # Human-readable plugin name (e.g., "Custom Plugin") 'plugin_name': str, # Python class name without spaces (e.g., "CustomPlugin") 'plugin_slug': str, # URL-friendly name with hyphens (e.g., "custom-plugin") 'package_name': str, # Python package name with underscores (e.g., "custom_plugin") 'distribution_name': str, # PyPI distribution name (e.g., "inventree-custom-plugin") # Plugin metadata 'plugin_description': str, # Short description of the plugin 'plugin_version': str, # Initial version (e.g., "0.1.0") # Author information 'author_name': str, # Plugin author name 'author_email': str, # Author email address 'project_url': str, # Project/repository URL # License 'license_key': str, # License identifier (e.g., "MIT") 'license_text': str, # Full license text # Plugin mixins 'plugin_mixins': { 'mixin_list': list[str] # List of selected mixin class names }, # Frontend configuration 'frontend': { 'enabled': bool, # Whether frontend is enabled 'features': { 'dashboard': bool, # Custom dashboard items enabled 'panel': bool, # Custom panel items enabled 'settings': bool, # Custom settings display enabled 'spotlight': bool # Custom spotlight actions enabled }, 'translation': bool, # Whether translation support is enabled 'react_version': str, # React version requirement 'mantine_version': str, # Mantine UI library version 'lingui_version': str, # Lingui i18n library version 'vite_version': str # Vite bundler version }, # DevOps configuration 'git_support': bool, # Whether to initialize git repository 'ci_support': str, # CI/CD system ('none', 'github', 'gitlab') # Creator tool metadata 'plugin_creator_version': str # Version of the plugin-creator tool used } ``` -------------------------------- ### Prompt User to Enable Translation Support Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Asks the user if they want to enable translation support. Returns True if confirmed, False otherwise. Defaults to True. ```python from plugin_creator.frontend import enable_translation if enable_translation(): print('Translation support enabled') else: print('Translation support disabled') ``` -------------------------------- ### Configuration File Format Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/types.md Specifies the format for the InvenTree plugin creator configuration file, including author details and license. ```json { "author_name": "John Doe", "author_email": "john@example.com", "license_key": "MIT", "ci_support": "github" } ``` -------------------------------- ### config_file Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Returns the full path to the plugin creator configuration file (`config.json`). This file is located within the platform-specific configuration directory. ```APIDOC ## config_file ### Description Returns the full path to the plugin creator configuration file. ### Returns - `str`: Full path to `config.json` file within the config directory. ### Example ```python from plugin_creator.config import config_file config_path = config_file() print(config_path) # e.g., '/home/user/.config/inventree-plugin-creator/config.json' ``` ``` -------------------------------- ### gather_info Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/cli.md Prompts the user interactively for project information, validates inputs, and derives related naming conventions. It uses a provided context dictionary with default values and returns an updated context with user-provided and derived information. ```APIDOC ## gather_info ### Description Prompts the user for project information through an interactive questionnaire. Validates inputs and derives related naming conventions. ### Method ```python def gather_info(context: dict) -> dict ``` ### Parameters #### Request Body - `context` (dict) - Required - A dictionary containing default values for prompts. Keys used: `plugin_title`, `plugin_description`, `author_name`, `author_email`, `project_url`, `git_support`, `license_key`. ### Returns - `dict`: Updated context dictionary with user-provided values and derived naming conventions. Added/modified keys: `plugin_name`, `plugin_slug`, `package_name`, `distribution_name`, `license_text`, `plugin_mixins`, `frontend`, `ci_support`. ### Naming Conventions This function enforces the following naming conventions: - **plugin_title**: Human-readable name (e.g., "Custom Plugin") - **plugin_name**: Python class name derived from title with spaces removed (e.g., "CustomPlugin") - **plugin_slug**: URL-friendly version with hyphens and lowercase (e.g., "custom-plugin") - **package_name**: Python package name with underscores (e.g., "custom_plugin") - **distribution_name**: PyPI distribution name with "inventree-" prefix (e.g., "inventree-custom-plugin") ### Prompts 1. Plugin name (validated by `ProjectNameValidator`) 2. Plugin description (non-empty validation) 3. Author name (non-empty validation) 4. Author email (optional) 5. Project URL (optional) 6. License selection from available licenses (default: MIT) 7. Plugin mixins selection (via `mixins.get_mixins()`) 8. Frontend support options (via `frontend.define_frontend()`) 9. Git integration confirmation 10. DevOps CI/CD mode selection (if git enabled, via `devops.get_devops_mode()`) ### Example ```python from plugin_creator.cli import gather_info context = { 'plugin_title': 'Default Plugin', 'plugin_description': 'A plugin', 'author_name': 'Jane Doe', 'author_email': 'jane@example.com', 'project_url': 'https://example.com', 'git_support': True, 'license_key': 'MIT' } result = gather_info(context) # User is prompted interactively for information # Returns updated context with user input ``` ``` -------------------------------- ### all_features Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/frontend.md Returns a dictionary where all frontend feature keys are mapped to `True`, indicating all features are enabled. ```APIDOC ## all_features ### Description Returns a dictionary with all frontend features enabled (True). ### Method ```python def all_features() -> dict ``` ### Parameters None ### Returns - `dict`: Dictionary mapping feature keys to `True`. Keys from `frontend_features()` all set to `True`. ### Example ```python from plugin_creator.frontend import all_features features = all_features() # {'dashboard': True, 'panel': True, 'settings': True, 'spotlight': True} ``` ``` -------------------------------- ### config_keys Source: https://github.com/inventree/plugin-creator/blob/main/_autodocs/api-reference/config.md Returns a list of configuration keys that are persisted to the configuration file. Only these specified keys are saved and loaded from disk. ```APIDOC ## config_keys ### Description Returns the list of configuration keys that are persisted to the configuration file. Only these keys are saved and loaded from disk. ### Returns - `list`: List of configuration keys that are persisted. Current keys: `['author_name', 'author_email', 'license_key', 'ci_support']` ### Example ```python from plugin_creator.config import config_keys keys = config_keys() print(keys) # ['author_name', 'author_email', 'license_key', 'ci_support'] ``` ```