logo_smallAxellero.io

Create Directory

Create directories and manage folder structures in the sandbox environment with permission control, nested creation, and template support.

Create Directory

Create and manage directory structures within the sandbox environment with support for nested creation, permission control, directory templates, and organizational patterns.

📁 Directory Management

Directory creation includes permission control, nested structure support, template-based organization, and validation to ensure proper file system organization within the sandbox.

Overview

The Create Directory tool enables comprehensive directory management within the sandbox environment, supporting nested directory creation, permission control, organizational templates, and batch operations for efficient file system organization.

Key Features

  • Nested Creation - Create deep directory structures in single operations
  • Permission Control - Set directory permissions and access controls
  • Template Support - Create standardized directory structures
  • Validation - Path validation and conflict resolution
  • Batch Operations - Create multiple directories efficiently

Methods

createDirectory

Create directories and directory structures in the sandbox environment.

ParameterTypeRequiredDescription
directoryPathStringYesPath where directory should be created
recursiveBooleanNoCreate parent directories if needed (default: true)
permissionsStringNoDirectory permissions (e.g., '755', '644') (default: '755')
overwriteBooleanNoOverwrite existing directory (default: false)
templateStringNoUse predefined directory template
metadataObjectNoDirectory metadata and properties
{
  "directoryPath": "/sandbox/projects/new-project",
  "recursive": true,
  "permissions": "755",
  "template": "project",
  "metadata": {
    "description": "New data analysis project",
    "created_by": "system"
  }
}

Output:

  • success (Boolean) - Directory creation success status
  • directoryPath (String) - Path to the created directory
  • created (Boolean) - Whether directory was newly created
  • exists (Boolean) - Whether directory already existed
  • permissions (String) - Applied directory permissions
  • parentDirectories (Array) - List of parent directories created
  • structure (Object) - Created directory structure information
  • metadata (Object) - Applied metadata and properties

Basic Directory Creation

Simple Directory Operations

Directory Templates

Predefined Structures

Batch Directory Operations

Multiple Directory Creation

def create_directory_batch(directory_specs):
    """Create multiple directories in a batch operation."""
    
    results = {
        "successful": [],
        "failed": [],
        "total": len(directory_specs)
    }
    
    for spec in directory_specs:
        try:
            # Handle both string paths and detailed specifications
            if isinstance(spec, str):
                directory_spec = {
                    "directoryPath": spec,
                    "recursive": True,
                    "permissions": "755"
                }
            else:
                directory_spec = spec
            
            result = createDirectory(directory_spec)
            
            if result['success']:
                results["successful"].append({
                    "path": directory_spec['directoryPath'],
                    "result": result
                })
                print(f"✅ Created: {directory_spec['directoryPath']}")
            else:
                results["failed"].append({
                    "path": directory_spec['directoryPath'],
                    "error": result.get('error', 'Unknown error')
                })
                print(f"❌ Failed: {directory_spec['directoryPath']}")
                
        except Exception as e:
            path = spec if isinstance(spec, str) else spec.get('directoryPath', 'Unknown')
            results["failed"].append({
                "path": path,
                "error": str(e)
            })
            print(f"💥 Exception: {path} - {str(e)}")
    
    return results

def setup_workspace_directories(workspace_name):
    """Set up complete workspace with multiple directory types."""
    
    base_path = f"/sandbox/workspaces/{workspace_name}"
    
    directory_specs = [
        f"{base_path}/input",
        f"{base_path}/processing",
        f"{base_path}/output",
        f"{base_path}/temp",
        f"{base_path}/archive",
        f"{base_path}/logs",
        f"{base_path}/config",
        f"{base_path}/scripts",
        f"{base_path}/data/raw",
        f"{base_path}/data/processed",
        f"{base_path}/reports/daily",
        f"{base_path}/reports/weekly",
        f"{base_path}/reports/monthly",
        f"{base_path}/backup/incremental",
        f"{base_path}/backup/full"
    ]
    
    batch_result = create_directory_batch(directory_specs)
    
    if batch_result["successful"]:
        # Create workspace manifest
        manifest = {
            "workspace_name": workspace_name,
            "created_at": datetime.datetime.now().isoformat(),
            "directories": [item["path"] for item in batch_result["successful"]],
            "total_directories": len(batch_result["successful"]),
            "failed_directories": len(batch_result["failed"])
        }
        
        writeFile({
            "filePath": f"{base_path}/workspace_manifest.json",
            "content": manifest,
            "format": "json"
        })
    
    return batch_result

# Usage
workspace_result = setup_workspace_directories("analytics-workspace")
print(f"Workspace setup: {len(workspace_result['successful'])} directories created, {len(workspace_result['failed'])} failed")

Directory Validation and Management

Structure Validation

def validate_and_repair_structure(base_path, expected_structure):
    """Validate directory structure and repair missing directories."""
    
    validation_results = {
        "valid": True,
        "missing": [],
        "repaired": [],
        "errors": []
    }
    
    def validate_level(current_path, expected):
        """Recursively validate and repair directory structure."""
        
        for dir_name, subdirs in expected.items():
            dir_path = f"{current_path}/{dir_name}"
            
            # Check if directory exists
            check_result = listFiles({
                "path": dir_path,
                "recursive": False,
                "limit": 1
            })
            
            if not check_result['success']:
                # Directory missing, attempt to create
                validation_results["missing"].append(dir_path)
                validation_results["valid"] = False
                
                try:
                    repair_result = createDirectory({
                        "directoryPath": dir_path,
                        "recursive": True,
                        "permissions": "755"
                    })
                    
                    if repair_result['success']:
                        validation_results["repaired"].append(dir_path)
                        print(f"🔧 Repaired: {dir_path}")
                    else:
                        validation_results["errors"].append({
                            "path": dir_path,
                            "error": "Failed to repair"
                        })
                        print(f"❌ Cannot repair: {dir_path}")
                        
                except Exception as e:
                    validation_results["errors"].append({
                        "path": dir_path,
                        "error": str(e)
                    })
            else:
                print(f"✅ Valid: {dir_path}")
            
            # Recursively validate subdirectories
            if subdirs and isinstance(subdirs, dict):
                validate_level(dir_path, subdirs)
    
    validate_level(base_path, expected_structure)
    
    return validation_results

# Usage with automatic repair
repair_result = validate_and_repair_structure("/sandbox/projects/data-analysis", project_structure)
print(f"Validation: {len(repair_result['missing'])} missing, {len(repair_result['repaired'])} repaired")

Error Handling

Common Directory Creation Issues

Error TypeCauseResolution
Permission DeniedInsufficient create permissionsCheck parent directory permissions
Path Already ExistsDirectory already existsUse overwrite option or check existence first
Invalid PathMalformed directory pathValidate path format and characters
Disk Space FullInsufficient storage spaceFree up space or use different location
Parent Directory MissingParent directory doesn't existUse recursive=true or create parents first

Robust Directory Creation

def robust_directory_creation(directory_path, max_retries=3):
    """Create directory with comprehensive error handling."""
    
    import time
    
    for attempt in range(max_retries):
        try:
            # Validate path first
            if not directory_path.startswith("/sandbox/"):
                return {"error": "Path must be within sandbox"}
            
            # Attempt creation
            result = createDirectory({
                "directoryPath": directory_path,
                "recursive": True,
                "permissions": "755"
            })
            
            if result['success']:
                # Verify creation by listing
                verify_result = listFiles({
                    "path": directory_path,
                    "recursive": False,
                    "limit": 1
                })
                
                if verify_result['success']:
                    return {
                        "success": True,
                        "directoryPath": directory_path,
                        "verified": True,
                        "attempt": attempt + 1
                    }
                else:
                    print(f"⚠️ Created but cannot verify: {directory_path}")
                    return result
            else:
                error_msg = result.get('error', 'Unknown error')
                print(f"Attempt {attempt + 1} failed: {error_msg}")
                
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)  # Exponential backoff
                
        except Exception as e:
            print(f"Attempt {attempt + 1} exception: {str(e)}")
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)
    
    return {"error": f"Failed to create directory after {max_retries} attempts"}

# Usage with retry logic
robust_result = robust_directory_creation("/sandbox/critical/important-data")
if robust_result.get('success'):
    print(f"✅ Directory created successfully (attempt {robust_result['attempt']})")
else:
    print(f"❌ Failed to create directory: {robust_result['error']}")

Next Steps: Use with Write File to populate created directories, or List Files to verify directory structures.