Compare commits

...

32 Commits
v1 ... dev

Author SHA1 Message Date
ff8cd3350b Added more debugging
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 18s
2026-02-15 12:49:58 +01:00
7e4abe9efd Readded delete function
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 19s
2026-02-15 12:46:24 +01:00
706d9f89f0 Fixed download url of cleanup tool
All checks were successful
Build on push / prepare (push) Successful in 27s
Build on push / build (push) Successful in 30s
2026-02-15 12:42:40 +01:00
a2e4152d5e Should fix exec problems
All checks were successful
Build on push / prepare (push) Successful in 27s
Build on push / build (push) Successful in 28s
2026-02-15 12:24:00 +01:00
4497b67b70 force dry run via start arg
All checks were successful
Build on push / prepare (push) Successful in 20s
Build on push / build (push) Successful in 39s
2026-02-15 12:17:45 +01:00
c1a882d1a2 Cleanup to ensure repull
All checks were successful
Build on push / prepare (push) Successful in 30s
Build on push / build (push) Successful in 40s
2026-02-15 12:12:52 +01:00
3ba2b71f4a Hold to debug
All checks were successful
Build on push / prepare (push) Successful in 8s
Build on push / build (push) Successful in 21s
2026-02-15 12:08:45 +01:00
17a4e57fa4 Added test output
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 19s
2026-02-15 12:07:19 +01:00
79902f323d Better output
All checks were successful
Build on push / prepare (push) Successful in 7s
Build on push / build (push) Successful in 22s
2026-02-15 12:03:52 +01:00
213fc4685d Build as single file
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 18s
2026-02-15 11:57:46 +01:00
c6fe9f7397 Added output manually
All checks were successful
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Successful in 14s
2026-02-15 10:37:47 +01:00
4ff5680310 Changed logging
All checks were successful
Build on push / prepare (push) Successful in 7s
Build on push / build (push) Successful in 15s
2026-02-15 10:29:52 +01:00
6d3a5b1930 Fixe build
All checks were successful
Build on push / prepare (push) Successful in 5s
Build on push / build (push) Successful in 15s
2026-02-15 10:19:44 +01:00
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
ca51f738c0 Some improvements
Some checks failed
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Failing after 4s
2026-02-15 03:20:03 +01:00
8586a09cd0 Added package cleanup 2026-02-15 03:02:20 +01:00
1764ddcb2b Smaller fix
Some checks failed
Build on push / prepare (push) Successful in 18s
Build on push / build (push) Failing after 4s
2026-02-14 20:52:20 +01:00
98abbe661c Added package filtering
Some checks failed
Build on push / prepare (push) Successful in 5s
Build on push / build (push) Failing after 15s
2026-02-14 20:48:40 +01:00
5e493513f1 ich hab kein bock mehr
All checks were successful
Build on push / prepare (push) Successful in 28s
Build on push / build (push) Successful in 34s
Build on push / test (push) Successful in 2s
2026-02-14 18:00:45 +01:00
0332f08194 Try generic upload
All checks were successful
Build on push / prepare (push) Successful in 19s
Build on push / build (push) Successful in 23s
2026-02-14 17:56:57 +01:00
c19921eb85 Try fix install
Some checks failed
Build on push / prepare (push) Successful in 5s
Build on push / build (push) Successful in 25s
Build on push / test (push) Failing after 2s
2026-02-14 17:45:35 +01:00
fef6b580e3 Auth for nuget tooling
Some checks failed
Build on push / prepare (push) Successful in 27s
Build on push / build (push) Successful in 14s
Build on push / test (push) Failing after 2s
2026-02-14 17:42:04 +01:00
0f48552783 Use local action
Some checks failed
Build on push / prepare (push) Successful in 26s
Build on push / build (push) Successful in 31s
Build on push / test (push) Failing after 2s
2026-02-14 17:26:55 +01:00
a06557dc48 use local action
Some checks failed
Build on push / prepare (push) Failing after 1s
Build on push / build (push) Has been skipped
Build on push / test (push) Has been skipped
2026-02-14 17:24:54 +01:00
22d0361afe Fixed install
Some checks failed
Build on push / prepare (push) Successful in 28s
Build on push / build (push) Successful in 33s
Build on push / test (push) Failing after 2s
2026-02-14 17:15:07 +01:00
008de6593c Refixed action
Some checks failed
Build on push / prepare (push) Successful in 27s
Build on push / build (push) Successful in 34s
Build on push / test (push) Failing after 2s
2026-02-14 17:13:07 +01:00
c6465b70d1 test local action
Some checks failed
Build on push / prepare (push) Failing after 1s
Build on push / build (push) Has been skipped
Build on push / test (push) Has been skipped
2026-02-14 17:09:05 +01:00
f3cff58707 Fixed tool install
Some checks failed
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Failing after 5s
Build on push / test (push) Has been skipped
2026-02-14 16:58:03 +01:00
9e25b8c4a1 Fixed build
Some checks failed
Build on push / prepare (push) Successful in 5s
Build on push / build (push) Successful in 13s
Build on push / test (push) Failing after 2s
2026-02-14 16:56:38 +01:00
bcfbbfc470 Added readme
Some checks failed
Build on push / prepare (push) Successful in 6s
Build on push / build (push) Failing after 13s
Build on push / test (push) Has been skipped
2026-02-14 16:55:11 +01:00
20 changed files with 807 additions and 78 deletions

View File

@@ -10,7 +10,7 @@ jobs:
runs-on: [runner] runs-on: [runner]
container: git.sh-edraft.de/sh-edraft.de/act-runner:latest container: git.sh-edraft.de/sh-edraft.de/act-runner:latest
steps: steps:
- uses: https://git.sh-edraft.de/sh-edraft.de/actions/set-version@v1 - uses: https://git.sh-edraft.de/sh-edraft.de/actions/set-version@dev
with: with:
version_suffix: dev version_suffix: dev
env: env:
@@ -31,36 +31,17 @@ jobs:
with: with:
name: version name: version
- name: Build package - name: Build single file executables
run: | run: |
cd sh.actions/sh.actions.package-cleanup cd sh.actions.package-cleanup
dotnet build -c Release -p:Version=$(cat ../../version.txt)
- name: Configure nuget # Build for Linux x64
run: | dotnet publish -c Release -r linux-x64 -p:Version=$(cat ../version.txt) -o publish/linux-x64
dotnet nuget add source --name git_sh-edraft_de --username ${{ secrets.CI_USERNAME }} --password ${{ secrets.CI_ACCESS_TOKEN }} --store-password-in-clear-text https://git.sh-edraft.de/api/packages/sh-edraft.de/nuget/index.json
- name: Upload - name: Upload to Gitea Generic Package Registry
run: | run: |
cd sh.actions/sh.actions.package-cleanup cd sh.actions.package-cleanup
VERSION_FIXED=$(cat ../../version.txt | sed 's/\.0\([0-9]\)/.\1/g' | sed 's/\.0-/-/g') curl -X PUT \
dotnet nuget push --source git_sh-edraft_de sh.actions.package-cleanup/bin/Release/sh.actions.package-cleanup.$VERSION_FIXED.nupkg -H "Authorization: token ${{ secrets.CI_ACCESS_TOKEN }}" \
-T publish/linux-x64/sh.actions.package-cleanup \
test: "https://git.sh-edraft.de/api/packages/sh-edraft.de/generic/package-cleanup/$(cat ../version.txt)/package-cleanup-linux-x64"
runs-on: [runner]
needs: build
container: git.sh-edraft.de/sh-edraft.de/act-runner:latest
steps:
- name: Install set-version tool
shell: bash
run: |
dotnet tool install \
--tool-path .tools \
package-cleanup \
--version 1.0.0 \
--add-source https://git.sh-edraft.de/api/packages/sh-edraft.de/nuget/index.json
- name: Run set-version
shell: bash
run: |
./.tools/package-cleanup

10
.gitignore vendored
View File

@@ -2,4 +2,12 @@
.code .code
bin/ bin/
obj/ obj/
publish/
# Environment Variables - DO NOT COMMIT
.env
.env.local
*.env.local
**/appsettings.local.json

View File

@@ -1,19 +1,56 @@
name: "package cleanup" name: "package cleanup"
description: "Cleans up old packages and versions" description: "Cleans up old packages and versions"
inputs:
url:
description: "Server URL"
required: true
names:
description: "Names of packages"
required: true
owner:
description: "Owner of the package"
required: true
types:
description: "Types of packages (e.g. Container, PyPi, NuGet)"
required: false
default: "Container,PyPi,NuGet"
api_token:
description: "API token for authentication"
required: true
dry_run:
description: "Execute without deleting packages"
required: false
default: "false"
runs: runs:
using: "composite" using: "composite"
steps: steps:
- name: Install set-version tool - name: Download and test package-cleanup tool
shell: bash shell: bash
run: | run: |
dotnet tool install \ latest_path=$(curl -sI https://git.sh-edraft.de/sh-edraft.de/-/packages/generic/package-cleanup/ \
--tool-path .tools \ | awk -F ' ' '/Location:/ {print $2}' \
ShEdraft.SetVersion \ | tr -d '\r')
--version 1.0.0 \
--add-source https://git.sh-edraft.de/api/packages/sh-edraft.de/nuget/index.json
- name: Run set-version version=$(basename "$latest_path")
echo "Downloading package-cleanup version $version..."
curl -OJ https://git.sh-edraft.de/api/packages/sh-edraft.de/generic/package-cleanup/$version/package-cleanup-linux-x64
# Make executable
chmod +x package-cleanup-linux-x64
- name: Run package-cleanup
id: cleanup
shell: bash shell: bash
env:
URL: ${{ inputs.url }}
OWNER: ${{ inputs.owner }}
TYPES: ${{ inputs.types }}
NAMES: ${{ inputs.names }}
API_TOKEN: ${{ inputs.api_token }}
DRY_RUN: ${{ inputs.dry_run }}
GITHUB_OUTPUT: ${{ env.GITHUB_OUTPUT }}
run: | run: |
./.tools/set-version --suffix dev ./package-cleanup-linux-x64

View File

@@ -0,0 +1,146 @@
using Moq;
using sh.actions.package_cleanup.Models;
using sh.actions.package_cleanup.Service;
using Xunit;
namespace sh.actions.package_cleanup.Tests.Service;
public class PackageFilterTests
{
private readonly IPackageService _packageService;
private readonly Mock<IGiteaPackageService> _giteaPackageServiceMock = new Mock<IGiteaPackageService>();
private readonly List<GiteaPackage> _packages;
public PackageFilterTests()
{
_packageService = new PackageService(_giteaPackageServiceMock.Object);
_packages = _versions.Select(v => new GiteaPackage
{
Version = v,
Name = $"test-{v}"
}).ToList();
}
[Fact]
public void TestFilterPackagesToDelete()
{
var toDelete = _packageService.FilterPackagesToDelete(_packages);
var toDeleteVersions = toDelete
.Select(x => x.Version)
.OrderByDescending(x => x)
.ToList();
var expected = _expectDeleted.OrderByDescending(x => x).ToList();
Assert.Equal(expected.Count, toDeleteVersions.Count);
Assert.Equal(expected, toDeleteVersions);
}
private readonly List<string> _versions =
[
"0.1.0",
"0.1.1",
"0.1.2",
"1.0",
"1.1",
"1.2",
"2024.8.6.0",
"2024.8.7.0",
"2024.8.8.0",
"2024.8.9.0",
"2024.8.10.0",
"2024.8.11.0",
"latest",
// dev
"0-dev",
"1-dev",
"2-dev",
"1.0-dev",
"1.1-dev",
"1.2-dev",
"0.1.0-dev",
"0.1.1-dev",
"0.1.2-dev",
"2024.8.6.0-dev",
"2024.8.6.1-dev",
"2024.8.7.0-dev",
"2024.8.7.1-dev",
"2024.8.8.0-dev",
"2024.8.8.1-dev",
"2024.8.9.0-dev",
"2024.8.9.1-dev",
"2024.8.10.0-dev",
"2024.8.10.1-dev",
"2024.8.11.0-dev",
"2024.8.11.1-dev",
// test
"0.1.0-test",
"0.1.1-test",
"0.1.2-test",
"2024.8.6.0-test",
"2024.8.6.1-test",
"2024.8.7.0-test",
"2024.8.7.1-test",
"2024.8.8.0-test",
"2024.8.8.1-test",
"2024.8.9.0-test",
"2024.8.9.1-test",
"2024.8.10.0-test",
"2024.8.10.1-test",
"2024.8.11.0-test",
// exp
"0.1.0-exp",
"0.1.1-exp",
"0.1.2-exp",
"2024.8.6.0-exp",
"2024.8.6.1-exp",
"2024.8.7.0-exp",
"2024.8.7.1-exp",
"2024.8.8.0-exp",
"2024.8.8.1-exp",
"2024.8.9.0-exp",
"2024.8.9.1-exp",
"2024.8.10.0-exp",
"2024.8.10.1-exp",
"2024.8.11.0-exp",
"2024.8.11.2-exp"
];
private readonly List<string> _versionsToHold =
[
// prod (no suffix)
"0.1.0",
"0.1.1",
"0.1.2",
"1.0",
"1.1",
"1.2",
"2024.8.6.0",
"2024.8.7.0",
"2024.8.8.0",
"2024.8.9.0",
"2024.8.10.0",
"2024.8.11.0",
"latest",
// dev
"1-dev",
"2-dev",
"1.1-dev",
"1.2-dev",
"0.1.1-dev",
"0.1.2-dev",
"2024.8.11.0-dev",
"2024.8.11.1-dev",
// test
"0.1.1-test",
"0.1.2-test",
"2024.8.10.1-test",
"2024.8.11.0-test",
// exp
"0.1.1-exp",
"0.1.2-exp",
"2024.8.11.0-exp",
"2024.8.11.2-exp"
];
private List<string> _expectDeleted => _versions.Except(_versionsToHold).ToList();
}

View File

@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsTestProject>true</IsTestProject>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>sh.actions.package_cleanup.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Moq" Version="4.20.70" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../sh.actions.package-cleanup/sh.actions.package-cleanup.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,27 @@
namespace sh.actions.package_cleanup;
public static class ConfigurationExtension
{
private const string MissingConfigurationError = "Configuration variable '{0}' is required but was not found.";
private static void ValidateConfigurationVariable(IConfiguration configuration, string key)
{
if (string.IsNullOrWhiteSpace(configuration[key]))
{
throw new InvalidOperationException(string.Format(MissingConfigurationError, key));
}
}
public static IConfigurationBuilder EnsureGiteaConfig(this IConfigurationBuilder builder)
{
var configuration = builder.Build();
var requiredKeys = new[] { "URL", "OWNER", "TYPES", "NAMES", "API_TOKEN" };
foreach (var key in requiredKeys)
{
ValidateConfigurationVariable(configuration, key);
}
return builder;
}
}

View File

@@ -0,0 +1,10 @@
namespace sh.actions.package_cleanup.Models;
public class GiteaPackage
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}

View File

@@ -0,0 +1,97 @@
using System.Text.RegularExpressions;
namespace sh.actions.package_cleanup.Models;
public class SoftwareVersion(
int major,
int minor,
int patch = 0,
int build = 0,
string? suffix = null,
string? input = null,
bool isLatest = false)
{
public int Major { get; set; } = major;
public int Minor { get; set; } = minor;
public int Patch { get; set; } = patch;
public int Build { get; set; } = build;
public string? Suffix { get; set; } = suffix;
public string? Input { get; set; } = input;
public bool IsLatest { get; set; } = isLatest;
public override string ToString()
{
var versionStr = $"{Major}.{Minor}.{Patch}.{Build}";
if (!string.IsNullOrEmpty(Suffix))
{
versionStr += $"-{Suffix}";
}
return versionStr;
}
public override bool Equals(object? obj)
{
return obj is SoftwareVersion version && ToString() == version.ToString();
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public static SoftwareVersion Parse(string versionString)
{
// Try matching format: X.X.X.X or X.X.X.X-suffix
var match = Regex.Match(versionString, @"(\d+)\.(\d+)\.(\d+)\.(\d+)(?:-(.*))?");
if (match.Success)
{
var major = int.Parse(match.Groups[1].Value);
var minor = int.Parse(match.Groups[2].Value);
var patch = int.Parse(match.Groups[3].Value);
var build = int.Parse(match.Groups[4].Value);
var suffix = match.Groups[5].Value;
return new SoftwareVersion(major, minor, patch, build, string.IsNullOrEmpty(suffix) ? null : suffix,
versionString);
}
// Try matching format: X.X.X or X.X.X-suffix
match = Regex.Match(versionString, @"(\d+)\.(\d+)\.(\d+)(?:-(.*))?");
if (match.Success)
{
var major = int.Parse(match.Groups[1].Value);
var minor = int.Parse(match.Groups[2].Value);
var patch = int.Parse(match.Groups[3].Value);
var suffix = match.Groups[4].Value;
return new SoftwareVersion(major, minor, patch, 0, string.IsNullOrEmpty(suffix) ? null : suffix,
versionString);
}
// Try matching format: X.X or X.X-suffix
match = Regex.Match(versionString, @"(\d+)\.(\d+)(?:-(.*))?");
if (match.Success)
{
var major = int.Parse(match.Groups[1].Value);
var minor = int.Parse(match.Groups[2].Value);
var suffix = match.Groups[3].Value;
return new SoftwareVersion(major, minor, 0, 0, string.IsNullOrEmpty(suffix) ? null : suffix, versionString);
}
// Try matching format: X or X-suffix
match = Regex.Match(versionString, @"(\d+)(?:-(.*))?");
if (match.Success)
{
var major = int.Parse(match.Groups[1].Value);
var suffix = match.Groups[2].Value;
return new SoftwareVersion(major, 0, 0, 0, string.IsNullOrEmpty(suffix) ? null : suffix, versionString);
}
// Special case for "latest"
if (versionString == "latest")
{
return new SoftwareVersion(1, 0, 0, 0, null, versionString, isLatest: true);
}
throw new ArgumentException($"Invalid version string: {versionString}");
}
}

View File

@@ -0,0 +1,30 @@
using sh.actions.package_cleanup;
using sh.actions.package_cleanup.Service;
var builder = Host.CreateApplicationBuilder(args);
// Check for --dry-run argument
var isDryRun = args.Contains("--dry-run");
if (isDryRun)
{
Environment.SetEnvironmentVariable("DRY_RUN", "true");
}
builder.Configuration
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.EnsureGiteaConfig();
builder.Services
.AddSingleton<IPackageService, PackageService>()
.AddScoped<IGiteaPackageService, GiteaPackageService>()
.AddHostedService<Worker>()
.AddHttpClient<IGiteaPackageService, GiteaPackageService>();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.SetMinimumLevel(LogLevel.Debug);
var host = builder.Build();
await host.RunAsync();

View File

@@ -0,0 +1,12 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"sh.actions.package_cleanup": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,155 @@
namespace sh.actions.package_cleanup.Service;
using System.Net.Http.Json;
using Microsoft.Extensions.Logging;
using sh.actions.package_cleanup.Models;
public class GiteaPackageService(
ILogger<GiteaPackageService> logger,
IConfiguration configuration,
HttpClient httpClient)
: IGiteaPackageService
{
private string GetBaseUrl() =>
$"{configuration["URL"]?.TrimEnd('/')}/packages/{configuration["OWNER"]}";
private void AddAuthorizationHeader(HttpRequestMessage request)
{
var token = configuration["API_TOKEN"];
if (!string.IsNullOrEmpty(token))
{
request.Headers.Add("Authorization", $"token {token}");
}
}
public async Task<IEnumerable<GiteaPackage>> GetPackagesByNameAsync(string name, CancellationToken cancellationToken = default)
{
try
{
var baseUrl = GetBaseUrl();
var packages = new List<GiteaPackage>();
// Parse comma-separated types
var types = (configuration["TYPES"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (types.Length == 0)
{
logger.LogWarning("No package types configured");
return packages;
}
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"] ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (names.Length == 0)
{
logger.LogWarning("No package names configured");
return allPackages;
}
foreach (var name in names)
{
var packages = await GetPackagesByNameAsync(name, cancellationToken);
allPackages.AddRange(packages);
}
logger.LogInformation("Successfully fetched {Count} packages in total", allPackages.Count);
return allPackages;
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Error fetching packages from Gitea");
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error fetching packages");
throw;
}
}
public async Task DeletePackage(GiteaPackage package, CancellationToken cancellationToken = default)
{
try
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}/{package.Type}/{package.Name}/{package.Version}";
logger.LogInformation("Deleting package {PackageName} (ID: {PackageId}) from Gitea",
package.Name, package.Id);
var request = new HttpRequestMessage(HttpMethod.Delete, url);
AddAuthorizationHeader(request);
var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
logger.LogInformation("Successfully deleted package {PackageName} (ID: {PackageId})",
package.Name, package.Id);
}
catch (HttpRequestException ex)
{
logger.LogError(ex, "Error deleting package {PackageName} (ID: {PackageId}) from Gitea",
package.Name, package.Id);
throw;
}
catch (Exception ex)
{
logger.LogError(ex, "Unexpected error deleting package {PackageName} (ID: {PackageId})",
package.Name, package.Id);
throw;
}
}
}

View File

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

View File

@@ -0,0 +1,9 @@
using sh.actions.package_cleanup.Models;
namespace sh.actions.package_cleanup.Service;
public interface IPackageService
{
Task<List<GiteaPackage>> GetFilteredPackages();
List<GiteaPackage> FilterPackagesToDelete(List<GiteaPackage> packages);
}

View File

@@ -0,0 +1,50 @@
using sh.actions.package_cleanup.Models;
namespace sh.actions.package_cleanup.Service;
public class PackageService(IGiteaPackageService packageService) : IPackageService
{
public async Task<List<GiteaPackage>> GetFilteredPackages()
{
return (await packageService.GetPackagesByOwnerAsync()).ToList();
}
public List<GiteaPackage> FilterPackagesToDelete(List<GiteaPackage> packages)
{
var versionMap = packages.ToDictionary(p => p.Version, p => SoftwareVersion.Parse(p.Version));
var versionsToKeep = new HashSet<string>();
foreach (var package in packages
.Where(p => string.IsNullOrEmpty(versionMap[p.Version].Suffix))
.GroupBy(p => versionMap[p.Version].ToString())
.Select(g => g.OrderBy(p => p.Version.Length).First()))
{
versionsToKeep.Add(package.Version);
}
var latestVersion = packages.FirstOrDefault(p => versionMap[p.Version].IsLatest);
if (latestVersion != null)
{
versionsToKeep.Add(latestVersion.Version);
}
var suffixedVersionsToKeep = packages
.Where(p => !string.IsNullOrEmpty(versionMap[p.Version].Suffix) &&
!(versionMap[p.Version].Major == 0 && versionMap[p.Version].Minor == 0 &&
versionMap[p.Version].Patch == 0))
.GroupBy(p => (versionMap[p.Version].Suffix, versionMap[p.Version].Major, versionMap[p.Version].Minor))
.SelectMany(g => g
.OrderByDescending(p => versionMap[p.Version].Patch)
.ThenByDescending(p => versionMap[p.Version].Build)
.Take(2)
.GroupBy(p => versionMap[p.Version].ToString())
.Select(group => group.OrderBy(p => p.Version.Length).First()));
foreach (var package in suffixedVersionsToKeep)
{
versionsToKeep.Add(package.Version);
}
return packages.Where(p => !versionsToKeep.Contains(p.Version)).ToList();
}
}

View File

@@ -0,0 +1,88 @@
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();
}
}
}

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-sh.actions.package_cleanup-2b7a013f-ec22-4325-9832-0c9ca9b8ced9</UserSecretsId>
<RootNamespace>sh.actions.package_cleanup</RootNamespace>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.3" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.3" />
</ItemGroup>
<ItemGroup>
<_ContentIncludedByDefault Remove="publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\appsettings.local.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.deps.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.runtimeconfig.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.deps.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.runtimeconfig.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.deps.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.runtimeconfig.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.deps.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\publish\linux-x64\sh.actions.package-cleanup.runtimeconfig.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\sh.actions.package-cleanup.deps.json" />
<_ContentIncludedByDefault Remove="publish\linux-x64\sh.actions.package-cleanup.runtimeconfig.json" />
</ItemGroup>
</Project>

View File

@@ -1,16 +1,44 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "sh.actions.package-cleanup", "sh.actions.package-cleanup\sh.actions.package-cleanup.csproj", "{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "sh.actions.package-cleanup", "sh.actions/sh.actions.package-cleanup\sh.actions.package-cleanup.csproj", "{F4995B6A-2CA1-4CD4-AEAC-BE397AF1910A}" EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "sh.actions.package-cleanup.Tests", "sh.actions.package-cleanup.Tests\sh.actions.package-cleanup.Tests.csproj", "{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F4995B6A-2CA1-4CD4-AEAC-BE397AF1910A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F4995B6A-2CA1-4CD4-AEAC-BE397AF1910A}.Debug|Any CPU.Build.0 = Debug|Any CPU {2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4995B6A-2CA1-4CD4-AEAC-BE397AF1910A}.Release|Any CPU.ActiveCfg = Release|Any CPU {2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|x64.ActiveCfg = Debug|Any CPU
{F4995B6A-2CA1-4CD4-AEAC-BE397AF1910A}.Release|Any CPU.Build.0 = Release|Any CPU {2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|x64.Build.0 = Debug|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|x86.ActiveCfg = Debug|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Debug|x86.Build.0 = Debug|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|Any CPU.Build.0 = Release|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|x64.ActiveCfg = Release|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|x64.Build.0 = Release|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|x86.ActiveCfg = Release|Any CPU
{2C97D0E2-CD3F-4468-B963-E1F0211C4D3A}.Release|x86.Build.0 = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|x64.ActiveCfg = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|x64.Build.0 = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|x86.ActiveCfg = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Debug|x86.Build.0 = Debug|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|Any CPU.Build.0 = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|x64.ActiveCfg = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|x64.Build.0 = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|x86.ActiveCfg = Release|Any CPU
{8F1A9B3E-5D2C-4A1F-B8E7-9C2D5F6A3B1C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@@ -1,2 +0,0 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World! from ci");

View File

@@ -1,30 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>sh.actions.package_cleanup</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- NuGet Package Information -->
<PackAsTool>true</PackAsTool>
<ToolCommandName>package-cleanup</ToolCommandName>
<PackageId>sh.actions.package-cleanup</PackageId>
<Version Condition="'$(Version)' == ''">0.0.1</Version>
<Title>sh-edraft gitea package cleanup</Title>
<Description>Tool to cleanup gitea packages</Description>
<Authors>edraft</Authors>
<PackageProjectUrl>https://git.sh-edraft.de/sh-edraft.de/actions</PackageProjectUrl>
<RepositoryUrl>https://git.sh-edraft.de/sh-edraft.de/actions</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<PackageReadmeFile>README.md</PackageReadmeFile>
</PropertyGroup>
</Project>