using sh.actions.package_cleanup.Models; using sh.actions.package_cleanup.Service; namespace sh.actions.package_cleanup; public class Worker( ILogger logger, IConfiguration configuration, IHostApplicationLifetime appLifetime, IPackageService packageService, IGiteaPackageService giteaPackageService ) : BackgroundService { private async Task DeletePackages(List packages, CancellationToken cancellationToken = default) { var dryRun = configuration["DRY_RUN"]?.ToLower() == "true"; if (dryRun) { logger.LogInformation("Dry run enabled, not deleting {Count} packages", packages.Count); } foreach (var giteaPackage in packages) { try { await giteaPackageService.DeletePackage(giteaPackage, cancellationToken); } catch (Exception ex) { logger.LogError(ex, "Failed to delete package {PackageName} version {Version}", giteaPackage.Name, giteaPackage.Version); } } } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { try { var dryRun = configuration["DRY_RUN"]?.ToLower() == "true"; if (dryRun) { logger.LogInformation("DRY RUN MODE ENABLED - No packages will be deleted"); } // Parse comma-separated names var names = (configuration["NAMES"] ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (names.Length == 0) { logger.LogWarning("No package names configured"); appLifetime.StopApplication(); return; } // Process each name separately: collect -> filter -> delete foreach (var name in names) { logger.LogInformation("Processing packages for name '{Name}'", name); var packages = (await giteaPackageService.GetPackagesByNameAsync(name, cancellationToken)).ToList(); logger.LogInformation("Found {Count} packages for name '{Name}'", packages.Count, name); var packagesToDelete = packageService.FilterPackagesToDelete(packages); logger.LogInformation("Found {Count} packages to delete for name '{Name}'", packagesToDelete.Count, name); // await DeletePackages(packagesToDelete, cancellationToken); logger.LogInformation("Deleted {Count} packages for name '{Name}'", packagesToDelete.Count, name); logger.LogInformation("Cleanup finished for name '{Name}'", name); } logger.LogInformation("All package names processed successfully"); } catch (Exception ex) { logger.LogError(ex, "Cleanup failed with an error"); } finally { appLifetime.StopApplication(); } } }