Compare commits

..

3 Commits

Author SHA1 Message Date
5dca7e693b Fixed file structure
Some checks failed
Build on push / prepare (push) Successful in 8s
Build on push / build (push) Failing after 10s
2026-02-15 10:18:56 +01:00
a2fe4cb960 Added debug info [skip ci] 2026-02-15 10:17:48 +01:00
8cdd6a6e0e Should fix output problem
Some checks failed
Build on push / prepare (push) Successful in 7s
Build on push / build (push) Failing after 4s
2026-02-15 10:11:29 +01:00
7 changed files with 143 additions and 50 deletions

View File

@@ -33,14 +33,14 @@ jobs:
- name: Build single file executables - name: Build single file executables
run: | run: |
cd sh.actions/sh.actions.package-cleanup cd sh.actions.package-cleanup
# Build for Linux x64 # Build for Linux x64
dotnet publish -c Release -r linux-x64 -p:Version=$(cat ../../version.txt) -o publish/linux-x64 dotnet publish -c Release -r linux-x64 -p:Version=$(cat ../../version.txt) -o publish/linux-x64
- name: Upload to Gitea Generic Package Registry - name: Upload to Gitea Generic Package Registry
run: | run: |
cd sh.actions/sh.actions.package-cleanup cd sh.actions.package-cleanup
curl -X PUT \ curl -X PUT \
-H "Authorization: token ${{ secrets.CI_ACCESS_TOKEN }}" \ -H "Authorization: token ${{ secrets.CI_ACCESS_TOKEN }}" \
-T publish/linux-x64/sh.actions.package-cleanup \ -T publish/linux-x64/sh.actions.package-cleanup \

View File

@@ -18,6 +18,18 @@ inputs:
api_token: api_token:
description: "API token for authentication" description: "API token for authentication"
required: true required: true
dry_run:
description: "Execute without deleting packages"
required: false
default: "false"
outputs:
deleted_packages:
description: "Number of packages deleted"
value: ${{ steps.cleanup.outputs.deleted_packages }}
processed_names:
description: "Number of package names processed"
value: ${{ steps.cleanup.outputs.processed_names }}
runs: runs:
using: "composite" using: "composite"
@@ -31,6 +43,7 @@ runs:
chmod +x package-cleanup-linux-x64 chmod +x package-cleanup-linux-x64
- name: Run package-cleanup - name: Run package-cleanup
id: cleanup
shell: bash shell: bash
env: env:
URL: ${{ inputs.url }} URL: ${{ inputs.url }}
@@ -38,5 +51,8 @@ runs:
TYPES: ${{ inputs.types }} TYPES: ${{ inputs.types }}
NAMES: ${{ inputs.names }} NAMES: ${{ inputs.names }}
API_TOKEN: ${{ inputs.api_token }} API_TOKEN: ${{ inputs.api_token }}
DRY_RUN: ${{ inputs.dry_run }}
GITHUB_OUTPUT: ${{ env.GITHUB_OUTPUT }}
run: | run: |
echo "Starting cleanup..."
./package-cleanup-linux-x64 ./package-cleanup-linux-x64

View File

@@ -15,7 +15,7 @@ public static class ConfigurationExtension
public static IConfigurationBuilder EnsureGiteaConfig(this IConfigurationBuilder builder) public static IConfigurationBuilder EnsureGiteaConfig(this IConfigurationBuilder builder)
{ {
var configuration = builder.Build(); var configuration = builder.Build();
var requiredKeys = new[] { "URL", "OWNER", "TYPES", "NAME", "API_TOKEN" }; var requiredKeys = new[] { "URL", "OWNER", "TYPES", "NAMES", "API_TOKEN" };
foreach (var key in requiredKeys) foreach (var key in requiredKeys)
{ {

View File

@@ -22,24 +22,75 @@ public class GiteaPackageService(
} }
} }
public async Task<IEnumerable<GiteaPackage>> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default) public async Task<IEnumerable<GiteaPackage>> GetPackagesByNameAsync(string name, CancellationToken cancellationToken = default)
{ {
try try
{ {
var baseUrl = GetBaseUrl(); var baseUrl = GetBaseUrl();
var allPackages = new List<GiteaPackage>(); var packages = new List<GiteaPackage>();
// Parse comma-separated types // Parse comma-separated types
var types = (configuration["TYPE"] ?? "") var types = (configuration["TYPES"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (types.Length == 0) if (types.Length == 0)
{ {
logger.LogWarning("No package types configured"); logger.LogWarning("No package types configured");
return allPackages; return packages;
} }
// Parse comma-separated names foreach (var type in types)
{
var page = 1;
while (true)
{
var url = $"{baseUrl}/{type}/{name}?page={page}";
logger.LogInformation("Fetching packages from Gitea: {Url}", url);
var request = new HttpRequestMessage(HttpMethod.Get, url);
AddAuthorizationHeader(request);
var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
var fetchedPackages =
await response.Content.ReadFromJsonAsync<List<GiteaPackage>>(cancellationToken: cancellationToken)
?? [];
if (fetchedPackages.Count == 0)
{
break;
}
packages.AddRange(fetchedPackages);
logger.LogInformation("Fetched {Count} packages from page {Page}", fetchedPackages.Count, page);
page++;
}
}
logger.LogInformation("Successfully fetched {Count} packages for name '{Name}'", packages.Count, name);
return packages;
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Error fetching packages from Gitea for name '{Name}'", name);
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error fetching packages for name '{Name}'", name);
throw;
}
}
public async Task<IEnumerable<GiteaPackage>> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default)
{
try
{
var allPackages = new List<GiteaPackage>();
var names = (configuration["NAMES"] ?? "") var names = (configuration["NAMES"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
@@ -49,38 +100,10 @@ public class GiteaPackageService(
return allPackages; return allPackages;
} }
foreach (var type in types) foreach (var name in names)
{ {
foreach (var name in names) var packages = await GetPackagesByNameAsync(name, cancellationToken);
{ allPackages.AddRange(packages);
var page = 1;
while (true)
{
var url = $"{baseUrl}/{type}/{name}?page={page}";
logger.LogInformation("Fetching packages from Gitea: {Url}", url);
var request = new HttpRequestMessage(HttpMethod.Get, url);
AddAuthorizationHeader(request);
var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
var packages =
await response.Content.ReadFromJsonAsync<List<GiteaPackage>>(cancellationToken: cancellationToken)
?? [];
if (packages.Count == 0)
{
break;
}
allPackages.AddRange(packages);
logger.LogInformation("Fetched {Count} packages from page {Page}", packages.Count, page);
page++;
}
}
} }
logger.LogInformation("Successfully fetched {Count} packages in total", allPackages.Count); logger.LogInformation("Successfully fetched {Count} packages in total", allPackages.Count);

View File

@@ -4,6 +4,7 @@ using sh.actions.package_cleanup.Models;
public interface IGiteaPackageService public interface IGiteaPackageService
{ {
Task<IEnumerable<GiteaPackage>> GetPackagesByNameAsync(string name, CancellationToken cancellationToken = default);
Task<IEnumerable<GiteaPackage>> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default); Task<IEnumerable<GiteaPackage>> GetPackagesByOwnerAsync(CancellationToken cancellationToken = default);
Task DeletePackage(GiteaPackage package, CancellationToken cancellationToken = default); Task DeletePackage(GiteaPackage package, CancellationToken cancellationToken = default);
} }

View File

@@ -6,8 +6,7 @@ public class PackageService(IGiteaPackageService packageService) : IPackageServi
{ {
public async Task<List<GiteaPackage>> GetFilteredPackages() public async Task<List<GiteaPackage>> GetFilteredPackages()
{ {
var packages = (await packageService.GetPackagesByOwnerAsync()).ToList(); return (await packageService.GetPackagesByOwnerAsync()).ToList();
return packages;
} }
public List<GiteaPackage> FilterPackagesToDelete(List<GiteaPackage> packages) public List<GiteaPackage> FilterPackagesToDelete(List<GiteaPackage> packages)

View File

@@ -11,20 +11,22 @@ public class Worker(
IGiteaPackageService giteaPackageService IGiteaPackageService giteaPackageService
) : BackgroundService ) : BackgroundService
{ {
private async Task DeletePackages(List<GiteaPackage> packages, CancellationToken cancellationToken = default) private async Task<int> DeletePackages(List<GiteaPackage> packages, CancellationToken cancellationToken = default)
{ {
var dryRun = configuration["DRY_RUN"]?.ToLower() == "true"; var dryRun = configuration["DRY_RUN"]?.ToLower() == "true";
if (dryRun) if (dryRun)
{ {
logger.LogInformation("Dry run enabled, not deleting {Count} packages", packages.Count); logger.LogInformation("Dry run enabled, not deleting {Count} packages", packages.Count);
return; return 0;
} }
var deletedCount = 0;
foreach (var giteaPackage in packages) foreach (var giteaPackage in packages)
{ {
try try
{ {
await giteaPackageService.DeletePackage(giteaPackage, cancellationToken); await giteaPackageService.DeletePackage(giteaPackage, cancellationToken);
deletedCount++;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -32,25 +34,77 @@ public class Worker(
giteaPackage.Name, giteaPackage.Version); giteaPackage.Name, giteaPackage.Version);
} }
} }
return deletedCount;
}
private void WriteGitHubOutput(string name, string value)
{
var githubOutput = configuration["GITHUB_OUTPUT"];
if (string.IsNullOrEmpty(githubOutput))
{
logger.LogDebug("GITHUB_OUTPUT not set, skipping output: {Name}={Value}", name, value);
return;
}
try
{
File.AppendAllText(githubOutput, $"{name}={value}{Environment.NewLine}");
logger.LogInformation("Wrote to GITHUB_OUTPUT: {Name}={Value}", name, value);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to write to GITHUB_OUTPUT file");
}
} }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{ {
try try
{ {
var packages = await packageService.GetFilteredPackages(); // Parse comma-separated names
logger.LogInformation("Found {Count} packages", packages.Count); var names = (configuration["NAMES"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (names.Length == 0)
{
logger.LogWarning("No package names configured");
WriteGitHubOutput("deleted_packages", "0");
WriteGitHubOutput("processed_names", "0");
appLifetime.StopApplication();
return;
}
var totalDeleted = 0;
// 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);
var deletedCount = await DeletePackages(packagesToDelete, cancellationToken);
totalDeleted += deletedCount;
logger.LogInformation("Deleted {Count} packages for name '{Name}'", deletedCount, name);
logger.LogInformation("Cleanup finished for name '{Name}'", name);
}
var packagesToDelete = packageService.FilterPackagesToDelete(packages); logger.LogInformation("All package names processed successfully");
logger.LogInformation("Found {Count} packages to delete", packagesToDelete.Count);
await DeletePackages(packagesToDelete, cancellationToken); // Write outputs to GITHUB_OUTPUT
WriteGitHubOutput("deleted_packages", totalDeleted.ToString());
logger.LogInformation("Cleanup finished successfully"); WriteGitHubOutput("processed_names", names.Length.ToString());
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError(ex, "Cleanup failed with an error"); logger.LogError(ex, "Cleanup failed with an error");
WriteGitHubOutput("deleted_packages", "0");
WriteGitHubOutput("processed_names", "0");
} }
finally finally
{ {