### Install Crossplane CLI Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Installs the Crossplane CLI. Ensure you have the necessary permissions. ```bash curl -sL https://raw.githubusercontent.com/crossplane/crossplane/master/install | bash ``` -------------------------------- ### Install Crossplane Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/00-START-HERE.md Install the crossplane library using pip. ```bash pip install crossplane ``` -------------------------------- ### Simple Directive Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md Example of a simple NGINX directive like 'worker_processes'. ```python { "directive": "worker_processes", "line": 1, "args": ["4"] } ``` -------------------------------- ### Example NGINX Main Configuration Source: https://github.com/nginxinc/crossplane/blob/master/README.md This is the main NGINX configuration file. It includes directives for events and http. ```nginx events { worker_connections 1024; } http { include conf.d/*.conf; } ``` -------------------------------- ### Include Directive Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md Example of an 'include' directive, showing arguments and the 'includes' field which points to other parsed configurations. ```python { "directive": "include", "line": 5, "args": ["conf.d/*.conf"], "includes": [1, 2, 3] # Indices into config array } ``` -------------------------------- ### List Installed Providers Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Lists all providers currently installed in your Crossplane environment. ```bash kubectl crossplane beta list provider ``` -------------------------------- ### Install a Provider Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Installs a specific Crossplane provider, such as the AWS provider. Ensure the provider name is correct. ```bash kubectl crossplane beta install provider crossplane-aws ``` -------------------------------- ### Example NGINX Server Configuration Source: https://github.com/nginxinc/crossplane/blob/master/README.md This configuration file defines two server blocks, each listening on a different port and handling requests. ```nginx server { listen 8080; location / { try_files 'foo bar' baz; } } server { listen 8081; location / { return 200 'success!'; } } ``` -------------------------------- ### Lex Token Tuple Examples Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md Illustrates various examples of Lex Token Tuples, showing different tokens, line numbers, and quoted status. ```python # "events" on line 1, unquoted ("events", 1, False) ``` ```python # Opening brace on line 1, unquoted ("{ ", 1, False) ``` ```python # Quoted argument on line 4 ("hello world", 4, True) ``` ```python # Comment on line 5, unquoted ("# This is a comment", 5, False) ``` -------------------------------- ### Extract HTTP Configuration from Nginx Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md This example demonstrates how to parse an Nginx configuration and extract all directives within the 'http' block. It requires the Crossplane library to be installed. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') def find_directive(directives, name): for d in directives: if d['directive'] == name: return d return None for config in payload['config']: http = find_directive(config['parsed'], 'http') if http: for directive in http.get('block', []): print(f"HTTP directive: {directive['directive']}") ``` -------------------------------- ### Custom Crossplane Extension Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/module-overview.md Demonstrates how to create a custom Crossplane extension by subclassing CrossplaneExtension and implementing lexing, parsing, and building logic for new directives. ```python from crossplane.ext.abstract import CrossplaneExtension class MyExtension(CrossplaneExtension): directives = {'my_directive': [...]} def lex(self, char_iterator, directive): # Custom lexing pass def parse(self, stmt, parsing, tokens, ctx=(), consume=False): # Custom parsing pass def build(self, stmt, padding, indent=4, tabs=False): # Custom building pass ext = MyExtension() ext.register_extension() ``` -------------------------------- ### Get Crossplane Version Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Displays the installed version of the Crossplane CLI. ```bash crossplane --version ``` -------------------------------- ### Directive with Block Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md Example of a block directive like 'server', containing nested directives. ```python { "directive": "server", "line": 10, "args": [], "block": [ { "directive": "listen", "line": 11, "args": ["80"] }, { "directive": "server_name", "line": 12, "args": ["example.com"] } ] } ``` -------------------------------- ### Lexing NGINX Config to JSON Tokens Source: https://github.com/nginxinc/crossplane/blob/master/README.md Demonstrates how to use 'crossplane lex' to convert an NGINX configuration file into a JSON array of tokens. This example shows the basic output without line numbers. ```nginx events { worker_connections 1024; } http { include conf.d/*.conf; } ``` ```bash crossplane lex /etc/nginx/nginx.conf ``` ```json ["events","{","worker_connections","1024",";","}","http","{","include","conf.d/*.conf",";","}"] ``` -------------------------------- ### Nginx Lua Block Syntax Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/extensions.md Illustrates the syntax for enclosing Lua code within braces for Nginx directives like `content_by_lua_block`. Supports nested braces. ```nginx content_by_lua_block { local ngx = ngx if ngx.var.request_method == "GET" then ngx.say("Hello") end } ``` -------------------------------- ### Crossplane Parse Command Example Source: https://github.com/nginxinc/crossplane/blob/master/README.md Command to parse an NGINX configuration file using crossplane, with indentation set to 4 spaces for prettified JSON output. ```bash crossplane parse --indent=4 /etc/nginx/nginx.conf ``` -------------------------------- ### Run All Test Environments in Parallel Source: https://github.com/nginxinc/crossplane/blob/master/CONTRIBUTING.md Utilize detox to run all tox test environments concurrently for faster testing. Ensure detox is installed via pip. ```bash detox ``` -------------------------------- ### Format NGINX Config with Custom Indentation and Write to File Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/format.md Format an NGINX configuration file with a custom indentation level (e.g., 2 spaces) and write the result to a new file. This is useful for enforcing specific style guides. ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf', indent=2) with open('/tmp/formatted.conf', 'w') as f: f.write(formatted) ``` -------------------------------- ### Parse for Performance (Follow Includes, No Analysis) Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Parses a configuration file and follows included files, but skips context and argument analysis. Offers a balance between speed and completeness for performance optimization. ```python # Medium: follow includes but no analysis payload = crossplane.parse( filename, check_ctx=False, check_args=False ) ``` -------------------------------- ### Comment Directive Example Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md Example of a comment directive, where the 'directive' is '#' and the 'comment' field holds the text. ```python { "directive": "#", "line": 3, "args": [], "comment": " This is a comment" } ``` -------------------------------- ### High-Level Architecture: Building Pipeline Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/architecture.md Shows the reverse pipeline for building an NGINX configuration string from a directive tree. ```text Directive Tree → Builder → Config String → Output ↓ Formatted Config ``` -------------------------------- ### Example Error Object Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/types.md An example of a fully populated Error Object, demonstrating the expected fields and their values for a parsing error. ```python { "file": "/etc/nginx/nginx.conf", "line": 42, "error": "invalid number of arguments in \"proxy_pass\" directive", "callback": "Traceback (most recent call last):\n File ...\n ..." } ``` -------------------------------- ### Standard Formatting with Build Function Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Use this snippet for standard output formatting with 4-space indentation, spaces, and no header. It parses an NGINX configuration and builds the output. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') output = crossplane.build( payload['config'][0]['parsed'], indent=4, tabs=False, header=False ) ``` -------------------------------- ### Basic File Building Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build-files.md Builds NGINX configuration files from a parsed payload and writes them to a specified directory. Ensure the 'crossplane' library is imported. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files(payload, dirname='/tmp/nginx-output') # All config files from the parse are now written to /tmp/nginx-output ``` -------------------------------- ### String Representation of NgxParserBaseException Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/errors.md Illustrates how to get a formatted string representation of an error, including the line number if available. ```python str(error) # "error message in /path/to/file.conf:123" ``` ```python str(error) # "error message in /path/to/file.conf" ``` -------------------------------- ### Build NGINX Configuration with Verbose Output Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files and enables verbose output, which prints the paths of created files. ```bash # Build with verbose output crossplane build -v config.json ``` -------------------------------- ### Parse NGINX Configuration Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/00-START-HERE.md Parses an NGINX configuration file into a structured payload. Use this to get the status of the parse operation. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') print(payload['status']) # 'ok' or 'failed' ``` -------------------------------- ### Running Tests with Pytest Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/utilities-and-compat.md Commands to execute the test suite using pytest or setup.py. ```bash python -m pytest ``` ```bash python setup.py test ``` -------------------------------- ### Build NGINX Configuration to Stdout Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files and directs all output to standard output instead of creating files. ```bash # Output to stdout instead of files crossplane build --stdout config.json ``` -------------------------------- ### Basic NGINX Configuration Building Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build.md Parses an NGINX configuration file and builds a formatted string from its configuration directives. Use this for a standard round-trip conversion. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') for config in payload['config']: output = crossplane.build(config['parsed']) print(output) ``` -------------------------------- ### Display Crossplane Help Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md The 'help' command displays general help information or specific help for a given command. Use it to understand available commands and their options. ```bash crossplane help ``` ```bash crossplane help parse ``` ```bash crossplane help build ``` -------------------------------- ### Parse for Performance (Full Validation with Includes) Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Performs a full validation of the configuration file, including all included files. This is the slowest but most thorough parsing option. ```python # Slow but thorough: full validation with includes payload = crossplane.parse( filename, catch_errors=True, strict=True, check_ctx=True, check_args=True ) ``` -------------------------------- ### Exclude Sensitive Directives from Nginx Config Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use this snippet to remove sensitive directives from an Nginx configuration before sending it to an external service. Ensure the Crossplane library is installed. ```python import crossplane # Remove sensitive directives before sending to external service payload = crossplane.parse( '/etc/nginx/nginx.conf', ignore=( 'ssl_certificate_key', 'ssl_password_file', 'auth_basic_user_file', 'secure_link_secret' ) ) # Send payload['config'] to external service ``` -------------------------------- ### Enabling and Importing Crossplane Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/extensions.md Demonstrates how to import the Crossplane library and parse an Nginx configuration file. The LuaBlockPlugin is enabled by default upon import. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') # Lua block directives are now parsed correctly ``` -------------------------------- ### Tokenize Nginx config and show tokens Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'lex' command to tokenize an Nginx configuration file and display the resulting tokens. ```bash # Show tokens crossplane lex /etc/nginx/nginx.conf ``` -------------------------------- ### Tokenize Nginx Config File Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Tokenize an Nginx configuration file to get a list of all tokens along with their line numbers. This is useful for low-level analysis of the configuration syntax. ```python import crossplane # Get all tokens for token, lineno, quoted in crossplane.lex('/etc/nginx/nginx.conf'): print(f"Line {lineno}: {token}") ``` -------------------------------- ### Processing Directives and Delimiters in NGINX Configuration Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/lex.md Iterates through tokens of an NGINX configuration file, identifying and printing delimiters ('{', '}', ';') and directives/arguments that are not quoted and do not start with '#'. Requires the 'crossplane' library. ```python import crossplane for token, lineno, quoted in crossplane.lex('/etc/nginx/nginx.conf'): if token in ('{', '}', ';'): print(f"Delimiter at line {lineno}: {token}") elif not quoted and not token.startswith('#'): print(f"Directive/arg at line {lineno}: {token}") ``` -------------------------------- ### build_files() Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build-files.md Builds NGINX configuration files from a parse payload and writes them to disk. It handles directory creation, path resolution, and file writing with specified formatting options. ```APIDOC ## build_files() ### Description Builds NGINX configuration files from a parse payload and writes them to disk. It handles directory creation, path resolution, and file writing with specified formatting options. ### Signature ```python def build_files(payload, dirname=None, indent=4, tabs=False, header=False) ``` ### Parameters #### Parameters - **payload** (dict) - Required - Complete parse payload (output from `parse()`) containing config objects with file paths - **dirname** (str) - Optional - Base directory to write files to; defaults to current working directory - **indent** (int) - Optional - Number of spaces per indentation level (ignored if `tabs=True`); defaults to 4 - **tabs** (bool) - Optional - If True, use tabs instead of spaces for indentation; defaults to False - **header** (bool) - Optional - If True, prepend a header comment to each built file; defaults to False ### Return Type `None` — Writes files to disk as a side effect ### Throws #### Throws - **OSError** - Cannot create output directory or write to file ### Examples #### Basic file building ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files(payload, dirname='/tmp/nginx-output') # All config files from the parse are now written to /tmp/nginx-output ``` #### Build to current directory ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files(payload) # Files are written to the current working directory ``` #### Build with custom formatting ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files( payload, dirname='/tmp/nginx-output', indent=2, tabs=False, header=True ) ``` #### Rebuild relative paths ```python import crossplane # Original config at /etc/nginx/nginx.conf with includes at /etc/nginx/conf.d/ payload = crossplane.parse('/etc/nginx/nginx.conf') # Files with relative paths in the payload are resolved relative to dirname crossplane.build_files(payload, dirname='/var/www/nginx') # Writes /var/www/nginx/nginx.conf and /var/www/nginx/conf.d/*.conf ``` #### Full parse-modify-build cycle ```python import crossplane import json # Parse original config payload = crossplane.parse('/etc/nginx/nginx.conf') # Modify parsed directives (e.g., add a directive) for config in payload['config']: if config['file'].endswith('nginx.conf'): config['parsed'].append({ 'directive': 'worker_processes', 'args': ['auto'], 'line': 1 }) # Write modified config crossplane.build_files(payload, dirname='/tmp/modified-nginx') ``` ### Notes - Creates output directories as needed (creates parent directories if they don't exist). - Absolute paths in the payload are used as-is; relative paths are joined with `dirname`. - Preserves the file structure from the original parse, including all included files. - Files are written with UTF-8 encoding and a trailing newline. - The function calls `build()` internally for each config object. ### Related Functions - `build()` — Build a config string without writing to disk - `parse()` — Parse config files to get the payload ### Source `crossplane/builder.py:126-149` ``` -------------------------------- ### Nginx Contexts Dictionary Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/analyzer.md Maps context tuples to their corresponding Nginx configuration context flags. ```python CONTEXTS = { ('events',): NGX_EVENT_CONF, ('mail',): NGX_MAIL_MAIN_CONF, ('mail', 'server'): NGX_MAIL_SRV_CONF, ('stream',): NGX_STREAM_MAIN_CONF, ('stream', 'server'): NGX_STREAM_SRV_CONF, ('stream', 'upstream'): NGX_STREAM_UPS_CONF, ('http',): NGX_HTTP_MAIN_CONF, ('http', 'server'): NGX_HTTP_SRV_CONF, ('http', 'location'): NGX_HTTP_LOC_CONF, ('http', 'upstream'): NGX_HTTP_UPS_CONF, ('http', 'server', 'if'): NGX_HTTP_SIF_CONF, ('http', 'location', 'if'): NGX_HTTP_LIF_CONF, ('http', 'location', 'limit_except'): NGX_HTTP_LMT_CONF } ``` -------------------------------- ### Cross-Version Input Function Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/utilities-and-compat.md Provides a consistent way to get user input across Python 2 and 3. Use this function instead of raw_input() or input() directly for compatibility. ```python from crossplane.compat import input response = input("Enter value: ") ``` -------------------------------- ### Extract Server Blocks from Nginx Configuration Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md This snippet shows how to parse an Nginx configuration and extract details from 'server' blocks, including server names and listen ports. The Crossplane library must be installed. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') def get_servers(directives): for directive in directives: if directive['directive'] == 'http': for item in directive.get('block', []): if item['directive'] == 'server': yield item for config in payload['config']: for server in get_servers(config['parsed']): names = [] ports = [] for item in server.get('block', []): if item['directive'] == 'server_name': names.extend(item['args']) elif item['directive'] == 'listen': ports.extend(item['args']) print(f"Server: {names} on {ports}") ``` -------------------------------- ### Build with Custom Formatting Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build-files.md Customizes the output format of NGINX configuration files, including indentation (spaces or tabs) and the addition of a header comment. Uses the build_files() function with specific parameters. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files( payload, dirname='/tmp/nginx-output', indent=2, tabs=False, header=True ) ``` -------------------------------- ### Format Nginx config and display Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'format' command to reformat an Nginx configuration file and display the output. ```bash # Format and display crossplane format /etc/nginx/nginx.conf ``` -------------------------------- ### Check Directive Validity in Context Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/directives-reference.md This example demonstrates how to check if a directive is allowed within a specific context (e.g., 'http', 'server') and if its arguments are valid. It uses the `analyze` function and raises an exception if the directive is not allowed. ```python from crossplane.analyzer import analyze try: analyze( fname='test.conf', stmt={'directive': 'listen', 'line': 10, 'args': ['80']}, term=';', ctx=('http', 'server'), strict=False, check_ctx=True, check_args=True ) print("Directive is valid in this context") except Exception as e: print(f"Directive not allowed: {e}") ``` -------------------------------- ### Build NGINX Configuration with Custom Space Indentation Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files with a specified number of spaces for indentation. ```bash # Build with 2-space indentation crossplane build -i 2 config.json ``` -------------------------------- ### Pretty-print Nginx config to stdout Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'parse' command to pretty-print an Nginx configuration file to standard output. ```bash # Pretty-print to stdout crossplane parse /etc/nginx/nginx.conf ``` -------------------------------- ### Crossplane CLI Build Command Usage Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Shows the general usage and available arguments for the 'crossplane build' command. ```bash crossplane build [-h] [-d PATH] [-f] [-i NUM | -t] [--no-headers] [--stdout] [-v] filename ``` -------------------------------- ### Build NGINX Configuration with Tab Indentation Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files using tab characters for indentation. ```bash # Build with tab indentation crossplane build --tabs config.json ``` -------------------------------- ### Compact Two-Space Indentation with Build Function Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Use this snippet to achieve compact configuration output with only two spaces per indentation level. This is useful for minimizing file size or for specific formatting requirements. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') output = crossplane.build( payload['config'][0]['parsed'], indent=2 # 2 spaces per level ) ``` -------------------------------- ### Basic Nginx Configuration Parsing Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/parse.md Parses a given Nginx configuration file and prints the status and file paths of the parsed configurations. This is the most straightforward way to use the `parse` function. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') print(payload['status']) # 'ok' or 'failed' for config in payload['config']: print(config['file']) print(config['parsed']) ``` -------------------------------- ### crossplane.build() Source: https://github.com/nginxinc/crossplane/blob/master/README.md Builds an NGINX configuration file content from a Python dictionary structure. ```APIDOC ## crossplane.build() ### Description Builds an NGINX configuration file content as a string from a Python list of dictionaries. ### Method `build(config_structure)` ### Parameters #### Request Body - **config_structure** (list) - Required - A list of dictionaries representing the NGINX configuration. ### Request Example ```python import crossplane config = crossplane.build([ { "directive": "events", "args": [], "block": [ { "directive": "worker_connections", "args": ["1024"] } ] } ]) ``` ### Response #### Success Response - Returns a string containing the entire NGINX configuration file content. ``` -------------------------------- ### Round-trip NGINX Configuration Parse and Build Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build.md Demonstrates a full round-trip process: parsing an existing NGINX configuration, rebuilding it into a string, and writing it to a new file. Useful for testing or modifying configurations. ```python import crossplane # Parse original config payload = crossplane.parse('/etc/nginx/nginx.conf') parsed = payload['config'][0]['parsed'] # Build it back to a string rebuilt = crossplane.build(parsed, indent=4) # Write to file or compare with open('/tmp/nginx_rebuilt.conf', 'w') as f: f.write(rebuilt) ``` -------------------------------- ### CLI Commands Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/README.md Provides reference for the command-line interface tools, including parsing, building, tokenizing, reformatting, and compressing NGINX configurations. ```APIDOC ## CLI Commands ### Description Reference for the command-line interface tools provided by crossplane. ### Commands - **`crossplane parse`**: Parse NGINX config to JSON. - **`crossplane build`**: Build NGINX config from JSON. - **`crossplane lex`**: Tokenize NGINX config. - **`crossplane format`**: Reformat NGINX config. - **`crossplane minify`**: Compress NGINX config. ### Usage (Details on specific command usage, options, and examples would be found in the linked `cli-commands.md` file) ``` -------------------------------- ### Build Multiple Files from Payload Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Parses a configuration file and then builds multiple output files from the resulting payload. Each config object in the payload corresponds to a file. ```python payload = crossplane.parse(filename) # Each config object corresponds to a file for config in payload['config']: output = crossplane.build(config['parsed']) path = config['file'] # Use output and path... ``` -------------------------------- ### Basic Lexing of NGINX Configuration Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/lex.md Tokenizes an NGINX configuration file and prints each token with its line number and quoted status. Requires the 'crossplane' library. ```python import crossplane tokens = list(crossplane.lex('/etc/nginx/nginx.conf')) for token, lineno, quoted in tokens: print(f"Line {lineno}: {token} (quoted={quoted})") ``` -------------------------------- ### Parse for Performance (Single File) Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Parses only the specified filename, ignoring any included files. This is the fastest parsing option for large configurations. ```python # Fast: single file only payload = crossplane.parse(filename, single=True) ``` -------------------------------- ### build() Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build.md Builds a formatted NGINX configuration string from a list of directive objects. This function is essential for programmatically generating or modifying NGINX configurations. ```APIDOC ## build() ### Description Build an NGINX configuration string from a list of directive objects. ### Signature ```python def build(payload, indent=4, tabs=False, header=False) ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **payload** (list) - Required - List of directive objects to build (typically `config['parsed']` from parse output) * **indent** (int) - Optional - Number of spaces per indentation level (ignored if `tabs=True`). Default: 4 * **tabs** (bool) - Optional - If True, use tabs instead of spaces for indentation. Default: False * **header** (bool) - Optional - If True, prepend a header comment explaining the file was built from JSON. Default: False ### Request Example ```json { "payload": [ { "directive": "worker_processes", "args": ["4"] }, { "directive": "events", "args": [], "block": [ { "directive": "worker_connections", "args": ["1024"] } ] } ], "indent": 2, "tabs": false, "header": true } ``` ### Response #### Success Response (200) `str` — A formatted NGINX configuration string #### Response Example ```nginx # This config was built from JSON using NGINX crossplane. # If you encounter any bugs please report them here: # https://github.com/nginxinc/crossplane/issues worker_processes 4; events { worker_connections 1024; } ``` ``` -------------------------------- ### Combine Included Nginx Configuration Files Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/parse.md Parses an Nginx configuration file and merges all included configurations into a single configuration object. Use `combine=True` to achieve this. ```python import crossplane # Merge all included configs into one payload = crossplane.parse( '/etc/nginx/nginx.conf', combine=True ) # payload['config'] now has only one element with all directives merged print(len(payload['config'])) # 1 ``` -------------------------------- ### format() Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/format.md Parses an NGINX configuration file and returns it as a reformatted string with consistent indentation and style. It preserves comments and does not follow include directives. ```APIDOC ## format() ### Description Parses an NGINX configuration file and returns it as a reformatted string with consistent indentation and style. It preserves comments and does not follow include directives. ### Signature ```python def format(filename, indent=4, tabs=False) ``` ### Parameters #### Path Parameters - **filename** (str) - Required - Path to the NGINX config file to format #### Query Parameters - **indent** (int) - Optional - Number of spaces per indentation level (ignored if `tabs=True`). Default: 4 - **tabs** (bool) - Optional - If True, use tabs instead of spaces for indentation. Default: False ### Return Type `str` — Formatted NGINX configuration string ### Throws - **NgxParserBaseException** - Parser error in the config file - **Other parsing exceptions** - Any error encountered during parsing ### Examples #### Format with default indentation ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf') print(formatted) ``` #### Format with 2-space indentation ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf', indent=2) with open('/tmp/formatted.conf', 'w') as f: f.write(formatted) ``` #### Format with tabs ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf', tabs=True) print(formatted) ``` #### Format and write to file ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf', indent=4) with open('/tmp/nginx_formatted.conf', 'w') as f: f.write(formatted) ``` ### Notes - This function is a convenience wrapper that calls `parse()` with `comments=True` and `single=True`, then calls `build()` on the result. - Does not follow include directives; formats only the main config file. - Comments are preserved in the formatted output. - Raises an exception if the first error in the file causes parsing to fail; does not continue on error. - See `parse()` documentation for details on the parsing process. - See `build()` documentation for formatting details. ### Related Functions - `parse()` — Parse config file to get directive structure - `build()` — Build config string from directives ``` -------------------------------- ### Crossplane Build Command Usage Source: https://github.com/nginxinc/crossplane/blob/master/README.md Displays the usage instructions for the 'crossplane build' command, which constructs NGINX configurations from JSON payloads. It outlines available arguments for specifying input files, output directories, and formatting options. ```bash usage: crossplane build [-h] [-d PATH] [-f] [-i NUM | -t] [--no-headers] [--stdout] [-v] filename builds an nginx config from a json payload positional arguments: filename the file with the config payload optional arguments: -h, --help show this help message and exit -v, --verbose verbose output -d PATH, --dir PATH the base directory to build in -f, --force overwrite existing files -i NUM, --indent NUM number of spaces to indent output -t, --tabs indent with tabs instead of spaces --no-headers do not write header to configs --stdout write configs to stdout instead ``` -------------------------------- ### Build NGINX Configuration String with Python Source: https://github.com/nginxinc/crossplane/blob/master/README.md Use the `crossplane.build()` function to generate a complete NGINX configuration file as a string from a Python dictionary structure. This is helpful for dynamically creating configurations. ```python import crossplane config = crossplane.build( [{ "directive": "events", "args": [], "block": [{ "directive": "worker_connections", "args": ["1024"] }] }] ) ``` -------------------------------- ### Run All Tests with Tox Source: https://github.com/nginxinc/crossplane/blob/master/CONTRIBUTING.md Ensure your changes pass style and unit tests across all supported Python versions using tox. ```bash tox ``` -------------------------------- ### Format NGINX Config and Write to File (Default Indentation) Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/format.md Format an NGINX configuration file with default 4-space indentation and write the reformatted content to a specified file. This is a common use case for standardizing configuration files. ```python import crossplane formatted = crossplane.format('/etc/nginx/nginx.conf', indent=4) with open('/tmp/nginx_formatted.conf', 'w') as f: f.write(formatted) ``` -------------------------------- ### Build NGINX Configuration to Custom Directory Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files and specifies a custom directory for the output files. ```bash # Build to custom directory crossplane build -d /tmp/nginx config.json ``` -------------------------------- ### Build NGINX Configuration from JSON Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Builds NGINX configuration files from a specified JSON payload file. Headers are added by default. ```bash # Build from JSON payload crossplane build config.json ``` -------------------------------- ### Run a Subset of Tests with Tox Source: https://github.com/nginxinc/crossplane/blob/master/CONTRIBUTING.md Execute a specific environment or test file using tox to quickly verify changes. ```bash tox -e -- tests/[::test] ``` -------------------------------- ### Full Parse-Modify-Build Cycle Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build-files.md Illustrates a complete workflow: parsing an NGINX configuration, modifying its structure programmatically, and then rebuilding the configuration files to disk. Requires 'crossplane' and 'json' libraries. ```python import crossplane import json # Parse original config payload = crossplane.parse('/etc/nginx/nginx.conf') # Modify parsed directives (e.g., add a directive) for config in payload['config']: if config['file'].endswith('nginx.conf'): config['parsed'].append({ 'directive': 'worker_processes', 'args': ['auto'], 'line': 1 }) # Write modified config crossplane.build_files(payload, dirname='/tmp/modified-nginx') ``` -------------------------------- ### Batch Process Configuration Files Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/utilities-and-compat.md Iterate through a list of configuration files and parse each one independently using `crossplane.parse` with `single=True` for batch processing. ```python import crossplane files = ['/etc/nginx/nginx.conf', '/etc/nginx/conf.d/default.conf'] for filename in files: payload = crossplane.parse(filename, single=True) # Process each file independently ``` -------------------------------- ### build() - Generate NGINX config strings Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/INDEX.md Generates NGINX configuration strings from a structured dictionary of directives. This function recursively formats blocks, automatically quotes arguments, and supports configurable indentation. ```APIDOC ## build() ### Description Generates NGINX configuration strings from a structured dictionary representation of directives. It recursively formats configuration blocks, automatically adds quotes around arguments where necessary, and allows for customizable indentation levels. ### Function Signature `build(directive_structure: dict, indent_level: int = 0) -> str` ### Parameters #### Path Parameters - **directive_structure** (dict) - Required - The nested dictionary representing the NGINX configuration. - **indent_level** (int) - Optional - The initial indentation level for the generated configuration. Defaults to 0. ``` -------------------------------- ### Build to Current Directory Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build-files.md Writes NGINX configuration files to the current working directory using the build_files() function. Requires the 'crossplane' library. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') crossplane.build_files(payload) # Files are written to the current working directory ``` -------------------------------- ### build_files() - Write config files to disk Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/INDEX.md Writes configuration files to disk, creating directories as needed. This function handles multiple files and preserves the original file structure. ```APIDOC ## build_files() ### Description Writes generated NGINX configuration content to one or more files on disk. This function automatically creates any necessary parent directories and is capable of handling the writing of multiple configuration files while maintaining their original directory structure. ### Function Signature `build_files(file_configs: dict, base_path: str = '.')` ### Parameters #### Path Parameters - **file_configs** (dict) - Required - A dictionary where keys are file paths and values are the configuration content strings. - **base_path** (str) - Optional - The base directory where the files should be written. Defaults to the current directory. ``` -------------------------------- ### File Encoding with UTF-8 Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/utilities-and-compat.md Demonstrates opening a file with UTF-8 encoding and the 'replace' error handler to prevent UnicodeDecodeError. ```python import io with io.open(filename, 'r', encoding='utf-8', errors='replace') as f: # UTF-8 with replacement error handler ``` -------------------------------- ### Clone Crossplane Repository Source: https://github.com/nginxinc/crossplane/blob/master/CONTRIBUTING.md Clone your forked Crossplane repository locally to begin development. ```bash git clone git@github.com:your_name_here/crossplane.git ``` -------------------------------- ### Format Nginx config using tabs Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'format' command with the '--tabs' flag to format the Nginx configuration using tab characters instead of spaces. ```bash # Use tabs instead of spaces crossplane format --tabs /etc/nginx/nginx.conf ``` -------------------------------- ### format() Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/README.md Formats NGINX configuration files with consistent indentation. This function helps in maintaining code style and readability of configuration files. ```APIDOC ## format() ### Description Formats NGINX configuration files with consistent indentation. This function is used to standardize the appearance of configuration files, improving readability. ### Method N/A (Function Signature) ### Endpoint N/A (Library Function) ### Parameters (Details on parameters, return type, and examples would be found in the linked `format.md` file) ### Request Example N/A ### Response (Details on response structure would be found in the linked `format.md` file) ``` -------------------------------- ### Save formatted Nginx config with custom indentation Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'format' command with the '--indent' and '-o' flags to save the formatted Nginx configuration to a file with specified indentation. ```bash # Save formatted output crossplane format --indent 2 -o /tmp/formatted.conf /etc/nginx/nginx.conf ``` -------------------------------- ### NGX_ANY_CONF Convenience Constant Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/analyzer.md A predefined constant that represents a common set of NGINX directive contexts, simplifying configuration validation by including most contexts except 'if' and 'limit_except'. ```python NGX_ANY_CONF = ( NGX_MAIN_CONF | NGX_EVENT_CONF | NGX_MAIL_MAIN_CONF | NGX_MAIL_SRV_CONF | NGX_STREAM_MAIN_CONF | NGX_STREAM_SRV_CONF | NGX_STREAM_UPS_CONF | NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_HTTP_UPS_CONF ) ``` -------------------------------- ### crossplane.lex() Source: https://github.com/nginxinc/crossplane/blob/master/README.md Lexes an NGINX configuration file into a list of token tuples. ```APIDOC ## crossplane.lex() ### Description Lexes an NGINX configuration file into a list of 2-tuples, where each tuple represents a token. ### Method `lex(file_path)` ### Parameters #### Path Parameters - **file_path** (string) - Required - The path to the NGINX configuration file. ### Request Example ```python import crossplane tokens = crossplane.lex('/etc/nginx/nginx.conf') ``` ### Response #### Success Response - Returns a list of 2-tuples representing the tokens of the NGINX configuration. ``` -------------------------------- ### format() - Format NGINX config files Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/INDEX.md Formats NGINX configuration files by parsing them into a structured dictionary and then rebuilding them. This function preserves comments and supports a single-file mode. ```APIDOC ## format() ### Description Formats NGINX configuration files, acting as a convenience wrapper around the `parse()` and `build()` functions. It preserves comments within the configuration and can operate in a single-file mode. ### Function Signature `format(config_path: str, output_path: str = None) -> str` ### Parameters #### Path Parameters - **config_path** (str) - Required - The path to the NGINX configuration file to format. - **output_path** (str) - Optional - The path to write the formatted configuration. If None, the formatted content is returned as a string without writing to a file. ``` -------------------------------- ### Build NGINX Config with Header Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/build.md Generates an NGINX configuration string with a prepended header comment. This is useful for indicating that the configuration was automatically generated. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') config = payload['config'][0] output = crossplane.build(config['parsed'], header=True) print(output) # Output starts with: # # This config was built from JSON using NGINX crossplane. # # If you encounter any bugs please report them here: # # https://github.com/nginxinc/crossplane/issues ``` -------------------------------- ### Lex Configuration File Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Tokenizes an Nginx configuration file. Useful for basic parsing and analysis. ```python import crossplane tokens = crossplane.lex('/etc/nginx/nginx.conf') for token, lineno, quoted in tokens: print(f"Line {lineno}: {token} (quoted={quoted})") ``` -------------------------------- ### Build Function Output with Generation Header Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/configuration.md Include a file generation header comment in the output by setting the `header` option to `True`. This is helpful for tracking the origin of generated configuration files. ```python import crossplane payload = crossplane.parse('/etc/nginx/nginx.conf') output = crossplane.build( payload['config'][0]['parsed'], header=True # Add comment explaining file was generated ) # Output starts with: # # This config was built from JSON using NGINX crossplane. # # If you encounter any bugs please report them here: # # https://github.com/nginxinc/crossplane/issues ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/nginxinc/crossplane/blob/master/CONTRIBUTING.md Stage all changes, commit them with a descriptive message, and push your branch to GitHub. ```bash git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Tokenize Nginx config and save to JSON Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/quick-start.md Use the 'lex' command with the '-o' flag to save the tokenized Nginx configuration to a JSON file. ```bash # Save to file crossplane lex -o tokens.json /etc/nginx/nginx.conf ``` -------------------------------- ### Python Module Entry Points Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/module-overview.md Import and use the main functions from the Crossplane Python module for parsing, building, lexing, and formatting NGINX configurations. ```python import crossplane # Main functions payload = crossplane.parse(filename) output = crossplane.build(directives) tokens = crossplane.lex(filename) formatted = crossplane.format(filename) ``` -------------------------------- ### Main Crossplane CLI Usage Source: https://github.com/nginxinc/crossplane/blob/master/_autodocs/cli-commands.md Displays the main command structure and available sub-commands for the Crossplane CLI. Use this to understand the overall functionality and available operations. ```bash usage: crossplane [options] various operations for nginx config files optional arguments: -h, --help show this help message and exit -V, --version show program's version number and exit commands: parse parses a json payload for an nginx config build builds an nginx config from a json payload lex lexes tokens from an nginx config file minify removes all whitespace from an nginx config format formats an nginx config file help show help for commands ```