diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 9eeb879..795b936 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -43,22 +43,33 @@ jobs: - name: Publish shell: bash run: | + PUBLISH_DIR="${{ github.workspace }}/publish-artifacts" + if [ "${{ runner.os }}" == "Windows" ]; then - dotnet publish "${{ github.workspace }}" -r win-x64 $DOTNET_PUBLISH_COMMON + dotnet publish "${{ github.workspace }}" -r win-x64 $DOTNET_PUBLISH_COMMON -o "$PUBLISH_DIR" elif [ "${{ runner.os }}" == "Linux" ]; then - dotnet publish ${{ github.workspace }} -r linux-x64 $DOTNET_PUBLISH_COMMON + dotnet publish ${{ github.workspace }} -r linux-x64 $DOTNET_PUBLISH_COMMON -o "$PUBLISH_DIR" elif [ "${{ runner.os }}" == "macOS" ]; then - dotnet publish ${{ github.workspace }} -r osx-arm64 -p:PlatformTarget=arm64 $DOTNET_PUBLISH_COMMON + dotnet publish ${{ github.workspace }} -r osx-arm64 -p:PlatformTarget=arm64 $DOTNET_PUBLISH_COMMON -o "$PUBLISH_DIR" fi - name: Run Self-Tests shell: bash run: | + EXE_PATH="${{ github.workspace }}/publish-artifacts/premake-manager-cli" + if [ "${{ runner.os }}" == "Windows" ]; then - "${{ github.workspace }}/bin/Release/net9.0/win-x64/publish/premake-manager-cli.exe" test all - elif [ "${{ runner.os }}" == "Linux" ]; then - ${{ github.workspace }}/bin/Release/net9.0/linux-x64/publish/premake-manager-cli test all - elif [ "${{ runner.os }}" == "macOS" ]; then - ${{ github.workspace }}/bin/Release/net9.0/osx-arm64/publish/premake-manager-cli test all + "$EXE_PATH.exe" test all + else + chmod +x "$EXE_PATH" + "$EXE_PATH" test all fi - + - name: Upload Artifacts + uses: actions/upload-artifact@v6 + with: + # Use the matrix OS to create unique names like: build-windows-latest + name: build-${{ matrix.os }} + # Point to the same directory used in the Publish step + path: ${{ github.workspace }}/publish-artifacts/ + # Optional: How long to keep the artifact (default 90 days) + retention-days: 10 diff --git a/.gitignore b/.gitignore index 86d7b92..26252bb 100644 --- a/.gitignore +++ b/.gitignore @@ -58,4 +58,7 @@ nunit-*.xml /.vs/premake-manager-cli/FileContentIndex /.premake/Premake 5.0-beta6/windows /.vs/** -settings.json \ No newline at end of file +settings.json +/Nieuw - Tekstdocument.txt +premake-manager-cli/premake-manager-cli.csproj.Backup.tmp +*.slnx diff --git a/.vscode/settings.json b/.vscode/settings.json index d438b01..43ade81 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,6 +4,7 @@ "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.3\\resources\\language\\premakeFields_1.lua", "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.3\\resources\\language\\premakeFields_2.lua", "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.3\\resources\\language\\premakeFields_3.lua", - "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.3\\resources\\language\\premakeGlobals.lua" + "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.3\\resources\\language\\premakeGlobals.lua", + "c:\\Users\\robbe\\.vscode\\extensions\\lolrobbe2.premake-manager-0.1.7\\resources\\language" ] } \ No newline at end of file diff --git a/premake-manager-cli/packages.lock.json b/premake-manager-cli/packages.lock.json index 0e9e02b..51f1ee1 100644 --- a/premake-manager-cli/packages.lock.json +++ b/premake-manager-cli/packages.lock.json @@ -1,12 +1,34 @@ { "version": 1, "dependencies": { - "net9.0": { - "Microsoft.NET.ILLink.Tasks": { + "net10.0": { + "EasyCaching.Disk": { "type": "Direct", - "requested": "[9.0.11, )", - "resolved": "9.0.11", - "contentHash": "vvB9rtDmWaXgYkViT00KORBVmA3pcYsHlgd9vOPqL9sf5bKy3rvLMF1+sI1uUfVj28S3itirHlHmX5/kcpZKNw==" + "requested": "[1.9.2, )", + "resolved": "1.9.2", + "contentHash": "5LXQutSoGxX2JDKs4nAewXy5rPmMaRlHdF3zPcdKuDDXEuf67fsBI4AAQxiaGDsvPMeD9rRM5TruA6PB27c5Sg==", + "dependencies": { + "EasyCaching.Core": "1.9.2" + } + }, + "EasyCaching.Serialization.Json": { + "type": "Direct", + "requested": "[1.9.2, )", + "resolved": "1.9.2", + "contentHash": "1dAu1iLDOEWurh1z3Y61cSzEGUZXLYjsHxONA6yt5vmhUwnPH7jv8p9t/Q540vQm5U+mQbc1uKqAlTts8V3a/Q==", + "dependencies": { + "EasyCaching.Core": "1.9.2", + "Newtonsoft.Json": "13.0.1" + } + }, + "EasyCaching.Serialization.SystemTextJson": { + "type": "Direct", + "requested": "[1.9.2, )", + "resolved": "1.9.2", + "contentHash": "7SZ7DbN8EC2YPXS2BHM3WZ3lUkvI35zIan6jlOKO+OnkYgGBgNYn/3zcqgiZUj4zcZrSjh3asg/57wUFxNWXQg==", + "dependencies": { + "EasyCaching.Core": "1.9.2" + } }, "Octokit": { "type": "Direct", @@ -14,14 +36,20 @@ "resolved": "14.0.0", "contentHash": "jGOuTH1l+TCpJH+fwYOp7USzHDuGfN1jKbLz3J2COwyn+wL08eynvpnM6rY2qkzIEXum3PN2p2QkP3BW/p9Qcw==" }, + "Semver": { + "type": "Direct", + "requested": "[3.0.0, )", + "resolved": "3.0.0", + "contentHash": "9jZCicsVgTebqkAujRWtC9J1A5EQVlu0TVKHcgoCuv345ve5DYf4D1MjhKEnQjdRZo6x/vdv6QQrYFs7ilGzLA==", + "dependencies": { + "Microsoft.Extensions.Primitives": "5.0.1" + } + }, "Spectre.Console": { "type": "Direct", "requested": "[0.50.0, )", "resolved": "0.50.0", - "contentHash": "gkwYncFqMjlPF6Yz8KeVsKWpdfv15sr6uKm+vXVa/8Q4tvx52LPzMQOO5m+bXwI3AGGFeY3cok3ZJbguYizswg==", - "dependencies": { - "System.Memory": "4.6.3" - } + "contentHash": "gkwYncFqMjlPF6Yz8KeVsKWpdfv15sr6uKm+vXVa/8Q4tvx52LPzMQOO5m+bXwI3AGGFeY3cok3ZJbguYizswg==" }, "Spectre.Console.Cli": { "type": "Direct", @@ -42,8 +70,7 @@ "Microsoft.VisualStudio.Threading.Only": "17.13.61", "Microsoft.VisualStudio.Validation": "17.8.8", "Nerdbank.Streams": "2.12.87", - "Newtonsoft.Json": "13.0.3", - "System.IO.Pipelines": "8.0.0" + "Newtonsoft.Json": "13.0.3" } }, "YamlDotNet": { @@ -52,6 +79,16 @@ "resolved": "16.3.0", "contentHash": "SgMOdxbz8X65z8hraIs6hOEdnkH6hESTAIUa7viEngHOYaH+6q5XJmwr1+yb9vJpNQ19hCQY69xbFsLtXpobQA==" }, + "EasyCaching.Core": { + "type": "Transitive", + "resolved": "1.9.2", + "contentHash": "26gxpME2bJpOgF5H/ih3Xi48+GvpRHcPs0ifUwL3IUv3ya7G1rURxRz0LzuhiYQ3YtzpR5VgdK1PDX+tIrq69w==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "6.0.0", + "Microsoft.Extensions.Logging": "6.0.0", + "Microsoft.Extensions.Options.ConfigurationExtensions": "6.0.0" + } + }, "MessagePack": { "type": "Transitive", "resolved": "2.5.192", @@ -66,6 +103,77 @@ "resolved": "2.5.192", "contentHash": "jaJuwcgovWIZ8Zysdyf3b7b34/BrADw4v82GaEZymUhDd3ScMPrYd/cttekeDteJJPXseJxp04yTIcxiVUjTWg==" }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "qWzV9o+ZRWq+pGm+1dF+R7qTgTYoXvbyowRoBxQJGfqTpqDun2eteerjRQhq5PQ/14S+lqto3Ft4gYaRyl4rdQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "6.0.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "b3ErKzND8LIC7o08QAVlKfaEIYEvLJbtmVbFZVBRXeu9YkKfSSzLZfR1SUfQPBIy9mKLhEtJgGYImkcMNaKE0A==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "6.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "k6PWQMuoBDGGHOQTtyois2u4AwyVcIwL2LaSLlTZQm2CYcJ1pxbt6jfAnpWmzENA/wfrYRI/X9DTLoUkE4AsLw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "6.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "xlzi2IYREJH3/m6+lUrQlujzX8wDitm4QGnUu6kUXTQAWPuZY8i+ticFJbzfqaetLA6KR/rO6Ew/HuYD+bxifg==" + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "eIbyj40QDg1NDz0HBW0S5f3wrLVnKWnDJ/JtZ+yJDFnDj90VoPuoPmFkeaXrtu+0cKm5GRAwoDf+dBWXK0TUdg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection": "6.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "6.0.0", + "Microsoft.Extensions.Logging.Abstractions": "6.0.0", + "Microsoft.Extensions.Options": "6.0.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "/HggWBbTwy8TgebGSX5DBZ24ndhzi93sHUBDvP1IxbZD7FDokYzdAr6+vbWGjw2XAfR2EJ1sfKUotpjHnFWPxA==" + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "dzXN0+V1AyjOe2xcJ86Qbo233KHuLEY0njf/P2Kw8SfJU+d45HNS2ctJdnEnrWbM9Ye2eFgaC5Mj9otRMU6IsQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "6.0.0", + "Microsoft.Extensions.Primitives": "6.0.0" + } + }, + "Microsoft.Extensions.Options.ConfigurationExtensions": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "bXWINbTn0vC0FYc9GaQTISbxhQLAMrvtbuvD9N6JelEaIS/Pr62wUCinrq5bf1WRBGczt1v4wDhxFtVFNcMdUQ==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "6.0.0", + "Microsoft.Extensions.Configuration.Binder": "6.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "6.0.0", + "Microsoft.Extensions.Options": "6.0.0", + "Microsoft.Extensions.Primitives": "6.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "6.0.0", + "contentHash": "9+PnzmQFfEFNR9J2aDTfJGGupShHjOuGw4VUv+JB044biSHrnmCIMD+mJHmb2H7YryrfBEXDurxQ47gJZdCKNQ==" + }, "Microsoft.NET.StringTools": { "type": "Transitive", "resolved": "17.6.3", @@ -90,26 +198,14 @@ "contentHash": "oDKOeKZ865I5X8qmU3IXMyrAnssYEiYWTobPGdrqubN3RtTzEHIv+D6fwhdcfrdhPJzHjCkK/ORztR/IsnmA6g==", "dependencies": { "Microsoft.VisualStudio.Threading.Only": "17.13.61", - "Microsoft.VisualStudio.Validation": "17.8.8", - "System.IO.Pipelines": "8.0.0" + "Microsoft.VisualStudio.Validation": "17.8.8" } }, "Newtonsoft.Json": { "type": "Transitive", "resolved": "13.0.3", "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" - }, - "System.IO.Pipelines": { - "type": "Transitive", - "resolved": "8.0.0", - "contentHash": "FHNOatmUq0sqJOkTx+UF/9YK1f180cnW5FVqnQMvYUN0elp6wFzbtPSiqbo1/ru8ICp43JM1i7kKkk6GsNGHlA==" - }, - "System.Memory": { - "type": "Transitive", - "resolved": "4.6.3", - "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==" } - }, - "net9.0/win-x64": {} + } } } \ No newline at end of file diff --git a/premake-manager-cli/src/Github.cs b/premake-manager-cli/src/Github.cs index c57a632..ae318e2 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -1,12 +1,19 @@ using Octokit; +using Octokit.Caching; +using Octokit.Internal; +using Spectre.Console; +using src.utils; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; +using System.Net; using System.Text; using System.Threading.Tasks; namespace src { + [DebuggerDisplay("{owner,nq}/{name,nq}")] internal struct GithubRepo { public string owner; @@ -15,14 +22,23 @@ internal struct GithubRepo internal class Github { /* Static instance of the GitHubClient */ - private static readonly GitHubClient _instance; + private static GitHubClient _instance; // Static constructor to initialize the instance static Github() { + var connection = new Connection( + new ProductHeaderValue("premake-manager-cli"), + GitHubClient.GitHubApiUrl, + new InMemoryCredentialStore(new Credentials("token")), + new CachingHttpClient(new HttpClientAdapter(() => HttpMessageHandlerFactory.CreateDefault(new WebProxy())), new CacheProvider()), + new SimpleJsonSerializer()); + GitHubClient client = new GitHubClient( - new ProductHeaderValue("premake-manager-cli") + connection ); + + string? githubToken = Environment.GetEnvironmentVariable("GITHUB_TOKEN"); @@ -30,10 +46,25 @@ static Github() { client.Credentials = new Credentials(githubToken); } - + ApiInfo apiInfo = client.GetLastApiInfo(); + var rateLimit = apiInfo?.RateLimit; + if(rateLimit?.Remaining < 10) + { + AnsiConsole.WriteLine("[RED]github client is rate limited[/]"); + } + _instance = client; } + public static async Task SetSession(string session) + { + if (!string.IsNullOrWhiteSpace(session)) + { + _instance.Credentials = new Credentials(session); + MiscellaneousRateLimit rate = await _instance.RateLimit.GetRateLimits(); + } + + } // Public static property to access the instance public static GitHubClient Instance => _instance; public static IRepositoriesClient Repositories => _instance.Repository; @@ -47,10 +78,38 @@ public static string FormatZipballUrl(GithubRepo repo, string refName) { return $"https://github.com/{repo.owner}/{repo.name}/zipball/{refName}"; } + internal static async Task GetRepo(GithubRepo repo) + { + Repository repository = await Repositories.Get(repo.owner, repo.name); + return repository; + } + internal static async Task GetDescription(GithubRepo repo) + { + return (await GetRepo(repo)).Description; + } + internal static async Task> GetRepoVersions(GithubRepo repo) + { + var releases = await Repositories.Release.GetAll(repo.owner, repo.name); + return releases; + } - internal static string GetDescription(GithubRepo repo) + internal static async Task> GetRepoCommits(GithubRepo repo) + { + var commits = await Repositories.Commit.GetAll(repo.owner, repo.name); + return commits; + } + internal static async Task> GetRepoTags(GithubRepo repo) + { + return await Repositories.GetAllTags(repo.owner, repo.name); + } + internal static async Task GetAllContentsByRef(GithubRepo repo, string path, string branch) + { + + return (await Github.Repositories.Content.GetAllContentsByRef(repo.owner, repo.name, path, branch))[0]; + } + internal static async Task> GetBranches(GithubRepo repo) { - throw new NotImplementedException(); + return await _instance.Repository.Branch.GetAll(repo.owner, repo.name); } } } diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs new file mode 100644 index 0000000..f24283a --- /dev/null +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -0,0 +1,206 @@ +using Spectre.Console; +using Spectre.Console.Cli; +using src.config; +using src.dependencies; +using src.dependencies.types; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.common_index +{ + /// + /// Command to create a new index + /// + internal class CommonIndexCommand : AsyncCommand + { + internal class Settings : CommandSettings + { + [CommandArgument(0, "[REMOTE]")] + [Description("remote github url of the repo")] + public string? remote { get; set; } + } + public override Task ExecuteAsync(CommandContext context, Settings settings) + { + if (string.IsNullOrEmpty(settings.remote)) + { + TextPrompt prompt = new TextPrompt("Enter the remote githubUrl:") + .Validate(input => + { + if (string.IsNullOrWhiteSpace(input)) + return ValidationResult.Error("Url cannot be empty"); + + if (!Uri.TryCreate(input, UriKind.Absolute, out Uri? uri)) + return ValidationResult.Error("Invalid url format"); + + if (!string.Equals(uri.Host, "github.com", StringComparison.OrdinalIgnoreCase)) + return ValidationResult.Error("Url must be a github.com repository"); + + string[] segments = uri.AbsolutePath.Trim('/').Split('/'); + if (segments.Length != 2) + return ValidationResult.Error("Url must be in the form https://github.com/owner/repo"); + + if (string.IsNullOrWhiteSpace(segments[0]) || string.IsNullOrWhiteSpace(segments[1])) + return ValidationResult.Error("Owner and repo must be non-empty"); + + return ValidationResult.Success(); + }); + + settings.remote = AnsiConsole.Prompt(prompt); + } + IndexView index = CommonIndex.CreateNew(settings.remote!); + CommonIndex.WriteFileIndex(index, "premakeIndex.yml"); + AnsiConsole.MarkupLine("[green]✔ Index file created successfully[/]"); + return Task.FromResult(1); + } + } + + internal class CommonAddLibCommand : AsyncCommand + { + public override Task ExecuteAsync(CommandContext context, Settings settings) + { + IndexView index = CommonIndex.ReadFileIndex(); + IndexLibrary library = new IndexLibrary() { name = settings.repo ?? string.Empty, description = settings.description ?? string.Empty }; + if (string.IsNullOrEmpty(settings.owner)) + { + settings.owner = AnsiConsole.Prompt(new TextPrompt("[green]owner: [/]")); + } + + if (string.IsNullOrEmpty(settings.repo)) + { + library.name = AnsiConsole.Prompt(new TextPrompt("[green]repo: [/]")); + } + + if (string.IsNullOrEmpty(settings.description)) + { + library.description = AnsiConsole.Prompt(new TextPrompt("[green]description: [/]")); + } + CommonIndex.CreateNewLibrary(ref index, library, settings.owner!); + CommonIndex.WriteFileIndex(index); + return Task.FromResult(0); + } + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) + { + if (!Path.Exists("premakeIndex.yml")) + { + return ValidationResult.Error("no existing index found!"); + } + return ValidationResult.Success(); + } + internal class Settings : CommandSettings + { + [CommandArgument(0, "[OWNER]")] + [Description("the owner of the library (github name)")] + public string? owner { get; set; } + [CommandArgument(0, "[REPO]")] + [Description("the name of the repo")] + public string? repo { get; set; } + + [CommandArgument(0, "[DESRIPTION]")] + [Description("the library desciption")] + public string? description { get; set; } + } + + } + internal class CommonAddUriLibCommand : AsyncCommand + { + internal class Settings : CommandSettings + { + [CommandArgument(0, "")] + [Description("The GitHub link of the library or the owner/repo.")] + public string githublink { get; set; } = ""; + } + + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) + { + + if (!settings.githublink.StartsWith("https://github.com/")) + return ValidationResult.Error("the link should start with https://github.com/"); + GithubRepo repo = Github.GetRepoFromLink(settings.githublink); + if (string.IsNullOrEmpty(repo.owner)) + return ValidationResult.Error("the repo owner name should be valid"); + + if (string.IsNullOrEmpty(repo.name)) + return ValidationResult.Error("the repo name name should be valid"); + + + return ValidationResult.Success(); + + } + + public override async Task ExecuteAsync(CommandContext context, Settings settings) + { + IndexView index = CommonIndex.ReadFileIndex(); + GithubRepo libRepo = Github.GetRepoFromLink(settings.githublink); + string description = await Github.GetDescription(libRepo); + IndexLibrary library = new IndexLibrary() { name = libRepo.name, description = description }; + + CommonIndex.CreateNewLibrary(ref index, library, libRepo.owner); + CommonIndex.WriteFileIndex(index); + return 0; + } + } + + internal class CommonAddDependencyCommand : AsyncCommand + { + internal class Settings : CommandSettings + { + [CommandArgument(0, "[githublink]")] + [Description("The GitHub link of the library or the owner/repo.")] + public string? githublink { get; set; } = ""; + [CommandArgument(0, "[OWNER]")] + [Description("the owner of the dependency (github name)")] + public string? owner { get; set; } + [CommandArgument(0, "[REPO]")] + [Description("the name of the dependency")] + public string? repo { get; set; } + + [CommandArgument(0, "[RANGE]")] + [Description("the version range of the dependency")] + public string? range { get; set; } + } + + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) + { + if(string.IsNullOrEmpty(settings.githublink)) + { + settings.githublink = AnsiConsole.Prompt(new TextPrompt("[green]library githublink: [/]")); + } + if (!settings.githublink!.StartsWith("https://github.com/")) + return ValidationResult.Error("the link should start with https://github.com/"); + GithubRepo repo = Github.GetRepoFromLink(settings.githublink); + if (string.IsNullOrEmpty(repo.owner)) + return ValidationResult.Error("the repo owner name should be valid"); + + if (string.IsNullOrEmpty(repo.name)) + return ValidationResult.Error("the repo name name should be valid"); + + if (string.IsNullOrEmpty(settings.owner)) + { + settings.owner = AnsiConsole.Prompt(new TextPrompt("[green]owner: [/]")); + } + if (string.IsNullOrEmpty(settings.repo)) + { + settings.owner = AnsiConsole.Prompt(new TextPrompt("[green]repo: [/]")); + } + if (string.IsNullOrEmpty(settings.range)) + { + settings.range = AnsiConsole.Prompt(new TextPrompt("[green]range: [/]")); + } + return ValidationResult.Success(); + + } + + public override async Task ExecuteAsync(CommandContext context, Settings settings) + { + GithubRepo libRepo = Github.GetRepoFromLink(settings.githublink!); + await DependenciesManager.AddLibraryDependency(libRepo, new LibraryDependency { name = $"{settings.owner}/{settings.repo}", version = settings.range! }); + return 0; + } + } +} diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs new file mode 100644 index 0000000..96ad9fc --- /dev/null +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -0,0 +1,131 @@ +using Spectre.Console; +using src.libraries; +using src.utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; + +namespace src.common_index +{ + + internal class CommonIndex + { + #region STREAM + public static IndexView ReadStreamIndex(Stream stream) + { + return YamlSerializer.Deserialize(stream); + } + public static Stream WriteStreamIndex(IndexView index) + { + return YamlSerializer.Serialize(index); + } + #endregion + + #region FILE + public static IndexView ReadFileIndex(string filePath = "premakeIndex.yml") + { + return YamlSerializer.Deserialize(filePath); + } + + public static void WriteFileIndex(IndexView index, string filePath = "premakeIndex.yml") + { + YamlSerializer.Serialize(index, filePath); + } + + public static MemoryStream? ReadLibraryFile(IndexView index, GithubRepo repo) + { + if (index.libraries.TryGetValue(repo.owner, out IList? libraries)) + { + if (null == libraries.Where((lib) => lib.name == repo.name).FirstOrDefault()) + return null; + GithubRepo remote = Github.GetRepoFromLink(index.remote); + return ExtractUtils.ReadFile(PathUtils.GetRemotePath(remote.owner, remote.name), $"{repo}-main/libraries/{repo.owner}/{repo.name}/premake5.lua".ToLower()); + } + return null; //could not find library. + } + + public static MemoryStream? ReadLibraryDependencies(IndexView index, GithubRepo repo) + { + if (index.libraries.TryGetValue(repo.owner, out IList? libraries)) + { + if (null == libraries.Where((lib) => lib.name == repo.name).FirstOrDefault()) + return null; + GithubRepo remote = Github.GetRepoFromLink(index.remote); + return ExtractUtils.ReadFile(PathUtils.GetRemotePath(remote.owner, remote.name), $"{remote.name}-main/libraries/{repo.owner}/{repo.name}/premakeDependencies.yml"); + } + return null; //could not find library. + } + + /// + /// This function will attempt to Extract a premake5.lua from the given index + /// + /// + /// + /// + public static async Task ExtractLibraryFile(IndexView index, GithubRepo repo) + { + MemoryStream? stream = ReadLibraryFile(index, repo); + if (stream == null) return false; + + using (FileStream libraryFile = File.OpenWrite(await LibraryManager.GetLibraryPath(repo))) + { + stream.WriteTo(libraryFile); + } + return true; + } + #endregion + + #region REMOTE + public static async Task ReadRemoteIndex(string owner, string repo) + { + return await YamlSerializer.Deserialize(owner, repo, "premakeIndex.yml"); + } + public static IndexView ReadRemoteLocalIndex(string owner, string repo) + { + return YamlSerializer.Deserialize(ExtractUtils.ReadFile(PathUtils.GetRemotePath(owner, repo), $"{repo}-main/premakeIndex.yml")!); + } + #endregion + + #region CREATE + public static IndexView CreateNew(string remoteName) + { + return new IndexView() + { + remote = remoteName, + libraries = new Dictionary>() + }; + } + + public static void CreateNewLibrary(ref IndexView index, IndexLibrary library, string owner) + { + + library.description = library.description!.ToLower(); + library.name = library.name.ToLower(); + owner = owner.ToLower(); + + string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", owner, library.name]).ToLower(); + + if (index.libraries.TryGetValue(library.name, out IList? libraries)) + { + libraries.Add(library); + index.libraries[library.name] = libraries; + } + else + { + libraries = new List(); + libraries.Add(library); + index.libraries.Add(owner,libraries!); + } + YamlSerializer.Serialize(library, Path.Combine(LibraryDirectory,"premakeLib.yml")); + PathUtils.CreateEmpty(Path.Combine(LibraryDirectory, "premake5.lua")); + } + #endregion + + } +} diff --git a/premake-manager-cli/src/common-index/IndexView.cs b/premake-manager-cli/src/common-index/IndexView.cs new file mode 100644 index 0000000..682e423 --- /dev/null +++ b/premake-manager-cli/src/common-index/IndexView.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using YamlDotNet.Serialization; + +namespace src.common_index +{ + [YamlSerializable] + internal class IndexLibrary + { + [YamlMember(Order = 0)] + public required string name { get; set; } + [YamlMember(Order = 1)] + public string? description { get; set; } + + } + /// + /// Representation of the common-index yaml + /// + [YamlSerializable] + internal class IndexView + { + [YamlMember(Order = 0)] + public required string remote { get; set; } + [YamlMember(Order = 1)] + public required Dictionary> libraries; + } +} diff --git a/premake-manager-cli/src/common-index/RemotesCommand.cs b/premake-manager-cli/src/common-index/RemotesCommand.cs new file mode 100644 index 0000000..9c5b260 --- /dev/null +++ b/premake-manager-cli/src/common-index/RemotesCommand.cs @@ -0,0 +1,171 @@ +using Octokit; +using Spectre.Console; +using Spectre.Console.Cli; +using src.version; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.common_index +{ + #region REMOTES + #region VIEW + /// + /// This command shows all the remotes + /// + internal class RemotesViewCommand : AsyncCommand + { + public override Task ExecuteAsync(CommandContext context) + { + Table table = new Table() + .Border(TableBorder.Rounded) + .Title("[bold]Configured Remotes[/]"); + + table.AddColumn(new TableColumn("Owner").LeftAligned()); + table.AddColumn(new TableColumn("Repository").LeftAligned()); + table.AddColumn(new TableColumn("Enabled").Centered()); + + foreach (Remote item in RemotesManager.Remotes) + { + string enabledText = item.Enabled + ? "[green]Yes[/]" + : "[red]No[/]"; + + string ownerLink = + $"[link=https://github.com/{item.Owner}]{item.Owner}[/]"; + + string repoLink = + $"[link=https://github.com/{item.Owner}/{item.Repo}]{item.Repo}[/]"; + + + table.AddRow( + ownerLink, + repoLink, + enabledText + ); + } + + AnsiConsole.Write(table); + return Task.FromResult(0); + } + } + #endregion + + #region ADD + /// + /// This command allows for adding a remote + /// + internal class RemotesAddCommand : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, Settings settings) + { + await RemotesManager.AddRemote(settings.owner!, settings.repo!); + AnsiConsole.MarkupLine($"[green] Added new remote: {settings.owner}/{settings.repo}[/]"); + return 0; + } + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) + { + if (string.IsNullOrEmpty(settings.owner)) + { + settings.owner = AnsiConsole.Prompt(new TextPrompt("[green]owner: [/]")); + } + + if (string.IsNullOrEmpty(settings.repo)) + { + settings.repo = AnsiConsole.Prompt(new TextPrompt("[green]repo: [/]")); + } + return ValidationResult.Success(); + } + internal class Settings : CommandSettings + { + [CommandArgument(0, "[OWNER]")] + [Description("owner of the repo")] + public string? owner { get; set; } + + [CommandArgument(0, "[REPO]")] + [Description("name of the repo")] + public string? repo { get; set; } + } + } + #endregion + + #region REMOVE + /// + /// This command allows for removing a remote + /// + internal class RemotesRemoveCommand : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, Settings settings) + { + await RemotesManager.RemoveRemote(settings.owner!, settings.repo!); + AnsiConsole.MarkupLine($"[green] Remove remote: {settings.owner}/{settings.repo}[/]"); + return 0; + } + public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) + { + if (string.IsNullOrEmpty(settings.owner)) + { + settings.owner = AnsiConsole.Prompt(new TextPrompt("[green]owner: [/]")); + } + + if (string.IsNullOrEmpty(settings.repo)) + { + settings.repo = AnsiConsole.Prompt(new TextPrompt("[green]repo: [/]")); + } + return ValidationResult.Success(); + } + internal class Settings : CommandSettings + { + [CommandArgument(0, "[OWNER]")] + [Description("owner of the repo")] + public string? owner { get; set; } + + [CommandArgument(0, "[REPO]")] + [Description("name of the repo")] + public string? repo { get; set; } + } + } + #endregion + + #region UPDATE + /// + /// This + /// + internal class RemotesUpdateCommand : AsyncCommand + { + public async override Task ExecuteAsync(CommandContext context, RemotesUpdateCommand.Settings settings) + { + if(!settings.forceUpdate && !RemotesManager.RemotesOutdated()) + { + AnsiConsole.MarkupLine("[green]remotes are upto date[/]"); + } + await RemotesManager.UpdateRemotes(settings.forceUpdate); + return 0; + } + + internal class Settings : CommandSettings + { + [CommandArgument(0, "[FORCE]")] + [Description("owner of the repo")] + public bool forceUpdate { get; set; } = false; + } + } + #endregion + + #region RESET + internal class RemotesResetCommand : AsyncCommand + { + public override Task ExecuteAsync(CommandContext context) + { + RemotesManager.Reset(); + AnsiConsole.MarkupLine("[green]Remotes have been reset to default[/]"); + return Task.FromResult(0); + } + } + #endregion + #endregion +} diff --git a/premake-manager-cli/src/common-index/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs new file mode 100644 index 0000000..7f1090f --- /dev/null +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -0,0 +1,204 @@ +using src.config; +using src.dependencies; +using src.dependencies.types; +using src.utils; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using YamlDotNet.Serialization; + +namespace src.common_index +{ + /// + /// premake manager Remote yaml format + /// + [YamlSerializable] + internal sealed class Remote + { + [YamlMember(Alias ="owner", Order = 0)] + public required string Owner { get; set; } + [YamlMember(Alias = "repo", Order = 1)] + public required string Repo { get; set; } + [YamlMember(Alias = "enabled", Order = 2)] + public required bool Enabled { get; set; } + } + /// + /// Class representation for the remotes + /// + [YamlSerializable] + internal sealed class Remotes + { + [YamlMember(Alias = "remotes", Order = 0)] + public required Remote[] remotes {get; set;} + } + + internal sealed class RemoteIndex + { + public required Remote Remote { get; set; } + public required IndexView Index { get; set; } + } + internal class RemotesManager + { + private static readonly Remote DefaultRemote = new Remote() { Owner = "lolrobbe2", Repo = "premake-common-registry", Enabled = true }; + public static Remote[] Remotes { get => GetRemotes(); set => SetRemotes(value); } + public static RemoteIndex[] RemoteIndices { get => GetRemoteIndices(); } + public static RemoteIndex[] EnabledRemoteIndices { get => GetEnabledRemoteIndices(); } + + private static Remote[] GetRemotes() + { + string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yml"); + + if (Path.Exists(RemotePaths)) + { + return YamlSerializer.Deserialize(RemotePaths).remotes; + } + return [DefaultRemote]; + } + + private static RemoteIndex[] GetRemoteIndices() + { + UpdateRemotes().GetAwaiter().GetResult(); + return Remotes.Select((remote) => new RemoteIndex() { Remote = remote, Index = CommonIndex.ReadRemoteLocalIndex(remote.Owner, remote.Repo) }).ToArray(); + } + + private static RemoteIndex[] GetEnabledRemoteIndices() + { + return GetRemoteIndices() + .Where((RemoteIndex remoteIndex) => remoteIndex.Remote.Enabled) + .ToArray(); + } + private static void SetRemotes(Remote[] remotes) + { + string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yml"); + + YamlSerializer.Serialize(new Remotes() { remotes = remotes.ToArray() }, RemotePaths); + } + public static async Task AddRemote(string owner, string repo) + { + Remote remote = new Remote() { Owner = owner, Repo = repo, Enabled = true }; + IList remotes = Remotes.ToList(); + remotes.Add(remote); + Remotes = remotes.ToArray(); + await UpdateRemotes(true); + } + + public static async Task RemoveRemote(string owner, string repo) + { + Remote remote = new Remote() { Owner = owner, Repo = repo, Enabled = true }; + IList remotes = Remotes.ToList(); + remotes.Remove(remote); + Remotes = remotes.ToArray(); + await UpdateRemotes(true); + } + /// + /// resets all the remotes to default + /// + /// + public static void Reset() + { + string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yml"); + + if (Path.Exists(RemotePaths)) + { + File.Delete(RemotePaths); + } + } + /// + /// This function checks how old the remotes are and updates them when needed + /// + public static async Task UpdateRemotes(bool force = false) + { + if (!force && !RemotesOutdated()) + return; + await InstallRemotes(); + } + + private static async Task InstallRemotes() + { + PathUtils.ClearDirectory(PathUtils.GetRemotesPath()); //clear dir + + //install the remotes + (string url, string description, string destinationPath)[] downloads = + Remotes + .Select((Remote remote) => + { + string url = $"https://github.com/{remote.Owner}/{remote.Repo}/archive/refs/heads/main.{(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "zip" : "tar.gz")}"; + string description = $"Downloading Remote: {remote.Owner}/{remote.Repo}"; + return ( + url, + description, + PathUtils.GetRemotePath(remote.Owner, remote.Repo) + ); + }) + .ToArray(); + + await DownloadUtils.DownloadMultipleProgress(downloads); + CreateTimestamp(); + + } + + private static void CreateTimestamp() + { + string timestamp = DateTime.UtcNow.ToString("O"); // ISO 8601, UTC + File.WriteAllText(Path.Combine(PathUtils.GetRemotesPath(), ".timestamp"), timestamp, Encoding.UTF8); + } + + public static bool RemotesOutdated() + { + string remotesPath = PathUtils.GetRemotesPath(); + string timestampFilePath = Path.Combine(remotesPath, ".timestamp"); + + if (!File.Exists(timestampFilePath)) + return true; + + string content = File.ReadAllText(timestampFilePath).Trim(); + + if (!DateTime.TryParse( + content, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out DateTime timestamp)) + return true; // invalid timestamp -> outdated + + + TimeSpan age = DateTime.UtcNow - timestamp; + return age >= TimeSpan.FromDays(1); + } + /// + /// This function attempts to install the premake5.lua file + /// + /// repo to attempt installation + /// True on success + public static async Task InstallRemotesLibrary(GithubRepo repo) + { + //attempt to get the config to know where we have to copy the premake5.lua file to + foreach (RemoteIndex remote in GetEnabledRemoteIndices()) + { + if (await CommonIndex.ExtractLibraryFile(remote.Index, repo)) return; + } + } + + /// + /// This function attempts to resolve the dependencies from the localy installed remotes + /// + /// + /// + public static Dependencies? GetDependencies(GithubRepo repo) + { + foreach (RemoteIndex remote in GetEnabledRemoteIndices()) + { + MemoryStream? dependenciesStream = CommonIndex.ReadLibraryDependencies(remote.Index, repo); + if(dependenciesStream is not null) + { + return YamlSerializer.Deserialize(dependenciesStream); + } + } + return null; + } + } +} diff --git a/premake-manager-cli/src/config/Config.cs b/premake-manager-cli/src/config/Config.cs new file mode 100644 index 0000000..f68452a --- /dev/null +++ b/premake-manager-cli/src/config/Config.cs @@ -0,0 +1,140 @@ +using src.libraries; +using src.modules; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; + +namespace src.config +{ + internal sealed class Config + { + #region internal + /** + * this is used as when the libries are set we need to construct them and fill in the names etc + */ + private IDictionary? _libraries; + private IDictionary? _modules { get; set; } + + #endregion + + [YamlMember(Alias = "version")] + public string Version { get; set; } = string.Empty; + + [YamlMember(Alias = "modulesPath")] + public string? ModulesPath { get; set; } + + [YamlMember(Alias = "librariesPath")] + public string? LibrariesPath { get; set; } + + [YamlMember(Alias = "modules")] + public IDictionary? Modules + { + get => _modules; + set + { + _modules = value; + if (_modules != null) + { + foreach (var kvp in _modules) + { + // Inject the key into the object automatically + kvp.Value.module = kvp.Key; + } + } + } + } + [YamlMember(Alias = "libraries")] + public IDictionary? Libraries + { + get => _libraries; + set + { + _libraries = value; + if (_libraries != null) + { + foreach (var kvp in _libraries) + { + // Inject the key into the object automatically + kvp.Value.library = kvp.Key; + } + } + } + } + + /// + /// Adds a module to the Configuration + /// + /// + /// + public Config AddModule(PremakeModule module) + { + if(Modules == null) + Modules = new Dictionary(); + if (string.IsNullOrEmpty(module.version)) + module.version = "*"; + Modules.Add(module.module!, module); + return this; + } + + /// + /// Removes a Module from the configuration + /// + /// the name of the module to remove + /// This + public Config RemoveModule(string moduleName) + { + if (Modules == null) return this; + PremakeModule foundModule = Modules.First(module => + { + if (module.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) + { + moduleName = module.Key; + return true; + } + return false; + }).Value; + if (foundModule != null) + Modules.Remove(moduleName); + return this; + } + /// + /// Adds a module to the Configuration + /// + /// + /// + public Config AddLibrary(PremakeLibrary library) + { + if (Libraries == null) + Libraries = new Dictionary(); + if (string.IsNullOrEmpty(library.version)) + library.version = "*"; + Libraries.Add(library.library!, library); + return this; + } + + /// + /// Removes a Library from the configuration + /// + /// + /// + public Config RemoveLibrary(string libraryName) + { + if (Libraries == null) return this; + PremakeLibrary foundLibrary = Libraries.First(library => + { + if (library.Key.Equals(libraryName, StringComparison.OrdinalIgnoreCase)) + { + libraryName = library.Key; + return true; + } + return false; + }).Value; + if (foundLibrary != null) + Libraries.Remove(libraryName); + return this; + } + } +} diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index bb394cb..40906fd 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -1,7 +1,11 @@ using Octokit; using Spectre.Console; using Spectre.Console.Cli; +using src.dependencies; +using src.dependencies.graph; +using src.libraries; using src.modules; +using src.utils; using src.version; using System; using System.Collections.Generic; @@ -14,14 +18,38 @@ namespace src.config { + /** + * this commands intializes the workspace and fetches the libraries and modules + */ internal class ConfigCommand : AsyncCommand { public async override Task ExecuteAsync(CommandContext context) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + + PremakeLibrary[] libraries = []; + PremakeModule[] modules = []; + //TODO should we auto install the correct version of premake? - await VersionManager.SetVersion(config.version); - await ModuleManager.InstallModules(config.modules.Values.ToList()); + await VersionManager.SetVersion(config.Version); + if (config.Modules != null) + { + AnsiConsole.WriteLine("aquiring graph"); + modules = config.Modules.Values.ToArray(); + await ModuleManager.InstallModules(config.Modules.Values.ToList()); + } + //TODO dependencies + if(config.Libraries != null) + { + AnsiConsole.WriteLine("aquiring graph"); + DependencyGraph graph = await DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); + var libs = (await DependenciesManager.GetVersionsFromGraph(graph)).Distinct() + .ToList(); + + libraries = libs.ToArray(); + await LibraryManager.InstallLibraries(libs.ToList()); + } + PremakeSystemWriter.Write(config, libraries, modules); return 0; } } @@ -32,15 +60,15 @@ internal class Settings : CommandSettings { [CommandArgument(0, "[VERSION]")] [Description("version to install")] - public required string name { get; set; } + public required string version { get; set; } } public override async Task ExecuteAsync(CommandContext context, Settings settings) { - await VersionManager.SetVersion(settings.name); - ConfigReader reader = new ConfigReader(); - ConfigWriter writer = ConfigWriter.FromReader(reader); - writer.SetVersion(settings.name); - await writer.Write(); + await VersionManager.SetVersion(settings.version); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + + config.Version = settings.version; + ConfigManager.WriteConfig(config,null); return 0; } @@ -48,7 +76,7 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not { IReadOnlyList releases = VersionManager.GetVersions().ConfigureAwait(true).GetAwaiter().GetResult(); Release? release = null; - if (settings.name == null) + if (settings.version == null) { string selectedTag = AnsiConsole.Prompt( @@ -58,11 +86,11 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not .AddChoices(releases.Select(r => r.TagName)) ); - settings.name = selectedTag; + settings.version = selectedTag; } - release = releases.FirstOrDefault(release => release.TagName.Equals(settings.name)); + release = releases.FirstOrDefault(release => release.TagName.Equals(settings.version)); if (release == null) - return ValidationResult.Error($"Release with tag '{settings.name}' was not found. Please provide a valid release tag."); + return ValidationResult.Error($"Release with tag '{settings.version}' was not found. Please provide a valid release tag."); return ValidationResult.Success(); } } @@ -71,40 +99,80 @@ internal class ConfigViewCommand : AsyncCommand { public async override Task ExecuteAsync(CommandContext context) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); - var mainTable = new Table() + var modulesTable = new Table() .AddColumn("Owner") .AddColumn("Modules"); - mainTable.Border = TableBorder.Rounded; - mainTable.ShowRowSeparators = true; - - var groupedModules = config.modules - .GroupBy(m => m.Value.owner) - .OrderBy(g => g.Key); + modulesTable.Border = TableBorder.Rounded; + modulesTable.ShowRowSeparators = true; - foreach (var group in groupedModules) + if (config.Modules != null) { + var groupedModules = config.Modules + .GroupBy(m => m.Value.owner) + .OrderBy(g => g.Key); + + foreach (var group in groupedModules) + { + + // Create the subtable for the current owner + var subTable = new Table() + .AddColumn("Repo") + .AddColumn("Version"); + subTable.Border = TableBorder.Rounded; + subTable.ShowRowSeparators = true; + // Add rows to the subtable for each module of the owner$ - // Create the subtable for the current owner - var subTable = new Table() - .AddColumn("Repo") - .AddColumn("Version"); - subTable.Border = TableBorder.Rounded; - subTable.ShowRowSeparators = true; - // Add rows to the subtable for each module of the owner$ + foreach (var module in group) + { + subTable.AddRow($"[link=https://github.com/{group.Key}/{module.Value.repo}] {module.Value.repo}[/]", module.Value.version); + } - foreach (var module in group) + + // Add a row in the main table for the owner, with the subtable as its content + modulesTable.AddRow(new Markup($"[bold green][link=https://github.com/{group.Key}] {group.Key}[/][/]"), subTable); + } + AnsiConsole.Write(modulesTable); // Render the main table with the owner row + + } + + var librariesTable = new Table() + .AddColumn("Owner") + .AddColumn("Libraries"); + librariesTable.Border = TableBorder.Rounded; + librariesTable.ShowRowSeparators = true; + if (config.Libraries != null) + { + var groupedLibraries = config.Libraries + .GroupBy(m => m.Value.owner) + .OrderBy(g => g.Key); + + foreach (var group in groupedLibraries) { - subTable.AddRow($"[link=https://github.com/{group.Key}/{module.Value.repo}] {module.Value.repo}[/]", module.Value.version); + + // Create the subtable for the current owner + var subTable = new Table() + .AddColumn("Repo") + .AddColumn("Version"); + subTable.Border = TableBorder.Rounded; + subTable.ShowRowSeparators = true; + // Add rows to the subtable for each module of the owner$ + + + foreach (var library in group) + { + subTable.AddRow($"[link=https://github.com/{group.Key}/{library.Value.repo}] {library.Value.repo}[/]", library.Value.version); + } + + + // Add a row in the main table for the owner, with the subtable as its content + librariesTable.AddRow(new Markup($"[bold green][link=https://github.com/{group.Key}] {group.Key}[/][/]"), subTable); } - + AnsiConsole.Write(librariesTable); // Render the main table with the owner row - // Add a row in the main table for the owner, with the subtable as its content - mainTable.AddRow(new Markup($"[bold green][link=https://github.com/{group.Key}] {group.Key}[/][/]"),subTable); } - AnsiConsole.Write(mainTable); // Render the main table with the owner row return 0; } } diff --git a/premake-manager-cli/src/config/ConfigManager.cs b/premake-manager-cli/src/config/ConfigManager.cs new file mode 100644 index 0000000..fb2d0bb --- /dev/null +++ b/premake-manager-cli/src/config/ConfigManager.cs @@ -0,0 +1,38 @@ +using src.utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.config +{ + internal class ConfigManager + { + public static bool HasConfig(string? filePath = null) + { + string usedPath = filePath ?? Path.Combine(Directory.GetCurrentDirectory(), "premakeConfig.yml"); + return Path.Exists(usedPath); + } + public static Config ReadConfig(Stream stream) + { + return YamlSerializer.Deserialize(stream); + } + public static Config ReadConfig(string? filePath = null) + { + string usedPath = filePath ?? Path.Combine(Directory.GetCurrentDirectory(),"premakeConfig.yml"); + return YamlSerializer.Deserialize(usedPath); + } + public static Stream WriteConfig(Config config) + { + return YamlSerializer.Serialize(config); + } + public static void WriteConfig(Config config, string? filePath) + { + string usedPath = filePath ?? Path.Combine(Directory.GetCurrentDirectory(), "premakeConfig.yml"); + + YamlSerializer.Serialize(config, usedPath); + } + } +} diff --git a/premake-manager-cli/src/config/ConfigReader.cs b/premake-manager-cli/src/config/ConfigReader.cs deleted file mode 100644 index 7ab288e..0000000 --- a/premake-manager-cli/src/config/ConfigReader.cs +++ /dev/null @@ -1,61 +0,0 @@ -using src.libraries; -using src.modules; -using System.Collections.Generic; -using System.IO; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; - -namespace src.config -{ - internal class ConfigReader - { - [YamlMember(Alias = "version")] - public string version { get; set; } = string.Empty; - [YamlMember(Alias = "modulesPath")] - public string modulesPath { get; set; } = string.Empty; - [YamlMember(Alias = "librariesPath")] - public string librariesPath { get; set; } = string.Empty; - [YamlMember(Alias = "modules")] - public IDictionary modules { get; set; } = new Dictionary(); - [YamlMember(Alias = "libraries")] - public IDictionary libraries { get; set; } = new Dictionary(); - public ConfigReader(string path = "") - { - string configPath; - - if (string.IsNullOrEmpty(path)) - configPath = Path.Combine(Directory.GetCurrentDirectory(), "premakeConfig.yml"); - else - configPath = Path.Combine(path, "premakeConfig.yml"); - - - string deserializedConfig = File.Exists(configPath) ? File.ReadAllText(configPath) : ""; - - //If the desirialized config is not null or whitespace we want to read it. - if (!string.IsNullOrEmpty(deserializedConfig)) - { - var deserializer = new DeserializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .IgnoreUnmatchedProperties() - .Build(); - var tempInstance = deserializer.Deserialize(deserializedConfig); - if (tempInstance != null) - { - //extract version - version = tempInstance["version"] ?? string.Empty; - if (tempInstance["modules"] != null) - { - foreach (var module in tempInstance["modules"]) - modules.Add(module.Key, new PremakeModule(module.Value["version"], module.Key)); - } - - if (tempInstance["libraries"] != null) - { - foreach (var library in tempInstance["libraries"]) - libraries.Add(library.Key, new PremakeLibrary(library.Value["version"], library.Key)); - } - } - } - } - } -} diff --git a/premake-manager-cli/src/config/ConfigWriter.cs b/premake-manager-cli/src/config/ConfigWriter.cs deleted file mode 100644 index ddbf95f..0000000 --- a/premake-manager-cli/src/config/ConfigWriter.cs +++ /dev/null @@ -1,133 +0,0 @@ -using src.libraries; -using src.modules; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; -using static Microsoft.VisualStudio.Threading.AsyncReaderWriterLock; - -namespace src.config -{ - /// - /// This class is a builder style class but writes to the premakeConfig.yml instead of returning a class instance - /// - internal class ConfigWriter - { - public string version { get; set; } - - public IDictionary modules { get; set; } - public IDictionary libraries { get; set; } - - public static ConfigWriter FromReader(ConfigReader reader) - { - ConfigWriter writer = new(); - writer.version = reader.version; - writer.modules = reader.modules; - return writer; - } - public ConfigWriter() - { - this.modules = new Dictionary(); - } - /// - /// Sets the version of the config - /// - /// - /// - public ConfigWriter SetVersion(string versionTag) - { - this.version = versionTag; - return this; - } - - /// - /// Adds a module to the Configuration - /// - /// - /// - public ConfigWriter AddModule(PremakeModule module) - { - if (string.IsNullOrEmpty(module.version)) - module.version = "*"; - modules.Add(module.module,module); - return this; - } - - /// - /// Removes a Module from the configuration - /// - /// - /// - public ConfigWriter RemoveModule(string moduleName) - { - PremakeModule foundModule = modules.First(module => - { - if (module.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) - { - moduleName = module.Key; - return true; - } - return false; - }).Value; - if(foundModule != null) - modules.Remove(moduleName); - return this; - } - - /// - /// Adds a module to the Configuration - /// - /// - /// - public ConfigWriter AddLibrary(PremakeLibrary library) - { - if (string.IsNullOrEmpty(library.version)) - library.version = "*"; - libraries.Add(library.library, library); - return this; - } - - /// - /// Removes a Library from the configuration - /// - /// - /// - public ConfigWriter RemoveLibrary(string libraryName) - { - PremakeLibrary foundLibrary = libraries.First(library => - { - if (library.Key.Equals(libraryName, StringComparison.OrdinalIgnoreCase)) - { - libraryName = library.Key; - return true; - } - return false; - }).Value; - if (foundLibrary != null) - libraries.Remove(libraryName); - return this; - } - - public async Task Write(string path = "") - { - var serializer = new SerializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .Build(); - - string serializedConfig = serializer.Serialize(this); - - string outputPath; - - if (string.IsNullOrEmpty(path)) - outputPath = Path.Combine(Directory.GetCurrentDirectory(), "premakeConfig.yml"); - else - outputPath = Path.Combine(path, "premakeConfig.yml"); - - await File.WriteAllTextAsync(outputPath, serializedConfig); - } - } -} diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs new file mode 100644 index 0000000..1e1e5bc --- /dev/null +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -0,0 +1,251 @@ +using Octokit; +using Semver; +using Spectre.Console; +using src.common_index; +using src.dependencies.graph; +using src.dependencies.types; +using src.libraries; +using src.utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; +//TODO USE STREAMS => can be tested +namespace src.dependencies +{ + [YamlSerializable] + internal class Dependencies + { + [YamlMember] + public IList? libraries; + } + + //TODO Package Calculus + + //Add dependencies + internal class DependenciesManager + { + #region LIBRARIES + /// + /// Add a new library dependency to the index. + /// + /// the repo to add the dependency to + /// dependency to add + public static async Task AddLibraryDependency(GithubRepo repo, LibraryDependency dependency) + { + string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", repo.owner, repo.name]).ToLower(); + string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); + + #region EXTRACT_UPDATE + Dependencies dependencies = Path.Exists(LibraryDependencies) ? YamlSerializer.Deserialize(LibraryDependencies): new Dependencies(); + + if(dependencies.libraries == null) + dependencies.libraries = new List(); + dependencies.libraries.Add(dependency); + #endregion + + YamlSerializer.Serialize(dependencies, LibraryDependencies); + } + /// + /// Remove a library from the repo dependecies + /// + /// repo to remove the dependecy from + /// the name of the dependecy to remove + public async void RemoveLibraryDependency(GithubRepo repo, string name) + { + string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", repo.owner, repo.name]).ToLower(); + string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); + if(Path.Exists(LibraryDependencies)) + { + Dependencies dependencies = YamlSerializer.Deserialize(LibraryDependencies); + LibraryDependency? dependency = dependencies.libraries?.First((dependency) => dependency.name == name); + if (dependency != null) + dependencies.libraries?.Remove(dependency); + + YamlSerializer.Serialize(dependencies, LibraryDirectory); + } + } + #endregion + + #region GATHER_DEPENDENCIES + + private static async Task> GatherDependencies(PremakeLibrary library) + { + List libraryDependencies = new List(); + + IList dependencies = await GatherLibraryDependencies(library); + libraryDependencies.AddRange(dependencies); + libraryDependencies.AddRange(await GatherSubDependencies(dependencies)); + + return libraryDependencies; + } + private static async Task> GatherSubDependencies(IList dependencies) + { + List libraryDependencies = new List(); + foreach (var library in dependencies) + { + IList subDependencies = await GatherLibrarySubDependencies(library); + libraryDependencies.AddRange(subDependencies); + libraryDependencies.AddRange(await GatherSubDependencies(subDependencies)); + } + return libraryDependencies; + } + #region INDIVIDUAL + private static async Task> GatherLibraryDependencies(PremakeLibrary library) + { + //NOTE: dependencies must either be defined in the remoteIndex or in the github repo itself + //1) check local remotes. + //2) check github for dependencies + GithubRepo repo = Github.GetRepoFromLink(library.getLink()); + #region CHECK_REMOTES + Dependencies? dependencies = RemotesManager.GetDependencies(repo); + if (dependencies is not null) + { + return dependencies.libraries; + } + #endregion + + #region CHECK_GITHUB + /* DO NOT SUPPORT THIS AS WE WILL QUICKLY HOT THE RATE LIMIT */ + /* + string LibraryGitDirectory = Path.Combine(["libraries", repo.owner, repo.name]).ToLower(); + string LibraryGitDependencies = Path.Combine(LibraryGitDirectory, "premakeDependencies.yml"); + try + { + return (await YamlSerializer.Deserialize(repo.owner, repo.name, LibraryGitDependencies)).libraries; + } + catch (HttpRequestException) + { + return new List(); //return empty list when no dependencies where found. + } + */ + return new List(); + #endregion + } + + private static async Task> GatherLibrarySubDependencies(LibraryDependency library) + { + //NOTE: dependencies must either be defined in the remoteIndex or in the github repo itself + //1) check local remotes. + //2) check github for dependencies + GithubRepo repo = Github.GetRepoFromLink(library.name); + #region CHECK_REMOTES + Dependencies? dependencies = RemotesManager.GetDependencies(repo); + if(dependencies is not null) + { + return dependencies.libraries; + } + #endregion + + #region CHECK_GITHUB + /* DO NOT SUPPORT THIS AS WE WILL QUICKLY HOT THE RATE LIMIT */ + /* + string LibraryGitDirectory = Path.Combine(["libraries", repo.owner, repo.name]).ToLower(); + string LibraryGitDependencies = Path.Combine(LibraryGitDirectory, "premakeDependencies.yml"); + try + { + return (await YamlSerializer.Deserialize(repo.owner, repo.name, LibraryGitDependencies)).libraries; + } + catch (HttpRequestException) + { + return new List(); //return empty list when no dependencies where found. + } + */ + return new List(); + #endregion + } + #endregion + #endregion + + #region GRAPH + /// + /// This function resolves the dependecyGraph for the given list of premake libraries + /// + /// + /// + public static async Task GetDependencyGraph(IList libraries) + { + IList> rootDependencies = libraries.Select((library) => new KeyValuePair(library, new LibraryDependency() { name = library.library!, version = library.version })).ToList(); + DependencyGraph graph = new DependencyGraph(rootDependencies.Select((dep) => dep.Value).ToArray()); + foreach (KeyValuePair dependency in rootDependencies) + { + graph.AddDependencies(dependency.Value, await GatherDependencies(dependency.Key)); + } + return graph; + + } + static async Task GetLibVersions(Regex regex, LibraryDependency library) + { + GithubRepo repo = Github.GetRepoFromLink(library.name); + SemVersionRange range = SemVersionRange.Parse(library.version); + try + { + #region BATCH_CALC_SEMVERS + // fetch all tags + var versions = await Github.GetRepoTags(repo); + + // parse all valid SemVersions in one pass + int batchSize = 50; // Adjust based on your API limits + var batches = versions.Chunk(batchSize); + + var tasks = batches.Select(async batch => + { + // Process the batch in parallel or sequentially depending on your needs + return batch.Select(tag => + { + Match match = regex.Match(tag.Name); + if (match.Success && SemVersion.TryParse(match.Groups[1].Value, out SemVersion tmp)) + { + return (Success: true, Version: tmp); + } + return (Success: false, Version: null); + }) + .Where(t => t.Success) + .Select(t => t.Version) + .ToList(); + }); + #endregion + // Wait for all batches to finish + var semVersions = (await Task.WhenAll(tasks)).SelectMany(x => x).ToList(); + + // find the first version in range + SemVersion firstInRange = semVersions.FirstOrDefault(v => range.Contains(v)); + + if (firstInRange != null) + { + return new PremakeLibrary($"v{firstInRange.ToString()}", library.name); + } + } + catch (Exception) + { + AnsiConsole.WriteLine($"Library not found"); + } + //NO VERSION FOUND FOR RANGE + throw new InvalidOperationException("No valid version found for provided range"); + } + /// + /// This function fetches the versions from Github and resolves the correct version (if possible). + /// + /// the dependecy graph to resolve the versions of + /// a dictionary indexed, via the library name + public static async Task GetVersionsFromGraph(DependencyGraph graph) + { + var(libraries,conflict) = graph.GetResolvedLibraries(); + IList resultLibraries = new List(); + Regex regex = new Regex(@"(\d+\.\d+\.\d+)", RegexOptions.IgnoreCase); + + var tasks = libraries.Select(library => GetLibVersions(regex, library)); + + // 2. Start them all and wait for the whole group to complete + resultLibraries = await Task.WhenAll(tasks); + return resultLibraries.ToArray(); + } + #endregion + } +} diff --git a/premake-manager-cli/src/dependencies/DependenciesReader.cs b/premake-manager-cli/src/dependencies/DependenciesReader.cs deleted file mode 100644 index 441a99a..0000000 --- a/premake-manager-cli/src/dependencies/DependenciesReader.cs +++ /dev/null @@ -1,44 +0,0 @@ -using src.dependencies.types; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; - -namespace src.dependencies -{ - [YamlSerializable] - internal class Dependencies - { - [YamlMember] - IList? dependencies; - } - internal class DependenciesReader - { - private readonly IDeserializer _deserializer; - - public DependenciesReader() - { - _deserializer = new DeserializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .IgnoreUnmatchedProperties() - .Build(); - } - - public T Deserialize(Stream yamlStream) - { - if (yamlStream == null) - { - throw new ArgumentNullException(nameof(yamlStream)); - } - - using (StreamReader reader = new StreamReader(yamlStream, leaveOpen: true)) - { - return _deserializer.Deserialize(reader); - } - } - } -} diff --git a/premake-manager-cli/src/dependencies/DependenciesWriter.cs b/premake-manager-cli/src/dependencies/DependenciesWriter.cs deleted file mode 100644 index a02b905..0000000 --- a/premake-manager-cli/src/dependencies/DependenciesWriter.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace src.dependencies -{ - - internal class DependenciesWriter - { - } -} diff --git a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs index fce7106..6528ab6 100644 --- a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs +++ b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs @@ -1,11 +1,16 @@ -using Spectre.Console; +using Octokit; +using Semver; +using Spectre.Console; using src.dependencies.types; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; namespace src.dependencies.graph { + [DebuggerDisplay("Count = {_graph.Count} (Libraries)")] + [DebuggerTypeProxy(typeof(DependencyGraphDebugProxy))] internal class DependencyGraph { private readonly Dictionary> _graph @@ -29,92 +34,132 @@ public void AddDependency(LibraryDependency library, LibraryDependency dependsOn if (!_graph.ContainsKey(dependsOn)) _graph[dependsOn] = new HashSet(); + if (dependsOn.version == "@") + dependsOn.version = library.version; + _graph[library].Add(dependsOn); } + public void AddDependencies(LibraryDependency library, IEnumerable dependencies) + { + foreach (var dependency in dependencies) + { + AddDependency(library, dependency); + } + } + public IReadOnlyCollection GetDependencies(LibraryDependency library) => _graph.TryGetValue(library, out var deps) ? deps : Array.Empty(); public IReadOnlyCollection GetAllLibraries() => _graph.Keys; - public IReadOnlyDictionary> GetDependencyConflicts(bool showProgress = false) + public IReadOnlyDictionary GetDependencyConflicts(bool showProgress = false) { // Include all libraries: keys + dependencies - var allDeps = _graph.Keys - .Concat(_graph.SelectMany(kv => kv.Value)) - .ToList(); + var (resolved, conflict) = GetResolvedLibraries(); - var conflicts = new Dictionary>(); + return conflict!; + } - if (showProgress) - { - AnsiConsole.Progress() + + public (IReadOnlyCollection, IReadOnlyDictionary) GetResolvedLibraries() + { + // Include all libraries + var allDeps = _graph.Keys.Concat(_graph.SelectMany(kv => kv.Value)).ToList(); + + //contains all resolved non conflicting libraries. + var resolved = new List(); + //contains all conflicting libraries. + var conflict = new Dictionary(); + + AnsiConsole.Progress() .AutoClear(false) .Start(ctx => { + // Group by library name var task = ctx.AddTask("Checking dependencies...", maxValue: allDeps.Count); - foreach (var group in allDeps.GroupBy(lib => lib.name)) + var groups = allDeps.GroupBy(lib => lib.name); + foreach (var group in groups) { - var versions = group.Select(lib => lib.VersionRange).Distinct().ToList(); - if (versions.Count > 1 && VersionRange.ConflictsWithAll(versions)) - conflicts[group.Key] = group.ToList(); - + SemVersionRange final = SemVersionRange.Empty; + SemVersionRange[] ranges = group.Select(lib => SemVersionRange.Parse(lib.version)).ToArray(); + foreach (SemVersionRange range in ranges) + { + if (final != SemVersionRange.Empty) + final = SemVersionRange.Parse($"{final} {range}"); + else + final = SemVersionRange.Parse($"{range}"); + + if (final == SemVersionRange.Empty) + { + + conflict.Add(group.Key, new LibraryDependency() + { + name = group.Key, + version = range.ToString() + }); + break; + } + + + } + if (final == SemVersionRange.Empty) + continue; + if (resolved.Find(dep => dep.name == group.Key) is not null) + { + conflict.Add(group.Key, new LibraryDependency() + { + name = group.Key, + version = final.ToString() + }); + } + else + { + resolved.Add(new LibraryDependency() + { + name = group.Key, + version = final.ToString() + }); + } task.Increment(1); + ctx.Refresh(); } + + }); - } - else + + return (resolved, conflict); + } + + internal class DependencyGraphDebugProxy + { + private readonly DependencyGraph _graphObj; + + public DependencyGraphDebugProxy(DependencyGraph graphObj) { - foreach (var group in allDeps.GroupBy(lib => lib.name)) - { - var versions = group.Select(lib => lib.VersionRange).Distinct().ToList(); - if (versions.Count > 1 && VersionRange.ConflictsWithAll(versions)) - conflicts[group.Key] = group.ToList(); - } + _graphObj = graphObj; } - return conflicts; + // This shows up as a "Libraries" node you can expand + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public DependencyEntry[] Libraries => _graphObj.GetAllLibraries() + .Select(lib => new DependencyEntry(lib, _graphObj.GetDependencies(lib))) + .ToArray(); } - /// - /// Returns a flat list of all libraries with the best matching version, - /// resolving any compatible version ranges. Throws if no compatible version exists. - /// - public IReadOnlyCollection GetResolvedLibraries() + // A helper class just for the debugger view + [DebuggerDisplay("{Library.name,nq} -> {Dependencies.Count} deps")] + internal class DependencyEntry { - // Include all libraries - var allDeps = _graph.Keys.Concat(_graph.SelectMany(kv => kv.Value)).ToList(); + public LibraryDependency Library { get; } + public IReadOnlyCollection Dependencies { get; } - var resolved = new List(); - - // Group by library name - var groups = allDeps.GroupBy(lib => lib.name); - foreach (var group in groups) + public DependencyEntry(LibraryDependency lib, IReadOnlyCollection deps) { - var ranges = group.Select(lib => lib.VersionRange).ToList(); - - // Check for conflicts - if (VersionRange.ConflictsWithAll(ranges)) - continue; //skip the conflicts - - // Pick the "best" version: choose the highest lower bound - long bestVersion = ranges - .Where(r => !r.AnyVersion) - .Max(r => r.LowerBound ?? 0); - - // If all are *, just pick * - var finalRange = ranges.FirstOrDefault(r => r.AnyVersion) - ?? new VersionRange(bestVersion.ToString()); - - resolved.Add(new LibraryDependency - { - name = group.Key, - version = finalRange.ToString() - }); + Library = lib; + Dependencies = deps; } - - return resolved; } } } diff --git a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs index e8b1207..6e56e7e 100644 --- a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs +++ b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs @@ -1,23 +1,38 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Text.RegularExpressions; using YamlDotNet.Serialization; namespace src.dependencies.types { + [DebuggerDisplay("{name} -> {version}")] [YamlSerializable] internal class LibraryDependency { [YamlMember] - public string name { get; set; } // format: / + public string name { get; set; } = ""; // format: / [YamlMember] - public string version { get; set; } // format: "*", "=x.y.z", ">x.y.z", "=x.y.z", "<=x.y.z" + public string version { get; set; } = "";// format: "*", "=x.y.z", ">x.y.z", "=x.y.z", "<=x.y.z", "@ => parent version" public bool IsValid() => LibraryDependencyValidator.ValidateLibrary(name, version); - [YamlIgnore] - public VersionRange VersionRange => new VersionRange(version); + public override bool Equals(object? obj) + { + //same name -> same key + if (obj is LibraryDependency other) + { + return string.Equals(name, other.name, StringComparison.OrdinalIgnoreCase); + } + return false; + } + + public override int GetHashCode() + { + // Use the same property here as in Equals + return name?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0; + } } internal static class LibraryDependencyValidator diff --git a/premake-manager-cli/src/dependencies/types/ModuleDependency.cs b/premake-manager-cli/src/dependencies/types/ModuleDependency.cs index f52a311..f2ad894 100644 --- a/premake-manager-cli/src/dependencies/types/ModuleDependency.cs +++ b/premake-manager-cli/src/dependencies/types/ModuleDependency.cs @@ -11,8 +11,8 @@ namespace src.dependencies.types internal class ModuleDependency { [YamlMember] - public string name { get; set; } + public string name { get; set; } = ""; [YamlMember] - public string version { get; set; } + public string version { get; set; } = ""; } } diff --git a/premake-manager-cli/src/libraries/LibraryCommand.cs b/premake-manager-cli/src/libraries/LibraryCommand.cs index 1b1aa03..37c514c 100644 --- a/premake-manager-cli/src/libraries/LibraryCommand.cs +++ b/premake-manager-cli/src/libraries/LibraryCommand.cs @@ -56,7 +56,7 @@ internal class Settings : CommandSettings } public override async Task ExecuteAsync(CommandContext context, Settings settings) { - await LibraryManager.InstallLibrary(settings.githublink, settings.version); + await LibraryManager.InstallLibrary(settings.githublink, settings.version ?? "*"); return 0; } @@ -91,14 +91,17 @@ internal class Settings : CommandSettings public override async Task ExecuteAsync(CommandContext context, Settings settings) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + string[] libraryString = settings.githublink.Replace("https://github.com/", "").Split('/'); await AnsiConsole.Status().StartAsync("Adding library", async ctx => { ctx.Spinner(Spinner.Known.Aesthetic); ctx.SpinnerStyle(Style.Parse("green")); - await ConfigWriter.FromReader(config).AddLibrary(new PremakeLibrary() { owner = libraryString[0], repo = libraryString[1], version = settings.version }).Write(); + + config.AddLibrary(new PremakeLibrary() { owner = libraryString[0], repo = libraryString[1], version = settings.version ?? "*"}); }); + ConfigManager.WriteConfig(config,null); return 0; } } @@ -113,19 +116,26 @@ internal class Settings : CommandSettings } [RequiresUnreferencedCode("Calls src.config.ConfigReader.ConfigReader(String)")] + [UnconditionalSuppressMessage("Trimming", "IL2026", + Justification = "Reflection in ConfigManager is manually preserved via DynamicDependency")] public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) { if (string.IsNullOrEmpty(settings.githublink)) { - ConfigReader reader = new ConfigReader(); - IList modules = reader.libraries.Values.ToList(); - string selectedLink = AnsiConsole.Prompt( - new SelectionPrompt() - .Title("Select a [green]Library to remove[/]:") - .PageSize(10) - .AddChoices(modules.Select(m => m.getLink())) - ); - settings.githublink = selectedLink; + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + + if (config.Libraries != null) + { + string selectedLink = AnsiConsole.Prompt( + new SelectionPrompt() + .Title("Select a [green]Library to remove[/]:") + .PageSize(10) + .AddChoices(config.Libraries.Values.Select(m => m.getLink())) + ); + settings.githublink = selectedLink; + } else { + AnsiConsole.MarkupLine("[red] No libraries to remove [/]"); + } } else { @@ -145,16 +155,18 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not public override async Task ExecuteAsync(CommandContext context, Settings settings) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + string libraryString = settings.githublink!.Replace("https://github.com/", ""); await AnsiConsole.Status().StartAsync("Removing Library", async ctx => { ctx.Spinner(Spinner.Known.Aesthetic); ctx.SpinnerStyle(Style.Parse("green")); - await ConfigWriter.FromReader(config).RemoveLibrary(libraryString).Write(); + config.RemoveLibrary(libraryString); }); + ConfigManager.WriteConfig(config, null); return 0; } } diff --git a/premake-manager-cli/src/libraries/LibraryManager.cs b/premake-manager-cli/src/libraries/LibraryManager.cs index 85f9e3b..8519508 100644 --- a/premake-manager-cli/src/libraries/LibraryManager.cs +++ b/premake-manager-cli/src/libraries/LibraryManager.cs @@ -1,5 +1,7 @@ using Octokit; +using Semver; using Spectre.Console; +using src.common_index; using src.config; using src.modules; using src.utils; @@ -8,6 +10,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; +using System.Net.Http; using System.Text; using System.Threading.Tasks; @@ -19,16 +22,22 @@ internal class LibraryManager public static async Task GetLibraryConfig(string githubLink) { GithubRepo repo = Github.GetRepoFromLink(githubLink); + return await GetLibraryConfig(repo); + } + public static async Task GetLibraryConfig(GithubRepo repo) + { try { Octokit.RepositoryContent config = (await Github.Repositories.Content.GetAllContentsByRef(repo.owner, repo.name, "premakeLibrary.yml", "main"))[0]; await DownloadUtils.DownloadStatus(config.DownloadUrl, $"Fetching library info: {repo.name}", Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeLibrary.yml")); return new LibraryConfig(Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeLibrary.yml")); - } catch (Octokit.NotFoundException) { - return new LibraryConfig() { name = repo.name, entryPoint = "premake5.lua", description = Github.GetDescription(repo) }; + } + catch (Octokit.NotFoundException) + { + //default for when we are installing from a remote with no LibraryConfig + return new LibraryConfig() { name = repo.name, entryPoint = "premake5.lua", description = await Github.GetDescription(repo) }; } } - public static async Task GetLibrariesConfig(string[] githubLinks) { IList> tasks = new List>(); @@ -80,7 +89,7 @@ await AnsiConsole.Progress().Columns(new ProgressColumn[] [RequiresUnreferencedCode("Calls src.config.ConfigReader.ConfigReader(String)")] public static async Task InstallLibraryCtx(ProgressContext ctx, string githubLink, string version = "*") { - ConfigReader reader = new ConfigReader(""); + if (!githubLink.StartsWith("https://github.com/")) { string[] repoInfo = githubLink.Split('/'); @@ -90,14 +99,17 @@ public static async Task InstallLibraryCtx(ProgressContext ctx, string githubLin if (string.IsNullOrEmpty(version)) version = "*"; - LibraryConfig config = await GetLibraryConfig(githubLink); + LibraryConfig libconfig = await GetLibraryConfig(githubLink); GithubRepo repo = Github.GetRepoFromLink(githubLink); string downloadUrl = await ResolveDownloadUrl(repo, version); - await DownloadUtils.DownloadProgressCtx(ctx, downloadUrl, $"downloading {config.name} library", Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip")); - await ExtractUtils.ExtractZipProgressCtx(ctx, Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip"), $"{reader.librariesPath}/{repo.name}", $"extracting {config.name}"); + await DownloadUtils.DownloadProgressCtx(ctx, downloadUrl, $"downloading {libconfig.name} library", Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip")); + await ExtractUtils.ExtractZipProgressCtx(ctx, Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip"), await GetLibraryPath(repo), $"extracting {libconfig.name}"); + await RemotesManager.InstallRemotesLibrary(repo); + } + [RequiresUnreferencedCode("Calls src.libraries.LibraryManager.InstallLibraryCtx(ProgressContext, String, String)")] public static async Task InstallLibrariesCtx(ProgressContext ctx, List<(string githubLink, string version)> modules) { foreach (var (githubLink, version) in modules) @@ -110,28 +122,43 @@ private static async Task ResolveDownloadUrl(GithubRepo repo, string ver { GitHubClient client = new GitHubClient(new ProductHeaderValue("premake-manager")); + if (SemVersion.TryParse(version, SemVersionStyles.Any, out _)) + { + using var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.Add("User-Agent", "premake-manager"); + // 1. Try the version exactly as provided + string firstUrl = Github.FormatZipballUrl(repo, version); + var firstResponse = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, firstUrl)); + + if (firstResponse.IsSuccessStatusCode) + return firstUrl; + + + // 2. If first fails, toggle the 'v' prefix and try again + string toggledVersion = version.StartsWith("v", StringComparison.OrdinalIgnoreCase) + ? version.Substring(1) + : $"v{version}"; + + string secondUrl = Github.FormatZipballUrl(repo, toggledVersion); + var secondResponse = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, secondUrl)); + + if (secondResponse.IsSuccessStatusCode) + return secondUrl; + } if (version == "*" || string.IsNullOrWhiteSpace(version)) { - Repository repoInfo = await client.Repository.Get(repo.owner, repo.name); + Repository repoInfo = await Github.GetRepo(repo); return Github.FormatZipballUrl(repo, repoInfo.DefaultBranch); } - // Check if it's a branch - IReadOnlyList branches = await client.Repository.Branch.GetAll(repo.owner, repo.name); + IReadOnlyList branches = await Github.GetBranches(repo); Branch? branch = branches.FirstOrDefault(b => b.Name == version); if (branch != null) return Github.FormatZipballUrl(repo, branch.Name); - /* Check if it's a tag */ - IReadOnlyList releases = await client.Repository.Release.GetAll(repo.owner, repo.name); - Release? tagRelease = releases.FirstOrDefault(r => r.TagName == version); - if (tagRelease != null) - return tagRelease.ZipballUrl; - - /* Assume it's a commit SHA (Octokit throws on invalid SHA so we fetch all commits and match manually) */ - IReadOnlyList commits = await client.Repository.Commit.GetAll(repo.owner, repo.name); + IReadOnlyList commits = await Github.GetRepoCommits(repo); bool commitExists = commits.Any(c => c.Sha.StartsWith(version)); if (commitExists) return Github.FormatZipballUrl(repo, version); @@ -139,5 +166,11 @@ private static async Task ResolveDownloadUrl(GithubRepo repo, string ver throw new InvalidOperationException($"Could not resolve tag, branch, or commit '{version}' for repository {repo.owner}/{repo.name}."); } + + public static async Task GetLibraryPath(GithubRepo library) + { + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + return $"{config.LibrariesPath ?? "libraries"}/{library.name}"; + } } } diff --git a/premake-manager-cli/src/libraries/PremakeLibrary.cs b/premake-manager-cli/src/libraries/PremakeLibrary.cs index 52a6312..599358d 100644 --- a/premake-manager-cli/src/libraries/PremakeLibrary.cs +++ b/premake-manager-cli/src/libraries/PremakeLibrary.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -7,7 +8,8 @@ namespace src.libraries { - internal class PremakeLibrary + [DebuggerDisplay("{owner}/{repo}")] + public class PremakeLibrary { [YamlIgnore] public string repo { get => getRepo(); set => setRepo(value); } diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 54d76b7..8c7e06f 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -15,14 +15,29 @@ public class main { static async Task Main(string[] args) { + string sessionToken = ""; #if DEBUG bool interactive = true; #else bool interactive = false; #endif - if (args.Length > 0 && args[0] == "--interactive") - interactive = true; + foreach (var arg in args) + { + if (arg == "--interactive") + { + interactive = true; + } + if (arg.StartsWith("--session=")) + { + // Extracts the part after "--session=" + sessionToken = arg.Substring("--session=".Length).Trim('"'); + await Github.SetSession(sessionToken); + + } + } + + Console.CancelKeyPress += (sender, e) => { PathUtils.ClearDirectory(PathUtils.GetTempPath()); @@ -84,6 +99,21 @@ static async Task Main(string[] args) branch.AddCommand("remove"); }); + config.AddBranch("library", branch => + { + branch.SetDescription("Manage premake libraries"); + branch.AddCommand("info") + .WithDescription("get the info from a library"); + + branch.AddCommand("install") + .WithDescription("install a library given its github link"); + + branch.AddCommand("add") + .WithDescription("add a library to the confiuration"); + + branch.AddCommand("remove"); + }); + config.AddBranch("test", branch => { branch.SetDescription("The Premake Manager selftest commands"); @@ -92,6 +122,35 @@ static async Task Main(string[] args) branch.AddCommand("group").WithDescription("run all the test in a certain group"); }); + config.AddBranch("index", branch => { + branch.SetDescription("All commands for managing the common index"); + branch.AddCommand("new"); + + branch.AddBranch("add", branch => { + branch.AddCommand("library").WithDescription("Add a library to the local index"); + branch.AddBranch("uri", uriBranch => + { + uriBranch.AddCommand("library").WithDescription("Add a library from a github uri to the local index"); + + }); + branch.AddCommand("dependency").WithDescription("Add a dependency to a local index library"); + + }); + }); + config.AddBranch("remotes", branch => { + branch.SetDescription("All commands for managing the localy used remotes"); + branch.AddCommand("view") + .WithDescription("Show all the local remotes"); + branch.AddCommand("add") + .WithDescription("Add a new local remote"); + branch.AddCommand("update") + .WithDescription("Update outdated remotes"); + branch.AddCommand("remove") + .WithDescription("Remove a remote"); + branch.AddCommand("reset") + .WithDescription("Reset remotes to default"); + + }); }); bool running = true; diff --git a/premake-manager-cli/src/modules/ModuleCommand.cs b/premake-manager-cli/src/modules/ModuleCommand.cs index bf8ba9a..5d884d1 100644 --- a/premake-manager-cli/src/modules/ModuleCommand.cs +++ b/premake-manager-cli/src/modules/ModuleCommand.cs @@ -54,7 +54,7 @@ internal class Settings : CommandSettings } public override async Task ExecuteAsync(CommandContext context, Settings settings) { - await ModuleManager.InstallModule(settings.githublink, settings.version); + await ModuleManager.InstallModule(settings.githublink, settings.version!); return 0; } @@ -89,15 +89,17 @@ internal class Settings : CommandSettings public override async Task ExecuteAsync(CommandContext context, Settings settings) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + string[] moduleString = settings.githublink.Replace("https://github.com/", "").Split('/'); await AnsiConsole.Status().StartAsync("Adding module", async ctx => { ctx.Spinner(Spinner.Known.Aesthetic); ctx.SpinnerStyle(Style.Parse("green")); - await ConfigWriter.FromReader(config).AddModule(new PremakeModule() { owner = moduleString[0], repo = moduleString[1], version = settings.version }).Write(); - + config.AddModule(new PremakeModule() { owner = moduleString[0], repo = moduleString[1], version = settings.version! }); }); + + ConfigManager.WriteConfig(config, null); return 0; } } @@ -114,15 +116,21 @@ internal class Settings : CommandSettings public override ValidationResult Validate([NotNull] CommandContext context, [NotNull] Settings settings) { if (string.IsNullOrEmpty(settings.githublink)) { - ConfigReader reader = new ConfigReader(); - IList modules = reader.modules.Values.ToList(); - string selectedLink = AnsiConsole.Prompt( - new SelectionPrompt() - .Title("Select a [green]Module to remove[/]:") - .PageSize(10) - .AddChoices(modules.Select(m => m.getLink())) - ); - settings.githublink = selectedLink; + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + + if (config.Modules != null) + { + string selectedLink = AnsiConsole.Prompt( + new SelectionPrompt() + .Title("Select a [green]Module to remove[/]:") + .PageSize(10) + .AddChoices(config.Modules.Values.Select(m => m.getLink())) + ); + settings.githublink = selectedLink; + } else + { + AnsiConsole.MarkupLine("[red] No modules to remove [/]"); + } } else { if (!settings.githublink.StartsWith("https://github.com/")) return ValidationResult.Error("the link should start with https://github.com/"); @@ -140,16 +148,18 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not public override async Task ExecuteAsync(CommandContext context, Settings settings) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + string moduleString = settings.githublink!.Replace("https://github.com/", ""); await AnsiConsole.Status().StartAsync("Removing Module", async ctx => { ctx.Spinner(Spinner.Known.Aesthetic); ctx.SpinnerStyle(Style.Parse("green")); - await ConfigWriter.FromReader(config).RemoveModule(moduleString).Write(); + config.RemoveModule(moduleString); }); + ConfigManager.WriteConfig(config, null); return 0; } } diff --git a/premake-manager-cli/src/modules/ModuleManager.cs b/premake-manager-cli/src/modules/ModuleManager.cs index 3ee1b17..d839e36 100644 --- a/premake-manager-cli/src/modules/ModuleManager.cs +++ b/premake-manager-cli/src/modules/ModuleManager.cs @@ -1,4 +1,5 @@ using Octokit; +using Semver; using Spectre.Console; using src.utils; using System; @@ -17,10 +18,17 @@ internal class ModuleManager public static async Task GetModuleConfig(string githubLink) { GithubRepo repo = Github.GetRepoFromLink(githubLink); - Octokit.RepositoryContent config = (await Github.Repositories.Content.GetAllContentsByRef(repo.owner, repo.name, "premakeModule.yml", "main"))[0]; + RepositoryContent config = await Github.GetAllContentsByRef(repo,"premakeModule.yml", "main"); await DownloadUtils.DownloadStatus(config.DownloadUrl, $"Fetching module info: {repo.name}", Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeModule.yml")); return new ModuleConfig(Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeModule.yml")); } + public static async Task GetModuleConfigCtx(ProgressContext ctx,string githubLink) + { + GithubRepo repo = Github.GetRepoFromLink(githubLink); + RepositoryContent config = await Github.GetAllContentsByRef(repo, "premakeModule.yml", "main"); + await DownloadUtils.DownloadProgressCtx(ctx,config.DownloadUrl, $"Fetching module info: {repo.name}", Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeModule.yml")); + return new ModuleConfig(Path.Combine(PathUtils.GetTempModulePath(repo.name), "premakeModule.yml")); + } public static async Task GetModulesConfig(string[] githubLinks) { @@ -80,12 +88,12 @@ public static async Task InstallModuleCtx(ProgressContext ctx, string githubLink if (string.IsNullOrEmpty(version)) version = "*"; - ModuleConfig config = await GetModuleConfig(githubLink); + ModuleConfig config = await GetModuleConfigCtx(ctx,githubLink); GithubRepo repo = Github.GetRepoFromLink(githubLink); string downloadUrl = await ResolveDownloadUrl(repo, version); await DownloadUtils.DownloadProgressCtx(ctx, downloadUrl, $"downloading {config.name} module", Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip")); - await ExtractUtils.ExtractZipProgressCtx(ctx, Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip"), $"modules/{repo.name}", $"extracting {config.name}"); + await ExtractUtils.ExtractZipProgressCtx(ctx, Path.Combine(PathUtils.GetTempModulePath(repo.name), $"{repo.name}.zip"), Path.Combine(Directory.GetCurrentDirectory(),$"modules/{repo.name}"), $"extracting {config.name}"); } public static async Task InstallModulesCtx(ProgressContext ctx, List<(string githubLink, string version)> modules) @@ -98,30 +106,25 @@ public static async Task InstallModulesCtx(ProgressContext ctx, List<(string git private static async Task ResolveDownloadUrl(GithubRepo repo, string version) { - GitHubClient client = new GitHubClient(new ProductHeaderValue("YourAppName")); + if (SemVersion.TryParse(version, SemVersionStyles.Any, out _)) + { + return Github.FormatZipballUrl(repo, version); + } if (version == "*" || string.IsNullOrWhiteSpace(version)) { - Repository repoInfo = await client.Repository.Get(repo.owner, repo.name); + Repository repoInfo = await Github.GetRepo(repo); return Github.FormatZipballUrl(repo, repoInfo.DefaultBranch); } // Check if it's a branch - IReadOnlyList branches = await client.Repository.Branch.GetAll(repo.owner, repo.name); + IReadOnlyList branches = await Github.GetBranches(repo); Branch? branch = branches.FirstOrDefault(b => b.Name == version); if (branch != null) - return Github.FormatZipballUrl(repo, branch.Name); - - - /* Check if it's a tag */ - IReadOnlyList releases = await client.Repository.Release.GetAll(repo.owner,repo.name); - Release? tagRelease = releases.FirstOrDefault(r => r.TagName == version); - if (tagRelease != null) - return tagRelease.ZipballUrl; - + return Github.FormatZipballUrl(repo, branch.Name); /* Assume it's a commit SHA (Octokit throws on invalid SHA so we fetch all commits and match manually) */ - IReadOnlyList commits = await client.Repository.Commit.GetAll(repo.owner,repo.name); + IReadOnlyList commits = await Github.GetRepoCommits(repo); bool commitExists = commits.Any(c => c.Sha.StartsWith(version)); if (commitExists) return Github.FormatZipballUrl(repo, version); diff --git a/premake-manager-cli/src/modules/PremakeModule.cs b/premake-manager-cli/src/modules/PremakeModule.cs index e906ff5..488209f 100644 --- a/premake-manager-cli/src/modules/PremakeModule.cs +++ b/premake-manager-cli/src/modules/PremakeModule.cs @@ -26,13 +26,11 @@ internal class PremakeModule public string version { get; set; } = "*"; - public string entryPoint { get; set; } + public string entryPoint { get; set; } = "premake5.lua"; - [YamlIgnore] public string? module { get; set; } = ""; public PremakeModule() { - } public PremakeModule(string version, string module) { diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 9190bd3..8db52ed 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -1,7 +1,8 @@ using Spectre.Console; using Spectre.Console.Cli; using src.selfTest; -using src.selfTest.config; +using src.selfTest.common_index; +using src.selfTest.utils; using src.selfTest.version; using System.ComponentModel; using System.Threading.Tasks; @@ -15,9 +16,9 @@ public async override Task ExecuteAsync(CommandContext context) // Register all test classes runner.AddTestClass(); - runner.AddTestClass(); runner.AddTestClass(); - + runner.AddTestClass(); + runner.AddTestClass(); await runner.RunAllAsync(); return 0; } @@ -38,8 +39,9 @@ public async override Task ExecuteAsync(CommandContext context, Settings se // Register all test classes runner.AddTestClass(); - runner.AddTestClass(); runner.AddTestClass(); + runner.AddTestClass(); + runner.AddTestClass(); // Determine which group to run string groupToRun = settings.GroupName; diff --git a/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs b/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs new file mode 100644 index 0000000..6225b0d --- /dev/null +++ b/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs @@ -0,0 +1,89 @@ +using src.common_index; +using src.selfTest; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.selfTest.common_index +{ + internal class CommonIndexTests : ITestClass + { + public IEnumerable<(string TestName, Func Action)> GetTests() + { + yield return ("WriteStreamIndex produces non-empty stream with grouped libraries", async () => + { + IndexView index = new IndexView + { + remote = "https://example.com", + libraries = new Dictionary> + { + { "premake", new List { + new IndexLibrary { name = "premake-core", description = "Core premake functionality" }, + new IndexLibrary { name = "premake-utils" } + }}, + { "community", new List { + new IndexLibrary { name = "imgui" }, + new IndexLibrary { name = "spdlog", description = "Fast logging library" } + }} + } + }; + + Stream stream = CommonIndex.WriteStreamIndex(index); + + if (stream == null) + throw new Exception("Stream is null"); + + if (stream.Length == 0) + throw new Exception("Stream is empty"); + + await Task.CompletedTask; + } + ); + + yield return ("ReadStreamIndex correctly deserializes grouped libraries", async () => + { + string yaml = @" +remote: https://example.com +libraries: + premake: + - name: premake-core + description: Core premake functionality + - name: premake-utils + community: + - name: imgui + - name: spdlog + description: Fast logging library +"; + + using MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(yaml)); + + IndexView index = CommonIndex.ReadStreamIndex(stream); + + if (index == null) + throw new Exception("Deserialized IndexView is null"); + + if (index.remote != "https://example.com") + throw new Exception("Remote value mismatch"); + + if (!index.libraries.ContainsKey("premake") || index.libraries["premake"].Count != 2) + throw new Exception("Premake libraries count mismatch"); + + if (index.libraries["premake"][0].name != "premake-core" || index.libraries["premake"][0].description != "Core premake functionality") + throw new Exception("Premake-core library data mismatch"); + + if (!index.libraries.ContainsKey("community") || index.libraries["community"].Count != 2) + throw new Exception("Community libraries count mismatch"); + + if (index.libraries["community"][1].name != "spdlog" || index.libraries["community"][1].description != "Fast logging library") + throw new Exception("Community spdlog library data mismatch"); + + await Task.CompletedTask; + } + ); + + } + } +} diff --git a/premake-manager-cli/src/selfTest/config/ConfigWriterTests.cs b/premake-manager-cli/src/selfTest/config/ConfigWriterTests.cs deleted file mode 100644 index 220cd14..0000000 --- a/premake-manager-cli/src/selfTest/config/ConfigWriterTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -using src.selfTest; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace src.selfTest.config -{ - internal class ConfigWriterTests : ITestClass - { - public IEnumerable<(string TestName, Func Action)> GetTests() - { - yield return ("Modules non null default constructor",async () => { - var writer = new src.config.ConfigWriter(); - if(writer.modules == null) - { - throw new Exception("Modules cannot be null"); - } - }); - - yield return ("SetVersion", async () => { - var writer = new src.config.ConfigWriter(); - string version = "v5.0.0-beta7"; - writer.SetVersion(version); - if(writer.version != version) - { - throw new Exception($"set version should be equal to {version}"); - } - } - ); - - yield return ("AddModule", async () => { - - var module = new modules.PremakeModule(">=3.3.0", "glfw"); - - var writer = new src.config.ConfigWriter() - .AddModule(module); - if (writer.modules[module.module!].module != module.module && writer.modules[module.module!].version != module.version) - { - throw new Exception($"the added modules parameters should match"); - } - } - ); - - yield return ("Write Config File Test", async () => - { - var tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "selftest_config"); - System.IO.Directory.CreateDirectory(tempPath); - - var writer = new src.config.ConfigWriter() - .SetVersion("1.0.0") - .AddModule(new src.modules.PremakeModule { module = "glfw", version = ">=3.3.0" }); - - await writer.Write(tempPath); - - var filePath = System.IO.Path.Combine(tempPath, "premakeConfig.yml"); - TestRunner.AssertFileExists(filePath); - - System.IO.File.Delete(filePath); - } - ); - } - } -} diff --git a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs index 1db1d09..4931515 100644 --- a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs +++ b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs @@ -1,4 +1,5 @@ -using src.dependencies.graph; +using src.dependencies; +using src.dependencies.graph; using src.dependencies.types; using src.selfTest; using System; @@ -91,7 +92,7 @@ internal class DependencyGraphTests : ITestClass var libraries = new[] { libA1, libA2, libB1, libB2 }; var graph = new DependencyGraph(libraries); - var resolved = graph.GetResolvedLibraries(); // function skips conflicts + var (resolved,conflict) = graph.GetResolvedLibraries(); // function skips conflicts // Check that lib/A is included if (!resolved.Any(l => l.name == "lib/A")) @@ -105,5 +106,37 @@ internal class DependencyGraphTests : ITestClass } ); + yield return ("Versions should be resolved correctly", async () => + { + // Library A: no conflict + var libA1 = new LibraryDependency { name = "KhronosGroup/Vulkan-ValidationLayers", version = ">=1.4.330" }; + var libA2 = new LibraryDependency { name = "KhronosGroup/Vulkan-ValidationLayers", version = "<1.4.332" }; + + var libraries = new[] { libA1, libA2 }; + var graph = new DependencyGraph(libraries); + + var result = await DependenciesManager.GetVersionsFromGraph(graph); + await Task.CompletedTask; + + } + ); + // Test 2: Adding dependencies + yield return ("Add Dependencies with @version should get parent range", async () => + { + var libA = new LibraryDependency { name = "glfw/glfw", version = ">=3.3.0" }; + var libB = new LibraryDependency { name = "vulkan/vulkan", version = "@" }; + var libC = new LibraryDependency { name = "ocornut/imgui", version = "=1.90.0" }; + + var graph = new DependencyGraph(new[] { libA, libB, libC }); + graph.AddDependency(libC, libA); + graph.AddDependency(libC, libB); + + var deps = graph.GetDependencies(libC); + if (deps.ElementAt(1).version != "=1.90.0") + throw new Exception("when dependency version is @ it should be repalced by its parent version"); + + await Task.CompletedTask; + } + ); } } diff --git a/premake-manager-cli/src/selfTest/utils/YamlSerializerTests.cs b/premake-manager-cli/src/selfTest/utils/YamlSerializerTests.cs new file mode 100644 index 0000000..1785cc6 --- /dev/null +++ b/premake-manager-cli/src/selfTest/utils/YamlSerializerTests.cs @@ -0,0 +1,101 @@ +using src.utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.selfTest.utils +{ + internal sealed class TestModel + { + public required string Name { get; set; } + public int Value { get; set; } + } + + internal class YamlSerializerTests : ITestClass + { + public IEnumerable<(string TestName, Func Action)> GetTests() + { + // Test 1: Deserialize known YAML from stream + yield return ("Deserialize known YAML from stream", async () => + { + string yaml = + @"name: test +value: 123 +"; + + byte[] data = System.Text.Encoding.UTF8.GetBytes(yaml); + using MemoryStream stream = new MemoryStream(data); + + TestModel model = YamlSerializer.Deserialize(stream); + + if (model == null) + throw new Exception("Expected non-null model"); + + if (model.Name != "test") + throw new Exception("Incorrect Name value"); + + if (model.Value != 123) + throw new Exception("Incorrect Value value"); + + await Task.CompletedTask; + } + ); + + // Test 2: Serialize produces expected YAML fields + yield return ("Serialize produces expected YAML fields", async () => + { + TestModel model = new TestModel + { + Name = "hello", + Value = 5 + }; + + using Stream stream = YamlSerializer.Serialize(model); + using StreamReader reader = new StreamReader(stream); + + string yaml = reader.ReadToEnd(); + + if (!yaml.Contains("name: hello")) + throw new Exception("Serialized YAML missing name"); + + if (!yaml.Contains("value: 5")) + throw new Exception("Serialized YAML missing value"); + + await Task.CompletedTask; + } + ); + + // Test 3: Deserialize from file + yield return ("Deserialize YAML from file", async () => + { + string yaml = + @"name: file +value: 9 +"; + + string path = Path.Combine(Path.GetTempPath(), "yaml_test.yml"); + File.WriteAllText(path, yaml); + + TestModel model = YamlSerializer.Deserialize(path); + + if (model == null) + throw new Exception("Expected non-null model"); + + if (model.Name != "file") + throw new Exception("Incorrect Name from file"); + + if (model.Value != 9) + throw new Exception("Incorrect Value from file"); + + File.Delete(path); + + await Task.CompletedTask; + } + ); + } + } + +} diff --git a/premake-manager-cli/src/utils/CacheUtils.cs b/premake-manager-cli/src/utils/CacheUtils.cs new file mode 100644 index 0000000..a6ec3d7 --- /dev/null +++ b/premake-manager-cli/src/utils/CacheUtils.cs @@ -0,0 +1,140 @@ +using EasyCaching.Core; +using EasyCaching.Core.Serialization; +using EasyCaching.Disk; +using EasyCaching.Serialization.SystemTextJson; +using Newtonsoft.Json; +using Octokit.Caching; +using Octokit.Internal; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.utils +{ + + + public class NewtonsoftEasyCachingSerializer : IEasyCachingSerializer + { + private readonly JsonSerializerSettings _settings; + + public string Name { get; } + + public NewtonsoftEasyCachingSerializer(string name = "newtonsoft_json", JsonSerializerSettings settings = null) + { + Name = name; + _settings = settings ?? new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Auto, // supports polymorphic types + NullValueHandling = NullValueHandling.Ignore + }; + } + + // Generic serialization + public byte[] Serialize(T value) + { + if (value == null) return Array.Empty(); + string json = JsonConvert.SerializeObject(value, _settings); + return Encoding.UTF8.GetBytes(json); + } + + // Generic deserialization + public T Deserialize(byte[] bytes) + { + if (bytes == null || bytes.Length == 0) return default(T); + string json = Encoding.UTF8.GetString(bytes); + return JsonConvert.DeserializeObject(json, _settings); + } + + // Non-generic deserialization + public object Deserialize(byte[] bytes, Type type) + { + if (bytes == null || bytes.Length == 0) return null; + string json = Encoding.UTF8.GetString(bytes); + return JsonConvert.DeserializeObject(json, type, _settings); + } + + // ArraySegment serialization (for EasyCaching newer versions) + public ArraySegment SerializeObject(object obj) + { + if (obj == null) return new ArraySegment(Array.Empty()); + string json = JsonConvert.SerializeObject(obj, _settings); + byte[] bytes = Encoding.UTF8.GetBytes(json); + return new ArraySegment(bytes); + } + + // ArraySegment deserialization + public object DeserializeObject(ArraySegment value) + { + if (value.Array == null || value.Count == 0) return null; + string json = Encoding.UTF8.GetString(value.Array, value.Offset, value.Count); + return JsonConvert.DeserializeObject(json, _settings); + } + } + + + class CacheProvider : Octokit.Caching.IResponseCache + { + private readonly DefaultDiskCachingProvider _provider; + + public CacheProvider() + { + var serializer = new NewtonsoftEasyCachingSerializer(); + var serializers = new List { serializer }; + + var options = new DiskOptions + { + DBConfig = new DiskDbOptions + { + BasePath = PathUtils.GetCachePath() + }, + SerializerName = "newtonsoft_json" + }; + + _provider = new DefaultDiskCachingProvider("default_disk", serializers, options, null); + } + + public async Task GetAsync(IRequest request) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + + string key = GenerateCacheKey(request); + var cached = await _provider.GetAsync(key); + + if (cached.HasValue) + { + return cached.Value; + } + + return null; + } + + public async Task SetAsync(IRequest request, CachedResponse.V1 cachedResponse) + { + if (request == null) throw new ArgumentNullException(nameof(request)); + if (cachedResponse == null) throw new ArgumentNullException(nameof(cachedResponse)); + + string key = GenerateCacheKey(request); + // Octokit cache doesn't provide expiration info, but you can set one if you want + await _provider.SetAsync(key, cachedResponse, TimeSpan.FromHours(1)); + } + + /// + /// Generates a unique cache key for the request. + /// You can include URL, method, and parameters to avoid collisions. + /// + private string GenerateCacheKey(IRequest request) + { + string endpointString = request.Endpoint?.ToString() ?? string.Empty; + string method = request.Method?.ToString() ?? string.Empty; + + // Include query parameters if present + string query = request.Parameters != null && request.Parameters.Count > 0 + ? string.Join("&", request.Parameters.Select(p => $"{p.Key}={p.Value}")) + : string.Empty; + + return $"octokit_cache:{method}:{endpointString}?{query}"; + } + } +} \ No newline at end of file diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index 1e786e3..64db60c 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -45,20 +45,28 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa ProgressTask downloadTask = ctx.AddTask($"[green]{description}[/]"); downloadTask.StartTask(); + destinationPath = destinationPath.Replace("\\", "/"); - string destinationDir = Path.GetDirectoryName(destinationPath); - if (!Directory.Exists(destinationDir)) + string destinationDir = Path.GetDirectoryName(destinationPath).Replace("\\", "/")!; + if (Directory.Exists(destinationDir) == false) Directory.CreateDirectory(destinationDir); else PathUtils.ClearDirectory(destinationDir); HttpClient httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.ExpectContinue = false;//ensure content length using (HttpResponseMessage response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead)) { + if(response.StatusCode == System.Net.HttpStatusCode.Forbidden) + { + AnsiConsole.MarkupLine("[red]Github Client rate limit reached[/]"); + return; + } + response.EnsureSuccessStatusCode(); - downloadTask.MaxValue = response.Content.Headers.ContentLength!.Value; + downloadTask.MaxValue = (double)(response.Content.Headers.ContentLength ?? -1); using (Stream contentStream = await response.Content.ReadAsStreamAsync(), fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None)) @@ -69,10 +77,16 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { + if(downloadTask.MaxValue == -1) + { + downloadTask.MaxValue = (double)(response.Content.Headers.ContentLength ?? -1); + } await fileStream.WriteAsync(buffer, 0, bytesRead); totalBytesRead += bytesRead; downloadTask.Value += bytesRead; } + /* flush otherwise there can be issues reading later on*/ + await fileStream.FlushAsync(); contentStream.Close(); } } @@ -100,7 +114,7 @@ public static async Task DownloadStatusCtx(StatusContext ctx, string downloadUrl ctx.SpinnerStyle(Style.Parse("green")); destinationPath = destinationPath.Replace("\\", "/"); - string destinationDir = Path.GetDirectoryName(destinationPath); + string destinationDir = Path.GetDirectoryName(destinationPath)!; if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir); else diff --git a/premake-manager-cli/src/utils/ExtractUtils.cs b/premake-manager-cli/src/utils/ExtractUtils.cs index b49b704..715c538 100644 --- a/premake-manager-cli/src/utils/ExtractUtils.cs +++ b/premake-manager-cli/src/utils/ExtractUtils.cs @@ -1,13 +1,14 @@ using Octokit; +using Spectre.Console; using System; using System.Collections.Generic; -using System.IO.Compression; +using System.Formats.Tar; using System.IO; +using System.IO.Compression; using System.Linq; +using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; -using Spectre.Console; -using System.Formats.Tar; #nullable enable namespace src.utils { @@ -137,32 +138,29 @@ public static async Task ExtractZipProgressCtx(ProgressContext ctx, string sourc commonPrefix = firstPrefix + "/"; } } - await Task.Run(() => + + + foreach (var entry in archive.Entries) { - Parallel.ForEach(archive.Entries, entry => - { - if (string.IsNullOrEmpty(entry.Name)) - return; + if (string.IsNullOrEmpty(entry.Name)) + continue; - string relativePath = commonPrefix != null && entry.FullName.StartsWith(commonPrefix) - ? entry.FullName.Substring(commonPrefix.Length) - : entry.FullName; + string relativePath = commonPrefix != null && entry.FullName.StartsWith(commonPrefix) + ? entry.FullName.Substring(commonPrefix.Length) + : entry.FullName; - string destinationPath = Path.Combine(destinationExtractDirectory, relativePath); - string? destinationDir = Path.GetDirectoryName(destinationPath); + string destinationPath = Path.Combine(destinationExtractDirectory, relativePath).Replace("\\", "/"); + string? destinationDir = Path.GetDirectoryName(destinationPath)!.Replace("\\", "/"); - if (!string.IsNullOrEmpty(destinationDir) && !Directory.Exists(destinationDir)) - Directory.CreateDirectory(destinationDir); + if (!string.IsNullOrEmpty(destinationDir) && !Directory.Exists(destinationDir)) + Directory.CreateDirectory(destinationDir); - entry.ExtractToFile(destinationPath, overwrite: true); + entry.ExtractToFile(destinationPath, overwrite: true); - lock (progressLock) - { - extractTask.Value += entry.Length; - } - }); - - }); + + extractTask.Value += entry.Length; + + } } extractTask.StopTask(); @@ -234,5 +232,66 @@ public static async Task ExtractTarGzProgressCtx(ProgressContext ctx, string sou File.Delete(sourcePath); } + public static MemoryStream? ReadFile(string sourcePath, string filePath) + { + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return ReadZipFile(sourcePath, filePath); + return ReadTarGzFile(sourcePath, filePath); + } + private static MemoryStream? ReadTarGzFile(string sourcePath, string filePath) + { + using (FileStream fileStream = File.OpenRead(sourcePath)) + using (GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Decompress)) + using (TarReader tarReader = new TarReader(gzipStream)) + { + TarEntry? entry; + + while ((entry = tarReader.GetNextEntry()) != null) + { + if (entry.EntryType != TarEntryType.RegularFile || !string.Equals(entry.Name, filePath, StringComparison.Ordinal)) + continue; + + + MemoryStream memoryStream = new MemoryStream(); + + using (Stream? entryStream = entry.DataStream) + { + if (entryStream == null) + return null; + + entryStream.CopyTo(memoryStream); + } + + memoryStream.Position = 0; + return memoryStream; + } + } + return null; + } + + + private static MemoryStream? ReadZipFile(string sourcePath, string filePath) + { + if (!Path.Exists(sourcePath)) + return null; + + using (ZipArchive archive = ZipFile.OpenRead(sourcePath)) + { + ZipArchiveEntry? entry = archive.GetEntry(filePath); + + if (entry == null) + return null; + MemoryStream memoryStream = new MemoryStream(); + + using (Stream entryStream = entry.Open()) + { + entryStream.CopyTo(memoryStream); + } + + memoryStream.Position = 0; + return memoryStream; + } + } + } } diff --git a/premake-manager-cli/src/utils/GihtubTypes.cs b/premake-manager-cli/src/utils/GihtubTypes.cs new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/premake-manager-cli/src/utils/GihtubTypes.cs @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/premake-manager-cli/src/utils/PathUtils.cs b/premake-manager-cli/src/utils/PathUtils.cs index ef49078..a84b59d 100644 --- a/premake-manager-cli/src/utils/PathUtils.cs +++ b/premake-manager-cli/src/utils/PathUtils.cs @@ -1,4 +1,5 @@ using Octokit; +using src.libraries; using System; using System.Collections.Generic; using System.IO; @@ -47,6 +48,29 @@ public static string GetTempModulePath(string moduleName) { return Path.Combine(GetTempPath(), moduleName); } + public static string GetRemotesPath() + { + return Path.Combine(GetRoamingPath(), "remotes"); + } + + public static string GetCachePath() + { + return Path.Combine(GetRoamingPath(), "cache"); + } + /// + /// returns the Remote path for the given remote (owner,repo) with .zip or tar.gz path + /// + /// + /// + /// + public static string GetRemotePath(string owner,string repo) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return Path.Combine(GetRemotesPath(), $"{owner}-{repo}.zip"); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + return Path.Combine(GetRemotesPath(), $"{owner}-{repo}.tar.gz"); + return string.Empty; + } public static void ClearDirectory(string path) { try @@ -66,5 +90,17 @@ public static void ClearDirectory(string path) catch (Exception) { /*ignore*/ } } + + public static void EnsureExists(string path) + { + + if(!Directory.Exists(Path.GetDirectoryName(path)) && Path.GetDirectoryName(path) != string.Empty) + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + } + public static void CreateEmpty(string path) + { + EnsureExists(path); + File.Create(path); + } } } diff --git a/premake-manager-cli/src/utils/PremakeSystem.cs b/premake-manager-cli/src/utils/PremakeSystem.cs index c043a23..06b446e 100644 --- a/premake-manager-cli/src/utils/PremakeSystem.cs +++ b/premake-manager-cli/src/utils/PremakeSystem.cs @@ -1,4 +1,6 @@ using src.config; +using src.libraries; +using src.modules; using System; using System.Collections.Generic; using System.IO; @@ -14,36 +16,65 @@ namespace src.utils internal class PremakeSystemWriter { static IList content = new List(); - public static void Write(ConfigReader config) + public static void Write(Config config, PremakeLibrary[] libraries, PremakeModule[] modules) { + File.Delete("premake-system.lua"); AddDisclaimer(); - AddPath(config.modulesPath,"modules"); - AddPath(config.librariesPath,"libraries"); - foreach (var item in config.modules) - { - AddModule(item.Value.entryPoint ?? item.Key); - } - try - { - File.Delete("premake-system.lua"); - } - catch (Exception) - { - - } + AddPath(config.ModulesPath,"modules"); + AddPath(config.LibrariesPath,"libraries"); + AddLibs(libraries); + AddModules(modules); File.WriteAllText("premake-system.lua", string.Join("\n", content)); } static void AddDisclaimer() { content.Add("---WARNING this file was generated by premake-manager-cli!!!\n---change at your own risk!"); } - static void AddPath(string path, string defaultPath) + static void AddPath(string? path, string defaultPath) { content.Add($"premake.path = premake.path..\";\"..path.join(_MAIN_SCRIPT_DIR, \"{(string.IsNullOrEmpty(path) ? defaultPath : path)}\")"); } - static void AddModule(string entryPoint) + static void AddLibs(PremakeLibrary[] libraries) + { + AddLibsStart(); + foreach (var lib in libraries) + { + AddLib(lib); + } + content.Add(" list = function() local c=0 for _,d in pairs(Libraries) do if type(d)=='table' then c=c+1 end end print('--- Libraries ('..c..') ---') for n,d in pairs(Libraries) do if type(d)=='table' then print(n..' version: '..d.version) end end print('----------------------- \\n') end,"); AddLibsEnd(); + } + static void AddModules(PremakeModule[] modules) + { + AddModulesStart(); + foreach (var module in modules) + { + AddModule(module); + } + content.Add(" list = function() local c=0 for _,d in pairs(Modules) do if type(d)=='table' then c=c+1 end end print('--- Modules ('..c..') ---') for n,d in pairs(Modules) do if type(d)=='table' then print(n..' version: '..d.version) end end print('-----------------------\\n') end,"); AddModulesEnd(); + } + static void AddLibsStart() + { + content.Add($"\n---LIBRARIES---\n_G.Libraries =\n{{"); + } + static void AddLib(PremakeLibrary lib) + { + content.Add($" [\"{lib.library.Split('/')[1]}\"] = {{ version = \"{lib.version}\" }},"); + } + static void AddLibsEnd() + { + content.Add($"}}"); + } + static void AddModulesStart() + { + content.Add($"\n---MODULES---\n_G.Modules =\n{{"); + } + static void AddModule(PremakeModule mod) + { + content.Add($" [\"{mod.module}\"] = {{ version = \"{mod.version}\" }},"); + } + static void AddModulesEnd() { - content.Add($"require \"{entryPoint}\""); + content.Add($"}}"); } } } diff --git a/premake-manager-cli/src/utils/YamlSerializer.cs b/premake-manager-cli/src/utils/YamlSerializer.cs new file mode 100644 index 0000000..fda3b81 --- /dev/null +++ b/premake-manager-cli/src/utils/YamlSerializer.cs @@ -0,0 +1,94 @@ +using Octokit; +using src.common_index; +using System; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using YamlDotNet.RepresentationModel; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; + + +namespace src.utils +{ + + internal static class YamlSerializer + { + private static readonly IDeserializer Deserializer; + private static readonly ISerializer Serializer; + + static YamlSerializer() + { + Deserializer = new DeserializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .IgnoreUnmatchedProperties() + .Build(); + + Serializer = new SerializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) + .Build(); + } + public static T Deserialize(string filePath) + { + using FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read); + return Deserialize(stream); + } + + public static async Task Deserialize(string owner, string repo, string filePath) + { + string url = "https://raw.githubusercontent.com/" + owner + "/" + repo + "/master/" + $"{filePath}"; + + using HttpClient client = new HttpClient(); + HttpResponseMessage response = await client.GetAsync(url); + + response.EnsureSuccessStatusCode(); + + using Stream stream = await response.Content.ReadAsStreamAsync(); + return Deserialize(stream); + } + + public static T Deserialize(string sourcePath, string filePath) + { + MemoryStream? compressedStream = ExtractUtils.ReadFile(sourcePath, filePath); + if (compressedStream == null) + throw new ArgumentNullException(nameof(compressedStream)); + return Deserialize(compressedStream); + } + + public static T Deserialize(Stream yamlStream) + { + if (yamlStream == null) + { + throw new ArgumentNullException(nameof(yamlStream)); + } + + using (StreamReader reader = new StreamReader(yamlStream, leaveOpen: true)) + { + return Deserializer.Deserialize(reader); + } + } + + public static Stream Serialize(T value) + { + + Stream stream = new MemoryStream(); + using (StreamWriter writer = new StreamWriter(stream, leaveOpen: true)) + { + Serializer.Serialize(writer, value); + writer.Flush(); + stream.Position = 0; + } + return stream; + } + + public static void Serialize(T value, string filePath) + { + filePath = Path.ChangeExtension(filePath, ".yml"); + PathUtils.EnsureExists(filePath); + using FileStream fileStream = new FileStream(filePath, System.IO.FileMode.Create, FileAccess.Write, FileShare.None); + Serialize(value).CopyTo(fileStream); + } + } + +} diff --git a/premake-manager-cli/src/version/VersionManager.cs b/premake-manager-cli/src/version/VersionManager.cs index b3cf332..932dba9 100644 --- a/premake-manager-cli/src/version/VersionManager.cs +++ b/premake-manager-cli/src/version/VersionManager.cs @@ -91,16 +91,19 @@ await AnsiConsole.Progress().Columns(new ProgressColumn[] return true; } #endregion - public static async Task SetVersion(string tagName) + + public static async Task SetVersion(string tagName) { Release? release = await GetVersion(tagName); string path = PathUtils.GetReleasePath(release!); AddPremakeToPath(path); - ConfigReader reader = new ConfigReader(); - ConfigWriter configWriter = ConfigWriter.FromReader(reader); - configWriter.SetVersion(tagName); + + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + config.Version = tagName; + ConfigManager.WriteConfig(config, null); return true; } + private static string GetPlatformIdentifier() { // Identify the current platform @@ -116,6 +119,7 @@ private static string GetPlatformIdentifier() return "unknown"; } } + #region LOCAL_VERSION_PATHS #endregion diff --git a/premake-system.lua b/premake-system.lua new file mode 100644 index 0000000..f812708 --- /dev/null +++ b/premake-system.lua @@ -0,0 +1,4 @@ +---WARNING this file was generated by premake-manager-cli!!! +---change at your own risk! +premake.path = premake.path..";"..path.join(_MAIN_SCRIPT_DIR, "modules") +premake.path = premake.path..";"..path.join(_MAIN_SCRIPT_DIR, "libraries") \ No newline at end of file diff --git a/premake5.lua b/premake5.lua index 3d09c2d..615af4d 100644 --- a/premake5.lua +++ b/premake5.lua @@ -1,28 +1,18 @@ require "vstudio" -function platformsElement(cfg) - _p(2,'x64') -end - -premake.override(premake.vstudio.cs2005.elements, "projectProperties", function (oldfn, cfg) - return table.join(oldfn(cfg), { - platformsElement, - }) -end) - workspace "premake-manager-cli" -architecture "x64" +architecture "x86_64" configurations { "Debug", "Release" } startproject "premake-manager-cli" project "premake-manager-cli" kind "ConsoleApp" -- CLI application - dotnetframework "net9.0" -- Targeting .NET 9.0 + dotnetframework "net10.0" -- Targeting .NET 9.0 location "premake-manager-cli" language "C#" targetdir "bin/%{cfg.buildcfg}" files { "%{prj.name}/src/**.cs" } -- Include all C# source files - nuget { "Spectre.Console:0.50.0", "Spectre.Console.Cli:0.50.0", "Octokit:14.0.0", "YamlDotNet:16.3.0", "StreamJsonRpc:2.22.11" } + nuget { "Spectre.Console:0.50.0", "Spectre.Console.Cli:0.50.0", "Octokit:14.0.0", "YamlDotNet:16.3.0", "StreamJsonRpc:2.22.11","Semver:3.0.0","EasyCaching.Disk:1.9.2","EasyCaching.Serialization.Json:1.9.2", "EasyCaching.Serialization.SystemTextJson:1.9.2" } vsprops { PublishSingleFile = "true", SelfContained = "true", diff --git a/premakeConfig.yml b/premakeConfig.yml new file mode 100644 index 0000000..497ed78 --- /dev/null +++ b/premakeConfig.yml @@ -0,0 +1,5 @@ +version: v5.0.0-beta7 +modulesPath: +librariesPath: +modules: {} +libraries: {}