-
-
Notifications
You must be signed in to change notification settings - Fork 13
Rewritten in C# #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Rewritten in C# #45
Conversation
* Introduce new `PowerForge` project with core abstractions and models: * `ILogger`, `IFileSystem`, `IFormatter`, `ILineEndingsNormalizer`, `IPowerShellRunner` * `ModuleInstallerOptions`, `ModuleInstallerResult`, `InstallationStrategy`, `FormatterResult`, `NormalizationResult` * Add concrete implementations and services: * `ConsoleLogger`, `RealFileSystem`, `LineEndingsNormalizer`, `PowerShellRunner` * `PssaFormatter` (out-of-proc PSScriptAnalyzer formatter), `ModuleInstaller` (versioned installs + pruning) * `PowerForgeFacade` wiring defaults for quick consumption * Add `PowerForge.Cli` dotnet tool (`powerforge`) with `Program.cs` supporting: * `normalize`, `format`, and `install` commands (verbose flag, argument parsing) * Update solution and `PSPublishModule.csproj`: * Add `PowerForge` and `PowerForge.Cli` projects to solution * Reference `PowerForge` from `PSPublishModule` for non-netstandard targets * Add `TODO.md` describing migration goals, architecture and roadmap * Key behaviors & safeguards: * Deterministic line-ending/encoding normalization (CRLF default, BOM configurable) * Out-of-proc formatting with timeouts and graceful fallback when PowerShell/PSSA is unavailable * Atomic staged installs, auto-revision strategy and pruning of old versions
…options * Add `FormatOptions` to configure preprocessing, PSSA settings, timeout, line endings and BOM. * Introduce `FormattingPipeline` to orchestrate preprocessing, PSSA formatting and normalization. * Add `Preprocessor` service that runs an out-of-process PowerShell script to strip comments and trim empty lines (flags passed as base64 JSON) and reports per-file results. * Extend `PssaFormatter` and `IFormatter` with `FormatFilesWithSettings` to accept PSScriptAnalyzer settings (passed as base64 JSON) and apply them when invoking `Invoke-Formatter`. * Ensure graceful fallbacks for missing PowerShell runtime and timeouts; return consistent `FormatterResult` entries for all inputs.
…ersionedInstallKeep` docs; remove deprecated Convert-* docs * Add `VersionedInstallStrategy` and `VersionedInstallKeep` parameter documentation to `New-ConfigurationBuild` (synopsis, examples, parameter details). Defaults: `AutoRevision` and `3`. * Update example splat to include `VersionedInstallStrategy = 'AutoRevision'` and `VersionedInstallKeep = 3`. * Remove obsolete help files `Convert-ProjectEncoding.md` and `Convert-ProjectLineEnding.md`. * Clean up `Module/Docs/Readme.md` by removing references to the removed Convert-* cmdlet docs.
…; remove legacy PS scripts; extend build config * Add `ConvertProjectEncodingCommand.cs` and `ConvertProjectLineEndingCommand.cs` as thin C# wrappers around `PowerForge.EncodingConverter` and `PowerForge.LineEndingConverter`. * New cmdlets accept the same high-level options (`ProjectKind`, custom patterns, backups, `PassThru`, etc.) and produce per-file results or a concise summary. * Preserve safety defaults (e.g. prefer UTF8-BOM for PowerShell) and backup handling. * Remove legacy public PowerShell implementations: * `Module/Public/Convert-ProjectEncoding.ps1` * `Module/Public/Convert-ProjectLineEnding.ps1` * Extend `New-ConfigurationBuild.ps1` with new build/install options: * Add `VersionedInstallStrategy` and `VersionedInstallKeep` parameters and include them in build metadata when provided. * Add locker control flags: `KillLockersBeforeInstall`, `KillLockersForce`. * Add `AutoSwitchExactOnPublish` and include behavior to emit corresponding `BuildModule` metadata entries. * Motivation/context: * Move heavy-lifting into typed .NET implementations (PowerForge) for better reliability, testability and reuse. * Remove duplicated/legacy PS implementations in favor of centralized converters. * Expose versioned-install and locker control options in build configuration to support safer iterative development and deployment workflows.
…ditor, lock inspector, enumerator; harden installer and add PS SDK refs * Add project/file conversion abstractions: `ProjectConversionOptions` types (`ProjectEnumeration`, `FileConversion`, `ProjectConversionResult`, `EncodingConversionOptions`, `LineEndingConversionOptions`, `TextEncodingKind`, `ProjectKind`). * Implement `EncodingConverter` and `LineEndingConverter` with detection, backup/verification, BOM handling and options for force/only-mixed/ensure-final-newline. * Add `ProjectFileEnumerator` to discover files by project kind or custom patterns while honoring exclude directories. * Add `ManifestEditor` to safely read/modify PSD1 hashtable entries using the PowerShell AST (get/set strings and arrays, insert keys). * Add `LockInspector` to report and optionally terminate processes locking files via Windows Restart Manager (no-op on non-Windows). * Harden `ModuleInstaller`: fallback copy locations for permission/IO issues, cross-volume rename handling, collect installation failures, expose `ResolveTargetVersion`, and best-effort directory deletion. * Update `PowerForge.csproj` to reference `Microsoft.PowerShell.SDK` for `net8.0` and `Microsoft.PowerShell.5.ReferenceAssemblies` for `net472`. * Provides core tooling for project-wide encoding/line-ending fixes, manifest manipulation and safer installs.
…ersioned install * Add `PSPublishModule/BuildServices.cs` — C# facade exposing `Format`, `FormatFiles`, `NormalizeFiles`, `InstallVersioned`, `GetLockingProcesses` and `TerminateLockingProcesses` to drive robust formatting, normalization and versioned installation from PowerShell. * Remove legacy `Format-Code.ps1` and update `Merge-Module`, `Start-ModuleBuilding` to call into `PSPublishModule.BuildServices::Format(...)`. Convert `FormatterSettings` to JSON and pass to C# pipeline. * Implement versioned installs in `Start-ModuleBuilding` using `BuildServices.InstallVersioned`: support `VersionedInstallStrategy` (`AutoRevision`/`Exact`), retention via `VersionedInstallKeep`, optional locker detection/termination (`KillLockersBeforeInstall`/`KillLockersForce`) and resolved-version install. * Improve self-build resilience: load `PowerForge.dll`/`PSPublishModule.dll` from project `Lib` when assemblies are missing. * Harden module import fallback in `Start-ImportingModules` — attempt PSD1/PSM1 under user module roots with clear errors. * Bump `PSPublishModule.psd1` `ModuleVersion` to `2.0.27`, update exported functions and enable exporting `Cmdlet '*'` in `PSPublishModule.psm1`. * Tidy `PSPublishModule.csproj` (formatting, enable nullable/docs/warnings) and add nullable annotations in `OnImportAndRemove`. * Update `TODO.md` to reflect CLI/branding rename and recommended dev build settings.
* Removed support for `netstandard2.0` and updated project references. * Added new methods for detecting script functions, cmdlets, and aliases. * Improved manifest export settings handling. * Cleaned up code by removing unnecessary preprocessor directives.
…detection * Refactor `Merge-Module` to use `[PowerForge.BuildServices]` instead of `[PSPublishModule.BuildServices]`. * Implement auto-detection of exports (functions/cmdlets/aliases) and write into PSD1 using C# services. * Enhance error handling for export detection failures.
… new classes and methods for export detection and manifest editing * Introduced `ExportSet` class to represent detected exports for module manifests. * Added `BuildServices` class with methods for file formatting, normalization, and module installation. * Implemented `ExportDetector` for detecting functions, cmdlets, and aliases from scripts and binaries. * Enhanced `ManifestEditor` with methods for managing `RequiredModules` in PSD1 files. * Updated project dependencies to include `System.Reflection.MetadataLoadContext`.
…ionaries method and new ManifestWriter class * Implemented `SetRequiredModulesFromDictionaries` to handle PowerShell dictionaries for required modules. * Introduced `ManifestWriter` class to generate well-formatted PSD1 manifests. * Enhanced modularity and maintainability of the codebase.
…e `Show-ProjectDocumentation` * Enhanced the `New-ConfigurationBuild` documentation with new parameters `-VersionedInstallStrategy` and `-VersionedInstallKeep`. * Removed the obsolete `Show-ProjectDocumentation` file to streamline documentation.
…ry important links and PSData sub-hashtable arrays * Implemented `SetDeliveryImportantLinks` in `BuildServices` to set `PrivateData.PSData.Delivery.ImportantLinks` from PowerShell dictionaries. * Added `TrySetPsDataSubHashtableArray` in `ManifestEditor` for setting PSData sub-hashtable arrays, enhancing manifest editing capabilities.
…y loading and module build options * Improved handling of local assemblies in `ExportDetector` for better resolution. * Added detailed XML documentation for `ModuleBuilder` options and methods. * Refactored `Build` method to `BuildInPlace` for clarity and separation of concerns. * Enhanced export detection logic to ensure proper handling of module DLLs.
* Implemented the `build` command to facilitate module building. * Added argument parsing for module properties such as `--name`, `--project-root`, `--csproj`, and `--version`. * Introduced staging directory management with error handling for existing directories. * Enhanced logging for build success and errors.
… improve output structure * Added XML documentation for parameters to clarify their purpose. * Updated output structure to use `ResolvedVersion` for better clarity.
* Added handling for null or empty arguments by appending `""` to the command. * Enhanced the argument construction logic to ensure proper formatting.
* Preserve existing manifest metadata when updating the module version and key fields. * Introduce conditional logic to either patch the manifest or generate a new one based on its existence.
- Introduced multiple cmdlets to facilitate the configuration of PowerShell module publishing, including: - `New-ConfigurationImportModule`: Configures module import settings. - `New-ConfigurationInformation`: Describes module build inclusion/exclusion. - `New-ConfigurationManifest`: Creates a manifest configuration for modules. - `New-ConfigurationModule`: Configures required, external, or approved modules. - `New-ConfigurationModuleSkip`: Allows skipping certain modules during the build. - `New-ConfigurationPlaceHolder`: Defines custom placeholders for content replacement. - `New-ConfigurationPublish`: Configures publishing settings for PowerShell Gallery or GitHub. - `New-ConfigurationTest`: Configures Pester test execution in the build. - `Set-ProjectVersion`: Updates version numbers across multiple project files. These cmdlets enhance the module publishing workflow, providing better control and flexibility for developers.
…gument completion and value pruning * Introduced `AutoLatestCompleter` to provide argument completion for "Auto" and "Latest". * Added `EmptyValuePruner` to remove empty values from dictionaries, with optional recursive pruning. * Implemented `ProjectVersionScanner` to discover project version information from various file types.
* Deleted obsolete functions for retrieving module versions from various files: - `Get-CurrentVersionFromBuildScript` - `Get-CurrentVersionFromCsProj` - `Get-CurrentVersionFromPsd1` - `Update-VersionInBuildScript` - `Update-VersionInCsProj` - `Update-VersionInPsd1` - `Update-VersionNumber` * Streamlined the module by removing unused code to enhance maintainability.
…tation * Introduced enums for `PublishDestination`, `ModuleDependencyKind`, `FileConsistencyEncoding`, `FileConsistencyLineEnding`, `DeliveryBundleDestination`, `DocumentationTool`, and `ArtefactType`. * These enums enhance the configuration options for module publishing and documentation generation.
…ands - Introduced `Get-ProjectEncoding` cmdlet to analyze encoding consistency across project files. - Introduced `Get-ProjectLineEnding` cmdlet to analyze line ending consistency across project files. - Both cmdlets support customizable project types, exclusion of directories, and export of detailed reports to CSV. - Enhanced user feedback with detailed summaries and recommendations for fixing issues.
…g detection * Introduced `DetectEncodingName` method to identify file encoding based on BOM and content. * Added `DetectLineEnding` method to analyze line endings and determine if a final newline exists. * Implemented `ComputeRelativePath` for generating relative paths based on base directory.
…nctionality * Removed legacy PowerShell scripts for test failure analysis and comment removal. * Introduced new C# cmdlets: `Get-ModuleTestFailures` and `Remove-Comments`. * Enhanced error handling and output formatting in the new cmdlets. * Improved performance and maintainability by leveraging C# features. * Updated documentation to reflect changes in cmdlet usage and parameters.
* Updated the module import in the test file to use a local path instead of the installed copy. * This change ensures that tests run against the latest version of the module from the repository.
- Deleted several private functions that are no longer in use: * `Get-FilteredScriptCommands` * `Get-ProjectCleanupPatterns` * `Get-ProjectItemsToRemove` * `Get-RestMethodExceptionDetailsOrNull` * `Get-ScriptCommands` * `Invoke-RestMethodAndThrowDescriptiveErrorOnFailure` * `New-ProjectItemBackups` * `Register-DataForInitialModule` * `Remove-ChildItems` * `Remove-FileItem` * `Remove-ProjectItemsWithMethod` * `Send-FilesToGitHubRelease` * `Test-AllFilePathsAndThrowErrorIfOneIsNotValid` * `Test-ExcludedPath` - These functions were removed to streamline the codebase and eliminate redundancy.
- Deleted `Publish-GitHubReleaseAsset.ps1`, `Publish-NugetPackage.ps1`, `Register-Certificate.ps1`, `Remove-ProjectFiles.ps1`, and `Send-GitHubRelease.ps1` scripts. - These scripts are no longer needed and have been removed to streamline the module.
* Implemented `Remove-ProjectFiles` cmdlet for safe deletion of project files and folders with backup options. * Introduced `Send-GitHubRelease` cmdlet to create GitHub releases and upload assets. * Both cmdlets include comprehensive parameter sets for flexibility and user control. * Enhanced error handling and user feedback for improved usability.
…Kind for pipeline management * Introduced `ModulePipelineStepKind` enum to define various pipeline step types. * Implemented `ModulePipelineStep` class to represent individual steps in a pipeline. * Added logic for creating an ordered list of steps based on the provided pipeline plan. * Enhanced progress reporting and UI rendering capabilities.
…peline execution * Added `ShouldUseInteractiveView` method to determine the console view based on CLI options. * Updated `Run` method to support interactive progress reporting using Spectre.Console. * Modified `Program.cs` to utilize the new interactive view logic for command execution and logging.
…rting - Introduced `IModulePipelineProgressReporter` interface for optional progress hooks during pipeline execution. - Updated `ModulePipelineRunner` to utilize progress reporting for various steps (build, documentation, install, cleanup). - Implemented safe methods to handle progress reporting, ensuring robust error handling.
…eter * Removed the alias `GUID` from the `Guid` parameter to maintain consistency with naming conventions. * This change ensures that the parameter name aligns with the standard casing used throughout the codebase.
…ck`/`pipeline` in Standard view * Progress indicator automatically disables in CI and when `--output json`/`--no-color`/`--quiet` is used.
* Introduced `PowerForgeCliJsonContext` for optimized JSON serialization of various types. * Refactored output handling in `Program.cs` to use a consistent `CliJsonEnvelope` structure for JSON responses. * Updated methods to load configuration specs with clearer error handling and path resolution. * Ensured that logging is serialized correctly into JSON format for better debugging and output clarity.
* Added `PowerShellGetSaveOptions` class for configuring save parameters. * Enhanced `PowerShellGetClient` with a new `Save` method to handle module saving. * Updated `ArtefactBuilder` to utilize new version handling logic for module saving.
…ecution * Added conditional argument handling for .NET Framework 472 and other frameworks. * Improved null checks for artefacts and publishes in `ModulePipelineStep`. * Updated project file to ensure NativeAOT publish does not evaluate the net472 TFM.
* Ensure local module is imported to avoid conflicts with installed versions. * Maintain consistency in test environment setup.
* Improved verbosity options for the build process. * Added success message upon successful build completion. * Redirected error output to host for better debugging.
* Updated the current status date to `2025-12-29`. * Improved `PowerForge.Cli` JSON output structure for stability and AOT/trim compatibility. * Enhanced `ModulePipelineRunner` to include PowerShellGet `Save-Module` fallback. * Defined a stable JSON envelope for CLI outputs.
…ethods * Added null checks for `outputFileName`, `text`, and `position` to prevent potential exceptions. * Ensured consistent trimming of strings to avoid whitespace issues.
* Introduced `Directory.Build.props` to manage project-wide properties. * Set `TreatWarningsAsErrors` to `true` to enforce stricter code quality.
…ish` method * Refactored logic to determine the repository name by prioritizing the configured repository name over the legacy repository name. * Default to "PSGallery" if no valid repository name is provided.
…sage` method * Added a check for null input to return an empty string. * Ensures that the method handles null values gracefully, preventing potential exceptions.
…build and documentation steps * Split the build step into sub-steps: "Stage to staging", "Build module", and "Patch manifest". * Split the documentation step into extraction and writing phases: "Extract help" and "Write docs". * Added an additional step for generating external help if enabled.
… ✨ Enhance documentation build process with progress reporting * Added `BuildWithProgress` method to `DocumentationEngine` for better tracking of documentation generation steps. * Introduced `StagingResult` class in `ModuleBuildPipeline` to encapsulate staging paths. * Updated `ModulePipelineRunner` to utilize new staging and documentation methods, improving error handling and progress visibility.
…ct information - Introduced a new table format for displaying project configuration details. - Added staging path and frameworks information to the console output. - Improved visibility of documentation and artefact statuses. - Updated step icons to use color coding for better differentiation.
…otNetReleaseBuildCommand` and `StepVersionCommand` * Cleaned up code by eliminating redundant logging implementation. * Simplifies the command classes for better maintainability.
* Implement tests to verify the inclusion of build and documentation substeps. * Ensure external help step is omitted when disabled. * Enhance test coverage for `ModulePipelineStep` functionality.
* Added tasks to validate AOT publishing for CLI. * Documented current blocker related to `dotnet publish -p:PublishAot=true` and suggested next steps for splitting AOT-safe core from PowerShell SDK-dependent services. * Included progress on unit tests for `ModulePipelineStep.Create` build/docs substeps.
- Introduced `ConsoleEncoding` class to ensure console input and output encoding is set to UTF-8 without BOM. - Implements a best-effort approach to handle environments that do not allow encoding changes.
…ror logging and fallback mechanism * Introduced `_skipPsResourceGetSave` flag to manage PSResourceGet failures. * Added detailed logging for various failure scenarios, including SecretStore access issues. * Updated `DotnetPublisher` to support isolated artifact paths to prevent file locking. * Modified `ModuleBuilder` to utilize isolated temp folders during publishing. * Changed error logging in `PSResourceGetClient` to verbose level for better debugging.
…t and improved logging * Added Unicode support for console output in `PipelineConsoleUi`. * Updated logging methods in `SpectreConsoleLogger` to use icons based on log levels. * Introduced a new `LogLevel` enum for better log management. * Enhanced the `WritePipelineSummary` method to display a summary table with icons.
…rameters * Introduced `ExcludeDirectories` and `ExcludeFiles` parameters to allow users to specify which directories and files should be excluded from the staging copy. * Enhanced logging with a new `ILogger` implementation for better error handling and output. * Improved the overall structure and readability of the `ProcessRecord` method.
* Introduced `BufferingLogger` for in-memory logging with various log levels. * Added `SpectreConsoleLogger` for enhanced console output using Spectre.Console. * Implemented `SpectrePipelineConsoleUi` for interactive console UI during module pipeline execution. * Updated project file to include `Spectre.Console` package dependency.
…uilding * Introduced a new `PackageReference` for `System.Text.Json` in the project file. * Updated `ModuleBuilder` to utilize `System.Text.Json` for enhanced JSON handling during module publishing. * Improved the logic for copying publish output binaries, ensuring better management of target frameworks and dependencies.
…tion * Removed `net10.0` from the `Frameworks` list in `powerforge.json`. * This change ensures compatibility with supported frameworks only.
* Improved logic for loading binary modules based on the environment. * Added support for preferring freshly built project output over stale binaries. * Ensured backwards-compatible aliases for public functions. * Enhanced error handling during module import.
Pull Request Review: PowerForge Migration (PR #45)OverviewThis is a massive architectural refactoring (396 files, 31,621 additions) that migrates PSPublishModule from PowerShell-based implementation to a hybrid C#/PowerShell architecture with a new core library called PowerForge. This is a foundational change that modernizes the entire module build/publish pipeline. 🎯 Strengths1. Excellent Architecture & Separation of Concerns
2. Strong Type Safety
3. Robust Error Handling
4. Security Best Practices
5. Well-Documented Migration Plan
|
No description provided.