Craft Parts

2.32.0 · active · verified Thu Apr 16

Craft Parts is a Python package that provides a reusable and extensible framework for defining, processing, and organizing software components into deployment-ready filesystems. It supports various source types and build plugins, enabling declarative management of complex build processes and dependencies. The library is actively developed by Canonical and is a core component for tools like Snapcraft and Charmcraft, with regular releases.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates programmatically defining a simple 'hello' part that uses the 'dump' plugin to copy a source file. It then initializes a `LifecycleManager` to plan and execute the full crafting process (pull, build, stage, prime) within a temporary project structure, printing the output file.

import os
import pathlib
from craft_parts.models import PartSpec, Part
from craft_parts.lifecycle import LifecycleManager, Step

# Create a dummy project directory
project_dir = pathlib.Path('./my-craft-project')
project_dir.mkdir(exist_ok=True)

# Create a simple parts.yaml content
parts_yaml_content = '''
parts:
  hello:
    plugin: dump
    source: hello.txt
'''
(project_dir / 'parts.yaml').write_text(parts_yaml_content)
(project_dir / 'hello.txt').write_text('Hello from Craft Parts!')

# Define the part specification programmatically
part_spec = PartSpec(
    name="hello",
    part=Part(
        plugin="dump",
        source="hello.txt"
    )
)

# Initialize LifecycleManager
lcm = LifecycleManager(
    parts={part_spec.name: part_spec.part},
    application_name="my-craft-app",
    project_dir=project_dir,
    build_dir=project_dir / 'build',
    stage_dir=project_dir / 'stage',
    prime_dir=project_dir / 'prime',
    cache_dir=project_dir / '.cache'
)

# Plan and execute the full lifecycle
actions = lcm.plan(Step.PRIME)
with lcm.action_executor() as aex:
    aex.execute(actions)

print(f"Project built to: {project_dir / 'prime'}")
print(f"Content of staged file: {(project_dir / 'prime' / 'hello.txt').read_text()}")

view raw JSON →