### Install and Configure Kotlin Environment Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Commands to install Kotlin, add its binary directory to the PATH, and verify the installation, addressing 'Kotlin runtime environment is not available' errors. ```bash # Install Kotlin # Add to PATH echo $PATH export PATH="$PATH:/path/to/kotlin/bin" kotlin -version ``` -------------------------------- ### Java Example setStep Method Implementation Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md An example implementation of the setStep method. It extracts configuration options from the migration step. ```java @Override public void setStep(MigrationStep step) { this.sourceConfiguration = step.getOption("source-map"); this.targetConfiguration = step.getOption("target-map"); this.filterConfiguration = step.getOption("filter-map"); } ``` -------------------------------- ### Example Usage of ConvertBuildGradle Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/ConvertBuildGradle.md Demonstrates how to instantiate and use the ConvertBuildGradle migrator. This example shows setting up a MigrationContext, defining a cartridge directory path, creating a preparer instance, and calling the migrate method. ```java MigrationContext context = new MigrationContext(); Path cartridgeDir = Paths.get("/path/to/cartridge"); MigrationPreparer preparer = new ConvertBuildGradle(); preparer.migrate(cartridgeDir, context); ``` -------------------------------- ### Kotlin Conversion Migration Step YAML Example Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Example YAML configuration for a migration step that converts build.gradle files to build.gradle.kts. ```yaml type: specs.intershop.com/v1beta/migrate migrator: com.intershop.customization.migration.gradle.ConvertToKotlin message: "refactor: convert 'build.gradle' files to 'build.gradle.kts'" ``` -------------------------------- ### Java Example migrate Method Implementation Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md An example implementation of the migrate method. It reads a build.gradle file, modifies its content, and records success or failure in the migration context. ```java @Override public void migrate(Path resource, MigrationContext context) { String cartridgeName = getResourceName(resource); Path buildGradle = resource.resolve("build.gradle"); try { List lines = FileUtils.readAllLines(buildGradle); String newContent = convertContent(lines); FileUtils.writeString(buildGradle, newContent); context.recordSuccess(cartridgeName, MODIFY, buildGradle, buildGradle); } catch (IOException e) { context.recordFailure(cartridgeName, MODIFY, buildGradle, buildGradle, e.getMessage()); } } ``` -------------------------------- ### Example Migration Step YAML File Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Define a migration step using YAML format. This example specifies the migration type, the migrator class to use, and a descriptive message for the change. ```yaml type: specs.intershop.com/v1beta/migrate migrator: com.intershop.customization.migration.gradle.ConvertBuildGradle message: "refactor: adapt build.gradle plugins" ``` -------------------------------- ### File Migration Step YAML Example Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md An example of a migration step configured for file operations. It specifies source, target, and filter mappings for file movements. ```yaml type: specs.intershop.com/v1beta/migrate migrator: com.intershop.customization.migration.file.MoveFiles message: "refactor: move dbinit and migration properties to new location" options: source-map: "dbprepare": "staticfiles/cartridge" target-map: "dbprepare": "src/main/resources/resources/{cartridgeName}" filter-map: "dbprepare": "(migration|dbinit).*\.properties" ``` -------------------------------- ### Example build.gradle Migration Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/ConvertBuildGradle.md Demonstrates the transformation of an input build.gradle file to its migrated output, including changes to plugins, description, dependencies, and task declarations. ```groovy apply plugin: 'java-cartridge' intershop { displayName = 'My Cartridge' } dependencies { compile 'com.example:library:1.0' testCompile 'junit:junit:4.13' } ``` ```groovy plugins { id 'com.intershop.icm.cartridge.product' id 'java' } description = 'My Cartridge' dependencies { implementation 'com.example:library:1.0' testImplementation 'junit:junit:4.13' } tasks.test.dependsOn(tasks.isml) ``` -------------------------------- ### Pre-Migration Checklist Commands Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Execute these commands before starting the migration to ensure the environment and repository are properly configured and ready. ```bash # 1. Verify git is configured git config user.name # Should output name git config user.email # Should output email # 2. Ensure repository is clean git status # Should show no changes # 3. Verify paths exist ls -d /path/to/project # Should exist ls -d /path/to/steps # Should exist # 4. Check migration steps ls /path/to/steps/*.yml # Should list YAML files ``` -------------------------------- ### Example Usage of prepareMigrate Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md Demonstrates how to use the prepareMigrate method to validate the availability of required tools like the Kotlin runtime. Records a critical error if the tool is not available. ```java @Override public void prepareMigrate(Path resource, MigrationContext context) { // Validate that required tools are available String kotlinVersion = getKotlinRuntimeVersion(); if (kotlinVersion == null) { context.recordCriticalError("Kotlin runtime not available"); } } ``` -------------------------------- ### Verify Kotlin Installation Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/errors.md This bash command verifies if the Kotlin runtime environment is available by checking its version. Ensure Kotlin is installed and accessible in your system's PATH. ```bash kotlin -version # Should work ``` -------------------------------- ### Java Method Signature Example Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/README.md Methods are shown with full parameter types and return types. This example demonstrates a method returning a String and another void method with multiple parameters. ```java public String commit(String message) public void recordOperation(String projectName, OperationType type, Path source, Path target, OperationStatus status, String message) ``` -------------------------------- ### Execute Command Based on OS Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/types.md Example demonstrating how to conditionally execute a command based on the operating system detected by OsCheck. Ensures the correct executable (e.g., kotlin.bat vs. kotlin) is used. ```java if (OsCheck.isWindows()) { executeCommand("kotlin.bat", args); } else { executeCommand("kotlin", args); } ``` -------------------------------- ### prepareMigrate Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md Prepares a specific resource for migration by performing validation or setup before the migration process begins. This method is invoked for each resource that requires preparation. ```APIDOC ## prepareMigrate(Path resource, MigrationContext context) ### Description Prepares a resource for migration. This method is called before the actual migration process starts and can be used to perform validation or setup. ### Method void ### Parameters #### Path Parameters - **resource** (Path) - Required - Path to the resource that needs to be prepared - **context** (MigrationContext) - Required - Migration context for tracking operations ### Behavior - Called once per migration step before migration starts - Used to validate preconditions (e.g., check if Kotlin is available) - If critical errors are recorded, migration is aborted ### Example ```java @Override public void prepareMigrate(Path resource, MigrationContext context) { // Validate that required tools are available String kotlinVersion = getKotlinRuntimeVersion(); if (kotlinVersion == null) { context.recordCriticalError("Kotlin runtime not available"); } } ``` ``` -------------------------------- ### Java Example getResourceName Usage Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md An example demonstrating the usage of getResourceName to obtain a cartridge name and log it. ```java String cartridgeName = getResourceName(resource); logger.info("Processing cartridge '{}'", cartridgeName); context.recordSuccess(cartridgeName, MODIFY, source, target); ``` -------------------------------- ### GitRepository Constructor Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/GitRepository.md Initializes a GitRepository instance. It searches for the .git directory starting from the provided project directory, up to a specified search depth. This is crucial for setting up Git operations within the migration context. ```APIDOC ## GitRepository(File projectDirectory, int maxRepoSearchDepth) ### Description Initializes a GitRepository by finding the .git directory relative to the project directory. This constructor is used to establish a connection with a local Git repository for migration-related tasks. ### Method Constructor ### Parameters #### Path Parameters - **projectDirectory** (File) - Required - The starting directory to search for the .git folder. - **maxRepoSearchDepth** (int) - Required - The maximum number of parent directories to search upwards for the .git folder. ### Throws - `GitInitializationException` - Thrown if no .git directory is found or if the initialization process fails. ### Example ```java try { // Search for .git up to 1 level above project directory GitRepository repo = new GitRepository(new File("/path/to/project"), 1); } catch (GitInitializationException e) { System.err.println("Failed to initialize: " + e.getMessage()); } ``` ``` -------------------------------- ### Initialize MigrationContext Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationContext.md Creates a new MigrationContext instance with empty operations and statistics. Use this to start tracking migration activities. ```java public MigrationContext() ``` -------------------------------- ### File Movement Configuration Example Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Illustrates the configuration for moving files and folders, specifying source, target, and optional filter mappings. Keys must match across maps, and {cartridgeName} is a placeholder. ```yaml migrator: com.intershop.customization.migration.file.MoveFiles message: "refactor: move files to new location" options: source-map: "key1": "relative/source/path" "key2": "another/source/path" target-map: "key1": "target/path/{cartridgeName}" "key2": "another/target/path/{cartridgeName}" filter-map: "key1": "regex_pattern" "key2": "another_pattern" ``` ```yaml options: source-map: "database": "staticfiles/cartridge" target-map: "database": "src/main/resources/resources/{cartridgeName}" filter-map: "database": "(migration|dbinit).*\.properties" ``` -------------------------------- ### Check Kotlin Version Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/errors.md Verifies the installed Kotlin version. This is relevant if the migration process involves Kotlin code conversion. ```bash kotlin -version # If using Kotlin conversion ``` -------------------------------- ### prepareMigrate Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Prepares resources before starting the migration process for a project. It validates migration steps and checks for critical errors, returning true to proceed or false to abort. ```APIDOC ## prepareMigrate(File projectDir, boolean isRoot, List allSteps) ### Description Prepares resources before starting the migration process. ### Method Signature `protected boolean prepareMigrate(File projectDir, boolean isRoot, List allSteps)` ### Parameters #### Path Parameters - **projectDir** (File) - Required - Project directory to prepare - **isRoot** (boolean) - Required - Whether the project is a root project - **allSteps** (List) - Required - All migration steps to execute ### Return Type boolean - true if preparation successful, false if critical errors occurred ### Behavior 1. Iterates through all migration steps 2. For each step, calls either `prepareMigrateRoot()` or `prepareMigrate()` depending on `isRoot` flag 3. Checks if any critical errors were recorded during preparation 4. If critical errors exist, logs them and returns false to abort migration 5. Otherwise returns true to proceed with migration ``` -------------------------------- ### Record Migration Success Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/README.md Example of how to record a successful migration operation using the MigrationContext. This is useful for tracking progress and identifying successful steps. ```java // Real usage examples showing how to use the API MigrationContext context = new MigrationContext(); context.recordSuccess("cartridge", OperationType.MOVE, source, target); ``` -------------------------------- ### build.gradle.kts Configuration for Migration Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Configure your project's build.gradle.kts file to include necessary dependencies for the migration library. This setup is part of the overall project build configuration. ```kotlin plugins { id("java") } group = "com.intershop.migration" version = "1.0.0" subprojects { plugins.withType { dependencies { // migration library dependencies } } } ``` -------------------------------- ### Clone ICM Migration Support Project Source: https://github.com/intershop/icm-migration-support/blob/main/docs/development.md Use this command to clone the project repository to your local machine. Ensure you have Git installed and configured. ```bash git clone git@github.com:intershop/icm-migration-support.git ``` -------------------------------- ### Prepare Migration Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Prepares resources before starting the migration process by iterating through migration steps and performing root-level or project-level preparation. Returns false if critical errors occur during preparation, aborting the migration. ```java protected boolean prepareMigrate(File projectDir, boolean isRoot, List allSteps) ``` -------------------------------- ### prepareMigrateRoot Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md Prepares the root resource of a project for migration. This method is called at the root project level before the migration process begins, useful for project-wide setup or validation. ```APIDOC ## prepareMigrateRoot(Path resource, MigrationContext context) ### Description Prepares a root resource for migration. This method is called before the actual migration process starts at the root project level. ### Method void ### Parameters #### Path Parameters - **resource** (Path) - Required - Path to the root directory that needs to be prepared - **context** (MigrationContext) - Required - Migration context for tracking operations ### Behavior - Called once per migration step at the root project level - Useful for project-wide setup or validation - If critical errors are recorded, migration is aborted ### Example ```java // Example implementation for prepareMigrateRoot ``` ``` -------------------------------- ### MigrationContext Usage Example Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationContext.md Demonstrates how to use MigrationContext to record migration operations, check for critical errors, and generate a summary report. This is useful for tracking the progress and outcome of migration tasks. ```java MigrationContext context = new MigrationContext(); // Record various operations context.recordSuccess("cartridge1", OperationType.MODIFY, Paths.get("build.gradle"), Paths.get("build.gradle")); context.recordWarning("cartridge1", OperationType.CREATE, Paths.get("new-file.txt"), Paths.get("new-file.txt"), "File already existed, overwritten"); context.recordFailure("cartridge2", OperationType.MOVE, Paths.get("source"), Paths.get("target"), "Insufficient permissions"); // Record critical error if (!kotlinAvailable) { context.recordCriticalError("Kotlin not found in PATH"); } // Check for critical errors if (context.hasCriticalError()) { System.err.println("Errors: " + context.getCriticalErrors()); return; } // Generate final report System.out.println(context.generateSummaryReport()); ``` -------------------------------- ### Get All Migration Steps Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Retrieves an ordered list of all discovered migration steps. The steps are mapped from file paths using MigrationStep.valueOf(Path) and returned in alphabetical order. ```java public List getSteps() ``` ```java MigrationStepFolder stepFolder = MigrationStepFolder.valueOf(stepsPath); List steps = stepFolder.getSteps(); for (MigrationStep step : steps) { System.out.println("Step: " + step.getMessage()); } ``` -------------------------------- ### prepareMigrateRoot Method Signature Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md Provides the default signature for the prepareMigrateRoot method. This method is called before the actual migration process starts at the root project level. ```java default void prepareMigrateRoot(Path resource, MigrationContext context) ``` -------------------------------- ### Add Runtime Dependency to build.gradle.kts Source: https://github.com/intershop/icm-migration-support/blob/main/docs/ai-instructions/dependencies-component-instances.md Example of how to add a runtime dependency for a cartridge in a `build.gradle.kts` file. This is necessary when a component is moved to a new cartridge or when a new cartridge is created. ```gradle cartridgeRuntime("com.intershop.business:sld_enterprise_app") ``` -------------------------------- ### API Reference Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/COMPLETION_SUMMARY.txt This section provides a detailed reference for all exported classes and their methods within the ICM Migration Support project. It includes parameter descriptions, return types, exception documentation, and usage examples. ```APIDOC ## API Reference This documentation covers the following key areas: ### Method Documentation - Every public method is documented. - Parameter descriptions are provided. - Return type documentation is included. - Exception documentation is available. - Usage examples are present. ### Type Coverage - All enumerations are documented. - All interfaces are documented. - All record types are documented. - Type relationships are explained. ### Configuration Coverage - All parameters are documented. - All configuration options are explained. - YAML structure is defined. - Examples are provided. ### Error Handling - All exception types are covered. - Error conditions are explained. - Recovery procedures are documented. - A troubleshooting guide is included. ## Key Features - Complete API reference for all exported classes. - Detailed type documentation with relationships. - Comprehensive error documentation with handling patterns. - Configuration guide with working examples. - Cross-references between related classes. - Source file references for every method. - Real usage examples in idiomatic Java. - Navigation index with quick search. - Best practices and patterns. - Troubleshooting guide. - Step-by-step migration procedures. - Integration patterns with examples. ## API Reference Classes - Migrator.md: 506 lines - MigrationContext.md: 645 lines - MigrationPreparer.md: 338 lines - MigrationStep.md: 376 lines - MigrationStepFolder.md: 383 lines - GitRepository.md: 227 lines - ConvertBuildGradle.md: 456 lines - MoveFiles.md: 387 lines - FileUtils.md: 506 lines - Position.md: 423 lines ``` -------------------------------- ### prepareMigrate Method Signature Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md Provides the default signature for the prepareMigrate method. This method is called before the actual migration process starts to perform validation or setup. ```java default void prepareMigrate(Path resource, MigrationContext context) ``` -------------------------------- ### Load Migration Steps from Multiple Folders Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Demonstrates loading migration steps from both the file system and the classpath, allowing you to choose the appropriate source based on your needs. ```java // Load from file system MigrationStepFolder fileFolder = MigrationStepFolder.valueOf( Paths.get("migration/steps") ); // Load from classpath MigrationStepFolder classpathFolder = MigrationStepFolder.valueOf("migration.resources"); // Use appropriate folder MigrationStepFolder folder = useFilesystem ? fileFolder : classpathFolder; List steps = folder.getSteps(); ``` -------------------------------- ### Loading and Processing Migration Steps Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Demonstrates how to load migration steps from a folder and iterate through them to execute the migration process. This includes accessing step messages, configured migrators, and options. ```java // Load migration steps Path stepsFolder = Paths.get("migration/src/main/resources/migration"); MigrationStepFolder stepFolder = MigrationStepFolder.valueOf(stepsFolder); List allSteps = stepFolder.getSteps(); // Process each step for (MigrationStep step : allSteps) { // Get step message for logging System.out.println("Executing: " + step.getMessage()); // Get configured migrator MigrationPreparer migrator = step.getMigrator(); // Access step options if needed Map config = step.getOption("source-map"); // Execute migration MigrationContext context = new MigrationContext(); migrator.migrate(projectPath, context); } ``` -------------------------------- ### Execute Migration with Classpath Steps Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Run the migration tool using the 'migrateAll' Gradle task, specifying the target project path and the relative path to the migration steps located in the classpath resources. ```bash ./gradlew migration:migrateAll \ -Ptarget=/path/to/icm-7.10 \ -Psteps=migration/src/main/resources/migration ``` -------------------------------- ### Complete Migration Flow Overview Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/INDEX.md Illustrates the sequential steps involved in a complete migration process, from initialization to final commit and reporting. ```text 1. Migrator.main(args) ├─ Initialize GitRepository ├─ Validate GitRepository state └─ Load MigrationSteps from folder ├─ For each MigrationStep: │ ├─ prepareMigrate() phase │ │ └─ Validate preconditions │ │ └─ Record critical errors if needed │ └─ migrate() phase │ ├─ Load configured MigrationPreparer │ ├─ Execute migration │ └─ Record operations in MigrationContext └─ Commit changes via GitRepository 2. Generate summary report 3. Exit with status ``` -------------------------------- ### Get Git Repository Directory Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/GitRepository.md Returns the directory of the git repository. Useful for logging or validation messages. ```java public File getRepositoryDirectory() ``` ```java GitRepository repo = new GitRepository(projectDir, 1); File gitDir = repo.getRepositoryDirectory(); System.out.println("Git repository: " + gitDir); // Output: /path/to/project/.git ``` -------------------------------- ### Migrator.main(String[] args) Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Serves as the entry point for command-line execution of the migration tool. It accepts arguments to specify the task type, project paths, migration steps directory, and optional flags like `--noAutoCommit`. ```APIDOC ## main(String[] args) ### Description Entry point for command-line execution of the migration tool. ### Method `public static void main(String[] args)` ### Parameters #### Path Parameters - **args** (String[]) - Required - Command-line arguments **Arguments Structure:** - `args[0]`: Task type - either `"project"` or `"projects"` - `args[1]`: Path to the project or projects directory to migrate - `args[2]`: Path to migration steps directory (e.g., `src/main/resources/001_migration_7x10_to_11`) - Optional flags: `--noAutoCommit` to disable automatic git commits ### Request Example ```java // Migrate all projects in a directory with auto-commit Migrator.main(new String[]{"projects", "/path/to/icm7.10", "/path/to/migration/steps"}); // Migrate a single cartridge without auto-commit Migrator.main(new String[]{"project", "/path/to/cartridge", "/path/to/migration/steps", "--noAutoCommit"}); ``` ### Response void ### Throws Exits with code 1 or 2 on error ``` -------------------------------- ### gradle.properties for Migration Configuration Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Set migration-specific properties in your gradle.properties file. This example shows how to enable auto-commit for migration steps. ```properties # Migration configuration migration.autoCommit=true ``` -------------------------------- ### Typical Migration Usage Sequence Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/INDEX.md Provides a command-line sequence for running migrations, including verification, configuration, execution, review, and commit/revert actions. ```bash # 1. Verify git state git status # 2. Configure git if needed git config user.name "Name" git config user.email "email@example.com" # 3. Run migration without auto-commit first ./gradlew migration:migrateAll \ -Ptarget=/path/to/project \ -Psteps=migration/src/main/resources/migration \ -PnoAutoCommit # 4. Review report # Check output for warnings, unknowns, or failures # 5. Commit if successful git add . git commit -m "Migration completed" # 6. Or revert if issues found git reset --hard HEAD ``` -------------------------------- ### validateGitRepository Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Validates that the git repository is clean before starting migration. It checks for uncommitted changes or untracked files and throws an exception if the repository is not clean. ```APIDOC ## `validateGitRepository()` ### Description Validates that the git repository is clean before starting migration. It checks for uncommitted changes or untracked files and throws an exception if the repository is not clean. ### Method Signature `public void validateGitRepository() throws GitValidationException` ### Return Type void ### Throws - `GitValidationException` if the git repository has uncommitted changes ### Behavior 1. If no git repository is initialized, validation passes 2. If git repository exists, checks that it is clean 3. If repository contains uncommitted changes or untracked files, throws exception 4. Logs the validation result at debug level ### Example ```java Migrator migrator = new Migrator(new File("steps")); migrator.initializeGitRepository(true, new File("/project")); try { migrator.validateGitRepository(); } catch (GitValidationException e) { System.err.println("Git repository is not clean: " + e.getMessage()); } ``` ``` -------------------------------- ### Initialize GitRepository Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/GitRepository.md Initializes a GitRepository instance. Specify the project directory and the maximum depth to search for the .git directory. Catches GitInitializationException if the repository cannot be initialized. ```java try { // Search for .git up to 1 level above project directory GitRepository repo = new GitRepository(new File("/path/to/project"), 1); } catch (GitInitializationException e) { System.err.println("Failed to initialize: " + e.getMessage()); } ``` -------------------------------- ### Record Migration Operation with Type Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/types.md Example of recording a successful MOVE operation and a failed MODIFY operation using OperationType. Requires a MigrationContext instance. ```java context.recordSuccess("cartridge", OperationType.MOVE, source, target); context.recordFailure("cartridge", OperationType.MODIFY, file, file, "Permission denied"); ``` -------------------------------- ### Creating and Recording an Operation Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/types.md Demonstrates how to create an `Operation` record and record it using the `MigrationContext`. This is typically done by migration step implementations to track operations. ```java // Operations are created and stored by MigrationContext Operation op = new Operation( OperationType.MOVE, Paths.get("old/path/file.txt"), Paths.get("new/path/file.txt"), OperationStatus.SUCCESS, null ); // Record the operation context.recordOperation("cartridge", op.type(), op.source(), op.target(), op.status(), op.message()); ``` -------------------------------- ### Create MigrationStepFolder from File System Path Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Use this method to load migration steps by scanning a specific directory on the file system. Ensure the provided path contains valid migration step YAML files. ```java Path stepsPath = Paths.get("migration/src/main/resources/migration"); MigrationStepFolder stepFolder = MigrationStepFolder.valueOf(stepsPath); List steps = stepFolder.getSteps(); ``` -------------------------------- ### Run Migration Steps from File System Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Execute all migration steps found in a specified folder on the file system. The folder is scanned for .yml files, which are then sorted alphabetically. ```bash ./gradlew migration:migrateAll \ -Ptarget=/path/to/project \ -Psteps=/absolute/or/relative/path/to/migration/folder ``` -------------------------------- ### Get Migration Step Message Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Retrieves the migration step's descriptive message from the YAML configuration. This message is often used for git commit messages. ```java public String getMessage() ``` ```java String message = step.getMessage(); // Returns: "refactor: adapt plugins in build.gradle" ``` -------------------------------- ### Execute Migrator from Command Line Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Use the main method to run the migration tool from the command line. Specify the task type (project/projects), paths, and optional flags like --noAutoCommit. ```java public static void main(String[] args) ``` ```java // Migrate all projects in a directory with auto-commit Migrator.main(new String[]{"projects", "/path/to/icm7.10", "/path/to/migration/steps"}); ``` ```java // Migrate a single cartridge without auto-commit Migrator.main(new String[]{"project", "/path/to/cartridge", "/path/to/migration/steps", "--noAutoCommit"}); ``` -------------------------------- ### Validate Git Repository Before Migration Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/errors.md Ensures the Git repository is in a clean state before starting a migration. A clean status prevents unexpected conflicts or data loss. ```bash git status # Must be clean ``` -------------------------------- ### Configure MoveFiles with MigrationStep Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MoveFiles.md Use this method to set up the MoveFiles preparer with configuration options extracted from a MigrationStep. This includes source, target, and filter maps. ```java public void setStep(MigrationStep step) ``` ```java MoveFiles moveFiles = new MoveFiles(); MigrationStep step = MigrationStep.valueOf(stepPath); moveFiles.setStep(step); // Now moveFiles is configured and ready to migrate ``` -------------------------------- ### Load Migration Steps from File System Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Loads migration steps from a specified directory on the file system. After loading, you can retrieve all migration steps and execute them. ```java // Load migration steps from folder Path stepsFolder = Paths.get("migration/src/main/resources/migration"); MigrationStepFolder stepFolder = MigrationStepFolder.valueOf(stepsFolder); // Get all steps List steps = stepFolder.getSteps(); // Process each step for (MigrationStep step : steps) { System.out.println("Message: " + step.getMessage()); MigrationPreparer migrator = step.getMigrator(); // ... execute migration } ``` -------------------------------- ### MigrationPreparer Implementation Pattern Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationPreparer.md This pattern demonstrates how to implement the MigrationPreparer interface, including setting the migration step, preparing for migration, and performing the migration with error handling. ```java import com.intershop.customization.migration.common.MigrationContext; import com.intershop.customization.migration.common.MigrationPreparer; import com.intershop.customization.migration.common.MigrationStep; import java.nio.file.Path; public class MyMigrationStep implements MigrationPreparer { private static final Logger LOGGER = LoggerFactory.getLogger(MyMigrationStep.class); @Override public void setStep(MigrationStep step) { // Extract configuration from step } @Override public void prepareMigrate(Path resource, MigrationContext context) { // Validate preconditions if (somethingRequired && !isAvailable()) { context.recordCriticalError("Required component not available"); } } @Override public void migrate(Path resource, MigrationContext context) { String resourceName = getResourceName(resource); try { // Perform migration // ... transformation code ... context.recordSuccess(resourceName, OperationType.MODIFY, source, target); } catch (Exception e) { context.recordFailure(resourceName, OperationType.MODIFY, source, target, e.getMessage()); } } } ``` -------------------------------- ### Record Migration Operation with Status Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/types.md Example of recording a successful MOVE operation and a warning for a MODIFY operation using OperationStatus. Supports recording detailed operation outcomes. ```java context.recordOperation("cartridge", OperationType.MOVE, source, target, OperationStatus.SUCCESS, null); context.recordWarning("cartridge", OperationType.MODIFY, file, file, "File already exists, overwritten"); ``` -------------------------------- ### Run OpenRewrite for Jakarta EE Migration Source: https://github.com/intershop/icm-migration-support/blob/main/docs/migration-11-12.md Apply OpenRewrite recipes for Jakarta EE migration to the project. This command requires a `rewrite.gradle` script to be present. ```bash gradlew --init-script rewrite.gradle rewriteRun ``` -------------------------------- ### Project Structure for Classpath Migration Steps Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Organize migration steps within the src/main/resources/migration directory of your project. The tool automatically discovers and processes these .yml files. ```text src/main/resources/migration/ ├── 001_*.yml ├── 002_*.yml └── ... ``` -------------------------------- ### Create MigrationStepFolder from Classpath Resource Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Use this method to load migration steps by scanning the classpath for a specified package. This is useful for including migration steps as part of your application's resources. ```java // Load from classpath MigrationStepFolder stepFolder = MigrationStepFolder.valueOf("migration.steps.v7to11"); List steps = stepFolder.getSteps(); ``` -------------------------------- ### removeEmptyDirectories(Path path) Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/FileUtils.md Recursively removes empty directories starting from the given path. The operation is designed to be robust, handling null paths and non-existent directories gracefully. ```APIDOC ## removeEmptyDirectories(Path path) ### Description Recursively removes empty directories. ### Method Signature `public static void removeEmptyDirectories(Path path) throws IOException` ### Parameters #### Path Parameters - **path** (Path) - Required - Path to directory or file to process ### Return Type - void ### Throws - `IOException` - if an I/O error occurs ### Behavior 1. If path is null or doesn't exist, returns silently 2. If path is a directory: - Recursively processes all subdirectories first - Attempts to delete subdirectories if empty - Then deletes the current directory if it becomes empty 3. If path is a file, does nothing 4. Logs errors but continues processing other directories ### Example ```java try { // Remove empty directories after migration FileUtils.removeEmptyDirectories(Paths.get("old/location")); } catch (IOException e) { System.err.println("Failed to remove directories: " + e.getMessage()); } ``` ``` -------------------------------- ### Move Database Initialization and Migration Files Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MoveFiles.md Use this configuration to move SQL files for database initialization and migrations from a source directory to a target directory within a cartridge's resource structure. It specifies the source, target, and a filter to include only migration and dbinit SQL files. ```yaml migrator: com.intershop.customization.migration.file.MoveFiles message: "refactor: move database files to new location" options: source-map: "database": "staticfiles/cartridge/database" target-map: "database": "src/main/resources/resources/{cartridgeName}/database" filter-map: "database": "(migration|dbinit).*\.sql" ``` -------------------------------- ### Retrieve Critical Migration Errors Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationContext.md Use this method to get a list of all recorded critical errors. The returned list is immutable, providing a safe way to review the errors that caused the migration to stop. ```java public List getCriticalErrors() ``` ```java List errors = context.getCriticalErrors(); errors.forEach(msg -> logger.error("Critical: {}", msg)); ``` -------------------------------- ### Run Specific Migration Steps on a Single Project Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/configuration.md Use `migration:migrateOne` with `task=project` to apply specific migration steps to a single cartridge. Provide the path to the target cartridge, the migration step(s), and optionally disable auto-commit. ```bash gradlew migration:migrateOne -Ptask= -Ptarget= -Psteps= [-PnoAutoCommit] ``` ```bash ./gradlew migration:migrateOne \ -Ptask=project \ -Ptarget=/path/to/icm-7.10-project/cartridge \ -Psteps=migration/src/main/resources/migration/001_initial_setup.yml ``` -------------------------------- ### Record and Report Migration Operations Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/types.md Demonstrates how to use the MigrationContext to record operations with details like type, paths, status, and generate a summary report. Use this to track migration steps and identify critical errors. ```java MigrationContext context = new MigrationContext(); // Record operations using enums context.recordOperation( "cartridge-name", OperationType.MOVE, Paths.get("old"), Paths.get("new"), OperationStatus.SUCCESS, null ); // Check operations String report = context.generateSummaryReport(); List errors = context.getCriticalErrors(); boolean hasCriticalError = context.hasCriticalError(); ``` -------------------------------- ### Constructor with Explicit Step Paths Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Creates a MigrationStepFolder by providing an explicit list of migration step YAML file paths. The list is assumed to be pre-sorted in the desired execution order. ```java public MigrationStepFolder(List steps) ``` ```java List stepPaths = Arrays.asList( Paths.get("migration/steps/001_setup.yml"), Paths.get("migration/steps/002_migrate.yml"), Paths.get("migration/steps/003_cleanup.yml") ); MigrationStepFolder folder = new MigrationStepFolder(stepPaths); ``` -------------------------------- ### Position.findBracketBlock Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Position.md Finds a code block within a list of strings that is bounded by curly braces. It searches for a line starting with a specified marker and then tracks the nesting level of curly braces to identify the complete block. ```APIDOC ## Position.findBracketBlock(String startMarker, List lines) ### Description Finds a code block bounded by curly braces. ### Method Signature `public static Optional findBracketBlock(String startMarker, List lines)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | startMarker | String | Yes | — | Text that marks the start of the block (e.g., "dependencies", "intershop") | | lines | List | Yes | — | List of lines to search | ### Return Type Optional - Position if block found, empty Optional otherwise ### Behavior 1. Scans through lines looking for line starting with startMarker (after trim) 2. When found, begins counting bracket depth 3. For each subsequent line: - Increments bracket counter for each `{` - Decrements bracket counter for each `}` - When counter reaches 0, block is complete 4. Returns Optional containing Position with start and end indices 5. If no complete block found, returns empty Optional ### Bracket Counting Logic - Only counts brackets after the start marker is found - Starts counting when first `{` is encountered - Stops when brackets balance (counter = 0) - Handles multiple brackets on same line ### Example ```java List lines = Arrays.asList( "dependencies {", " implementation 'junit:junit:4.13'", " testImplementation 'org.mockito:mockito-core:3.0'", "}" ); Optional pos = Position.findBracketBlock("dependencies", lines); if (pos.isPresent()) { List depBlock = pos.get().matchingLines(); // depBlock contains all 4 lines } ``` ``` -------------------------------- ### Remove Empty Directories Recursively Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/FileUtils.md This method recursively removes empty directories starting from a given path. It handles null paths, non-existent paths, files, and logs errors without halting the process. ```java public static void removeEmptyDirectories(Path path) throws IOException ``` ```java try { // Remove empty directories after migration FileUtils.removeEmptyDirectories(Paths.get("old/location")); } catch (IOException e) { System.err.println("Failed to remove directories: " + e.getMessage()); } ``` -------------------------------- ### Create MigrationStep from URI Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Use this method to create a MigrationStep instance when you have a URI pointing to the migration step's YAML configuration file. It loads options from the specified resource. ```java public static MigrationStep valueOf(URI resourceURI) ``` ```java URI stepURI = MigrationStepFolder.getURIs("migration.steps.v7to11").get(0); MigrationStep step = MigrationStep.valueOf(stepURI); ``` -------------------------------- ### MigrationStepFolder.valueOf(String resourceName) Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Creates a MigrationStepFolder by scanning the classpath for migration step YAML files in a package. It finds all .yml resources, converts URIs to Paths, and returns an instance ready to provide steps. ```APIDOC ## MigrationStepFolder.valueOf(String resourceName) ### Description Creates a MigrationStepFolder by scanning the classpath for migration step YAML files in a package. ### Method `static` ### Parameters #### Path Parameters - **resourceName** (String) - Required - Package name to scan for resources (e.g., "migration.steps.v7to11") ### Return Type MigrationStepFolder - instance containing all discovered steps ### Example ```java // Load from classpath MigrationStepFolder stepFolder = MigrationStepFolder.valueOf("migration.steps.v7to11"); List steps = stepFolder.getSteps(); ``` ``` -------------------------------- ### Validate Clean Git Repository Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Ensures the Git repository is clean (no uncommitted changes or untracked files) before starting a migration. Throws GitValidationException if the repository is not clean. Handles cases where no Git repository is initialized. ```java public void validateGitRepository() throws GitValidationException ``` ```java Migrator migrator = new Migrator(new File("steps")); migrator.initializeGitRepository(true, new File("/project")); try { migrator.validateGitRepository(); } catch (GitValidationException e) { System.err.println("Git repository is not clean: " + e.getMessage()); } ``` -------------------------------- ### Find a Bracket-Bounded Code Block Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Position.md This method searches a list of strings for a code block enclosed in curly braces, starting after a specified marker. It returns an Optional containing a Position object if a complete block is found, otherwise an empty Optional. ```java public static Optional findBracketBlock(String startMarker, List lines) ``` ```java List lines = Arrays.asList( "dependencies {", " implementation 'junit:junit:4.13'", " testImplementation 'org.mockito:mockito-core:3.0'", "}" ); Optional pos = Position.findBracketBlock("dependencies", lines); if (pos.isPresent()) { List depBlock = pos.get().matchingLines(); // depBlock contains all 4 lines } ``` -------------------------------- ### Multiple File Movements in One Step Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MoveFiles.md Configure the migrator to move multiple types of files (configuration, templates, assets) to their respective new locations in a single operation. This example demonstrates mapping different source directories to target directories and applying specific file filters for each type. ```yaml migrator: com.intershop.customization.migration.file.MoveFiles message: "refactor: move resources and configurations" options: source-map: "config": "staticfiles/cartridge/config" "templates": "staticfiles/cartridge/templates" "assets": "staticfiles/assets" target-map: "config": "src/main/resources/resources/{cartridgeName}/config" "templates": "src/main/resources/resources/{cartridgeName}/templates" "assets": "src/main/resources/public/assets" filter-map: "config": ".*\.xml" "templates": ".*\.html" "assets": ".*\.(js|css|png|jpg|gif)" ``` -------------------------------- ### Migrator Constructor Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Initializes a new Migrator instance. This constructor requires a `File` object pointing to the directory that contains the migration step descriptions in YAML format. ```APIDOC ## Migrator(File migrationStepFolder) ### Description Initializes a new Migrator instance with the folder containing migration step descriptions. ### Parameters #### Path Parameters - **migrationStepFolder** (File) - Required - Directory containing migration step YAML configuration files ``` -------------------------------- ### MigrationStepFolder.valueOf(Path path) Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Creates a MigrationStepFolder by scanning a file system directory for migration step YAML files. It filters for regular files, sorts them alphabetically, and returns an instance ready to provide steps. ```APIDOC ## MigrationStepFolder.valueOf(Path path) ### Description Creates a MigrationStepFolder by scanning a file system directory for migration step YAML files. ### Method `static` ### Parameters #### Path Parameters - **path** (Path) - Required - Path to directory containing migration step YAML files ### Return Type MigrationStepFolder - instance containing all discovered steps ### Throws - `RuntimeException` - wrapping IOException if directory cannot be read ### Example ```java Path stepsPath = Paths.get("migration/src/main/resources/migration"); MigrationStepFolder stepFolder = MigrationStepFolder.valueOf(stepsPath); List steps = stepFolder.getSteps(); ``` ``` -------------------------------- ### Find and Extract Dependencies Block Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Position.md Demonstrates the typical usage pattern for finding a bracketed block (e.g., 'dependencies') within a file's lines, processing the matching lines, and reconstructing the file with modifications. ```java List allLines = FileUtils.readAllLines(buildGradlePath); // Find and extract dependencies block Optional depPos = Position.findBracketBlock("dependencies", allLines); if (depPos.isPresent()) { List dependencies = depPos.get().matchingLines(); List otherLines = depPos.get().nonMatchingLines(); // Process dependencies List convertedDeps = convertDependencies(dependencies); // Reconstruct file List result = new ArrayList<>(); result.addAll(otherLines); result.addAll(convertedDeps); FileUtils.writeLines(buildGradlePath, result); } ``` -------------------------------- ### YAML File Format for Migration Steps Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStepFolder.md Migration steps must be valid YAML files with a .yml or .yaml extension. The file should include type, migrator class, a message, and optional options. ```yaml type: specs.intershop.com/v1beta/migrate migrator: com.fully.qualified.ClassName message: "Step description" options: key: value ``` -------------------------------- ### Create MigrationStep from Path Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Use this method to create a MigrationStep instance when you have a file system Path to the migration step's YAML configuration file. It reads and parses the YAML content. ```java public static MigrationStep valueOf(Path optionsPath) ``` ```java Path stepFile = Paths.get("migration/steps/001_initial_setup.yml"); MigrationStep step = MigrationStep.valueOf(stepFile); ``` -------------------------------- ### MigrationStep.valueOf(URI resourceURI) Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Creates a MigrationStep instance from a URI pointing to a migration step YAML file. This method loads configuration options from the specified resource. ```APIDOC ## valueOf(URI resourceURI) ### Description Creates a MigrationStep from a URI pointing to a migration step resource. ### Method Static Factory Method ### Parameters #### Path Parameters - **resourceURI** (URI) - Required - URI pointing to a migration step YAML file ### Return Type MigrationStep - newly created and populated instance ### Example ```java URI stepURI = MigrationStepFolder.getURIs("migration.steps.v7to11").get(0); MigrationStep step = MigrationStep.valueOf(stepURI); ``` ``` -------------------------------- ### Import YAML Options from String Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/MigrationStep.md Parses YAML configuration from a string. Uses SnakeYAML for parsing and stores the configuration internally. ```java public Map importOptions(String content) ``` ```java MigrationStep step = new MigrationStep(); String yamlContent = "migrator: com.example.MyMigrator\n" + "message: 'Step 1: Initial setup'\n" + "options:\n" + " key1: value1"; Map config = step.importOptions(yamlContent); ``` -------------------------------- ### migrateProject Source: https://github.com/intershop/icm-migration-support/blob/main/_autodocs/api-reference/Migrator.md Migrates a single cartridge project through all defined migration steps. It loads migration steps, prepares the project, executes each step, commits changes if Git is initialized, and logs a summary report. ```APIDOC ## migrateProject(File projectDir) ### Description Migrates a single cartridge project through all migration steps. ### Method Signature `protected void migrateProject(File projectDir)` ### Parameters #### Path Parameters - **projectDir** (File) - Required - Directory containing the cartridge to migrate ### Behavior 1. Loads all migration steps from the configured migration step folder 2. Calls `prepareMigrate()` for validation before processing 3. Executes each migration step's migrator on the project directory 4. Commits changes to git after each step (if git is initialized) 5. Logs summary report of all operations ### Example ```java Migrator migrator = new Migrator(new File("steps")); migrator.initializeGitRepository(true, new File("/cartridge/root")); migrator.migrateProject(new File("/cartridge/root/my-cartridge")); ``` ```