Files
actions/sh.actions.package-cleanup/Worker.cs
edraft ff8cd3350b
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 18s
Added more debugging
2026-02-15 12:49:58 +01:00

88 lines
3.2 KiB
C#

using sh.actions.package_cleanup.Models;
using sh.actions.package_cleanup.Service;
namespace sh.actions.package_cleanup;
public class Worker(
ILogger<Worker> logger,
IConfiguration configuration,
IHostApplicationLifetime appLifetime,
IPackageService packageService,
IGiteaPackageService giteaPackageService
) : BackgroundService
{
private async Task DeletePackages(List<GiteaPackage> packages, CancellationToken cancellationToken = default)
{
var dryRun = configuration["DRY_RUN"]?.ToLower() == "true";
if (dryRun)
{
logger.LogInformation("Dry run enabled, not deleting {Count} packages", packages.Count);
logger.LogInformation("Would delete packages: {versions}",
string.Join(", ", packages.Select(p => p.Version)));
}
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();
}
}
}