Kconfig Tools API

Overview

The Kconfig tools provide Python APIs for managing configuration files, validating Kconfig syntax, and generating C header files.

Module: generate_hal_config

Configuration Header Generation

generate_header(config_dict, output_file=None)

Generate C header file from configuration dictionary.

Parameters:
  • config_dict (dict) – Configuration key-value pairs

  • output_file (str) – Output file path (optional)

Returns:

Generated header content as string

Return type:

str

Example:

from generate_hal_config import generate_header

config = {
    'CONFIG_PLATFORM_STM32': 'y',
    'CONFIG_UART1_BAUDRATE': '115200',
    'CONFIG_OSAL_FREERTOS': 'y'
}

header = generate_header(config, 'nexus_config.h')
parse_config_file(config_path)

Parse .config file and return configuration dictionary.

Parameters:

config_path (str) – Path to .config file

Returns:

Configuration dictionary

Return type:

dict

Example:

from generate_hal_config import parse_config_file

config = parse_config_file('.config')
print(f"Platform: {config.get('CONFIG_PLATFORM_NAME')}")
generate_default_config(platform=None)

Generate default configuration for specified platform.

Parameters:

platform (str) – Platform name (native, STM32, GD32, etc.)

Returns:

Default configuration dictionary

Return type:

dict

Example:

from generate_hal_config import generate_default_config

# Generate default for STM32
config = generate_default_config('STM32')

# Generate default for current platform
config = generate_default_config()

Module: validate_kconfig

Kconfig Validation

class KconfigValidator(root_dir='.')

Validator for Kconfig files.

Parameters:

root_dir (str) – Root directory for resolving paths

validate_file(kconfig_path, is_included=False)

Validate a single Kconfig file.

Parameters:
  • kconfig_path (Path) – Path to Kconfig file

  • is_included (bool) – Whether file is included via source/rsource

Returns:

Tuple of (errors, warnings)

Return type:

tuple[list[str], list[str]]

Example:

from pathlib import Path
from validate_kconfig import KconfigValidator

validator = KconfigValidator('.')
errors, warnings = validator.validate_file(Path('Kconfig'))

if errors:
    print(f"Errors: {errors}")
if warnings:
    print(f"Warnings: {warnings}")
validate_all(kconfig_file)

Validate Kconfig file and all included files.

Parameters:

kconfig_file (Path) – Root Kconfig file path

Returns:

True if validation passed, False otherwise

Return type:

bool

Example:

from pathlib import Path
from validate_kconfig import KconfigValidator

validator = KconfigValidator('.')
success = validator.validate_all(Path('Kconfig'))

if not success:
    validator.print_results()
validate_dependencies()

Validate dependencies and selects.

Returns:

Tuple of (errors, warnings)

Return type:

tuple[list[str], list[str]]

validate_ranges()

Validate range constraints and default values.

Returns:

Tuple of (errors, warnings)

Return type:

tuple[list[str], list[str]]

print_results()

Print validation results to stdout.

errors

List of validation errors.

Type:

list[str]

warnings

List of validation warnings.

Type:

list[str]

symbols

Dictionary of parsed configuration symbols.

Type:

dict[str, dict]

dependencies

Dictionary of symbol dependencies.

Type:

dict[str, set[str]]

Module: kconfig_migrate

Configuration Migration

migrate_config(input_file, output_file, target_version=None)

Migrate configuration file to new version.

Parameters:
  • input_file (str) – Input configuration file path

  • output_file (str) – Output configuration file path

  • target_version (str) – Target version (optional)

Returns:

True if migration succeeded

Return type:

bool

Example:

from kconfig_migrate import migrate_config

success = migrate_config(
    'old.config',
    'new.config',
    target_version='2.0'
)

if success:
    print("Migration completed successfully")
detect_version(config_file)

Detect configuration file version.

Parameters:

config_file (str) – Configuration file path

Returns:

Version string or None

Return type:

str or None

get_symbol_mapping(from_version, to_version)

Get symbol mapping between versions.

Parameters:
  • from_version (str) – Source version

  • to_version (str) – Target version

Returns:

Symbol mapping dictionary

Return type:

dict[str, str]

Module: kconfig_diff

Configuration Comparison

diff_configs(config1_path, config2_path, format='text')

Compare two configuration files.

Parameters:
  • config1_path (str) – First configuration file path

  • config2_path (str) – Second configuration file path

  • format (str) – Output format (‘text’ or ‘json’)

Returns:

Difference report

Return type:

str or dict

Example:

from kconfig_diff import diff_configs

# Text format
diff_text = diff_configs('.config', 'platforms/native/.config')
print(diff_text)

# JSON format
diff_json = diff_configs(
    '.config',
    'platforms/native/.config',
    format='json'
)
parse_config(config_path)

Parse configuration file.

Parameters:

config_path (str) – Configuration file path

Returns:

Configuration dictionary

Return type:

dict

format_diff_text(diff_dict)

Format difference dictionary as text.

Parameters:

diff_dict (dict) – Difference dictionary

Returns:

Formatted text

Return type:

str

format_diff_json(diff_dict)

Format difference dictionary as JSON.

Parameters:

diff_dict (dict) – Difference dictionary

Returns:

JSON string

Return type:

str

Module: generate_config_docs

Documentation Generation

generate_docs(kconfig_file, output_file=None, format='markdown')

Generate documentation from Kconfig files.

Parameters:
  • kconfig_file (str) – Root Kconfig file path

  • output_file (str) – Output file path (optional)

  • format (str) – Output format (‘markdown’ or ‘rst’)

Returns:

Generated documentation

Return type:

str

Example:

from generate_config_docs import generate_docs

# Generate markdown documentation
docs = generate_docs('Kconfig', 'config_reference.md')

# Generate reStructuredText
docs = generate_docs('Kconfig', 'config_reference.rst', format='rst')
extract_config_options(kconfig_file)

Extract all configuration options from Kconfig file.

Parameters:

kconfig_file (str) – Kconfig file path

Returns:

List of configuration options

Return type:

list[dict]

format_option_markdown(option)

Format configuration option as markdown.

Parameters:

option (dict) – Configuration option dictionary

Returns:

Formatted markdown

Return type:

str

format_option_rst(option)

Format configuration option as reStructuredText.

Parameters:

option (dict) – Configuration option dictionary

Returns:

Formatted reStructuredText

Return type:

str

Command-Line Interface

nexus_config.py

Unified configuration management tool.

Usage:

python scripts/nexus_config.py <command> [options]

Commands:

  • generate - Generate configuration header file

  • validate - Validate Kconfig files

  • migrate - Migrate configuration to new version

  • diff - Compare configuration files

  • info - Display configuration information

Generate Command:

python scripts/nexus_config.py generate [options]

Options:
  -c, --config FILE    Input configuration file
  -o, --output FILE    Output header file
  -d, --default        Generate default configuration
  -p, --platform NAME  Platform name for default config

Validate Command:

python scripts/nexus_config.py validate [kconfig_file]

Arguments:
  kconfig_file         Root Kconfig file (default: Kconfig)

Migrate Command:

python scripts/nexus_config.py migrate input_file [options]

Arguments:
  input_file           Input configuration file

Options:
  -o, --output FILE    Output configuration file
  -t, --target-version VERSION  Target version

Diff Command:

python scripts/nexus_config.py diff config1 config2 [options]

Arguments:
  config1              First configuration file
  config2              Second configuration file

Options:
  -f, --format FORMAT  Output format (text or json)
  -o, --output FILE    Output file

Data Structures

Configuration Dictionary

Configuration dictionaries map symbol names to values:

{
    'CONFIG_PLATFORM_STM32': 'y',
    'CONFIG_STM32F407': 'y',
    'CONFIG_UART1_BAUDRATE': '115200',
    'CONFIG_UART1_MODE_DMA': 'y',
    'CONFIG_OSAL_FREERTOS': 'y',
    'CONFIG_OSAL_TICK_RATE_HZ': '1000'
}

Symbol Information

Symbol information dictionaries contain metadata:

{
    'name': 'UART1_BAUDRATE',
    'type': 'int',
    'default': '115200',
    'range': (9600, 921600),
    'help': 'Baud rate for UART1',
    'file': 'platforms/STM32/src/uart/Kconfig',
    'line': 42
}

Validation Results

Validation results contain errors and warnings:

{
    'errors': [
        'Kconfig:10: Unclosed if block',
        'platforms/STM32/Kconfig:25: Undefined symbol INVALID_SYMBOL'
    ],
    'warnings': [
        'platforms/native/Kconfig:15: default outside of config block'
    ]
}

Difference Report

Difference reports show configuration changes:

{
    'added': {
        'CONFIG_NEW_FEATURE': 'y'
    },
    'removed': {
        'CONFIG_OLD_FEATURE': 'y'
    },
    'changed': {
        'CONFIG_UART1_BAUDRATE': {
            'old': '9600',
            'new': '115200'
        }
    },
    'unchanged': {
        'CONFIG_PLATFORM_STM32': 'y'
    }
}

Error Handling

Exceptions

exception KconfigError

Base exception for Kconfig-related errors.

exception ValidationError

Raised when validation fails.

exception ParseError

Raised when parsing fails.

exception GenerationError

Raised when header generation fails.

Example:

from validate_kconfig import KconfigValidator, ValidationError

try:
    validator = KconfigValidator('.')
    success = validator.validate_all(Path('Kconfig'))
    if not success:
        raise ValidationError("Validation failed")
except ValidationError as e:
    print(f"Error: {e}")
    validator.print_results()

Best Practices

Validation

Always validate before generating:

from pathlib import Path
from validate_kconfig import KconfigValidator
from generate_hal_config import generate_header, parse_config_file

# Validate first
validator = KconfigValidator('.')
if not validator.validate_all(Path('Kconfig')):
    print("Validation failed!")
    validator.print_results()
    exit(1)

# Then generate
config = parse_config_file('.config')
generate_header(config, 'nexus_config.h')

Error Handling

Handle errors gracefully:

try:
    config = parse_config_file('.config')
except FileNotFoundError:
    print("Config file not found, using defaults")
    config = generate_default_config()
except Exception as e:
    print(f"Error parsing config: {e}")
    exit(1)

Logging

Use logging for debugging:

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

validator = KconfigValidator('.')
logger.debug("Starting validation")
success = validator.validate_all(Path('Kconfig'))
logger.info(f"Validation {'passed' if success else 'failed'}")

See Also