UNPKG

structure-validation

Version:

A Node.js CLI tool for validating codebase folder and file structure using a clean declarative configuration. Part of the guardz ecosystem for comprehensive TypeScript development.

554 lines (425 loc) 15.9 kB
# Structure Validation [![npm version](https://badge.fury.io/js/structure-validation.svg)](https://badge.fury.io/js/structure-validation) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md) A Node.js CLI tool for validating and maintaining consistent codebase folder and file structure using declarative configuration. **Now with automatic import updates!** 🚀 ## Why Structure Validation? Maintaining a clean, consistent file structure across your codebase is crucial for: - **Team Productivity** - Developers can quickly locate files - **Code Quality** - Enforced patterns prevent structural debt - **Scalability** - Consistent structure scales with your project - **Onboarding** - New team members understand the codebase faster ## Features - **🔍 Declarative Configuration** - Define your structure rules in TypeScript - **🚀 Fast Validation** - Built with performance in mind for large codebases - **🛠️ Auto-fix Mode** - Automatically move files to correct locations - **📦 Git Integration** - Validate staged, changed, or all files - **🎯 Pattern Matching** - Support for glob patterns and variable placeholders - **🔧 Husky Integration** - Pre-commit hooks for consistent validation - **📊 Detailed Reporting** - Clear error messages and suggestions - **🔄 Automatic Import Updates** - **NEW!** Automatically update import statements when files are moved or renamed - **📁 Smart File Operations** - Comprehensive file operations with import management - **🛡️ Enhanced Error Handling** - Better user experience with detailed error reporting - **⚡ Batch Operations** - Efficient handling of multiple file operations ## Quick Start ### Installation ```bash npm install structure-validation ``` ### Basic Usage 1. **Create Configuration** Create `structure-validation.config.json` in your project root: ```json { "root": ".", "structure": { "components": ["*.tsx"], "services": ["*.service.ts"], "hooks": ["use*.ts", "use*.tsx"], "utils": ["*.util.ts"], "{a}": ["{a}.ts", "{a}.tsx", "{a}.*.ts", "{a}.*.tsx"], "{root}": ["*.config.json", "package.json", "README.md", "tsconfig.json"], "**": ["*.test.ts", "*.test.tsx", "index.ts", "index.tsx", "page.tsx", "route.ts", "not-found.tsx"] } } ``` 2. **Run Validation** ```bash # Validate staged files (default) npx structure-validation # Validate all files npx structure-validation --scope all # Auto-fix issues with automatic import updates npx structure-validation --fix # Validate with root folder verification npx structure-validation --verify-root ``` ## CLI Options ```bash npx structure-validation [options] Options: --scope <scope> all, staged, or changes (default: staged) --files <files> Specific files to validate --config <path> Config file path (default: structure-validation.config.json) --fix Auto-fix file structure issues with import updates --dry-run Preview changes without applying --backup Create backup before fixing (default: true) --verify-root Enable root folder validation --skip-error Skip interactive mode and continue on errors -h, --help Show help -v, --version Show version ``` ## Automatic Import Updates **NEW FEATURE!** Structure Validation now automatically updates import statements when files are moved, renamed, or deleted. This ensures your code continues to work after file operations. ### How It Works When you move or rename files, the tool: 1. **Detects all import statements** that reference the moved/renamed files 2. **Calculates new relative paths** based on the new file location 3. **Updates all import statements** automatically 4. **Validates the changes** to ensure code functionality is maintained ### Example ```bash # Move a file and automatically update all imports npx structure-validation --fix # The tool will: # 1. Move src/utils/helper.ts → shared/utils/helper.ts # 2. Update all imports from './utils/helper' to '../../shared/utils/helper' # 3. Validate that all imports are correctly updated ``` ### Supported Import Types - **Named imports**: `import { name } from './module'` - **Default imports**: `import defaultExport from './module'` - **Namespace imports**: `import * as namespace from './module'` - **Type imports**: `import type { Type } from './module'` - **Mixed imports**: `import defaultExport, { named } from './module'` For detailed information about automatic import updates, see [AUTOMATIC_IMPORT_UPDATES.md](docs/AUTOMATIC_IMPORT_UPDATES.md). ## Pattern Examples ### Basic Patterns - `*.tsx` - Files ending with .tsx - `use*.ts` - Files starting with "use" and ending with .ts - `*.service.ts` - Files ending with .service.ts ### Variable Placeholders - `{a}.ts` - Matches `user.ts` in `user/` folder - `{a}.*.ts` - Matches `user.profile.ts` in `user/` folder - `{root}` - Root folder patterns (use with `--verify-root`) ### Global Patterns - `**` - Applies to all folders (e.g., `*.test.ts`, `index.ts`) ## Examples ### Validate All Files ```bash npx structure-validation --scope all ``` ### Auto-fix with Import Updates ```bash npx structure-validation --scope all --fix ``` ### Preview Changes ```bash npx structure-validation --scope all --dry-run ``` ### Validate Root Folder ```bash npx structure-validation --verify-root ``` ### Interactive Mode ```bash # Start interactive mode for fixing validation errors npx structure-validation # Skip interactive mode and continue on errors npx structure-validation --skip-error ``` In interactive mode, you'll be prompted for each file with validation errors: - **1** - Move to subfolder (automatically uses suggested folder name) - **2** - Rename file (keep extension) - **3** - Move to upper folder (creates folder with suggested name if needed) - **4** - Delete file - **5** - Add file to structure-validation.config.json (modifies config and restarts) - **6** - Add file pattern to structure-validation.config.json (modifies config and restarts) - **7** - Skip this file (adds to structure-validation.skip.json) The subfolder suggestions are based on your structure-validation.config.json file: - File patterns in the config determine the suggested folder - Matches are found by comparing filename against configured patterns - Special patterns like {root}, {a}, and ** are excluded from suggestions **Skip functionality:** - Skipped files are stored in `structure-validation.skip.json` - Skipped files are automatically excluded from future validation runs - The skip file persists across sessions ## Husky Integration Structure Validation integrates seamlessly with Husky to verify folder structure before commits, ensuring code quality and consistency across your team. ### 🚀 Quick Setup ```bash # Install Husky and structure-validation npm install --save-dev husky structure-validation # Initialize Husky npx husky init # Add pre-commit hook npx husky add .husky/pre-commit "npx structure-validation --scope staged --verify-root" ``` ### 📋 Recommended Configuration Add these scripts to your `package.json` for comprehensive validation: ```json { "scripts": { "validate:staged": "structure-validation --scope staged --verify-root", "validate:all": "structure-validation --scope all --verify-root", "validate:fix": "structure-validation --scope staged --fix --verify-root", "validate:preview": "structure-validation --scope staged --dry-run", "validate:interactive": "structure-validation --scope staged" }, "husky": { "hooks": { "pre-commit": "npm run validate:staged" } } } ``` ### 🔧 Advanced Husky Setup For more control over the validation process: ```bash # Create a custom pre-commit script cat > .husky/pre-commit << 'EOF' #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" # Validate staged files echo "🔍 Validating file structure..." npx structure-validation --scope staged --verify-root # If validation fails, show helpful message if [ $? -ne 0 ]; then echo "" echo "❌ File structure validation failed!" echo "💡 Run 'npm run validate:interactive' to fix issues interactively" echo "💡 Run 'npm run validate:fix' to auto-fix issues" echo "💡 Run 'npm run validate:preview' to preview changes" exit 1 fi echo "✅ File structure validation passed!" EOF # Make the script executable chmod +x .husky/pre-commit ``` ### 🎯 Validation Strategies #### 1. **Staged Files Only** (Recommended for pre-commit) ```bash # Validates only files that are staged for commit npx structure-validation --scope staged --verify-root ``` #### 2. **All Files** (Use for CI/CD or manual validation) ```bash # Validates all files in the repository npx structure-validation --scope all --verify-root ``` #### 3. **Auto-fix Mode** (Use with caution) ```bash # Automatically fixes structure issues with import updates npx structure-validation --scope staged --fix --verify-root ``` #### 4. **Interactive Mode** (Best for manual fixes) ```bash # Interactive mode for fixing validation errors npx structure-validation --scope staged ``` ### 🛠️ Team Workflow Integration #### For Development Teams 1. **Initial Setup**: ```bash # Install dependencies npm install --save-dev husky structure-validation # Setup Husky npx husky init # Add pre-commit hook npx husky add .husky/pre-commit "npm run validate:staged" ``` 2. **Configuration File**: Create `structure-validation.config.json` in your project root: ```json { "root": ".", "structure": { "components": ["*.tsx"], "services": ["*.service.ts"], "hooks": ["use*.ts", "use*.tsx"], "utils": ["*.util.ts"], "{root}": ["*.config.json", "package.json", "README.md"], "**": ["*.test.ts", "index.ts"] } } ``` 3. **Team Guidelines**: - Commit frequently to catch issues early - Use `npm run validate:interactive` for complex fixes - Use `npm run validate:preview` to preview changes - Run `npm run validate:all` before major releases #### For CI/CD Pipelines Add to your GitHub Actions workflow: ```yaml name: Structure Validation on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' cache: 'npm' - name: Install dependencies run: npm ci - name: Validate structure run: npx structure-validation --scope changes --verify-root - name: Auto-fix if needed run: npx structure-validation --scope changes --fix --verify-root continue-on-error: true ``` ### 🔍 Troubleshooting Husky Integration #### Common Issues 1. **Pre-commit hook not running**: ```bash # Check if Husky is properly installed ls -la .husky/ # Reinstall Husky if needed npm uninstall husky npm install --save-dev husky npx husky init ``` 2. **Validation taking too long**: ```bash # Use staged files only for faster validation npx structure-validation --scope staged # Or validate specific files npx structure-validation --files src/components/ ``` 3. **False positives**: ```bash # Add files to skip list npx structure-validation --scope staged # Choose option 7 to skip problematic files ``` 4. **Import update conflicts**: ```bash # Use dry-run to preview changes npx structure-validation --scope staged --dry-run # Or use interactive mode for manual control npx structure-validation --scope staged ``` #### Performance Tips - **Use staged files only** for pre-commit hooks - **Exclude large directories** in your config - **Use specific file patterns** instead of broad globs - **Run full validation** only in CI/CD ### 📊 Monitoring and Reporting #### Git Hooks Logging Add logging to your pre-commit hook: ```bash #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" echo "🔍 Validating file structure..." npx structure-validation --scope staged --verify-root 2>&1 | tee .validation.log if [ $? -ne 0 ]; then echo "❌ Validation failed. Check .validation.log for details" exit 1 fi echo "✅ Validation passed!" ``` #### Team Notifications For team environments, consider adding Slack/Discord notifications: ```bash #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" echo "🔍 Validating file structure..." npx structure-validation --scope staged --verify-root if [ $? -ne 0 ]; then # Send notification to team channel curl -X POST -H 'Content-type: application/json' \ --data '{"text":"❌ File structure validation failed in $(pwd)"}' \ $SLACK_WEBHOOK_URL exit 1 fi ``` ### 🎯 Best Practices 1. **Start Small**: Begin with basic validation, then add complexity 2. **Team Training**: Educate team on structure-validation commands 3. **Gradual Rollout**: Start with warnings, then enforce strictly 4. **Documentation**: Keep team guidelines updated 5. **Regular Reviews**: Periodically review and update validation rules ## Configuration ### Configuration Examples #### Basic Configuration ```json { "root": ".", "structure": { "components": ["*.tsx"], "services": ["*.service.ts"], "utils": ["*.util.ts"], "{a}": ["{a}.ts", "{a}.*.ts"], "{root}": ["*.config.json", "package.json"], "**": ["*.test.ts", "index.ts"] } } ``` #### Advanced Configuration with Import Updates ```json { "root": ".", "structure": { "components": ["*.tsx"], "services": ["*.service.ts"], "utils": ["*.util.ts"], "hooks": ["use*.ts", "use*.tsx"], "types": ["*.type.ts", "*.interface.ts", "*.d.ts"], "{a}": ["{a}.ts", "{a}.*.ts"], "{root}": ["*.config.json", "package.json"], "**": ["*.test.ts", "index.ts"] } } ``` ## File Operations with Import Updates The tool provides comprehensive file operations that automatically handle import updates: ### Moving Files ```typescript import { FileOperationService } from 'structure-validation'; const fileOperationService = new FileOperationService(); // Move a file and automatically update all imports const result = await fileOperationService.moveFile( 'src/utils/helper.ts', 'shared/utils/helper.ts' ); ``` ### Renaming Files ```typescript // Rename a file and automatically update all imports const result = await fileOperationService.renameFile( 'src/services/OldService.ts', 'NewService.ts' ); ``` ### Batch Operations ```typescript // Move multiple files and update all imports in a single operation const moves = [ { sourcePath: 'src/components/Button.tsx', targetPath: 'ui/components/Button.tsx' }, { sourcePath: 'src/components/Input.tsx', targetPath: 'ui/components/Input.tsx' } ]; const results = await fileOperationService.batchMoveFiles(moves); ``` ## Troubleshooting ### Configuration Not Found Create `structure-validation.config.json` in your project root. ### Git Repository Required Initialize git repository or run without `--scope` flag. ### Auto-fix Errors - Check if target files already exist - Verify write permissions - Check disk space for backups - Ensure TypeScript configuration is correct for import updates ### Import Update Issues - Verify that import paths are relative (not absolute) - Check that files actually import the moved/renamed files - Use `--dry-run` to preview changes before applying - Check the validation report for import update errors ## Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.