CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-clint

Python Command Line Interface Tools for colored output, progress bars, text formatting, and argument handling

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

resources.mddocs/

Application Resources

Cross-platform application directory management for user data, site data, cache, and log directories. The resources module provides file operations, subdirectory management with automatic directory creation, and platform-appropriate directory locations following OS conventions.

Capabilities

Initialization

Initialize application directories with vendor and application name for cross-platform directory management.

def init(vendor, name):
    """
    Initialize application directories for the given vendor and application name.
    
    Args:
        vendor (str): Vendor/company name
        name (str): Application name
    
    Side Effects:
        Sets up global user, site, cache, and log directory instances
        with platform-appropriate paths
    """

Usage Example:

from clint import resources

# Initialize application directories
resources.init('MyCompany', 'MyApp')

# Now you can use the global directory instances
config_file = resources.user.write('config.json', '{"setting": "value"}')
log_entry = resources.log.append('app.log', 'Application started\n')

Application Directory Class

Main class for managing application directories with file operations and subdirectory support.

class AppDir:
    """
    Application Directory object for managing files and subdirectories.
    
    Args:
        path (str): Directory path (optional, can be set later)
    
    Attributes:
        path (str): The directory path
        _exists (bool): Internal flag tracking directory existence
    """
    
    def __init__(self, path=None):
        """Initialize AppDir with optional path."""

File Writing Operations

Write content to files within the application directory with automatic directory creation.

def write(self, filename, content, binary=False):
    """
    Write content to a file in the application directory.
    
    Args:
        filename (str): Name of the file to write
        content (str or bytes): Content to write to the file
        binary (bool): Whether to write in binary mode (default: False)
    
    Side Effects:
        Creates the application directory if it doesn't exist
        Creates or overwrites the specified file
    """

def append(self, filename, content, binary=False):
    """
    Append content to a file in the application directory.
    
    Args:
        filename (str): Name of the file to append to
        content (str or bytes): Content to append to the file
        binary (bool): Whether to write in binary mode (default: False)
    
    Returns:
        bool: True on successful append
    
    Side Effects:
        Creates the application directory if it doesn't exist
        Creates the file if it doesn't exist, otherwise appends
    """

Usage Examples:

from clint import resources

resources.init('MyCompany', 'MyApp')

# Write configuration file
resources.user.write('settings.ini', '[DEFAULT]\ntheme=dark\n')

# Write binary data
image_data = b'\x89PNG\r\n\x1a\n...'  # PNG file data
resources.user.write('avatar.png', image_data, binary=True)

# Append to log file
resources.log.append('error.log', '2023-01-01 12:00:00 - Error occurred\n')

# Append binary data
resources.cache.append('data.bin', b'\x00\x01\x02', binary=True)

File Reading Operations

Read content from files within the application directory with support for both text and binary modes.

def read(self, filename, binary=False):
    """
    Read content from a file in the application directory.
    
    Args:
        filename (str): Name of the file to read
        binary (bool): Whether to read in binary mode (default: False)
    
    Returns:
        str or bytes or None: File content, or None if file doesn't exist
    """

def open(self, filename, mode='r'):
    """
    Open a file in the application directory and return file object.
    
    Args:
        filename (str): Name of the file to open
        mode (str): File open mode ('r', 'w', 'a', 'rb', etc.)
    
    Returns:
        file: File object for the opened file
    """

Usage Examples:

from clint import resources

resources.init('MyCompany', 'MyApp')

# Read text file
config_content = resources.user.read('config.txt')
if config_content:
    print("Config:", config_content)

# Read binary file
image_data = resources.user.read('avatar.png', binary=True)
if image_data:
    print("Image size:", len(image_data), "bytes")

# Use file object for more control
with resources.log.open('app.log', 'r') as f:
    for line in f:
        if 'ERROR' in line:
            print("Error found:", line.strip())

# Write with file object
with resources.user.open('data.csv', 'w') as f:
    f.write('name,age,city\n')
    f.write('John,25,NYC\n')

File and Directory Management

Delete files and directories, and manage subdirectories within the application directory.

def delete(self, filename=''):
    """
    Delete a file or directory within the application directory.
    
    Args:
        filename (str): Name of file/directory to delete, or empty string
                       to delete the application directory itself
    
    Side Effects:
        Removes the specified file or directory
        Ignores errors if file/directory doesn't exist
    """

def sub(self, path):
    """
    Create an AppDir instance for a subdirectory.
    
    Args:
        path (str or list): Subdirectory path or path components
    
    Returns:
        AppDir: New AppDir instance for the subdirectory
    """

Usage Examples:

from clint import resources

resources.init('MyCompany', 'MyApp')

# Create subdirectory
config_dir = resources.user.sub('config')
config_dir.write('database.ini', '[database]\nhost=localhost\n')

# Nested subdirectories
temp_dir = resources.cache.sub(['temp', 'downloads'])
temp_dir.write('file.tmp', 'temporary data')

# Delete specific file
resources.log.delete('old.log')

# Delete subdirectory
config_dir.delete()  # Deletes the entire config subdirectory

# Path components as list
logs_dir = resources.log.sub(['application', 'errors'])
logs_dir.write('critical.log', 'Critical error occurred')

Global Directory Instances

Pre-configured global directory instances available after initialization.

user = AppDir()    # User data directory
site = AppDir()    # Site-wide data directory  
cache = AppDir()   # User cache directory
log = AppDir()     # User log directory

Platform-specific Directory Locations:

After calling resources.init('Vendor', 'App'), directories are set to platform-appropriate locations:

  • Linux/Unix:

    • user: ~/.local/share/App
    • cache: ~/.cache/App
    • log: ~/.cache/App/log
  • macOS:

    • user: ~/Library/Application Support/App
    • cache: ~/Library/Caches/App
    • log: ~/Library/Logs/App
  • Windows:

    • user: %APPDATA%\Vendor\App
    • cache: %LOCALAPPDATA%\Vendor\App\Cache
    • log: %LOCALAPPDATA%\Vendor\App\Logs

Usage Examples:

from clint import resources

# Must initialize first
resources.init('MyCompany', 'MyApp')

# User data (settings, user files)
resources.user.write('preferences.json', '{"theme": "dark"}')

# Site-wide data (shared across users)
resources.site.write('templates.json', '{"default": "template.html"}')

# Cache data (temporary, can be deleted)
resources.cache.write('downloaded_data.json', '{"cached_at": "2023-01-01"}')

# Log files
resources.log.write('app.log', '2023-01-01 12:00:00 - App started\n')
resources.log.append('app.log', '2023-01-01 12:01:00 - User logged in\n')

Exception Handling

Exception raised when attempting to use directories before initialization.

class NotConfigured(IOError):
    """
    Exception raised when attempting to use AppDir before calling init().
    
    Raised when:
        - File operations are attempted on uninitialized AppDir instances
        - Global directory instances are used before resources.init()
    """

Usage Example:

from clint import resources

try:
    # This will raise NotConfigured
    resources.user.write('test.txt', 'content')
except resources.NotConfigured:
    print("Must call resources.init() first")
    resources.init('MyCompany', 'MyApp')
    resources.user.write('test.txt', 'content')  # Now works

Complete Usage Pattern

from clint import resources

# Initialize application directories
resources.init('MyCompany', 'AwesomeApp')

# Write configuration
config = {
    'database_url': 'sqlite:///app.db',
    'debug': False,
    'log_level': 'INFO'
}
resources.user.write('config.json', json.dumps(config, indent=2))

# Create organized subdirectories
db_dir = resources.user.sub('database')
db_dir.write('schema.sql', 'CREATE TABLE users (id INTEGER PRIMARY KEY);')

templates_dir = resources.site.sub('templates')
templates_dir.write('base.html', '<html><head><title>{{title}}</title></head></html>')

# Cache management
cache_data = {'last_update': '2023-01-01', 'version': '1.0'}
resources.cache.write('metadata.json', json.dumps(cache_data))

# Logging setup
import datetime
log_entry = f"{datetime.datetime.now()} - Application initialized\n"
resources.log.write('app.log', log_entry)

# Clean up old cache files
resources.cache.delete('old_cache.json')

# Read configuration on startup
saved_config = resources.user.read('config.json')
if saved_config:
    config = json.loads(saved_config)
    print(f"Loaded config: {config}")

Install with Tessl CLI

npx tessl i tessl/pypi-clint

docs

arguments.md

colored-text.md

english.md

index.md

progress.md

prompts.md

resources.md

text-output.md

utilities.md

validation.md

tile.json