Skip to content

Commit 20a372a

Browse files
authored
refactor: Migrate CLI to Spectre.Console.Cli with modular architecture (#63)
* Remove outdated PR review document * Add donation links to README files * Add donation buttons to README files * Update donation buttons in README files * Update Buy Me a Coffee button style in README files * Add OpenSpec for auto-update check and notification feature Includes design, proposal, requirements, and implementation tasks for automatic daily update checks, user notification, and update commands * Update package references to latest versions across projects * Remove unused methods and clean up Utils class * Refactor: Remove Winget and File services, and related models - Deleted WingetOperationOptions and WingetOperationResult models as they are no longer needed. - Removed WingetService which handled backup and restore operations for Winget packages. - Deleted FileService which provided file operations including combining files. - Updated DatabaseService to remove backup and restore methods, focusing on database listing and connection testing. - Introduced DatabaseConnectionOptions model to encapsulate database connection parameters. - Updated tests to remove dependencies on removed services. * Refactor: Remove unused health check, correlation context, resilience policies, and related models * Remove unused ServerConfig class and clean up ConsoleLogger * Refactor: Remove unused properties and methods from command options and services * Refactor: Remove unused PostgresBinaryLocator class and related methods; clean up configuration services * Refactor: Update database backup extension and remove unused ConsoleLogger and OperationResult classes; clean up SqlQueryAnalyzer and related tests * Refactor: Update .gitignore to ignore opencode.json and remove the opencode.json file * feat: migrate CLI from System.CommandLine to Spectre.Console.Cli - Added .openspec.yaml and design.md for migration details - Created proposal.md outlining the rationale and changes - Defined new specs for command structure, DI bridge, exception handling, and core services - Implemented tasks for core service preparation, CLI infrastructure setup, and command migration - Removed static façade classes and ensured all commands utilize constructor injection - Centralized exception handling with specific exit codes - Organized command files to reflect the command hierarchy * Refactor tests and services for improved structure and dependency injection - Updated DatabaseCommandTests to verify service resolution from DI. - Refactored FileCommandTests to enhance file handling and encoding checks. - Removed OpenCodeCommandTests due to redundancy. - Simplified PgPassCommandTests to focus on utility functions. - Enhanced QueryCommandTests for better command structure validation. - Removed WingetCommandTests as they were no longer necessary. - Updated task list in migration documentation to reflect completed tasks. * Refactor: Migrate CLI to Spectre.Console.Cli and implement dependency injection for commands * Refactor: Add CsvExporter as a singleton service in the DI container * Refactor file access methods to use simplified syntax - Removed redundant `System.IO` namespace references in multiple files. - Updated file access methods to use the `File` and `Directory` classes directly. - Ensured consistent usage of file reading and writing methods across the codebase. - Improved code readability by reducing verbosity in file operations. * Refactor: Rename variable for clarity in CsvExporter * Refactor: Standardize host option flag to uppercase across database commands * Refactor: Improve error handling in CLI by displaying clean error messages * Refactor: Mark task 6.10 as completed for database error simulation test * feat: add exception handling and exit code mapping for CLI commands - Implemented centralized exception handling in CommandApp using SetExceptionHandler. - Mapped specific exceptions to exit codes for better error handling. - Added visual exception formatting using Spectre.Console. - Introduced IDockerService and IPostgresBinaryLocator interfaces for Docker and PostgreSQL binary management. - Created IPostgresPasswordHandler for secure password input handling. - Established update check mechanism for automatic version notifications via NuGet API. - Enhanced user configuration structure to include update check state. - Added commands for manual update checks and executions. * Refactor test descriptions in PgPassServiceTests, SecurityUtilsTests, SqlQueryAnalyzerTests, and UserConfigServiceTests to improve clarity and consistency. Update comments and assertions to reflect English language standards and enhance readability. * Refactor: Remove CleanCommand and its references from the CLI and documentation * Refactor: Remove IConfigurationService and related command timeout properties from database commands and user configuration service * Refactor: Remove IConfigurationService and ConfigurationService to streamline health check dependencies * Refactor: Remove PostgresBinaryHealthCheck and its registration from service collection * Refactor: Remove NpgsqlConnectionString property from DatabaseBackupCommand, DatabaseRestoreCommand, and OperationProgress models to simplify configuration * Refactor: Remove OperationProgress model and related progress reporting from ProcessExecutor to simplify process execution * Refactor: Remove OutputFormat and FetchAllDatabases properties from UserDefaults to simplify configuration * Refactor: Introduce FurLabConstants for default host and port values to simplify configuration * Refactor: Consolidate exception handling by removing unused exceptions and introducing specific database exceptions * Refactor: Remove unused QueryType and SqlQueryAnalyzer classes to simplify codebase * Refactor: Move FileCombineCommand to Files namespace and add FileEncodingHelper for encoding detection * Refactor: Remove Utils class and update tests to use FileEncodingHelper for encoding detection * Refactor architecture documentation and feature specifications for FurLab CLI - Updated architecture overview to reflect changes in command parsing and dependency injection using Spectre.Console.Cli and Microsoft.Extensions.DependencyInjection. - Enhanced command structure in documentation, detailing new command organization and responsibilities. - Revised feature specifications to include new functionalities for database utilities, file management, and integration with Claude Code and OpenCode. - Improved clarity on command usage, error handling, and business rules across various functionalities. - Added new sections for managing database server configurations and enhanced security practices for credential handling. * Add Windows Features Export, Import, and List Commands - Implemented WindowsFeaturesExportSettings for export command settings. - Created WindowsFeaturesImportCommand to import and enable Windows features from a JSON file. - Added WindowsFeaturesImportSettings for import command settings. - Developed WindowsFeaturesListCommand to list available Windows features. - Introduced WindowsFeaturesListSettings to filter enabled features. - Updated Program.cs to register new Windows features commands. - Refactored process execution interfaces and models for better structure. - Removed obsolete WingetBackupCommand and adjusted related commands. - Added test support classes for improved unit testing. * Add examples and templates for CLI command management in FurLab * Refactor: Replace Utils references with Constants and remove unused Utils class * fix: Add Backup command files that were ignored by .gitignore * fix: Update .gitignore to include Backup command folders and files * fix: Use correct ApplicationName in CredentialServiceTests for DataProtection * fix: Use EphemeralDataProtectionProvider for tests to ensure consistent behavior across platforms * fix: Use temporary directory for DataProtection keys in tests * fix: Use EphemeralDataProtectionProvider with FurLab.Tests app name * fix: Remove unused Cleanup method from CredentialServiceTests * refactor: Reorder using directives for consistency across command files * debug: Add diagnostic tests for DataProtection and CredentialService * refactor: Enhance CredentialServiceTests with temporary key directory and cleanup logic * fix: Remove DisableAutomaticKeyGeneration to allow key creation in temp directory * fix: Configure explicit cryptographic algorithms for cross-platform DataProtection compatibility * refactor: Add missing using directive for AuthenticatedEncryption in CredentialServiceTests * refactor: Simplify DataProtection configuration in CredentialServiceTests * refactor: Update DataProtection configuration to use AES_256_GCM for improved compatibility on Linux
1 parent 77adb2b commit 20a372a

192 files changed

Lines changed: 7421 additions & 10485 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Exemplos de Uso - furlab-command-manager
2+
3+
## Criar um comando simples
4+
5+
```
6+
Crie um comando "database verify" que verifica a conexão com o banco de dados
7+
```
8+
9+
**Ações da skill:**
10+
1. Criar pasta: `FurLab.CLI/Commands/Database/Verify/`
11+
2. Criar `DatabaseVerifyCommand.cs` com classe `DatabaseVerifyCommand`
12+
3. Criar `DatabaseVerifySettings.cs` com classe `DatabaseVerifySettings`
13+
4. Adicionar em Program.cs:
14+
```csharp
15+
db.AddCommand<Commands.Database.Verify.DatabaseVerifyCommand>("verify");
16+
```
17+
18+
## Criar um comando aninhado
19+
20+
```
21+
Adicione o comando "claude settings reset" para resetar configurações do Claude
22+
```
23+
24+
**Ações da skill:**
25+
1. Criar pasta: `FurLab.CLI/Commands/Claude/Settings/Reset/`
26+
2. Criar `ClaudeSettingsResetCommand.cs`
27+
3. Criar `ClaudeSettingsResetSettings.cs`
28+
4. Adicionar em Program.cs:
29+
```csharp
30+
claude.AddBranch("settings", settings =>
31+
{
32+
settings.AddCommand<Commands.Claude.Settings.Reset.ClaudeSettingsResetCommand>("reset");
33+
});
34+
```
35+
36+
## Atualizar um comando existente
37+
38+
```
39+
Adicione um argumento "--timeout" no comando database backup
40+
```
41+
42+
**Ações da skill:**
43+
1. Localizar: `FurLab.CLI/Commands/Database/Backup/DatabaseBackupSettings.cs`
44+
2. Adicionar propriedade:
45+
```csharp
46+
[CommandOption("--timeout")]
47+
[Description("Timeout in seconds.")]
48+
public int? Timeout { get; init; }
49+
```
50+
3. Atualizar `DatabaseBackupCommand.cs` para usar o novo parâmetro
51+
4. Verificar build
52+
53+
## Remover um comando
54+
55+
```
56+
Remova o comando "docker redis" (já não usamos mais)
57+
```
58+
59+
**Ações da skill:**
60+
1. Localizar pasta: `FurLab.CLI/Commands/Docker/Redis/`
61+
2. Remover de Program.cs:
62+
```csharp
63+
// docker.AddCommand<Commands.Docker.Redis.DockerRedisCommand>("redis");
64+
```
65+
3. Deletar arquivos:
66+
- `DockerRedisCommand.cs`
67+
- `DockerRedisSettings.cs`
68+
4. Remover pasta se vazia
69+
5. Verificar build
70+
71+
## Criar comando com múltiplos argumentos
72+
73+
```
74+
Crie o comando "files copy" com argumentos: <source> <destination> [--overwrite]
75+
```
76+
77+
**Estrutura gerada:**
78+
79+
**FileCopySettings.cs:**
80+
```csharp
81+
using System.ComponentModel;
82+
using Spectre.Console.Cli;
83+
84+
namespace FurLab.CLI.Commands.Files.Copy;
85+
86+
public sealed class FileCopySettings : CommandSettings
87+
{
88+
[CommandArgument(0, "<source>")]
89+
[Description("Source file path.")]
90+
public string Source { get; init; } = string.Empty;
91+
92+
[CommandArgument(1, "<destination>")]
93+
[Description("Destination file path.")]
94+
public string Destination { get; init; } = string.Empty;
95+
96+
[CommandOption("--overwrite")]
97+
[Description("Overwrite existing file.")]
98+
public bool Overwrite { get; init; }
99+
}
100+
```
101+
102+
**FileCopyCommand.cs:**
103+
```csharp
104+
using Spectre.Console.Cli;
105+
106+
namespace FurLab.CLI.Commands.Files.Copy;
107+
108+
public sealed class FileCopyCommand : AsyncCommand<FileCopySettings>
109+
{
110+
protected override async Task<int> ExecuteAsync(CommandContext context, FileCopySettings settings, CancellationToken cancellation)
111+
{
112+
if (File.Exists(settings.Destination) && !settings.Overwrite)
113+
{
114+
AnsiConsole.MarkupLine("[red]Error:[/] Destination exists. Use --overwrite to replace.");
115+
return 1;
116+
}
117+
118+
File.Copy(settings.Source, settings.Destination, settings.Overwrite);
119+
return 0;
120+
}
121+
}
122+
```
123+
124+
## Convenções Importantes
125+
126+
Sempre siga estas regras:
127+
128+
1. **Nome do arquivo = Nome da classe**
129+
-`DatabaseBackupCommand.cs``class DatabaseBackupCommand`
130+
- ❌ Nunca `Command.cs``class BackupCommand`
131+
132+
2. **Estrutura de pastas hierárquica**
133+
```
134+
Commands/
135+
├── Database/
136+
│ ├── Backup/
137+
│ │ ├── DatabaseBackupCommand.cs
138+
│ │ └── DatabaseBackupSettings.cs
139+
│ └── Restore/
140+
│ ├── DatabaseRestoreCommand.cs
141+
│ └── DatabaseRestoreSettings.cs
142+
```
143+
144+
3. **Prefixo do arquivo**
145+
- Simples: `{Grupo}{Subcomando}`
146+
- Aninhado: `{Grupo}{Pai}{Subcomando}`
147+
148+
4. **Atualização do Program.cs**
149+
Sempre registrar o comando após criar

0 commit comments

Comments
 (0)