🔍 Code Extractor

function ensure_path_exists

Maturity: 56

Recursively creates a directory path in FileCloud storage by ensuring all parent directories exist before creating child directories.

File:
/tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
Lines:
162 - 199
Complexity:
moderate

Purpose

This function ensures that a complete directory path exists in FileCloud by recursively checking and creating each directory level from root to the target path. It handles the case where intermediate directories may not exist and creates them in the correct order. This is essential for file upload operations where the destination path must exist before files can be stored.

Source Code

def ensure_path_exists(client, path: str) -> bool:
    """
    Recursively ensure a path exists in FileCloud.
    
    Args:
        client: FileCloud client
        path: Path to ensure exists
    
    Returns:
        Boolean indicating success
    """
    # Base case - empty path
    if not path or path == '/':
        return True
    
    # Check if the path already exists
    try:
        exists = client.check_folder_exists(path)
        if exists:
            return True
    except Exception:
        pass
    
    # Split the path into parent and folder name
    path_parts = path.split('/')
    folder_name = path_parts[-1]
    parent_path = '/'.join(path_parts[:-1])
    
    # Ensure the parent path exists
    if not ensure_path_exists(client, parent_path):
        return False
    
    # Create the current folder
    try:
        result = client.create_folder(path=parent_path, folder_name=folder_name)
        return result.get('success', False)
    except Exception:
        return False

Parameters

Name Type Default Kind
client - - positional_or_keyword
path str - positional_or_keyword

Parameter Details

client: A FileCloud client object (FileCloudAPI instance) that provides methods for interacting with FileCloud storage, including check_folder_exists() and create_folder() methods. This client must be authenticated and connected to the FileCloud service.

path: A string representing the full directory path to ensure exists in FileCloud. Should be in Unix-style format with forward slashes (e.g., '/parent/child/grandchild'). Can be an empty string or '/' for the root directory. The path should not include a trailing slash unless it's the root path.

Return Value

Type: bool

Returns a boolean value: True if the path exists or was successfully created (including all parent directories), False if any error occurred during path creation or verification. A True return guarantees the complete path is available for use in FileCloud.

Dependencies

  • CDocs.utils.FC_api

Required Imports

from CDocs.utils.FC_api import FileCloudAPI

Usage Example

from CDocs.utils.FC_api import FileCloudAPI

# Initialize FileCloud client with credentials
client = FileCloudAPI(
    base_url='https://filecloud.example.com',
    username='user@example.com',
    password='password'
)

# Ensure a nested path exists
path = '/documents/2024/reports/quarterly'
success = ensure_path_exists(client, path)

if success:
    print(f'Path {path} is ready for use')
    # Now you can upload files to this path
    # client.upload_file(path, 'report.pdf')
else:
    print(f'Failed to create path {path}')

# Handle root path
ensure_path_exists(client, '/')  # Returns True

# Handle empty path
ensure_path_exists(client, '')  # Returns True

Best Practices

  • Always check the return value to ensure the path was successfully created before attempting to use it
  • The function silently catches all exceptions and returns False, so additional logging may be needed for debugging
  • Ensure the FileCloud client is properly authenticated before calling this function
  • The function uses recursion, so extremely deep paths could potentially cause stack overflow (though unlikely in practice)
  • Path should use forward slashes (/) as separators, consistent with Unix-style paths
  • The function is idempotent - calling it multiple times with the same path is safe and will return True if the path exists
  • Consider implementing retry logic at a higher level if network issues are common in your environment
  • The function does not validate path characters or length - ensure paths conform to FileCloud requirements before calling

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_dir_exists 70.9% similar

    Creates a directory and all necessary parent directories if they don't already exist, with logging support.

    From: /tf/active/vicechatdev/msg_to_eml.py
  • function ensure_dir 69.6% similar

    Creates a directory and all necessary parent directories if they don't already exist, returning a boolean indicating success or failure.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function create_folder 64.3% similar

    Creates a nested folder structure on a FileCloud server by traversing a path and creating missing directories.

    From: /tf/active/vicechatdev/filecloud_wuxi_sync.py
  • function ensure_document_folders 63.8% similar

    Ensures all required folder hierarchies exist in FileCloud storage for a controlled document, creating them if they don't exist.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function check_filecloud_structure 57.7% similar

    Diagnostic function that checks the FileCloud server structure and verifies accessibility of various paths including root, SHARED, and configured base paths.

    From: /tf/active/vicechatdev/SPFCsync/check_filecloud_structure.py
← Back to Browse