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); return; } 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 packages = await packageService.GetFilteredPackages(); logger.LogInformation("Found {Count} packages", packages.Count); var packagesToDelete = packageService.FilterPackagesToDelete(packages); logger.LogInformation("Found {Count} packages to delete", packagesToDelete.Count); await DeletePackages(packagesToDelete, cancellationToken); logger.LogInformation("Cleanup finished successfully"); } catch (Exception ex) { logger.LogError(ex, "Cleanup failed with an error"); } finally { appLifetime.StopApplication(); } } }