CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-beets

A comprehensive music library management system and command-line application for organizing and maintaining digital music collections

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

utilities-templates.mddocs/

Utilities and Templates

File operations, path manipulation, template formatting, and various utility functions for safe file handling and flexible path generation. These utilities provide the foundation for beets' file management and path formatting capabilities.

Capabilities

File Operations

Safe file operations with cross-platform compatibility and error handling.

def normpath(path: Union[str, bytes]) -> bytes:
    """
    Normalize a filesystem path to bytes representation.
    
    Parameters:
    - path: Filesystem path as string or bytes
    
    Returns:
    Normalized path as bytes
    """

def syspath(path: Union[str, bytes]) -> str:
    """
    Convert path to system's preferred string representation.
    
    Parameters:
    - path: Filesystem path as string or bytes
    
    Returns:
    Path as Unicode string suitable for system calls
    """

def bytestring_path(path: Union[str, bytes]) -> bytes:
    """
    Convert path to bytestring representation.
    
    Parameters:
    - path: Filesystem path as string or bytes
    
    Returns:
    Path as bytes using filesystem encoding
    """

def displayable_path(path: Union[str, bytes]) -> str:
    """
    Convert path to Unicode string safe for display.
    
    Parameters:
    - path: Filesystem path as string or bytes
    
    Returns:
    Unicode string representation of path
    """

def samefile(p1: Union[str, bytes], p2: Union[str, bytes]) -> bool:
    """
    Check if two paths refer to the same file.
    
    Parameters:
    - p1: First path to compare
    - p2: Second path to compare
    
    Returns:
    True if paths refer to the same file
    """

Safe File Operations

Functions for moving, copying, and linking files with error handling.

def move(src: Union[str, bytes], dest: Union[str, bytes]) -> None:
    """
    Safely move a file from source to destination.
    
    Parameters:
    - src: Source file path
    - dest: Destination file path
    
    Raises:
    FileOperationError: If move operation fails
    """

def copy(src: Union[str, bytes], dest: Union[str, bytes]) -> None:
    """
    Safely copy a file from source to destination.
    
    Parameters:
    - src: Source file path
    - dest: Destination file path
    
    Raises:
    FileOperationError: If copy operation fails
    """

def link(src: Union[str, bytes], dest: Union[str, bytes]) -> None:
    """
    Create a hard link from source to destination.
    
    Parameters:
    - src: Source file path
    - dest: Destination file path
    
    Raises:
    FileOperationError: If linking is not supported or fails
    """

def reflink(src: Union[str, bytes], dest: Union[str, bytes]) -> None:
    """
    Create a copy-on-write link (reflink) if supported.
    
    Parameters:
    - src: Source file path  
    - dest: Destination file path
    
    Raises:
    FileOperationError: If reflinking is not supported or fails
    """

def unique_path(path: Union[str, bytes]) -> Union[str, bytes]:
    """
    Generate a unique file path if the given path already exists.
    
    Parameters:
    - path: Desired file path
    
    Returns:
    Unique path (original or with numeric suffix)
    """

Path Utilities

Functions for path manipulation and analysis.

def ancestry(path: Union[str, bytes]) -> List[Union[str, bytes]]:
    """
    Get all parent directories of a path.
    
    Parameters:
    - path: Filesystem path
    
    Returns:
    List of parent directories from deepest to root
    """

def components(path: Union[str, bytes]) -> List[Union[str, bytes]]:
    """
    Split path into individual components.
    
    Parameters:
    - path: Filesystem path
    
    Returns:
    List of path components
    """

def as_string(value: Any) -> str:
    """
    Convert value to Unicode string safely.
    
    Parameters:
    - value: Value to convert (any type)
    
    Returns:
    Unicode string representation
    """

Template System

Flexible template formatting system for generating paths and strings.

class Template:
    """Template for string formatting with conditional logic and functions."""
    
    def __init__(self, template_string: str):
        """
        Initialize template from format string.
        
        Parameters:
        - template_string: Template format string with $field and %function{} syntax
        """
    
    def substitute(self, values: Dict[str, Any], functions: Dict[str, Callable] = None) -> str:
        """
        Substitute values into template.
        
        Parameters:
        - values: Dictionary mapping field names to values
        - functions: Optional dictionary of template functions
        
        Returns:
        Formatted string with substitutions applied
        """

def template(template_string: str) -> Template:
    """
    Create Template object from format string.
    
    Parameters:
    - template_string: Template format string
    
    Returns:
    Template object ready for substitution
    """

Template Environment

Context for template evaluation with built-in functions.

class Environment:
    """Template evaluation environment with built-in functions."""
    
    def __init__(self, values: Dict[str, Any]):
        """
        Initialize environment with field values.
        
        Parameters:
        - values: Dictionary mapping field names to values
        """
    
    def call_function(self, name: str, args: List[Any]) -> Any:
        """
        Call a template function by name.
        
        Parameters:
        - name: Function name
        - args: Function arguments
        
        Returns:
        Function result
        """

Built-in Template Functions

Template functions available for path formatting and string manipulation.

# String transformation functions
def tmpl_upper(text: str) -> str:
    """Convert text to uppercase."""

def tmpl_lower(text: str) -> str:
    """Convert text to lowercase."""

def tmpl_title(text: str) -> str:
    """Convert text to title case."""

# String manipulation functions  
def tmpl_left(text: str, length: int) -> str:
    """Take leftmost characters up to length."""

def tmpl_right(text: str, length: int) -> str:
    """Take rightmost characters up to length."""

def tmpl_if(condition: Any, then_value: Any, else_value: Any = '') -> Any:
    """Conditional expression (if condition then then_value else else_value)."""

def tmpl_ifdef(field: str, then_value: Any, else_value: Any = '') -> Any:
    """Conditional based on field existence (if field defined then then_value else else_value)."""

def tmpl_asciify(text: str) -> str:
    """Convert Unicode text to ASCII approximation."""

def tmpl_sanitize(text: str) -> str:
    """Remove/replace characters invalid in filenames."""

Template Syntax and Usage

Basic Field Substitution

from beets.util.functemplate import template

# Basic field substitution
tmpl = template('$artist - $title')
result = tmpl.substitute({
    'artist': 'The Beatles',
    'title': 'Hey Jude'
})
# Result: "The Beatles - Hey Jude"

# Path template
path_tmpl = template('$albumartist/$album/$track $title')
path = path_tmpl.substitute({
    'albumartist': 'The Beatles',
    'album': 'Abbey Road', 
    'track': 5,
    'title': 'Here Comes the Sun'
})
# Result: "The Beatles/Abbey Road/05 Here Comes the Sun"

Template Functions

# String transformations
tmpl = template('%upper{$artist} - %lower{$title}')
result = tmpl.substitute({
    'artist': 'The Beatles',
    'title': 'HEY JUDE'
})
# Result: "THE BEATLES - hey jude"

# Conditional formatting
tmpl = template('$artist%if{$year, - $year}')
result = tmpl.substitute({
    'artist': 'The Beatles',
    'year': 1969
})
# Result: "The Beatles - 1969"

# String truncation
tmpl = template('%left{$title,20}')
result = tmpl.substitute({
    'title': 'Very Long Song Title That Needs Truncation'
})
# Result: "Very Long Song Title "

Advanced Template Features

# Nested conditionals
tmpl = template('%if{$albumartist,$albumartist,%if{$artist,$artist,Unknown Artist}}')

# Field existence checks
tmpl = template('%ifdef{$year,$year,0000}')

# Multiple functions
tmpl = template('%upper{%left{$artist,10}}')

# Filename sanitization
tmpl = template('%sanitize{$artist - $title}')

Path Format Configuration

from beets import config
from beets.util.functemplate import template

# Get path formats from configuration
path_formats = config['paths'].get(dict)

# Common path formats
formats = {
    'default': '$albumartist/$album/$track $title',
    'singleton': 'Non-Album/$artist - $title', 
    'comp': 'Compilations/$album/$track $title',
    'albumtype:soundtrack': 'Soundtracks/$album/$track $title'
}

# Apply formats
for pattern, format_str in formats.items():
    tmpl = template(format_str)
    # Use template for path generation

File Operation Examples

Safe File Moving

from beets.util import move, copy, samefile
from beets.library import FileOperationError

def safe_file_operation(src_path, dest_path, operation='move'):
    """Safely perform file operations with error handling."""
    
    try:
        if samefile(src_path, dest_path):
            print("Source and destination are the same file")
            return
            
        if operation == 'move':
            move(src_path, dest_path)
            print(f"Moved: {src_path} -> {dest_path}")
        elif operation == 'copy':
            copy(src_path, dest_path)
            print(f"Copied: {src_path} -> {dest_path}")
            
    except FileOperationError as e:
        print(f"File operation failed: {e}")
        raise

Path Generation

from beets.util import unique_path, displayable_path
from beets.util.functemplate import template

def generate_item_path(item, library):
    """Generate destination path for a library item."""
    
    # Get path format template
    path_template = template(library.path_format_for_item(item))
    
    # Generate path
    dest_path = path_template.substitute(item.formatted())
    
    # Ensure path is unique
    dest_path = unique_path(dest_path)
    
    # Convert to displayable format
    display_path = displayable_path(dest_path)
    
    return dest_path, display_path

Directory Creation

import os
from beets.util import ancestry, displayable_path

def ensure_directory_exists(path):
    """Create directory and all parent directories if needed."""
    
    directory = os.path.dirname(path)
    
    if not os.path.exists(directory):
        try:
            os.makedirs(directory, exist_ok=True)
            print(f"Created directory: {displayable_path(directory)}")
        except OSError as e:
            print(f"Failed to create directory {displayable_path(directory)}: {e}")
            raise

Art and Image Utilities

Image Resizing

class ArtResizer:
    """Utility for resizing and processing album artwork."""
    
    def __init__(self, quality: int = 95):
        """
        Initialize art resizer.
        
        Parameters:
        - quality: JPEG quality for output (1-100)
        """
    
    def resize(self, image_path: str, output_path: str, size: Tuple[int, int]) -> None:
        """
        Resize image to specified dimensions.
        
        Parameters:
        - image_path: Source image file path
        - output_path: Destination image file path  
        - size: Target (width, height) tuple
        """
    
    def thumbnail(self, image_path: str, output_path: str, size: int) -> None:
        """
        Create square thumbnail of image.
        
        Parameters:
        - image_path: Source image file path
        - output_path: Destination image file path
        - size: Thumbnail size (width and height)
        """

Image Format Conversion

from beets.util.artresizer import ArtResizer

def convert_artwork(src_path, dest_path, max_size=500):
    """Convert and resize artwork for embedding."""
    
    resizer = ArtResizer(quality=90)
    
    try:
        # Create thumbnail
        resizer.thumbnail(src_path, dest_path, max_size)
        print(f"Created artwork: {dest_path}")
        
    except Exception as e:
        print(f"Artwork conversion failed: {e}")
        raise

Pipeline Processing

Parallel Processing Utilities

class Pipeline:
    """Parallel processing pipeline for import operations."""
    
    def __init__(self, stages: List[Callable]):
        """
        Initialize processing pipeline.
        
        Parameters:
        - stages: List of processing functions
        """
    
    def run_parallel(self, items: List[Any], threads: int = 4) -> List[Any]:
        """
        Process items through pipeline stages in parallel.
        
        Parameters:
        - items: List of items to process
        - threads: Number of worker threads
        
        Returns:
        List of processed items
        """

Processing Example

from beets.util.pipeline import Pipeline

def process_import_batch(items):
    """Process a batch of items through parallel pipeline."""
    
    def load_metadata(item):
        """Load metadata from file."""
        item.load()
        return item
    
    def tag_item(item):
        """Apply automatic tagging."""
        # Tagging logic here
        return item
    
    def write_tags(item):
        """Write tags back to file."""
        item.write()
        return item
    
    # Create processing pipeline
    pipeline = Pipeline([load_metadata, tag_item, write_tags])
    
    # Process items in parallel
    processed = pipeline.run_parallel(items, threads=4)
    
    return processed

Error Handling

class FileOperationError(Exception):
    """Raised when file operations fail."""
    
    def __init__(self, operation: str, path: str, error: Exception):
        """
        Initialize file operation error.
        
        Parameters:
        - operation: Operation that failed ('move', 'copy', etc.)
        - path: File path involved in operation
        - error: Underlying exception
        """

class HumanReadableError(Exception):
    """Base for errors with human-readable messages."""
    
    def log(self, logger) -> None:
        """Log error with appropriate level and formatting."""

Error Handling Examples

from beets.util import FileOperationError, displayable_path

def handle_file_errors(operation_func, *args):
    """Wrapper for file operations with error handling."""
    
    try:
        return operation_func(*args)
        
    except FileOperationError as e:
        print(f"File operation failed: {e}")
        print(f"Path: {displayable_path(e.path)}")
        raise
        
    except PermissionError as e:
        print(f"Permission denied: {displayable_path(e.filename)}")
        raise
        
    except OSError as e:
        print(f"System error: {e}")
        raise

This comprehensive utilities system provides the foundation for all file operations, path manipulation, and template formatting in beets, ensuring cross-platform compatibility and robust error handling.

Install with Tessl CLI

npx tessl i tessl/pypi-beets

docs

configuration.md

import-autotag.md

index.md

library-management.md

plugin-system.md

query-system.md

user-interface.md

utilities-templates.md

tile.json