From bd7e495a7ceb2e33f95161ffba61cc73134961af Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Thu, 18 Dec 2025 19:46:07 +0100 Subject: [PATCH 01/28] feat: common index --- .../src/common-index/CommonCommand.cs | 17 ++++ .../src/common-index/CommonIndex.cs | 93 +++++++++++++++++++ .../src/common-index/IndexView.cs | 26 ++++++ premake-manager-cli/src/selfTest/SelfTest.cs | 4 +- .../selfTest/common-index/CommonIndexTests.cs | 89 ++++++++++++++++++ 5 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 premake-manager-cli/src/common-index/CommonCommand.cs create mode 100644 premake-manager-cli/src/common-index/CommonIndex.cs create mode 100644 premake-manager-cli/src/common-index/IndexView.cs create mode 100644 premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs 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..aa3a5da --- /dev/null +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -0,0 +1,17 @@ +using Spectre.Console.Cli; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace src.common_index +{ + internal class CommonIndexCommand : AsyncCommand + { + public override Task ExecuteAsync(CommandContext context) + { + throw new NotImplementedException(); + } + } +} 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..b635529 --- /dev/null +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -0,0 +1,93 @@ +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) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + + + IDeserializer deserializer = new DeserializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .IgnoreUnmatchedProperties() + .Build(); + + using StreamReader reader = new StreamReader(stream, leaveOpen: true); + + IndexView indexView = deserializer.Deserialize(reader); + + if (indexView == null) + throw new InvalidDataException("Failed to deserialize IndexView from stream."); + + return indexView; + } + public static Stream WriteStreamIndex(IndexView index) + { + ISerializer serializer = new SerializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .Build(); + + MemoryStream stream = new MemoryStream(); + StreamWriter writer = new StreamWriter(stream); + + serializer.Serialize(writer, index); + writer.Flush(); + stream.Position = 0; + + return stream; + } + #endregion + + #region FILE + public static IndexView ReadFileIndex(string filePath) + { + using FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + return ReadStreamIndex(stream); + } + + public static void WriteFileIndex(IndexView index, string filePath) + { + using Stream stream = WriteStreamIndex(index); + using FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); + stream.CopyTo(fileStream); + } + + #endregion + #region REMOTE + public static IndexView ReadRemoteIndex(string owner, string repo) + { + string url = "https://raw.githubusercontent.com/" + owner + "/" + repo + "/master/premakeIndex.yml"; + + using HttpClient client = new HttpClient(); + HttpResponseMessage response = client.GetAsync(url).Result; + + response.EnsureSuccessStatusCode(); + + using Stream stream = response.Content.ReadAsStreamAsync().Result; + return ReadStreamIndex(stream); + } + + #endregion + public static IndexView CreateNew(string remoteName) + { + return new IndexView() + { + remote = remoteName, + libraries = new Dictionary>() + }; + } + } +} 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..cd164fb --- /dev/null +++ b/premake-manager-cli/src/common-index/IndexView.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using YamlDotNet.Serialization; + +namespace src.common_index +{ + internal class IndexLibrary + { + public string? description { get; set; } + public required string name { get; set; } + } + /// + /// Representation of the common-index yaml + /// + [YamlSerializable] + internal class IndexView + { + [YamlMember] + public required string remote { get; set; } + [YamlMember] + public required IDictionary> libraries; + } +} diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 9190bd3..2fccab5 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -1,6 +1,7 @@ using Spectre.Console; using Spectre.Console.Cli; using src.selfTest; +using src.selfTest.common_index; using src.selfTest.config; using src.selfTest.version; using System.ComponentModel; @@ -17,7 +18,7 @@ public async override Task ExecuteAsync(CommandContext context) runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); - + runner.AddTestClass(); await runner.RunAllAsync(); return 0; } @@ -40,6 +41,7 @@ public async override Task ExecuteAsync(CommandContext context, Settings se 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..ce2b403 --- /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; + } + ); + + } + } +} From 027b82931280e36a4ec59e38e8d474563c364c9d Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Fri, 19 Dec 2025 04:02:12 +0100 Subject: [PATCH 02/28] refactor: move code to new YamlSerializer to improve reuasabilty and safety/ maintainabilty --- .../src/common-index/CommonCommand.cs | 48 ++++++- .../src/common-index/CommonIndex.cs | 51 +------ .../src/common-index/IndexView.cs | 4 +- premake-manager-cli/src/config/Config.cs | 103 ++++++++++++++ .../src/config/ConfigCommand.cs | 74 +++++----- .../src/config/ConfigManager.cs | 38 +++++ .../src/config/ConfigReader.cs | 61 -------- .../src/config/ConfigWriter.cs | 133 ------------------ .../src/dependencies/DependenciesManager.cs | 24 ++++ .../src/dependencies/DependenciesReader.cs | 44 ------ .../src/dependencies/DependenciesWriter.cs | 13 -- .../src/libraries/LibraryCommand.cs | 36 +++-- .../src/libraries/LibraryManager.cs | 10 +- premake-manager-cli/src/main.cs | 4 + .../src/modules/ModuleCommand.cs | 40 ++++-- premake-manager-cli/src/selfTest/SelfTest.cs | 3 - .../src/selfTest/config/ConfigWriterTests.cs | 65 --------- .../src/utils/PremakeSystem.cs | 29 ++-- .../src/utils/YamlSerializer.cs | 82 +++++++++++ .../src/version/VersionManager.cs | 7 +- 20 files changed, 418 insertions(+), 451 deletions(-) create mode 100644 premake-manager-cli/src/config/Config.cs create mode 100644 premake-manager-cli/src/config/ConfigManager.cs delete mode 100644 premake-manager-cli/src/config/ConfigReader.cs delete mode 100644 premake-manager-cli/src/config/ConfigWriter.cs create mode 100644 premake-manager-cli/src/dependencies/DependenciesManager.cs delete mode 100644 premake-manager-cli/src/dependencies/DependenciesReader.cs delete mode 100644 premake-manager-cli/src/dependencies/DependenciesWriter.cs delete mode 100644 premake-manager-cli/src/selfTest/config/ConfigWriterTests.cs create mode 100644 premake-manager-cli/src/utils/YamlSerializer.cs diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index aa3a5da..2f36745 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -1,17 +1,57 @@ -using Spectre.Console.Cli; +using Spectre.Console; +using Spectre.Console.Cli; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace src.common_index { - internal class CommonIndexCommand : AsyncCommand + /// + /// Command to create a new index + /// + internal class CommonIndexCommand : AsyncCommand { - public override Task ExecuteAsync(CommandContext context) + internal class Settings : CommandSettings { - throw new NotImplementedException(); + [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); } } } diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index b635529..cf7be81 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -1,4 +1,5 @@ -using System; +using src.utils; +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -16,68 +17,30 @@ internal class CommonIndex #region STREAM public static IndexView ReadStreamIndex(Stream stream) { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - - IDeserializer deserializer = new DeserializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .IgnoreUnmatchedProperties() - .Build(); - - using StreamReader reader = new StreamReader(stream, leaveOpen: true); - - IndexView indexView = deserializer.Deserialize(reader); - - if (indexView == null) - throw new InvalidDataException("Failed to deserialize IndexView from stream."); - - return indexView; + return YamlSerializer.Deserialize(stream); } public static Stream WriteStreamIndex(IndexView index) { - ISerializer serializer = new SerializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .Build(); - - MemoryStream stream = new MemoryStream(); - StreamWriter writer = new StreamWriter(stream); - - serializer.Serialize(writer, index); - writer.Flush(); - stream.Position = 0; - - return stream; + return YamlSerializer.Serialize(index); } #endregion #region FILE public static IndexView ReadFileIndex(string filePath) { - using FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); - return ReadStreamIndex(stream); + return YamlSerializer.Deserialize(filePath); } public static void WriteFileIndex(IndexView index, string filePath) { - using Stream stream = WriteStreamIndex(index); - using FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); - stream.CopyTo(fileStream); + YamlSerializer.Serialize(index, filePath); } #endregion #region REMOTE public static IndexView ReadRemoteIndex(string owner, string repo) { - string url = "https://raw.githubusercontent.com/" + owner + "/" + repo + "/master/premakeIndex.yml"; - - using HttpClient client = new HttpClient(); - HttpResponseMessage response = client.GetAsync(url).Result; - - response.EnsureSuccessStatusCode(); - - using Stream stream = response.Content.ReadAsStreamAsync().Result; - return ReadStreamIndex(stream); + return YamlSerializer.Deserialize(owner, repo, "premakeIndex.yml"); } #endregion diff --git a/premake-manager-cli/src/common-index/IndexView.cs b/premake-manager-cli/src/common-index/IndexView.cs index cd164fb..5dfff50 100644 --- a/premake-manager-cli/src/common-index/IndexView.cs +++ b/premake-manager-cli/src/common-index/IndexView.cs @@ -18,9 +18,9 @@ internal class IndexLibrary [YamlSerializable] internal class IndexView { - [YamlMember] + [YamlMember(Order = 0)] public required string remote { get; set; } - [YamlMember] + [YamlMember(Order = 1)] public required IDictionary> libraries; } } diff --git a/premake-manager-cli/src/config/Config.cs b/premake-manager-cli/src/config/Config.cs new file mode 100644 index 0000000..5d229c6 --- /dev/null +++ b/premake-manager-cli/src/config/Config.cs @@ -0,0 +1,103 @@ +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 + { + [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; set; } + + [YamlMember(Alias = "libraries")] + public IDictionary? Libraries { get; set; } + + + /// + /// 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..3b85b05 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -18,10 +18,12 @@ internal class ConfigCommand : AsyncCommand { public async override Task ExecuteAsync(CommandContext context) { - ConfigReader config = new ConfigReader(); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + //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) + await ModuleManager.InstallModules(config.Modules.Values.ToList()); return 0; } } @@ -32,15 +34,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 +50,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 +60,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,7 +73,7 @@ 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() .AddColumn("Owner") @@ -79,32 +81,36 @@ public async override Task ExecuteAsync(CommandContext context) mainTable.Border = TableBorder.Rounded; mainTable.ShowRowSeparators = true; - var groupedModules = config.modules - .GroupBy(m => m.Value.owner) - .OrderBy(g => g.Key); - - foreach (var group in groupedModules) + if (config.Modules != null) { + var groupedModules = config.Modules + .GroupBy(m => m.Value.owner) + .OrderBy(g => g.Key); - // 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 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$ - foreach (var module in group) - { - subTable.AddRow($"[link=https://github.com/{group.Key}/{module.Value.repo}] {module.Value.repo}[/]", module.Value.version); - } - - // 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); + foreach (var module in group) + { + subTable.AddRow($"[link=https://github.com/{group.Key}/{module.Value.repo}] {module.Value.repo}[/]", module.Value.version); + } + + + // 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 + } - 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..a35d6ee --- /dev/null +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -0,0 +1,24 @@ +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; +//TODO USE STREAMS => can be tested +namespace src.dependencies +{ + [YamlSerializable] + internal class Dependencies + { + [YamlMember] + IList? libraries; + } + internal class DependenciesManager + { + + + } +} 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/libraries/LibraryCommand.cs b/premake-manager-cli/src/libraries/LibraryCommand.cs index 1b1aa03..fea9269 100644 --- a/premake-manager-cli/src/libraries/LibraryCommand.cs +++ b/premake-manager-cli/src/libraries/LibraryCommand.cs @@ -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; } } @@ -117,15 +120,20 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not { 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 +153,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..d690b7b 100644 --- a/premake-manager-cli/src/libraries/LibraryManager.cs +++ b/premake-manager-cli/src/libraries/LibraryManager.cs @@ -80,7 +80,8 @@ 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(""); + Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); + if (!githubLink.StartsWith("https://github.com/")) { string[] repoInfo = githubLink.Split('/'); @@ -90,14 +91,15 @@ 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"), $"{config.LibrariesPath}/{repo.name}", $"extracting {libconfig.name}"); } + [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) diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 54d76b7..edee5ee 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -92,6 +92,10 @@ 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"); + }); }); 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/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 2fccab5..bad45b2 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -2,7 +2,6 @@ using Spectre.Console.Cli; using src.selfTest; using src.selfTest.common_index; -using src.selfTest.config; using src.selfTest.version; using System.ComponentModel; using System.Threading.Tasks; @@ -16,7 +15,6 @@ public async override Task ExecuteAsync(CommandContext context) // Register all test classes runner.AddTestClass(); - runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); await runner.RunAllAsync(); @@ -39,7 +37,6 @@ public async override Task ExecuteAsync(CommandContext context, Settings se // Register all test classes runner.AddTestClass(); - runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); 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/utils/PremakeSystem.cs b/premake-manager-cli/src/utils/PremakeSystem.cs index c043a23..b8e7ebb 100644 --- a/premake-manager-cli/src/utils/PremakeSystem.cs +++ b/premake-manager-cli/src/utils/PremakeSystem.cs @@ -14,22 +14,25 @@ namespace src.utils internal class PremakeSystemWriter { static IList content = new List(); - public static void Write(ConfigReader config) + public static void Write(Config config) { 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"); + if (config.Modules != null) { + foreach (var item in config.Modules) + { + AddModule(item.Value.entryPoint ?? item.Key); + } + try + { + File.Delete("premake-system.lua"); + } + catch (Exception) + { + } } File.WriteAllText("premake-system.lua", string.Join("\n", content)); } @@ -37,7 +40,7 @@ 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)}\")"); } diff --git a/premake-manager-cli/src/utils/YamlSerializer.cs b/premake-manager-cli/src/utils/YamlSerializer.cs new file mode 100644 index 0000000..6e77089 --- /dev/null +++ b/premake-manager-cli/src/utils/YamlSerializer.cs @@ -0,0 +1,82 @@ +using Octokit; +using src.common_index; +using System; +using System.IO; +using System.Net.Http; +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 T Deserialize(string owner, string repo, string filePath) + { + string url = "https://raw.githubusercontent.com/" + owner + "/" + repo + "/master/" + $"{filePath}"; + + using HttpClient client = new HttpClient(); + HttpResponseMessage response = client.GetAsync(url).Result; + + response.EnsureSuccessStatusCode(); + + using Stream stream = response.Content.ReadAsStreamAsync().Result; + return Deserialize(stream); + } + 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) + { + + 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..a4c13c6 100644 --- a/premake-manager-cli/src/version/VersionManager.cs +++ b/premake-manager-cli/src/version/VersionManager.cs @@ -96,9 +96,10 @@ 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() From 2bec0e0f172b2bf1bb9490cb00f90368d0055e8e Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Fri, 19 Dec 2025 19:40:30 +0100 Subject: [PATCH 03/28] feat: added serializer tests --- premake-manager-cli/src/selfTest/SelfTest.cs | 4 + .../src/selfTest/utils/YamlSerializerTests.cs | 101 ++++++++++++++++++ premake-system.lua | 4 + 3 files changed, 109 insertions(+) create mode 100644 premake-manager-cli/src/selfTest/utils/YamlSerializerTests.cs create mode 100644 premake-system.lua diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index bad45b2..5d701e5 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -2,6 +2,7 @@ using Spectre.Console.Cli; using src.selfTest; using src.selfTest.common_index; +using src.selfTest.utils; using src.selfTest.version; using System.ComponentModel; using System.Threading.Tasks; @@ -17,6 +18,8 @@ public async override Task ExecuteAsync(CommandContext context) runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); + runner.AddTestClass(); + await runner.RunAllAsync(); return 0; } @@ -39,6 +42,7 @@ public async override Task ExecuteAsync(CommandContext context, Settings se 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/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-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 From 8a7c72f2db55ac1b748620b65b8d0f962f0a86c1 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Sun, 21 Dec 2025 17:21:05 +0100 Subject: [PATCH 04/28] feat: index lib creation --- .../src/common-index/CommonCommand.cs | 48 +++++++++++++++++++ .../src/common-index/CommonIndex.cs | 30 +++++++++++- .../src/common-index/IndexView.cs | 6 ++- premake-manager-cli/src/main.cs | 4 ++ premake-manager-cli/src/utils/PathUtils.cs | 12 +++++ .../src/utils/YamlSerializer.cs | 3 +- 6 files changed, 99 insertions(+), 4 deletions(-) diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index 2f36745..594672d 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -3,6 +3,8 @@ 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; @@ -54,4 +56,50 @@ public override Task ExecuteAsync(CommandContext context, Settings settings 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!); + 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; } + } + } } diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index cf7be81..b778fa0 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -1,4 +1,6 @@ -using src.utils; +using Spectre.Console; +using src.libraries; +using src.utils; using System; using System.Collections.Generic; using System.IO; @@ -26,7 +28,7 @@ public static Stream WriteStreamIndex(IndexView index) #endregion #region FILE - public static IndexView ReadFileIndex(string filePath) + public static IndexView ReadFileIndex(string filePath = "premakeIndex.yml") { return YamlSerializer.Deserialize(filePath); } @@ -37,6 +39,7 @@ public static void WriteFileIndex(IndexView index, string filePath) } #endregion + #region REMOTE public static IndexView ReadRemoteIndex(string owner, string repo) { @@ -52,5 +55,28 @@ public static IndexView CreateNew(string 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); + } + 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")); + } } } diff --git a/premake-manager-cli/src/common-index/IndexView.cs b/premake-manager-cli/src/common-index/IndexView.cs index 5dfff50..6a37fdd 100644 --- a/premake-manager-cli/src/common-index/IndexView.cs +++ b/premake-manager-cli/src/common-index/IndexView.cs @@ -7,10 +7,14 @@ 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; } - public required string name { get; set; } + } /// /// Representation of the common-index yaml diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index edee5ee..228aae8 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -95,6 +95,10 @@ static async Task Main(string[] args) config.AddBranch("index", branch => { branch.SetDescription("All commands for managing the common index"); branch.AddCommand("new"); + + branch.AddBranch("add", branch => { + branch.AddCommand("library"); + }); }); }); diff --git a/premake-manager-cli/src/utils/PathUtils.cs b/premake-manager-cli/src/utils/PathUtils.cs index ef49078..142ac09 100644 --- a/premake-manager-cli/src/utils/PathUtils.cs +++ b/premake-manager-cli/src/utils/PathUtils.cs @@ -66,5 +66,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/YamlSerializer.cs b/premake-manager-cli/src/utils/YamlSerializer.cs index 6e77089..c963df3 100644 --- a/premake-manager-cli/src/utils/YamlSerializer.cs +++ b/premake-manager-cli/src/utils/YamlSerializer.cs @@ -73,7 +73,8 @@ public static Stream Serialize(T value) 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); } From f802cc8f336ac565f48de7f1a07e89144da5d7d9 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Mon, 22 Dec 2025 22:42:46 +0100 Subject: [PATCH 05/28] feat: intermediate --- premake-manager-cli/src/utils/ExtractUtils.cs | 68 ++++++++++++++++++- .../src/utils/YamlSerializer.cs | 10 +++ 2 files changed, 75 insertions(+), 3 deletions(-) diff --git a/premake-manager-cli/src/utils/ExtractUtils.cs b/premake-manager-cli/src/utils/ExtractUtils.cs index b49b704..e95d8d1 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 { @@ -234,5 +235,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/YamlSerializer.cs b/premake-manager-cli/src/utils/YamlSerializer.cs index c963df3..40052e0 100644 --- a/premake-manager-cli/src/utils/YamlSerializer.cs +++ b/premake-manager-cli/src/utils/YamlSerializer.cs @@ -3,6 +3,7 @@ using System; using System.IO; using System.Net.Http; +using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -45,6 +46,15 @@ public static T Deserialize(string owner, string repo, string filePath) using Stream stream = response.Content.ReadAsStreamAsync().Result; 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) From 3c26b3f35466072fa7c6eef9c437db4b9bd77902 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Mon, 22 Dec 2025 23:24:33 +0100 Subject: [PATCH 06/28] feat: started work on the remotes --- .../src/common-index/CommonIndex.cs | 5 +- .../src/common-index/RemotesManager.cs | 55 +++++++++++++++++++ premake-manager-cli/src/utils/PathUtils.cs | 4 ++ .../src/version/VersionManager.cs | 3 + 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 premake-manager-cli/src/common-index/RemotesManager.cs diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index b778fa0..0754970 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -45,7 +45,10 @@ public static IndexView ReadRemoteIndex(string owner, string repo) { return YamlSerializer.Deserialize(owner, repo, "premakeIndex.yml"); } - + public static IndexView ReadRemoteLocalIndex(string owner, string repo) + { + return ExtractUtils.Read + } #endregion public static IndexView CreateNew(string remoteName) { 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..c06c91b --- /dev/null +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -0,0 +1,55 @@ +using src.utils; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using YamlDotNet.Serialization; + +namespace src.common_index +{ + [YamlSerializable] + internal sealed class Remote + { + [YamlMember(Alias ="owner", Description = "the repo owner", Order = 0)] + public required string Owner { get; set; } + [YamlMember(Alias = "repo", Description = "the repo name", Order = 1)] + public required string Repo { get; set; } + [YamlMember(Alias = "enabled", Description = "should the remote be used", Order = 2)] + public required bool Enabled { get; set; } + } + internal sealed class Remotes + { + internal 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 = "lolrobbe", Repo = "premake-common-registry", Enabled = true }; + private static Remote[] Remotes { get => GetRemotes(); } + static void Intialize() + { + + } + + private static Remote[] GetRemotes() { + string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yaml"); + if (Path.Exists(RemotePaths)) + { + return YamlSerializer.Deserialize(RemotePaths).remotes; + } + return [DefaultRemote]; + } + + private static RemoteIndex[] GetRemoteIndices() + { + Remotes.Select((remote)=> new RemoteIndex() { Remote = remote , Index = CommonIndex.ReadRemoteIndex()}).ToList(); + } + } +} diff --git a/premake-manager-cli/src/utils/PathUtils.cs b/premake-manager-cli/src/utils/PathUtils.cs index 142ac09..7cbb2eb 100644 --- a/premake-manager-cli/src/utils/PathUtils.cs +++ b/premake-manager-cli/src/utils/PathUtils.cs @@ -66,6 +66,10 @@ public static void ClearDirectory(string path) catch (Exception) { /*ignore*/ } } + public string GetRemotesPath() + { + return Path.Combine(GetRoamingPath(), "remotes"); + } public static void EnsureExists(string path) { diff --git a/premake-manager-cli/src/version/VersionManager.cs b/premake-manager-cli/src/version/VersionManager.cs index a4c13c6..0c29f1c 100644 --- a/premake-manager-cli/src/version/VersionManager.cs +++ b/premake-manager-cli/src/version/VersionManager.cs @@ -91,6 +91,7 @@ await AnsiConsole.Progress().Columns(new ProgressColumn[] return true; } #endregion + public static async Task SetVersion(string tagName) { Release? release = await GetVersion(tagName); @@ -102,6 +103,7 @@ public static async Task SetVersion(string tagName) ConfigManager.WriteConfig(config, null); return true; } + private static string GetPlatformIdentifier() { // Identify the current platform @@ -117,6 +119,7 @@ private static string GetPlatformIdentifier() return "unknown"; } } + #region LOCAL_VERSION_PATHS #endregion From e6c261705325deb3526dbb25d6072fc6cabe083d Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Sun, 28 Dec 2025 19:48:18 +0100 Subject: [PATCH 07/28] feat: installing/ adding remotes works --- .../src/common-index/CommonIndex.cs | 2 +- .../src/common-index/RemotesCommand.cs | 120 ++++++++++++++++ .../src/common-index/RemotesManager.cs | 128 ++++++++++++++++-- premake-manager-cli/src/main.cs | 7 + .../src/utils/DownloadUtils.cs | 4 +- premake-manager-cli/src/utils/PathUtils.cs | 22 ++- 6 files changed, 263 insertions(+), 20 deletions(-) create mode 100644 premake-manager-cli/src/common-index/RemotesCommand.cs diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index 0754970..b54cc67 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -47,7 +47,7 @@ public static IndexView ReadRemoteIndex(string owner, string repo) } public static IndexView ReadRemoteLocalIndex(string owner, string repo) { - return ExtractUtils.Read + return YamlSerializer.Deserialize(ExtractUtils.ReadFile(PathUtils.GetRemotePath(owner, repo), "premakeIndex.yml")!); } #endregion public static IndexView CreateNew(string remoteName) 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..2390d5b --- /dev/null +++ b/premake-manager-cli/src/common-index/RemotesCommand.cs @@ -0,0 +1,120 @@ +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 +{ + /// + /// 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); + } + } + + 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; } + } + } + + 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; } + } + } +} diff --git a/premake-manager-cli/src/common-index/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs index c06c91b..98da7b4 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -1,27 +1,37 @@ 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", Description = "the repo owner", Order = 0)] + [YamlMember(Alias ="owner", Order = 0)] public required string Owner { get; set; } - [YamlMember(Alias = "repo", Description = "the repo name", Order = 1)] + [YamlMember(Alias = "repo", Order = 1)] public required string Repo { get; set; } - [YamlMember(Alias = "enabled", Description = "should the remote be used", Order = 2)] + [YamlMember(Alias = "enabled", Order = 2)] public required bool Enabled { get; set; } } + /// + /// Class representation for the remotes + /// + [YamlSerializable] internal sealed class Remotes { - internal required Remote[] remotes {get; set;} + [YamlMember(Alias = "remotes", Order = 0)] + public required Remote[] remotes {get; set;} } internal sealed class RemoteIndex @@ -31,15 +41,14 @@ internal sealed class RemoteIndex } internal class RemotesManager { - private static readonly Remote DefaultRemote = new Remote() { Owner = "lolrobbe", Repo = "premake-common-registry", Enabled = true }; - private static Remote[] Remotes { get => GetRemotes(); } - static void Intialize() - { - - } + 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.yaml"); + private static Remote[] GetRemotes() + { + string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yml"); if (Path.Exists(RemotePaths)) { return YamlSerializer.Deserialize(RemotePaths).remotes; @@ -49,7 +58,100 @@ private static Remote[] GetRemotes() { private static RemoteIndex[] GetRemoteIndices() { - Remotes.Select((remote)=> new RemoteIndex() { Remote = remote , Index = CommonIndex.ReadRemoteIndex()}).ToList(); + 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); + } + + /// + /// This function checks how old the remotes are and updates them when needed + /// + private 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); + } + + private 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); } } } diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 228aae8..6d18ebb 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -100,6 +100,13 @@ static async Task Main(string[] args) branch.AddCommand("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"); + }); }); bool running = true; diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index 1e786e3..060ac4e 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -53,12 +53,12 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa PathUtils.ClearDirectory(destinationDir); HttpClient httpClient = new HttpClient(); - + httpClient.DefaultRequestHeaders.ExpectContinue = false; using (HttpResponseMessage response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead)) { response.EnsureSuccessStatusCode(); - downloadTask.MaxValue = response.Content.Headers.ContentLength!.Value; + downloadTask.MaxValue = (double)response.Content.Headers.ContentLength!; using (Stream contentStream = await response.Content.ReadAsStreamAsync(), fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None)) diff --git a/premake-manager-cli/src/utils/PathUtils.cs b/premake-manager-cli/src/utils/PathUtils.cs index 7cbb2eb..e0323b1 100644 --- a/premake-manager-cli/src/utils/PathUtils.cs +++ b/premake-manager-cli/src/utils/PathUtils.cs @@ -47,6 +47,24 @@ public static string GetTempModulePath(string moduleName) { return Path.Combine(GetTempPath(), moduleName); } + public static string GetRemotesPath() + { + return Path.Combine(GetRoamingPath(), "remotes"); + } + /// + /// 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,10 +84,6 @@ public static void ClearDirectory(string path) catch (Exception) { /*ignore*/ } } - public string GetRemotesPath() - { - return Path.Combine(GetRoamingPath(), "remotes"); - } public static void EnsureExists(string path) { From 100956d7b62b3de8cb7e71b9a71e3b79db9d18f8 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Wed, 31 Dec 2025 14:57:38 +0100 Subject: [PATCH 08/28] feat: intermediate REMOTES --- premake-manager-cli/src/common-index/CommonIndex.cs | 3 ++- premake-manager-cli/src/common-index/RemotesManager.cs | 1 + premake-manager-cli/src/utils/DownloadUtils.cs | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index b54cc67..8fa5f8d 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -47,7 +47,7 @@ public static IndexView ReadRemoteIndex(string owner, string repo) } public static IndexView ReadRemoteLocalIndex(string owner, string repo) { - return YamlSerializer.Deserialize(ExtractUtils.ReadFile(PathUtils.GetRemotePath(owner, repo), "premakeIndex.yml")!); + return YamlSerializer.Deserialize(ExtractUtils.ReadFile(PathUtils.GetRemotePath(owner, repo), $"{repo}-main/premakeIndex.yml")!); } #endregion public static IndexView CreateNew(string remoteName) @@ -71,6 +71,7 @@ public static void CreateNewLibrary(ref IndexView index, IndexLibrary library, s if (index.libraries.TryGetValue(library.name, out IList? libraries)) { libraries.Add(library); + index.libraries[library.name] = libraries; } else { diff --git a/premake-manager-cli/src/common-index/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs index 98da7b4..18118d2 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -49,6 +49,7 @@ internal class RemotesManager private static Remote[] GetRemotes() { string RemotePaths = Path.Combine(PathUtils.GetRoamingPath(), "premakeRemotes.yml"); + if (Path.Exists(RemotePaths)) { return YamlSerializer.Deserialize(RemotePaths).remotes; diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index 060ac4e..2c8959f 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -53,7 +53,8 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa PathUtils.ClearDirectory(destinationDir); HttpClient httpClient = new HttpClient(); - httpClient.DefaultRequestHeaders.ExpectContinue = false; + httpClient.DefaultRequestHeaders.ExpectContinue = false;//ensure content length + using (HttpResponseMessage response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead)) { response.EnsureSuccessStatusCode(); From 8837b86d8079c487270baa0170fafcf372fabb07 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Fri, 9 Jan 2026 10:54:13 +0100 Subject: [PATCH 09/28] feat: added ability to add a library directly from a uri. Added the ability to update local remotes. Fixed bug where the index was not being updated on adding a new library --- premake-manager-cli/packages.lock.json | 31 ++++---------- premake-manager-cli/src/Github.cs | 5 ++- .../src/common-index/CommonCommand.cs | 41 +++++++++++++++++++ .../src/common-index/CommonIndex.cs | 2 +- .../src/common-index/IndexView.cs | 2 +- .../src/common-index/RemotesCommand.cs | 19 +++++++++ .../src/common-index/RemotesManager.cs | 4 +- .../src/libraries/LibraryManager.cs | 2 +- premake-manager-cli/src/main.cs | 8 +++- .../src/utils/DownloadUtils.cs | 6 ++- premake5.lua | 2 +- 11 files changed, 89 insertions(+), 33 deletions(-) diff --git a/premake-manager-cli/packages.lock.json b/premake-manager-cli/packages.lock.json index 0e9e02b..c7bfbe3 100644 --- a/premake-manager-cli/packages.lock.json +++ b/premake-manager-cli/packages.lock.json @@ -1,12 +1,12 @@ { "version": 1, "dependencies": { - "net9.0": { + "net10.0": { "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[9.0.11, )", - "resolved": "9.0.11", - "contentHash": "vvB9rtDmWaXgYkViT00KORBVmA3pcYsHlgd9vOPqL9sf5bKy3rvLMF1+sI1uUfVj28S3itirHlHmX5/kcpZKNw==" + "requested": "[10.0.1, )", + "resolved": "10.0.1", + "contentHash": "ISahzLHsHY7vrwqr2p1YWZ+gsxoBRtH7gWRDK8fDUst9pp2He0GiesaqEfeX0V8QMCJM3eNEHGGpnIcPjFo2NQ==" }, "Octokit": { "type": "Direct", @@ -18,10 +18,7 @@ "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 +39,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": { @@ -90,26 +86,15 @@ "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": {} + "net10.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..857ce0a 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -48,9 +48,10 @@ public static string FormatZipballUrl(GithubRepo repo, string refName) return $"https://github.com/{repo.owner}/{repo.name}/zipball/{refName}"; } - internal static string GetDescription(GithubRepo repo) + internal static async Task GetDescription(GithubRepo repo) { - throw new NotImplementedException(); + Repository repository = await Repositories.Get(repo.owner, repo.name); + return repository.Description; } } } diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index 594672d..bb70a42 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -1,5 +1,6 @@ using Spectre.Console; using Spectre.Console.Cli; +using src.config; using System; using System.Collections.Generic; using System.ComponentModel; @@ -78,6 +79,7 @@ public override Task ExecuteAsync(CommandContext context, Settings settings 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) @@ -101,5 +103,44 @@ internal class Settings : CommandSettings [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; + } } } diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index 8fa5f8d..c55fc30 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -33,7 +33,7 @@ public static IndexView ReadFileIndex(string filePath = "premakeIndex.yml") return YamlSerializer.Deserialize(filePath); } - public static void WriteFileIndex(IndexView index, string filePath) + public static void WriteFileIndex(IndexView index, string filePath = "premakeIndex.yml") { YamlSerializer.Serialize(index, filePath); } diff --git a/premake-manager-cli/src/common-index/IndexView.cs b/premake-manager-cli/src/common-index/IndexView.cs index 6a37fdd..682e423 100644 --- a/premake-manager-cli/src/common-index/IndexView.cs +++ b/premake-manager-cli/src/common-index/IndexView.cs @@ -25,6 +25,6 @@ internal class IndexView [YamlMember(Order = 0)] public required string remote { get; set; } [YamlMember(Order = 1)] - public required IDictionary> libraries; + public required Dictionary> libraries; } } diff --git a/premake-manager-cli/src/common-index/RemotesCommand.cs b/premake-manager-cli/src/common-index/RemotesCommand.cs index 2390d5b..208f964 100644 --- a/premake-manager-cli/src/common-index/RemotesCommand.cs +++ b/premake-manager-cli/src/common-index/RemotesCommand.cs @@ -117,4 +117,23 @@ internal class Settings : CommandSettings public string? repo { get; set; } } } + 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; + } + } } diff --git a/premake-manager-cli/src/common-index/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs index 18118d2..7a6f813 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -96,7 +96,7 @@ public static async Task RemoveRemote(string owner, string repo) /// /// This function checks how old the remotes are and updates them when needed /// - private static async Task UpdateRemotes(bool force = false) + public static async Task UpdateRemotes(bool force = false) { if (!force && !RemotesOutdated()) return; @@ -133,7 +133,7 @@ private static void CreateTimestamp() File.WriteAllText(Path.Combine(PathUtils.GetRemotesPath(), ".timestamp"), timestamp, Encoding.UTF8); } - private static bool RemotesOutdated() + public static bool RemotesOutdated() { string remotesPath = PathUtils.GetRemotesPath(); string timestampFilePath = Path.Combine(remotesPath, ".timestamp"); diff --git a/premake-manager-cli/src/libraries/LibraryManager.cs b/premake-manager-cli/src/libraries/LibraryManager.cs index d690b7b..484d5ff 100644 --- a/premake-manager-cli/src/libraries/LibraryManager.cs +++ b/premake-manager-cli/src/libraries/LibraryManager.cs @@ -25,7 +25,7 @@ public static async Task GetLibraryConfig(string githubLink) 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) }; + return new LibraryConfig() { name = repo.name, entryPoint = "premake5.lua", description = await Github.GetDescription(repo) }; } } diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 6d18ebb..f1a21dd 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -97,7 +97,11 @@ static async Task Main(string[] args) branch.AddCommand("new"); branch.AddBranch("add", branch => { - branch.AddCommand("library"); + 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"); + }); }); }); config.AddBranch("remotes", branch => { @@ -106,6 +110,8 @@ static async Task Main(string[] args) .WithDescription("Show all the local remotes"); branch.AddCommand("add") .WithDescription("Add a new local remote"); + branch.AddCommand("update") + .WithDescription("Update outdated remotes"); }); }); diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index 2c8959f..321a2cd 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -59,7 +59,7 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa { response.EnsureSuccessStatusCode(); - downloadTask.MaxValue = (double)response.Content.Headers.ContentLength!; + 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)) @@ -70,6 +70,10 @@ 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; diff --git a/premake5.lua b/premake5.lua index 3d09c2d..252df28 100644 --- a/premake5.lua +++ b/premake5.lua @@ -17,7 +17,7 @@ architecture "x64" 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}" From e73a5d02cad1ff8d349b683cc0a7327ecb7c2e63 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Fri, 16 Jan 2026 12:15:01 +0100 Subject: [PATCH 10/28] feat: intermediate --- .../src/common-index/RemotesCommand.cs | 20 +++ .../src/dependencies/DependenciesManager.cs | 119 +++++++++++++++++- .../src/dependencies/graph/DependecyGraph.cs | 2 +- premakeConfig.yml | 5 + 4 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 premakeConfig.yml diff --git a/premake-manager-cli/src/common-index/RemotesCommand.cs b/premake-manager-cli/src/common-index/RemotesCommand.cs index 208f964..3938a34 100644 --- a/premake-manager-cli/src/common-index/RemotesCommand.cs +++ b/premake-manager-cli/src/common-index/RemotesCommand.cs @@ -12,6 +12,8 @@ namespace src.common_index { + #region REMOTES + #region VIEW /// /// This command shows all the remotes /// @@ -51,7 +53,12 @@ public override Task ExecuteAsync(CommandContext context) 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) @@ -84,7 +91,12 @@ internal class Settings : CommandSettings 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) @@ -117,6 +129,12 @@ internal class Settings : CommandSettings public string? repo { get; set; } } } + #endregion + + #region UPDATE + /// + /// This + /// internal class RemotesUpdateCommand : AsyncCommand { public async override Task ExecuteAsync(CommandContext context, RemotesUpdateCommand.Settings settings) @@ -136,4 +154,6 @@ internal class Settings : CommandSettings public bool forceUpdate { get; set; } = false; } } + #endregion + #endregion } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index a35d6ee..f0e011b 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -1,4 +1,7 @@ -using src.dependencies.types; +using src.dependencies.graph; +using src.dependencies.types; +using src.libraries; +using src.utils; using System; using System.Collections.Generic; using System.IO; @@ -14,11 +17,123 @@ namespace src.dependencies internal class Dependencies { [YamlMember] - IList? libraries; + public IList? libraries; } + //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 async void 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, LibraryDirectory); + } + /// + /// 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 IList GatherDependencies(IList libraries) + { + List libraryDependencies = new List(); + foreach (var library in libraries) + { + IList dependencies = GatherLibraryDependencies(library); + libraryDependencies.AddRange(dependencies); + libraryDependencies.AddRange(GatherSubDependencies(dependencies)); + } + return libraryDependencies; + } + private static IList GatherSubDependencies(IList dependencies) + { + List libraryDependencies = new List(); + foreach (var library in dependencies) + { + IList subDependencies = GatherLibrarySubDependencies(library); + libraryDependencies.AddRange(subDependencies); + libraryDependencies.AddRange(GatherSubDependencies(subDependencies)); + } + return libraryDependencies; + } + #region INDIVIDUAL + private static IList 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 + #region CHECK_REMOTES + string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", library.owner, library.repo]).ToLower(); + string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); + + if (Path.Exists(LibraryDependencies)) + return YamlSerializer.Deserialize(LibraryDependencies).libraries; + #endregion + + #region CHECK_GITHUB + return YamlSerializer.Deserialize(library.owner, library.repo, LibraryDependencies).libraries; + #endregion + } + + private static IList 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 + string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", repo.owner, repo.name]).ToLower(); + string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); + + if (Path.Exists(LibraryDependencies)) + return YamlSerializer.Deserialize(LibraryDependencies).libraries; + #endregion + + #region CHECK_GITHUB + return YamlSerializer.Deserialize(repo.owner, repo.name, LibraryDependencies).libraries; + #endregion + } + #endregion + #endregion + + #region GRAPH + public static DependencyGraph GetDependencyGraph(IList libraries) + { + IList dependencies = GatherDependencies(libraries); + return new DependencyGraph(dependencies.ToArray()); + } + #endregion } } diff --git a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs index fce7106..bc2d6ad 100644 --- a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs +++ b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs @@ -110,7 +110,7 @@ public IReadOnlyCollection GetResolvedLibraries() resolved.Add(new LibraryDependency { name = group.Key, - version = finalRange.ToString() + version = finalRange!.ToString() }); } 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: {} From db4d4aa91ece63b00330ec59b1639bf18decdf1a Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Mon, 26 Jan 2026 21:39:04 +0100 Subject: [PATCH 11/28] feat: intermediate --- premake-manager-cli/packages.lock.json | 6 +-- .../src/common-index/CommonIndex.cs | 34 +++++++++++++++- .../src/common-index/RemotesManager.cs | 40 +++++++++++++------ .../src/libraries/LibraryManager.cs | 22 ++++++++-- premake-manager-cli/src/utils/PathUtils.cs | 1 + 5 files changed, 82 insertions(+), 21 deletions(-) diff --git a/premake-manager-cli/packages.lock.json b/premake-manager-cli/packages.lock.json index c7bfbe3..46e1e00 100644 --- a/premake-manager-cli/packages.lock.json +++ b/premake-manager-cli/packages.lock.json @@ -4,9 +4,9 @@ "net10.0": { "Microsoft.NET.ILLink.Tasks": { "type": "Direct", - "requested": "[10.0.1, )", - "resolved": "10.0.1", - "contentHash": "ISahzLHsHY7vrwqr2p1YWZ+gsxoBRtH7gWRDK8fDUst9pp2He0GiesaqEfeX0V8QMCJM3eNEHGGpnIcPjFo2NQ==" + "requested": "[10.0.2, )", + "resolved": "10.0.2", + "contentHash": "sXdDtMf2qcnbygw9OdE535c2lxSxrZP8gO4UhDJ0xiJbl1wIqXS1OTcTDFTIJPOFd6Mhcm8gPEthqWGUxBsTqw==" }, "Octokit": { "type": "Direct", diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index c55fc30..7ba1e4e 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -38,8 +38,36 @@ public static void WriteFileIndex(IndexView index, string filePath = "premakeInd 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/{repo.owner}/{repo.name}/premake5.lua".ToLower()); + } + 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 IndexView ReadRemoteIndex(string owner, string repo) { @@ -50,6 +78,8 @@ 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() @@ -82,5 +112,7 @@ public static void CreateNewLibrary(ref IndexView index, IndexLibrary library, s 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/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs index 7a6f813..cb93f91 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -1,4 +1,5 @@ -using src.utils; +using src.config; +using src.utils; using System; using System.Collections.Generic; using System.Globalization; @@ -109,18 +110,18 @@ private static async Task InstallRemotes() //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(); + 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(); @@ -154,5 +155,18 @@ public static bool RemotesOutdated() 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; + } + } } } diff --git a/premake-manager-cli/src/libraries/LibraryManager.cs b/premake-manager-cli/src/libraries/LibraryManager.cs index 484d5ff..7c2063d 100644 --- a/premake-manager-cli/src/libraries/LibraryManager.cs +++ b/premake-manager-cli/src/libraries/LibraryManager.cs @@ -1,5 +1,6 @@ using Octokit; using Spectre.Console; +using src.common_index; using src.config; using src.modules; using src.utils; @@ -19,16 +20,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) { + } + 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 +87,6 @@ await AnsiConsole.Progress().Columns(new ProgressColumn[] [RequiresUnreferencedCode("Calls src.config.ConfigReader.ConfigReader(String)")] public static async Task InstallLibraryCtx(ProgressContext ctx, string githubLink, string version = "*") { - Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); if (!githubLink.StartsWith("https://github.com/")) { @@ -96,7 +102,9 @@ public static async Task InstallLibraryCtx(ProgressContext ctx, string githubLin string downloadUrl = await ResolveDownloadUrl(repo, version); 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"), $"{config.LibrariesPath}/{repo.name}", $"extracting {libconfig.name}"); + 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)")] @@ -141,5 +149,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.Libraries}/{library.name}"; + } } } diff --git a/premake-manager-cli/src/utils/PathUtils.cs b/premake-manager-cli/src/utils/PathUtils.cs index e0323b1..46da6f5 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; From d3fcee79ea1b2cf2e4ba23ec3fee39b2ff43767b Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Sat, 31 Jan 2026 14:46:13 +0100 Subject: [PATCH 12/28] feat: intermediate --- .gitignore | 3 ++- premake-manager-cli/src/Github.cs | 4 ++++ .../src/config/ConfigCommand.cs | 7 ++++++ .../src/dependencies/DependenciesManager.cs | 24 +++++++++++++++++++ premake-manager-cli/src/selfTest/SelfTest.cs | 1 - .../selfTest/common-index/CommonIndexTests.cs | 20 ++++++++-------- 6 files changed, 47 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 86d7b92..e73a253 100644 --- a/.gitignore +++ b/.gitignore @@ -58,4 +58,5 @@ 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 diff --git a/premake-manager-cli/src/Github.cs b/premake-manager-cli/src/Github.cs index 857ce0a..616532f 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -53,5 +53,9 @@ internal static async Task GetDescription(GithubRepo repo) Repository repository = await Repositories.Get(repo.owner, repo.name); return repository.Description; } + internal static async Task> GetRepoVersions(GithubRepo repo) + { + return await Repositories.Release.GetAll(repo.owner, repo.name); + } } } diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index 3b85b05..469cf97 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -1,6 +1,8 @@ using Octokit; using Spectre.Console; using Spectre.Console.Cli; +using src.dependencies; +using src.dependencies.graph; using src.modules; using src.version; using System; @@ -24,6 +26,11 @@ public async override Task ExecuteAsync(CommandContext context) await VersionManager.SetVersion(config.Version); if(config.Modules != null) await ModuleManager.InstallModules(config.Modules.Values.ToList()); + //TODO dependencies + if(config.Libraries != null) + { + DependencyGraph graph = DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); + } return 0; } } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index f0e011b..a3ea431 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -19,6 +19,9 @@ internal class Dependencies [YamlMember] public IList? libraries; } + + //TODO Package Calculus + //Add dependencies internal class DependenciesManager { @@ -129,11 +132,32 @@ private static IList GatherLibrarySubDependencies(LibraryDepe #endregion #region GRAPH + /// + /// This function resolves the dependecyGraph for the given list of premake libraries + /// + /// + /// public static DependencyGraph GetDependencyGraph(IList libraries) { IList dependencies = GatherDependencies(libraries); return new DependencyGraph(dependencies.ToArray()); } + /// + /// 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) + { + IReadOnlyCollection libraries = graph.GetResolvedLibraries(); + foreach (LibraryDependency library in libraries) + { + GithubRepo repo = Github.GetRepoFromLink(library.name); + var versions = await Github.GetRepoVersions(repo); + //TODO + + } + } #endregion } } diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 5d701e5..8db52ed 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -19,7 +19,6 @@ public async override Task ExecuteAsync(CommandContext context) runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); - await runner.RunAllAsync(); return 0; } diff --git a/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs b/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs index ce2b403..6225b0d 100644 --- a/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs +++ b/premake-manager-cli/src/selfTest/common-index/CommonIndexTests.cs @@ -19,16 +19,16 @@ internal class CommonIndexTests : ITestClass { 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" } - }} - } + { + { "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); From 090478e24fcb098c995621cab7f70a5e67857414 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Wed, 4 Feb 2026 11:11:31 +0100 Subject: [PATCH 13/28] feat: initial work on VersionRange for improved dependecy graphs --- .../src/common-index/CommonIndex.cs | 3 +- .../src/dependencies/DependenciesManager.cs | 3 +- premake-manager-cli/src/selfTest/SelfTest.cs | 2 + .../src/selfTest/utils/VersionUtilsTest.cs | 109 +++++++++++ premake-manager-cli/src/utils/VersionUtils.cs | 181 ++++++++++++++++++ 5 files changed, 296 insertions(+), 2 deletions(-) create mode 100644 premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs create mode 100644 premake-manager-cli/src/utils/VersionUtils.cs diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index 7ba1e4e..86797ca 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -61,7 +61,8 @@ public static async Task ExtractLibraryFile(IndexView index, GithubRepo re MemoryStream? stream = ReadLibraryFile(index, repo); if (stream == null) return false; - using (FileStream libraryFile = File.OpenWrite(await LibraryManager.GetLibraryPath(repo)){ + using (FileStream libraryFile = File.OpenWrite(await LibraryManager.GetLibraryPath(repo))) + { stream.WriteTo(libraryFile); } return true; diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index a3ea431..d06b584 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -154,9 +154,10 @@ public static async Task> GetVersionsFromGraph(Depen { GithubRepo repo = Github.GetRepoFromLink(library.name); var versions = await Github.GetRepoVersions(repo); - //TODO + //TODO } + return new Dictionary(); } #endregion } diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 8db52ed..5f767ff 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -19,6 +19,7 @@ public async override Task ExecuteAsync(CommandContext context) runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); + runner.AddTestClass(); await runner.RunAllAsync(); return 0; } @@ -42,6 +43,7 @@ public async override Task ExecuteAsync(CommandContext context, Settings se 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/utils/VersionUtilsTest.cs b/premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs new file mode 100644 index 0000000..d020d59 --- /dev/null +++ b/premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using src.utils; +using Version = src.utils.Version; +namespace src.selfTest.utils +{ + internal class VersionUtilsTest : ITestClass + { + public IEnumerable<(string TestName, Func Action)> GetTests() + { + yield return ("versionFromString (limited)", async () => + { + Version version = new Version("3.2.1"); + if (version.major != 3) + throw new Exception("Version.major should be 3"); + else if (version.minor != 2) + throw new Exception("Version.minor should be 2"); + else if (version.patch != 1) + throw new Exception("Version.patch should be 1"); + else if (version.VersionInt != 50462976) + throw new Exception("Version.VersionInt should be 50462976"); //HEX: 03 02 01 00 + } + ); + yield return ("versionFromString (extended)", async () => + { + Version version = new Version("3.2.1.1"); + if (version.major != 3) + throw new Exception("Version.major should be 3"); + else if (version.minor != 2) + throw new Exception("Version.minor should be 2"); + else if (version.patch != 1) + throw new Exception("Version.patch should be 1"); + else if (version.revision != 1) + throw new Exception("Version.patch should be 1"); + else if (version.VersionInt != 50462977) + throw new Exception("Version.VersionInt should be 50462977"); //HEX: 03 02 01 01 + } + ); + yield return ("version2(3.2.2) > version1(3.2.1)", async () => + { + Version version1 = new Version("3.2.1"); + Version version2 = new Version("3.2.2"); + if (!(version2 > version1)) + throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 + } + ); + yield return ("version1(3.2.1) < version2(3.2.2)", async () => + { + Version version1 = new Version("3.2.1"); + Version version2 = new Version("3.2.2"); + if (!(version1 < version2)) + throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 + } + ); + yield return ("version2(3.2.1.1) > version1(3.2.1.0)", async () => + { + Version version1 = new Version("3.2.1.0"); + Version version2 = new Version("3.2.1.1"); + if (!(version2 > version1)) + throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 + } + ); + yield return ("version1(3.2.1.0) < version2(3.2.1.1)", async () => + { + Version version1 = new Version("3.2.1.0"); + Version version2 = new Version("3.2.1.1"); + if (!(version1 < version2)) + throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 + } + ); + yield return ("versionFromString (limited, suffix)", async () => + { + Version version = new Version("3.2.1-alpha"); + if (version.major != 3) + throw new Exception("Version.major should be 3"); + else if (version.minor != 2) + throw new Exception("Version.minor should be 2"); + else if (version.patch != 1) + throw new Exception("Version.patch should be 1"); + else if (version.VersionInt != 50462976) + throw new Exception("Version.VersionInt should be 50462976"); //HEX: 03 02 01 00 + } + ); + yield return ("versionFromString (extended, suffix)", async () => + { + Version version = new Version("3.2.1.1-rc1"); + if (version.major != 3) + throw new Exception("Version.major should be 3"); + else if (version.minor != 2) + throw new Exception("Version.minor should be 2"); + else if (version.patch != 1) + throw new Exception("Version.patch should be 1"); + else if (version.revision != 1) + throw new Exception("Version.patch should be 1"); + else if (version.VersionInt != 50462977) + throw new Exception("Version.VersionInt should be 50462977"); //HEX: 03 02 01 01 + } + ); + + yield return ("rangeFromString", async () => + { + VersionRange range = VersionUtils.GetRangeFromString(">=3.2.1"); + } + ); + } + } +} diff --git a/premake-manager-cli/src/utils/VersionUtils.cs b/premake-manager-cli/src/utils/VersionUtils.cs new file mode 100644 index 0000000..f55d052 --- /dev/null +++ b/premake-manager-cli/src/utils/VersionUtils.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; + +namespace src.utils +{ + class EnumHelper + { + public static string GetEnumValue(T enumValue) where T : Enum + { + var type = enumValue.GetType(); + var memInfo = type.GetMember(enumValue.ToString()); + var attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false); + return ((EnumMemberAttribute)attributes[0]).Value; + } + } + public enum ComparisonOperator + { + [EnumMember(Value = "")] + None, + [EnumMember(Value = ">")] + GreaterThan, + [EnumMember(Value = "<")] + LessThan, + [EnumMember(Value = ">=")] + GreaterThanOrEqual, + [EnumMember(Value = "<=")] + LessThanOrEqual, + Equal + } + + [DebuggerDisplay("{VersionArray[3]}.{VersionArray[2]}.{VersionArray[1]}.{VersionArray[0]}")] + public class Version : IEqualityComparer + { + #region PARTS + public byte major { get => VersionArray[3]; set => VersionArray[3] = value; } + public byte minor { get => VersionArray[2]; set => VersionArray[2] = value; } + public byte patch { get => VersionArray[1]; set => VersionArray[1] = value; } + public byte revision { get => VersionArray[0]; set => VersionArray[0] = value; } + #endregion + + private byte[] VersionArray = new byte[4]; + public UInt32 VersionInt { get => GetVersion(); set => SetVersion(value); } + + #region SETTERS + public void SetVersion(UInt32 version) => VersionArray = BitConverter.GetBytes(version); + public void SetMajor(byte major) => this.major = major; + public void SetMinor(byte minor) => this.minor = minor; + public void SetPatch(byte patch) => this.patch = patch; + public void SetRevision(byte revision) => this.revision = revision; + #endregion + + #region GETTERS + public UInt32 GetVersion() => BitConverter.ToUInt32(VersionArray, 0); + + public byte GetMajor() => this.major; + public byte GetMinor() => this.minor; + public byte GetPatch() => this.patch; + public byte GetRevision() => this.revision; + + #endregion + + #region OPERATORS + static public bool operator >(Version a, Version b) => a.VersionInt > b.VersionInt; + static public bool operator <(Version a, Version b) => a.VersionInt < b.VersionInt; + static public bool operator >=(Version a, Version b) => a.VersionInt >= b.VersionInt; + static public bool operator <=(Version a, Version b) => a.VersionInt <= b.VersionInt; + + #region EQUALS + public bool Equals(Version? x, Version? y) + { + if (x == null || y == null) return false; + return x.GetVersion() == y.GetVersion(); + } + + public int GetHashCode([DisallowNull] Version obj) + { + return obj.VersionInt.GetHashCode(); + } + #endregion + #endregion + public override string ToString() + { + return $"{major}.{minor}.{patch}.{revision}"; + } + public Version(string versionString) + { + string[] versionSections = versionString.Split("-")[0].Split("."); + + for (int i = 0; i < versionSections.Length; i++) + { + VersionArray[i] = byte.Parse(versionSections[i]); + } + VersionArray = VersionArray.Reverse().ToArray();//we need to reverse because we put the numbers in backwards + } + } + [DebuggerDisplay("{DebuggerDisplay,nq}")] + internal class VersionRange + { + private string DebuggerDisplay + { + get + { + string startPart = $"{EnumHelper.GetEnumValue(OperatorStart)}{start}"; + + // Only add the end part if 'end' is not null or empty + string endPart = !string.IsNullOrEmpty(end?.ToString()) + ? $":{EnumHelper.GetEnumValue(OperatorEnd)}{end}" + : string.Empty; + + return $"{startPart}{endPart}"; + } + } + Version? start { get; set; }//start of the range + Version? end { get; set; }//end of the range + ComparisonOperator OperatorStart { get; set; } + ComparisonOperator OperatorEnd { get; set; } + public VersionRange(ComparisonOperator OperatorStart, Version versionStart) + { + this.OperatorStart = OperatorStart; + start = versionStart; + } + public VersionRange(string OperatorStart, Version versionStart) : this(ParseOperator(OperatorStart), versionStart) { } + public VersionRange(ComparisonOperator OperatorStart, Version versionStart, ComparisonOperator OperatorEnd, Version versionEnd) + { + this.OperatorStart = OperatorStart; + start= versionStart; + this.OperatorEnd = OperatorEnd; + end = versionEnd; + } + public VersionRange(string OperatorStart, Version versionStart, string OperatorEnd, Version versionEnd) : this(ParseOperator(OperatorStart), versionStart, ParseOperator(OperatorEnd), versionEnd) { } + + public static ComparisonOperator ParseOperator(string op) => op switch + { + ">" => ComparisonOperator.GreaterThan, + "<" => ComparisonOperator.LessThan, + ">=" => ComparisonOperator.GreaterThanOrEqual, + "<=" => ComparisonOperator.LessThanOrEqual, + "==" => ComparisonOperator.Equal, + _ => ComparisonOperator.None + }; + } + internal class VersionUtils + { + /// + /// This function generates a VersionRange + /// + /// + /// + public static VersionRange GetRangeFromString(string range) + { + string[] splitRange = range.Split(":"); + string? versionStart = splitRange.ElementAtOrDefault(0); + string? versionEnd = splitRange.ElementAtOrDefault(1); + string versionPattern = @"(\d(\.\d)+)"; + string comparatorPattern = @"[><=!]+(?=\d)"; + + if(versionStart != null) + { + Version versionBegin = new Version(Regex.Matches(versionStart ?? "0.0.0.0", versionPattern).ElementAtOrDefault(0)!.Value); + string operatorBegin = Regex.Matches(versionStart ?? "0.0.0.0", comparatorPattern).ElementAtOrDefault(0)!.Value; + if (versionEnd != null) + { + Version versionLimit = new Version(Regex.Matches(versionEnd ?? "0.0.0.0", versionPattern).ElementAtOrDefault(0)!.Value); + string operatorLimit = Regex.Matches(versionEnd ?? "0.0.0.0", comparatorPattern).ElementAtOrDefault(0)!.Value; + } + return new VersionRange(operatorBegin, versionBegin); + } + + return new VersionRange(ComparisonOperator.LessThan,new Version("3.1.1")); + } + } +} + From bc12974f778dc7ff0670ad47cebf76b096ae1448 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Sun, 8 Feb 2026 18:20:40 +0100 Subject: [PATCH 14/28] refactor: use semver library for dependency managemen --- premake-manager-cli/packages.lock.json | 14 ++ .../src/dependencies/DependenciesManager.cs | 16 ++- .../src/dependencies/graph/DependecyGraph.cs | 120 ++++++++---------- .../dependencies/types/LibraryDependency.cs | 3 - premake-manager-cli/src/selfTest/SelfTest.cs | 2 - .../dependecies/DependencyGraphTests.cs | 2 +- .../src/selfTest/utils/VersionUtilsTest.cs | 109 ---------------- premake-manager-cli/src/utils/VersionUtils.cs | 99 ++------------- premake5.lua | 2 +- 9 files changed, 98 insertions(+), 269 deletions(-) delete mode 100644 premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs diff --git a/premake-manager-cli/packages.lock.json b/premake-manager-cli/packages.lock.json index 46e1e00..3aa1cdd 100644 --- a/premake-manager-cli/packages.lock.json +++ b/premake-manager-cli/packages.lock.json @@ -14,6 +14,15 @@ "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, )", @@ -62,6 +71,11 @@ "resolved": "2.5.192", "contentHash": "jaJuwcgovWIZ8Zysdyf3b7b34/BrADw4v82GaEZymUhDd3ScMPrYd/cttekeDteJJPXseJxp04yTIcxiVUjTWg==" }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "5.0.1", + "contentHash": "5WPSmL4YeP7eW+Vc8XZ4DwjYWBAiSwDV9Hm63JJWcz1Ie3Xjv4KuJXzgCstj48LkLfVCYa7mLcx7y+q6yqVvtw==" + }, "Microsoft.NET.StringTools": { "type": "Transitive", "resolved": "17.6.3", diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index d06b584..026ce8f 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -1,4 +1,5 @@ -using src.dependencies.graph; +using Semver; +using src.dependencies.graph; using src.dependencies.types; using src.libraries; using src.utils; @@ -149,12 +150,21 @@ public static DependencyGraph GetDependencyGraph(IList libraries /// a dictionary indexed, via the library name public static async Task> GetVersionsFromGraph(DependencyGraph graph) { - IReadOnlyCollection libraries = graph.GetResolvedLibraries(); + var(libraries,conflict) = graph.GetResolvedLibraries(); foreach (LibraryDependency library in libraries) { GithubRepo repo = Github.GetRepoFromLink(library.name); var versions = await Github.GetRepoVersions(repo); - //TODO + SemVersion[] semVersions = versions.Select((version) => SemVersion.Parse(version.TagName)).ToArray(); + + semVersions.Reverse(); //we reverse such that we can start with the greatest version + + SemVersionRange range = SemVersionRange.Parse(library.version); + foreach (var item in semVersions) + { + if(range.Contains(item)) + //TODO add and break; + } } return new Dictionary(); diff --git a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs index bc2d6ad..ec38e07 100644 --- a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs +++ b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs @@ -1,4 +1,5 @@ -using Spectre.Console; +using Semver; +using Spectre.Console; using src.dependencies.types; using System; using System.Collections.Generic; @@ -37,84 +38,73 @@ public IReadOnlyCollection GetDependencies(LibraryDependency 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!; + } + + + 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(); - if (showProgress) - { - AnsiConsole.Progress() + 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; + resolved.Add(new LibraryDependency() + { + name = group.Key, + version = final.ToString() + }); - task.Increment(1); } + + task.Increment(1); + ctx.Refresh(); }); - } - else - { - 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(); - } - } - - return conflicts; - } - - /// - /// 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() - { - // Include all libraries - var allDeps = _graph.Keys.Concat(_graph.SelectMany(kv => kv.Value)).ToList(); - - var resolved = new List(); - // Group by library name - var groups = allDeps.GroupBy(lib => lib.name); - foreach (var group in groups) - { - 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() - }); - } - - return resolved; + return (resolved,conflict); } } } diff --git a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs index e8b1207..624af9f 100644 --- a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs +++ b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs @@ -15,9 +15,6 @@ internal class LibraryDependency public string version { get; set; } // format: "*", "=x.y.z", ">x.y.z", "=x.y.z", "<=x.y.z" public bool IsValid() => LibraryDependencyValidator.ValidateLibrary(name, version); - - [YamlIgnore] - public VersionRange VersionRange => new VersionRange(version); } internal static class LibraryDependencyValidator diff --git a/premake-manager-cli/src/selfTest/SelfTest.cs b/premake-manager-cli/src/selfTest/SelfTest.cs index 5f767ff..8db52ed 100644 --- a/premake-manager-cli/src/selfTest/SelfTest.cs +++ b/premake-manager-cli/src/selfTest/SelfTest.cs @@ -19,7 +19,6 @@ public async override Task ExecuteAsync(CommandContext context) runner.AddTestClass(); runner.AddTestClass(); runner.AddTestClass(); - runner.AddTestClass(); await runner.RunAllAsync(); return 0; } @@ -43,7 +42,6 @@ public async override Task ExecuteAsync(CommandContext context, Settings se 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/dependecies/DependencyGraphTests.cs b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs index 1db1d09..afa8d32 100644 --- a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs +++ b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs @@ -91,7 +91,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")) diff --git a/premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs b/premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs deleted file mode 100644 index d020d59..0000000 --- a/premake-manager-cli/src/selfTest/utils/VersionUtilsTest.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using src.utils; -using Version = src.utils.Version; -namespace src.selfTest.utils -{ - internal class VersionUtilsTest : ITestClass - { - public IEnumerable<(string TestName, Func Action)> GetTests() - { - yield return ("versionFromString (limited)", async () => - { - Version version = new Version("3.2.1"); - if (version.major != 3) - throw new Exception("Version.major should be 3"); - else if (version.minor != 2) - throw new Exception("Version.minor should be 2"); - else if (version.patch != 1) - throw new Exception("Version.patch should be 1"); - else if (version.VersionInt != 50462976) - throw new Exception("Version.VersionInt should be 50462976"); //HEX: 03 02 01 00 - } - ); - yield return ("versionFromString (extended)", async () => - { - Version version = new Version("3.2.1.1"); - if (version.major != 3) - throw new Exception("Version.major should be 3"); - else if (version.minor != 2) - throw new Exception("Version.minor should be 2"); - else if (version.patch != 1) - throw new Exception("Version.patch should be 1"); - else if (version.revision != 1) - throw new Exception("Version.patch should be 1"); - else if (version.VersionInt != 50462977) - throw new Exception("Version.VersionInt should be 50462977"); //HEX: 03 02 01 01 - } - ); - yield return ("version2(3.2.2) > version1(3.2.1)", async () => - { - Version version1 = new Version("3.2.1"); - Version version2 = new Version("3.2.2"); - if (!(version2 > version1)) - throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 - } - ); - yield return ("version1(3.2.1) < version2(3.2.2)", async () => - { - Version version1 = new Version("3.2.1"); - Version version2 = new Version("3.2.2"); - if (!(version1 < version2)) - throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 - } - ); - yield return ("version2(3.2.1.1) > version1(3.2.1.0)", async () => - { - Version version1 = new Version("3.2.1.0"); - Version version2 = new Version("3.2.1.1"); - if (!(version2 > version1)) - throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 - } - ); - yield return ("version1(3.2.1.0) < version2(3.2.1.1)", async () => - { - Version version1 = new Version("3.2.1.0"); - Version version2 = new Version("3.2.1.1"); - if (!(version1 < version2)) - throw new Exception("Version2 should be larger then Version1"); //HEX: 03 02 01 01 - } - ); - yield return ("versionFromString (limited, suffix)", async () => - { - Version version = new Version("3.2.1-alpha"); - if (version.major != 3) - throw new Exception("Version.major should be 3"); - else if (version.minor != 2) - throw new Exception("Version.minor should be 2"); - else if (version.patch != 1) - throw new Exception("Version.patch should be 1"); - else if (version.VersionInt != 50462976) - throw new Exception("Version.VersionInt should be 50462976"); //HEX: 03 02 01 00 - } - ); - yield return ("versionFromString (extended, suffix)", async () => - { - Version version = new Version("3.2.1.1-rc1"); - if (version.major != 3) - throw new Exception("Version.major should be 3"); - else if (version.minor != 2) - throw new Exception("Version.minor should be 2"); - else if (version.patch != 1) - throw new Exception("Version.patch should be 1"); - else if (version.revision != 1) - throw new Exception("Version.patch should be 1"); - else if (version.VersionInt != 50462977) - throw new Exception("Version.VersionInt should be 50462977"); //HEX: 03 02 01 01 - } - ); - - yield return ("rangeFromString", async () => - { - VersionRange range = VersionUtils.GetRangeFromString(">=3.2.1"); - } - ); - } - } -} diff --git a/premake-manager-cli/src/utils/VersionUtils.cs b/premake-manager-cli/src/utils/VersionUtils.cs index f55d052..fdbac3e 100644 --- a/premake-manager-cli/src/utils/VersionUtils.cs +++ b/premake-manager-cli/src/utils/VersionUtils.cs @@ -1,4 +1,5 @@ -using System; +using Octokit; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; @@ -21,19 +22,21 @@ public static string GetEnumValue(T enumValue) where T : Enum return ((EnumMemberAttribute)attributes[0]).Value; } } - public enum ComparisonOperator + public enum ComparisonOperator : byte { [EnumMember(Value = "")] - None, + None = 0, + [EnumMember(Value = "=")] + Equal = 1, [EnumMember(Value = ">")] - GreaterThan, - [EnumMember(Value = "<")] - LessThan, + GreaterThan = 2, [EnumMember(Value = ">=")] - GreaterThanOrEqual, + GreaterThanOrEqual = 3, + [EnumMember(Value = "<")] + LessThan = 4, [EnumMember(Value = "<=")] - LessThanOrEqual, - Equal + LessThanOrEqual = 5, + } [DebuggerDisplay("{VersionArray[3]}.{VersionArray[2]}.{VersionArray[1]}.{VersionArray[0]}")] @@ -72,6 +75,8 @@ public class Version : IEqualityComparer static public bool operator <(Version a, Version b) => a.VersionInt < b.VersionInt; static public bool operator >=(Version a, Version b) => a.VersionInt >= b.VersionInt; static public bool operator <=(Version a, Version b) => a.VersionInt <= b.VersionInt; + static public bool operator ==(Version a, Version b) => a.VersionInt == b.VersionInt; + static public bool operator !=(Version a, Version b) => a.VersionInt != b.VersionInt; #region EQUALS public bool Equals(Version? x, Version? y) @@ -101,81 +106,5 @@ public Version(string versionString) VersionArray = VersionArray.Reverse().ToArray();//we need to reverse because we put the numbers in backwards } } - [DebuggerDisplay("{DebuggerDisplay,nq}")] - internal class VersionRange - { - private string DebuggerDisplay - { - get - { - string startPart = $"{EnumHelper.GetEnumValue(OperatorStart)}{start}"; - - // Only add the end part if 'end' is not null or empty - string endPart = !string.IsNullOrEmpty(end?.ToString()) - ? $":{EnumHelper.GetEnumValue(OperatorEnd)}{end}" - : string.Empty; - - return $"{startPart}{endPart}"; - } - } - Version? start { get; set; }//start of the range - Version? end { get; set; }//end of the range - ComparisonOperator OperatorStart { get; set; } - ComparisonOperator OperatorEnd { get; set; } - public VersionRange(ComparisonOperator OperatorStart, Version versionStart) - { - this.OperatorStart = OperatorStart; - start = versionStart; - } - public VersionRange(string OperatorStart, Version versionStart) : this(ParseOperator(OperatorStart), versionStart) { } - public VersionRange(ComparisonOperator OperatorStart, Version versionStart, ComparisonOperator OperatorEnd, Version versionEnd) - { - this.OperatorStart = OperatorStart; - start= versionStart; - this.OperatorEnd = OperatorEnd; - end = versionEnd; - } - public VersionRange(string OperatorStart, Version versionStart, string OperatorEnd, Version versionEnd) : this(ParseOperator(OperatorStart), versionStart, ParseOperator(OperatorEnd), versionEnd) { } - - public static ComparisonOperator ParseOperator(string op) => op switch - { - ">" => ComparisonOperator.GreaterThan, - "<" => ComparisonOperator.LessThan, - ">=" => ComparisonOperator.GreaterThanOrEqual, - "<=" => ComparisonOperator.LessThanOrEqual, - "==" => ComparisonOperator.Equal, - _ => ComparisonOperator.None - }; - } - internal class VersionUtils - { - /// - /// This function generates a VersionRange - /// - /// - /// - public static VersionRange GetRangeFromString(string range) - { - string[] splitRange = range.Split(":"); - string? versionStart = splitRange.ElementAtOrDefault(0); - string? versionEnd = splitRange.ElementAtOrDefault(1); - string versionPattern = @"(\d(\.\d)+)"; - string comparatorPattern = @"[><=!]+(?=\d)"; - - if(versionStart != null) - { - Version versionBegin = new Version(Regex.Matches(versionStart ?? "0.0.0.0", versionPattern).ElementAtOrDefault(0)!.Value); - string operatorBegin = Regex.Matches(versionStart ?? "0.0.0.0", comparatorPattern).ElementAtOrDefault(0)!.Value; - if (versionEnd != null) - { - Version versionLimit = new Version(Regex.Matches(versionEnd ?? "0.0.0.0", versionPattern).ElementAtOrDefault(0)!.Value); - string operatorLimit = Regex.Matches(versionEnd ?? "0.0.0.0", comparatorPattern).ElementAtOrDefault(0)!.Value; - } - return new VersionRange(operatorBegin, versionBegin); - } - - return new VersionRange(ComparisonOperator.LessThan,new Version("3.1.1")); - } - } } diff --git a/premake5.lua b/premake5.lua index 252df28..52319ca 100644 --- a/premake5.lua +++ b/premake5.lua @@ -22,7 +22,7 @@ architecture "x64" 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" } vsprops { PublishSingleFile = "true", SelfContained = "true", From 3dacb769c3b04b4273876b89458301e99cd92259 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Tue, 10 Feb 2026 13:36:08 +0100 Subject: [PATCH 15/28] feat: versions from graph --- premake-manager-cli/src/Github.cs | 6 ++- .../src/dependencies/DependenciesManager.cs | 42 ++++++++++++++----- .../dependecies/DependencyGraphTests.cs | 20 ++++++++- 3 files changed, 55 insertions(+), 13 deletions(-) diff --git a/premake-manager-cli/src/Github.cs b/premake-manager-cli/src/Github.cs index 616532f..6248d21 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -55,7 +55,11 @@ internal static async Task GetDescription(GithubRepo repo) } internal static async Task> GetRepoVersions(GithubRepo repo) { - return await Repositories.Release.GetAll(repo.owner, repo.name); + return await Repositories.Release.GetAll(repo.owner, repo.name); + } + internal static async Task> GetRepoTags(GithubRepo repo) + { + return await Repositories.GetAllTags(repo.owner, repo.name); } } } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 026ce8f..07b25b5 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -1,4 +1,6 @@ -using Semver; +using Octokit; +using Semver; +using Spectre.Console; using src.dependencies.graph; using src.dependencies.types; using src.libraries; @@ -8,6 +10,7 @@ using System.IO; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -151,23 +154,42 @@ public static DependencyGraph GetDependencyGraph(IList libraries public static async Task> GetVersionsFromGraph(DependencyGraph graph) { var(libraries,conflict) = graph.GetResolvedLibraries(); + IDictionary resultLibraries = new Dictionary(); + Regex regex = new Regex("v([0-9]+(\\.[0-9]+)+)", RegexOptions.IgnoreCase); + foreach (LibraryDependency library in libraries) { GithubRepo repo = Github.GetRepoFromLink(library.name); - var versions = await Github.GetRepoVersions(repo); - SemVersion[] semVersions = versions.Select((version) => SemVersion.Parse(version.TagName)).ToArray(); + SemVersionRange range = SemVersionRange.Parse(library.version); + try + { + var versions = await Github.GetRepoTags(repo); + IList tags = new List(); + //TODO use tryparse to only add valid versions + foreach (RepositoryTag item in versions) + { + Match tagMatch = regex.Match(item.Name); + if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version)) + { + if (range.Contains(version)) + { + resultLibraries.Add(library.name, version.ToString()); + continue; + } + } + } - semVersions.Reverse(); //we reverse such that we can start with the greatest version - SemVersionRange range = SemVersionRange.Parse(library.version); - foreach (var item in semVersions) + + } + catch (Exception e) { - if(range.Contains(item)) - //TODO add and break; + AnsiConsole.WriteLine($"{e.Message}"); } - + //NO VERSION FOUND FOR RANGE + throw new InvalidOperationException("No valid version found for provided range"); } - return new Dictionary(); + return resultLibraries; } #endregion } diff --git a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs index afa8d32..0927c4e 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; @@ -105,5 +106,20 @@ 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; + + } + ); + + } } From 1135dcd8cc82959e5de5445586c5ce68bfc52dfa Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 13:56:16 +0100 Subject: [PATCH 16/28] fix: added build artifacts --- .github/workflows/build-and-test.yml | 29 +++++++++++++++++++--------- .gitignore | 1 + 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 9eeb879..4fb9af1 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 "$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 "$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 "$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 e73a253..7799929 100644 --- a/.gitignore +++ b/.gitignore @@ -60,3 +60,4 @@ nunit-*.xml /.vs/** settings.json /Nieuw - Tekstdocument.txt +premake-manager-cli/premake-manager-cli.csproj.Backup.tmp From b998eddf2e31b7235f68af8f0d41836044e3a4b8 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 13:58:56 +0100 Subject: [PATCH 17/28] fix: -o --- .github/workflows/build-and-test.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 4fb9af1..407f703 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -46,11 +46,11 @@ jobs: PUBLISH_DIR="${{ github.workspace }}/publish-artifacts" if [ "${{ runner.os }}" == "Windows" ]; then - dotnet publish "${{ github.workspace }}" -r win-x64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" + dotnet publish "${{ github.workspace }}" -r win-x64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" -o elif [ "${{ runner.os }}" == "Linux" ]; then - dotnet publish ${{ github.workspace }} -r linux-x64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" + dotnet publish ${{ github.workspace }} -r linux-x64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" -o elif [ "${{ runner.os }}" == "macOS" ]; then - dotnet publish ${{ github.workspace }} -r osx-arm64 -p:PlatformTarget=arm64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" + dotnet publish ${{ github.workspace }} -r osx-arm64 -p:PlatformTarget=arm64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" -o fi - name: Run Self-Tests shell: bash From 0ea52637de5d91d6113ba5c3c733fbffaa35deff Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 14:06:40 +0100 Subject: [PATCH 18/28] fix: placement of -o --- .github/workflows/build-and-test.yml | 6 +++--- .../src/dependencies/DependenciesManager.cs | 13 ++++--------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 407f703..795b936 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -46,11 +46,11 @@ jobs: PUBLISH_DIR="${{ github.workspace }}/publish-artifacts" if [ "${{ runner.os }}" == "Windows" ]; then - dotnet publish "${{ github.workspace }}" -r win-x64 $DOTNET_PUBLISH_COMMON "$PUBLISH_DIR" -o + 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 "$PUBLISH_DIR" -o + 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 "$PUBLISH_DIR" -o + dotnet publish ${{ github.workspace }} -r osx-arm64 -p:PlatformTarget=arm64 $DOTNET_PUBLISH_COMMON -o "$PUBLISH_DIR" fi - name: Run Self-Tests shell: bash diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 07b25b5..4b6ce6a 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -169,18 +169,13 @@ public static async Task> GetVersionsFromGraph(Depen foreach (RepositoryTag item in versions) { Match tagMatch = regex.Match(item.Name); - if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version)) + if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version) && range.Contains(version)) { - if (range.Contains(version)) - { - resultLibraries.Add(library.name, version.ToString()); - continue; - } + resultLibraries.Add(library.name, version.ToString()); + continue; + } } - - - } catch (Exception e) { From 5e2d3066c5ef21972bf8e860b8edce8c505ae855 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 14:31:07 +0100 Subject: [PATCH 19/28] feat: fixed config command --- premake-manager-cli/src/config/ConfigCommand.cs | 5 +++++ .../src/dependencies/DependenciesManager.cs | 12 ++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index 469cf97..3dbceba 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -3,6 +3,7 @@ using Spectre.Console.Cli; using src.dependencies; using src.dependencies.graph; +using src.libraries; using src.modules; using src.version; using System; @@ -30,6 +31,10 @@ public async override Task ExecuteAsync(CommandContext context) if(config.Libraries != null) { DependencyGraph graph = DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); + var libs = await DependenciesManager.GetVersionsFromGraph(graph); + + await LibraryManager.InstallLibraries(libs.ToList()); + } return 0; } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 4b6ce6a..12d0da1 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -151,10 +151,10 @@ public static DependencyGraph GetDependencyGraph(IList libraries /// /// the dependecy graph to resolve the versions of /// a dictionary indexed, via the library name - public static async Task> GetVersionsFromGraph(DependencyGraph graph) + public static async Task GetVersionsFromGraph(DependencyGraph graph) { var(libraries,conflict) = graph.GetResolvedLibraries(); - IDictionary resultLibraries = new Dictionary(); + IList resultLibraries = new List(); Regex regex = new Regex("v([0-9]+(\\.[0-9]+)+)", RegexOptions.IgnoreCase); foreach (LibraryDependency library in libraries) @@ -171,20 +171,20 @@ public static async Task> GetVersionsFromGraph(Depen Match tagMatch = regex.Match(item.Name); if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version) && range.Contains(version)) { - resultLibraries.Add(library.name, version.ToString()); + resultLibraries.Add(new PremakeLibrary(version.ToString(),library.name)); continue; - } } + AnsiConsole.WriteLine($"[red]Library: {library.name}, not found[/]"); } catch (Exception e) { - AnsiConsole.WriteLine($"{e.Message}"); + AnsiConsole.WriteLine($"Library not found"); } //NO VERSION FOUND FOR RANGE throw new InvalidOperationException("No valid version found for provided range"); } - return resultLibraries; + return resultLibraries.ToArray(); } #endregion } From 2b4e8c5b925e7850a3e1c2508e9ca74865c9efcc Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 15:20:17 +0100 Subject: [PATCH 20/28] feat: added commands for remotes (reset, remove) --- .../src/common-index/RemotesCommand.cs | 12 ++++++++++++ .../src/common-index/RemotesManager.cs | 12 ++++++++++++ premake-manager-cli/src/config/ConfigCommand.cs | 1 - premake-manager-cli/src/main.cs | 5 +++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/premake-manager-cli/src/common-index/RemotesCommand.cs b/premake-manager-cli/src/common-index/RemotesCommand.cs index 3938a34..9c5b260 100644 --- a/premake-manager-cli/src/common-index/RemotesCommand.cs +++ b/premake-manager-cli/src/common-index/RemotesCommand.cs @@ -155,5 +155,17 @@ internal class Settings : CommandSettings } } #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 index cb93f91..b77ff41 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -93,7 +93,19 @@ public static async Task RemoveRemote(string owner, string repo) 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 /// diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index 3dbceba..9d1a86e 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -34,7 +34,6 @@ public async override Task ExecuteAsync(CommandContext context) var libs = await DependenciesManager.GetVersionsFromGraph(graph); await LibraryManager.InstallLibraries(libs.ToList()); - } return 0; } diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index f1a21dd..21c1c73 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -112,6 +112,11 @@ static async Task Main(string[] args) .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"); + }); }); From d4881f284e4fbbeba2469bee39080a61bfebb281 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Tue, 10 Feb 2026 16:00:56 +0100 Subject: [PATCH 21/28] feat: added command to add dependency to index --- .../src/common-index/CommonCommand.cs | 62 ++++++++++++++++++- .../src/dependencies/DependenciesManager.cs | 2 +- premake-manager-cli/src/main.cs | 3 + 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index bb70a42..86fc502 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -1,6 +1,8 @@ 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; @@ -126,7 +128,7 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not if (string.IsNullOrEmpty(repo.name)) return ValidationResult.Error("the repo name name should be valid"); - + return ValidationResult.Success(); } @@ -143,4 +145,62 @@ public override async Task ExecuteAsync(CommandContext context, Settings se 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/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 12d0da1..0744070 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -35,7 +35,7 @@ internal class DependenciesManager /// /// the repo to add the dependency to /// dependency to add - public async void AddLibraryDependency(GithubRepo repo, LibraryDependency dependency) + 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"); diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 21c1c73..e1cda03 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -101,7 +101,10 @@ static async Task Main(string[] args) 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 => { From 7b77a8f5e340c64757687a7052bb9051b505c170 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Wed, 11 Feb 2026 16:57:10 +0100 Subject: [PATCH 22/28] fix: build warnings --- .../src/common-index/CommonCommand.cs | 4 +- .../src/dependencies/DependenciesManager.cs | 2 +- .../src/utils/DownloadUtils.cs | 4 +- premake-manager-cli/src/utils/VersionUtils.cs | 110 ------------------ 4 files changed, 5 insertions(+), 115 deletions(-) delete mode 100644 premake-manager-cli/src/utils/VersionUtils.cs diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index 86fc502..22a4993 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -35,7 +35,7 @@ public override Task ExecuteAsync(CommandContext context, Settings settings if (string.IsNullOrWhiteSpace(input)) return ValidationResult.Error("Url cannot be empty"); - if (!Uri.TryCreate(input, UriKind.Absolute, out Uri uri)) + if (!Uri.TryCreate(input, UriKind.Absolute, out Uri? uri)) return ValidationResult.Error("Invalid url format"); if (!string.Equals(uri.Host, "github.com", StringComparison.OrdinalIgnoreCase)) @@ -199,7 +199,7 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not 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 }); + await DependenciesManager.AddLibraryDependency(libRepo, new LibraryDependency { name = $"{settings.owner}/{settings.repo}", version = settings.range! }); return 0; } } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 0744070..8c92988 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -177,7 +177,7 @@ public static async Task GetVersionsFromGraph(DependencyGraph } AnsiConsole.WriteLine($"[red]Library: {library.name}, not found[/]"); } - catch (Exception e) + catch (Exception) { AnsiConsole.WriteLine($"Library not found"); } diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index 321a2cd..c4e0e1d 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -46,7 +46,7 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa downloadTask.StartTask(); destinationPath = destinationPath.Replace("\\", "/"); - string destinationDir = Path.GetDirectoryName(destinationPath); + string destinationDir = Path.GetDirectoryName(destinationPath)!; if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir); else @@ -105,7 +105,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/VersionUtils.cs b/premake-manager-cli/src/utils/VersionUtils.cs deleted file mode 100644 index fdbac3e..0000000 --- a/premake-manager-cli/src/utils/VersionUtils.cs +++ /dev/null @@ -1,110 +0,0 @@ -using Octokit; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using System.Text; -using System.Text.RegularExpressions; - -namespace src.utils -{ - class EnumHelper - { - public static string GetEnumValue(T enumValue) where T : Enum - { - var type = enumValue.GetType(); - var memInfo = type.GetMember(enumValue.ToString()); - var attributes = memInfo[0].GetCustomAttributes(typeof(EnumMemberAttribute), false); - return ((EnumMemberAttribute)attributes[0]).Value; - } - } - public enum ComparisonOperator : byte - { - [EnumMember(Value = "")] - None = 0, - [EnumMember(Value = "=")] - Equal = 1, - [EnumMember(Value = ">")] - GreaterThan = 2, - [EnumMember(Value = ">=")] - GreaterThanOrEqual = 3, - [EnumMember(Value = "<")] - LessThan = 4, - [EnumMember(Value = "<=")] - LessThanOrEqual = 5, - - } - - [DebuggerDisplay("{VersionArray[3]}.{VersionArray[2]}.{VersionArray[1]}.{VersionArray[0]}")] - public class Version : IEqualityComparer - { - #region PARTS - public byte major { get => VersionArray[3]; set => VersionArray[3] = value; } - public byte minor { get => VersionArray[2]; set => VersionArray[2] = value; } - public byte patch { get => VersionArray[1]; set => VersionArray[1] = value; } - public byte revision { get => VersionArray[0]; set => VersionArray[0] = value; } - #endregion - - private byte[] VersionArray = new byte[4]; - public UInt32 VersionInt { get => GetVersion(); set => SetVersion(value); } - - #region SETTERS - public void SetVersion(UInt32 version) => VersionArray = BitConverter.GetBytes(version); - public void SetMajor(byte major) => this.major = major; - public void SetMinor(byte minor) => this.minor = minor; - public void SetPatch(byte patch) => this.patch = patch; - public void SetRevision(byte revision) => this.revision = revision; - #endregion - - #region GETTERS - public UInt32 GetVersion() => BitConverter.ToUInt32(VersionArray, 0); - - public byte GetMajor() => this.major; - public byte GetMinor() => this.minor; - public byte GetPatch() => this.patch; - public byte GetRevision() => this.revision; - - #endregion - - #region OPERATORS - static public bool operator >(Version a, Version b) => a.VersionInt > b.VersionInt; - static public bool operator <(Version a, Version b) => a.VersionInt < b.VersionInt; - static public bool operator >=(Version a, Version b) => a.VersionInt >= b.VersionInt; - static public bool operator <=(Version a, Version b) => a.VersionInt <= b.VersionInt; - static public bool operator ==(Version a, Version b) => a.VersionInt == b.VersionInt; - static public bool operator !=(Version a, Version b) => a.VersionInt != b.VersionInt; - - #region EQUALS - public bool Equals(Version? x, Version? y) - { - if (x == null || y == null) return false; - return x.GetVersion() == y.GetVersion(); - } - - public int GetHashCode([DisallowNull] Version obj) - { - return obj.VersionInt.GetHashCode(); - } - #endregion - #endregion - public override string ToString() - { - return $"{major}.{minor}.{patch}.{revision}"; - } - public Version(string versionString) - { - string[] versionSections = versionString.Split("-")[0].Split("."); - - for (int i = 0; i < versionSections.Length; i++) - { - VersionArray[i] = byte.Parse(versionSections[i]); - } - VersionArray = VersionArray.Reverse().ToArray();//we need to reverse because we put the numbers in backwards - } - } -} - From 32db61dd1bc39d6a4b5149811c616c35b796446f Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Fri, 13 Feb 2026 16:43:26 +0100 Subject: [PATCH 23/28] feat: added @ dependencies --- .../src/common-index/CommonCommand.cs | 2 +- .../src/dependencies/graph/DependecyGraph.cs | 3 +++ .../src/dependencies/types/LibraryDependency.cs | 2 +- .../dependecies/DependencyGraphTests.cs | 17 +++++++++++++++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/premake-manager-cli/src/common-index/CommonCommand.cs b/premake-manager-cli/src/common-index/CommonCommand.cs index 22a4993..f24283a 100644 --- a/premake-manager-cli/src/common-index/CommonCommand.cs +++ b/premake-manager-cli/src/common-index/CommonCommand.cs @@ -171,7 +171,7 @@ public override ValidationResult Validate([NotNull] CommandContext context, [Not { settings.githublink = AnsiConsole.Prompt(new TextPrompt("[green]library githublink: [/]")); } - if (settings.githublink!.StartsWith("https://github.com/")) + 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)) diff --git a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs index ec38e07..37481db 100644 --- a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs +++ b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs @@ -30,6 +30,9 @@ 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); } diff --git a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs index 624af9f..84d6fe6 100644 --- a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs +++ b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs @@ -12,7 +12,7 @@ internal class LibraryDependency 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); } diff --git a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs index 0927c4e..4931515 100644 --- a/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs +++ b/premake-manager-cli/src/selfTest/dependecies/DependencyGraphTests.cs @@ -120,6 +120,23 @@ internal class DependencyGraphTests : ITestClass } ); + // 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; } + ); + } } From 2cafa22c3c072403c9034e0f0295da7a919f28f6 Mon Sep 17 00:00:00 2001 From: Robbe Beernaert Date: Fri, 13 Feb 2026 16:51:59 +0100 Subject: [PATCH 24/28] fix: write dependencies to correct folder --- premake-manager-cli/src/dependencies/DependenciesManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 8c92988..31055a2 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -48,7 +48,7 @@ public static async Task AddLibraryDependency(GithubRepo repo, LibraryDependency dependencies.libraries.Add(dependency); #endregion - YamlSerializer.Serialize(dependencies, LibraryDirectory); + YamlSerializer.Serialize(dependencies, LibraryDependencies); } /// /// Remove a library from the repo dependecies From e5bc9ef29c062efe98e0b8d93f9af4e8b8fc5a89 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Sun, 8 Mar 2026 21:24:50 +0100 Subject: [PATCH 25/28] fix: library commands are gone with the wind! --- premake-manager-cli/src/main.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index e1cda03..8924ba8 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -84,6 +84,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"); From 0d9e9499746bafc73bfea9545693c6799c6299a1 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Sun, 15 Mar 2026 13:00:29 +0100 Subject: [PATCH 26/28] feat: started work on fixing the libraries download --- .gitignore | 1 + premake-manager-cli/packages.lock.json | 113 ++++++++++++++++-- premake-manager-cli/src/Github.cs | 25 +++- .../src/common-index/CommonIndex.cs | 18 ++- .../src/common-index/RemotesManager.cs | 20 ++++ premake-manager-cli/src/config/Config.cs | 45 ++++++- .../src/config/ConfigCommand.cs | 64 ++++++++-- .../src/dependencies/DependenciesManager.cs | 98 ++++++++++----- .../src/dependencies/graph/DependecyGraph.cs | 84 ++++++++++--- .../dependencies/types/LibraryDependency.cs | 22 +++- .../dependencies/types/ModuleDependency.cs | 4 +- .../src/libraries/LibraryCommand.cs | 6 +- .../src/libraries/PremakeLibrary.cs | 4 +- premake-manager-cli/src/main.cs | 21 +++- .../src/modules/ModuleManager.cs | 9 +- .../src/modules/PremakeModule.cs | 4 +- premake-manager-cli/src/utils/CacheUtils.cs | 24 ++++ .../src/utils/DownloadUtils.cs | 2 + premake-manager-cli/src/utils/ExtractUtils.cs | 37 +++--- .../src/utils/YamlSerializer.cs | 7 +- .../src/version/VersionManager.cs | 2 +- premake5.lua | 12 +- 22 files changed, 502 insertions(+), 120 deletions(-) create mode 100644 premake-manager-cli/src/utils/CacheUtils.cs diff --git a/.gitignore b/.gitignore index 7799929..26252bb 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,4 @@ nunit-*.xml settings.json /Nieuw - Tekstdocument.txt premake-manager-cli/premake-manager-cli.csproj.Backup.tmp +*.slnx diff --git a/premake-manager-cli/packages.lock.json b/premake-manager-cli/packages.lock.json index 3aa1cdd..51f1ee1 100644 --- a/premake-manager-cli/packages.lock.json +++ b/premake-manager-cli/packages.lock.json @@ -2,11 +2,33 @@ "version": 1, "dependencies": { "net10.0": { - "Microsoft.NET.ILLink.Tasks": { + "EasyCaching.Disk": { "type": "Direct", - "requested": "[10.0.2, )", - "resolved": "10.0.2", - "contentHash": "sXdDtMf2qcnbygw9OdE535c2lxSxrZP8gO4UhDJ0xiJbl1wIqXS1OTcTDFTIJPOFd6Mhcm8gPEthqWGUxBsTqw==" + "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", @@ -57,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", @@ -71,10 +103,76 @@ "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": "5.0.1", - "contentHash": "5WPSmL4YeP7eW+Vc8XZ4DwjYWBAiSwDV9Hm63JJWcz1Ie3Xjv4KuJXzgCstj48LkLfVCYa7mLcx7y+q6yqVvtw==" + "resolved": "6.0.0", + "contentHash": "9+PnzmQFfEFNR9J2aDTfJGGupShHjOuGw4VUv+JB044biSHrnmCIMD+mJHmb2H7YryrfBEXDurxQ47gJZdCKNQ==" }, "Microsoft.NET.StringTools": { "type": "Transitive", @@ -108,7 +206,6 @@ "resolved": "13.0.3", "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" } - }, - "net10.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 6248d21..ac09b42 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -1,12 +1,15 @@ using Octokit; +using Spectre.Console; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace src { + [DebuggerDisplay("{owner,nq}/{name,nq}")] internal struct GithubRepo { public string owner; @@ -15,7 +18,7 @@ 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() @@ -30,10 +33,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; @@ -50,15 +68,18 @@ public static string FormatZipballUrl(GithubRepo repo, string refName) internal static async Task GetDescription(GithubRepo repo) { + //TODO add cache. Repository repository = await Repositories.Get(repo.owner, repo.name); return repository.Description; } internal static async Task> GetRepoVersions(GithubRepo repo) { + //TODO add cache. return await Repositories.Release.GetAll(repo.owner, repo.name); } internal static async Task> GetRepoTags(GithubRepo repo) { + //TODO add cache. return await Repositories.GetAllTags(repo.owner, repo.name); } } diff --git a/premake-manager-cli/src/common-index/CommonIndex.cs b/premake-manager-cli/src/common-index/CommonIndex.cs index 86797ca..96ad9fc 100644 --- a/premake-manager-cli/src/common-index/CommonIndex.cs +++ b/premake-manager-cli/src/common-index/CommonIndex.cs @@ -45,7 +45,19 @@ public static void WriteFileIndex(IndexView index, string filePath = "premakeInd 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/{repo.owner}/{repo.name}/premake5.lua".ToLower()); + 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. } @@ -70,9 +82,9 @@ public static async Task ExtractLibraryFile(IndexView index, GithubRepo re #endregion #region REMOTE - public static IndexView ReadRemoteIndex(string owner, string repo) + public static async Task ReadRemoteIndex(string owner, string repo) { - return YamlSerializer.Deserialize(owner, repo, "premakeIndex.yml"); + return await YamlSerializer.Deserialize(owner, repo, "premakeIndex.yml"); } public static IndexView ReadRemoteLocalIndex(string owner, string repo) { diff --git a/premake-manager-cli/src/common-index/RemotesManager.cs b/premake-manager-cli/src/common-index/RemotesManager.cs index b77ff41..7f1090f 100644 --- a/premake-manager-cli/src/common-index/RemotesManager.cs +++ b/premake-manager-cli/src/common-index/RemotesManager.cs @@ -1,4 +1,6 @@ using src.config; +using src.dependencies; +using src.dependencies.types; using src.utils; using System; using System.Collections.Generic; @@ -180,5 +182,23 @@ public static async Task InstallRemotesLibrary(GithubRepo repo) 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 index 5d229c6..f68452a 100644 --- a/premake-manager-cli/src/config/Config.cs +++ b/premake-manager-cli/src/config/Config.cs @@ -11,6 +11,15 @@ 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; @@ -21,11 +30,39 @@ internal sealed class Config public string? LibrariesPath { get; set; } [YamlMember(Alias = "modules")] - public IDictionary? Modules { get; set; } - + 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; set; } - + 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 diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index 9d1a86e..b00eaa2 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -17,6 +17,9 @@ 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) @@ -25,14 +28,21 @@ public async override Task ExecuteAsync(CommandContext context) //TODO should we auto install the correct version of premake? await VersionManager.SetVersion(config.Version); - if(config.Modules != null) + if (config.Modules != null) + { + AnsiConsole.WriteLine("aquiring graph"); await ModuleManager.InstallModules(config.Modules.Values.ToList()); + } //TODO dependencies if(config.Libraries != null) { - DependencyGraph graph = DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); + AnsiConsole.WriteLine("aquiring graph"); + DependencyGraph graph = await DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); var libs = await DependenciesManager.GetVersionsFromGraph(graph); - + foreach (var lib in libs) + { + Console.WriteLine($"lib:{lib.version}, {lib.getLink()}"); + } await LibraryManager.InstallLibraries(libs.ToList()); } return 0; @@ -86,11 +96,11 @@ public async override Task ExecuteAsync(CommandContext context) { 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; + modulesTable.Border = TableBorder.Rounded; + modulesTable.ShowRowSeparators = true; if (config.Modules != null) { @@ -117,10 +127,46 @@ public async override Task ExecuteAsync(CommandContext context) // 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); + modulesTable.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 - + 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) + { + + // 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 + } return 0; } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index 31055a2..e761e22 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -1,6 +1,7 @@ using Octokit; using Semver; using Spectre.Console; +using src.common_index; using src.dependencies.graph; using src.dependencies.types; using src.libraries; @@ -9,6 +10,7 @@ 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; @@ -73,63 +75,89 @@ public async void RemoveLibraryDependency(GithubRepo repo, string name) #region GATHER_DEPENDENCIES - private static IList GatherDependencies(IList libraries) + private static async Task> GatherDependencies(PremakeLibrary library) { List libraryDependencies = new List(); - foreach (var library in libraries) - { - IList dependencies = GatherLibraryDependencies(library); - libraryDependencies.AddRange(dependencies); - libraryDependencies.AddRange(GatherSubDependencies(dependencies)); - } + + IList dependencies = await GatherLibraryDependencies(library); + libraryDependencies.AddRange(dependencies); + libraryDependencies.AddRange(await GatherSubDependencies(dependencies)); + return libraryDependencies; } - private static IList GatherSubDependencies(IList dependencies) + private static async Task> GatherSubDependencies(IList dependencies) { List libraryDependencies = new List(); foreach (var library in dependencies) { - IList subDependencies = GatherLibrarySubDependencies(library); + IList subDependencies = await GatherLibrarySubDependencies(library); libraryDependencies.AddRange(subDependencies); - libraryDependencies.AddRange(GatherSubDependencies(subDependencies)); + libraryDependencies.AddRange(await GatherSubDependencies(subDependencies)); } return libraryDependencies; } #region INDIVIDUAL - private static IList GatherLibraryDependencies(PremakeLibrary library) + 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 - string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", library.owner, library.repo]).ToLower(); - string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); - - if (Path.Exists(LibraryDependencies)) - return YamlSerializer.Deserialize(LibraryDependencies).libraries; + Dependencies? dependencies = RemotesManager.GetDependencies(repo); + if (dependencies is not null) + { + return dependencies.libraries; + } #endregion #region CHECK_GITHUB - return YamlSerializer.Deserialize(library.owner, library.repo, LibraryDependencies).libraries; + /* 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 IList GatherLibrarySubDependencies(LibraryDependency library) + 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 - string LibraryDirectory = Path.Combine([Directory.GetCurrentDirectory(), "libraries", repo.owner, repo.name]).ToLower(); - string LibraryDependencies = Path.Combine(LibraryDirectory, "premakeDependencies.yml"); - - if (Path.Exists(LibraryDependencies)) - return YamlSerializer.Deserialize(LibraryDependencies).libraries; + Dependencies? dependencies = RemotesManager.GetDependencies(repo); + if(dependencies is not null) + { + return dependencies.libraries; + } #endregion #region CHECK_GITHUB - return YamlSerializer.Deserialize(repo.owner, repo.name, LibraryDependencies).libraries; + /* 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 @@ -141,10 +169,16 @@ private static IList GatherLibrarySubDependencies(LibraryDepe /// /// /// - public static DependencyGraph GetDependencyGraph(IList libraries) + public static async Task GetDependencyGraph(IList libraries) { - IList dependencies = GatherDependencies(libraries); - return new DependencyGraph(dependencies.ToArray()); + 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; + } /// /// This function fetches the versions from Github and resolves the correct version (if possible). @@ -155,7 +189,7 @@ public static async Task GetVersionsFromGraph(DependencyGraph { var(libraries,conflict) = graph.GetResolvedLibraries(); IList resultLibraries = new List(); - Regex regex = new Regex("v([0-9]+(\\.[0-9]+)+)", RegexOptions.IgnoreCase); + Regex regex = new Regex(@"(\d+\.\d+\.\d+)", RegexOptions.IgnoreCase); foreach (LibraryDependency library in libraries) { @@ -164,7 +198,7 @@ public static async Task GetVersionsFromGraph(DependencyGraph try { var versions = await Github.GetRepoTags(repo); - IList tags = new List(); + bool found = false; //TODO use tryparse to only add valid versions foreach (RepositoryTag item in versions) { @@ -172,10 +206,12 @@ public static async Task GetVersionsFromGraph(DependencyGraph if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version) && range.Contains(version)) { resultLibraries.Add(new PremakeLibrary(version.ToString(),library.name)); - continue; + found = true; + break; } } - AnsiConsole.WriteLine($"[red]Library: {library.name}, not found[/]"); + if (found) + continue; } catch (Exception) { diff --git a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs index 37481db..6528ab6 100644 --- a/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs +++ b/premake-manager-cli/src/dependencies/graph/DependecyGraph.cs @@ -1,12 +1,16 @@ -using Semver; +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 @@ -36,6 +40,14 @@ public void AddDependency(LibraryDependency library, LibraryDependency dependsOn _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(); @@ -49,8 +61,8 @@ public IReadOnlyDictionary GetDependencyConflicts(boo return conflict!; } - - public (IReadOnlyCollection, IReadOnlyDictionary) GetResolvedLibraries() + + public (IReadOnlyCollection, IReadOnlyDictionary) GetResolvedLibraries() { // Include all libraries var allDeps = _graph.Keys.Concat(_graph.SelectMany(kv => kv.Value)).ToList(); @@ -58,7 +70,7 @@ public IReadOnlyDictionary GetDependencyConflicts(boo //contains all resolved non conflicting libraries. var resolved = new List(); //contains all conflicting libraries. - var conflict = new Dictionary(); + var conflict = new Dictionary(); AnsiConsole.Progress() .AutoClear(false) @@ -68,7 +80,6 @@ public IReadOnlyDictionary GetDependencyConflicts(boo var task = ctx.AddTask("Checking dependencies...", maxValue: allDeps.Count); var groups = allDeps.GroupBy(lib => lib.name); - foreach (var group in groups) { SemVersionRange final = SemVersionRange.Empty; @@ -79,7 +90,7 @@ public IReadOnlyDictionary GetDependencyConflicts(boo final = SemVersionRange.Parse($"{final} {range}"); else final = SemVersionRange.Parse($"{range}"); - + if (final == SemVersionRange.Empty) { @@ -90,24 +101,65 @@ public IReadOnlyDictionary GetDependencyConflicts(boo }); break; } - + } if (final == SemVersionRange.Empty) continue; - resolved.Add(new LibraryDependency() + if (resolved.Find(dep => dep.name == group.Key) is not null) { - name = group.Key, - version = final.ToString() - }); - + 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(); } - - task.Increment(1); - ctx.Refresh(); + + }); - return (resolved,conflict); + return (resolved, conflict); + } + + internal class DependencyGraphDebugProxy + { + private readonly DependencyGraph _graphObj; + + public DependencyGraphDebugProxy(DependencyGraph graphObj) + { + _graphObj = graphObj; + } + + // 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(); + } + + // A helper class just for the debugger view + [DebuggerDisplay("{Library.name,nq} -> {Dependencies.Count} deps")] + internal class DependencyEntry + { + public LibraryDependency Library { get; } + public IReadOnlyCollection Dependencies { get; } + + public DependencyEntry(LibraryDependency lib, IReadOnlyCollection deps) + { + Library = lib; + Dependencies = deps; + } } } } diff --git a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs index 84d6fe6..6e56e7e 100644 --- a/premake-manager-cli/src/dependencies/types/LibraryDependency.cs +++ b/premake-manager-cli/src/dependencies/types/LibraryDependency.cs @@ -1,20 +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", "@ => parent version" + 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); + + 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 fea9269..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; } @@ -99,7 +99,7 @@ await AnsiConsole.Status().StartAsync("Adding library", async ctx => ctx.Spinner(Spinner.Known.Aesthetic); ctx.SpinnerStyle(Style.Parse("green")); - config.AddLibrary(new PremakeLibrary() { owner = libraryString[0], repo = libraryString[1], version = settings.version }); + config.AddLibrary(new PremakeLibrary() { owner = libraryString[0], repo = libraryString[1], version = settings.version ?? "*"}); }); ConfigManager.WriteConfig(config,null); return 0; @@ -116,6 +116,8 @@ 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)) 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 8924ba8..36e3a28 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -15,14 +15,31 @@ 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('"'); + Console.WriteLine(sessionToken); + await Github.SetSession(sessionToken); + + } + + } + + Console.CancelKeyPress += (sender, e) => { PathUtils.ClearDirectory(PathUtils.GetTempPath()); diff --git a/premake-manager-cli/src/modules/ModuleManager.cs b/premake-manager-cli/src/modules/ModuleManager.cs index 3ee1b17..e854dbb 100644 --- a/premake-manager-cli/src/modules/ModuleManager.cs +++ b/premake-manager-cli/src/modules/ModuleManager.cs @@ -21,6 +21,13 @@ public static async Task GetModuleConfig(string githubLink) 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); + Octokit.RepositoryContent config = (await Github.Repositories.Content.GetAllContentsByRef(repo.owner, repo.name, "premakeModule.yml", "main"))[0]; + 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,7 +87,7 @@ 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); 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/utils/CacheUtils.cs b/premake-manager-cli/src/utils/CacheUtils.cs new file mode 100644 index 0000000..e19c360 --- /dev/null +++ b/premake-manager-cli/src/utils/CacheUtils.cs @@ -0,0 +1,24 @@ +using EasyCaching.Core.Serialization; +using EasyCaching.Disk; +using EasyCaching.Serialization.Json; +using EasyCaching.Serialization.SystemTextJson; // Add this +using System; +using System.Collections.Generic; +using System.Text; + +namespace src.utils +{ + internal class CacheUtils + { + private static readonly DefaultDiskCachingProvider _provider; + static CacheUtils() + { + + var serializer = new DefaultJsonSerializer("json", new SystemTextJsonSerializerOptions()); + var serializers = new List { serializer }; + + var options = new DiskDbOptions { BasePath = "app_cache" }; + _provider = new DefaultDiskCachingProvider("default_disk", options); + } + } +} diff --git a/premake-manager-cli/src/utils/DownloadUtils.cs b/premake-manager-cli/src/utils/DownloadUtils.cs index c4e0e1d..d178098 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -78,6 +78,8 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa totalBytesRead += bytesRead; downloadTask.Value += bytesRead; } + /* flush otherwise there can be issues reading later on*/ + await fileStream.FlushAsync(); contentStream.Close(); } } diff --git a/premake-manager-cli/src/utils/ExtractUtils.cs b/premake-manager-cli/src/utils/ExtractUtils.cs index e95d8d1..8bd8d40 100644 --- a/premake-manager-cli/src/utils/ExtractUtils.cs +++ b/premake-manager-cli/src/utils/ExtractUtils.cs @@ -138,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)) + return; - 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); + string? destinationDir = Path.GetDirectoryName(destinationPath); - 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(); diff --git a/premake-manager-cli/src/utils/YamlSerializer.cs b/premake-manager-cli/src/utils/YamlSerializer.cs index 40052e0..fda3b81 100644 --- a/premake-manager-cli/src/utils/YamlSerializer.cs +++ b/premake-manager-cli/src/utils/YamlSerializer.cs @@ -3,6 +3,7 @@ using System; using System.IO; using System.Net.Http; +using System.Threading.Tasks; using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -34,16 +35,16 @@ public static T Deserialize(string filePath) return Deserialize(stream); } - public static T Deserialize(string owner, string repo, string filePath) + 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 = client.GetAsync(url).Result; + HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); - using Stream stream = response.Content.ReadAsStreamAsync().Result; + using Stream stream = await response.Content.ReadAsStreamAsync(); return Deserialize(stream); } diff --git a/premake-manager-cli/src/version/VersionManager.cs b/premake-manager-cli/src/version/VersionManager.cs index 0c29f1c..932dba9 100644 --- a/premake-manager-cli/src/version/VersionManager.cs +++ b/premake-manager-cli/src/version/VersionManager.cs @@ -92,7 +92,7 @@ await AnsiConsole.Progress().Columns(new ProgressColumn[] } #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!); diff --git a/premake5.lua b/premake5.lua index 52319ca..ca2dce3 100644 --- a/premake5.lua +++ b/premake5.lua @@ -1,17 +1,9 @@ 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" @@ -22,7 +14,7 @@ architecture "x64" 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","Semver:3.0.0" } + 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", From cd0cf7857c6d43504faf127d77d5a28808da1017 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Fri, 20 Mar 2026 18:49:12 +0100 Subject: [PATCH 27/28] feat: configure, cache, blood, sweat, tears! --- .vscode/settings.json | 3 +- premake-manager-cli/src/Github.cs | 45 +++++- .../src/config/ConfigCommand.cs | 15 +- .../src/dependencies/DependenciesManager.cs | 88 +++++++---- .../src/libraries/LibraryManager.cs | 41 ++++-- premake-manager-cli/src/main.cs | 2 - .../src/modules/ModuleManager.cs | 28 ++-- premake-manager-cli/src/utils/CacheUtils.cs | 138 ++++++++++++++++-- .../src/utils/DownloadUtils.cs | 11 +- premake-manager-cli/src/utils/ExtractUtils.cs | 6 +- premake-manager-cli/src/utils/GihtubTypes.cs | 1 + premake-manager-cli/src/utils/PathUtils.cs | 5 + .../src/utils/PremakeSystem.cs | 64 +++++--- premake5.lua | 2 - 14 files changed, 337 insertions(+), 112 deletions(-) create mode 100644 premake-manager-cli/src/utils/GihtubTypes.cs 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/src/Github.cs b/premake-manager-cli/src/Github.cs index ac09b42..ae318e2 100644 --- a/premake-manager-cli/src/Github.cs +++ b/premake-manager-cli/src/Github.cs @@ -1,9 +1,13 @@ 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; @@ -23,9 +27,18 @@ internal class Github // 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"); @@ -65,22 +78,38 @@ public static string FormatZipballUrl(GithubRepo repo, string refName) { return $"https://github.com/{repo.owner}/{repo.name}/zipball/{refName}"; } - - internal static async Task GetDescription(GithubRepo repo) + internal static async Task GetRepo(GithubRepo repo) { - //TODO add cache. Repository repository = await Repositories.Get(repo.owner, repo.name); - return repository.Description; + return repository; + } + internal static async Task GetDescription(GithubRepo repo) + { + return (await GetRepo(repo)).Description; } internal static async Task> GetRepoVersions(GithubRepo repo) { - //TODO add cache. - return await Repositories.Release.GetAll(repo.owner, repo.name); + var releases = await Repositories.Release.GetAll(repo.owner, repo.name); + return releases; + } + + 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) { - //TODO add cache. 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) + { + return await _instance.Repository.Branch.GetAll(repo.owner, repo.name); + } } } diff --git a/premake-manager-cli/src/config/ConfigCommand.cs b/premake-manager-cli/src/config/ConfigCommand.cs index b00eaa2..40906fd 100644 --- a/premake-manager-cli/src/config/ConfigCommand.cs +++ b/premake-manager-cli/src/config/ConfigCommand.cs @@ -5,6 +5,7 @@ using src.dependencies.graph; using src.libraries; using src.modules; +using src.utils; using src.version; using System; using System.Collections.Generic; @@ -26,11 +27,15 @@ public async override Task ExecuteAsync(CommandContext context) { 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); if (config.Modules != null) { AnsiConsole.WriteLine("aquiring graph"); + modules = config.Modules.Values.ToArray(); await ModuleManager.InstallModules(config.Modules.Values.ToList()); } //TODO dependencies @@ -38,13 +43,13 @@ public async override Task ExecuteAsync(CommandContext context) { AnsiConsole.WriteLine("aquiring graph"); DependencyGraph graph = await DependenciesManager.GetDependencyGraph(config.Libraries.Values.ToList()); - var libs = await DependenciesManager.GetVersionsFromGraph(graph); - foreach (var lib in libs) - { - Console.WriteLine($"lib:{lib.version}, {lib.getLink()}"); - } + var libs = (await DependenciesManager.GetVersionsFromGraph(graph)).Distinct() + .ToList(); + + libraries = libs.ToArray(); await LibraryManager.InstallLibraries(libs.ToList()); } + PremakeSystemWriter.Write(config, libraries, modules); return 0; } } diff --git a/premake-manager-cli/src/dependencies/DependenciesManager.cs b/premake-manager-cli/src/dependencies/DependenciesManager.cs index e761e22..1e1e5bc 100644 --- a/premake-manager-cli/src/dependencies/DependenciesManager.cs +++ b/premake-manager-cli/src/dependencies/DependenciesManager.cs @@ -171,15 +171,64 @@ private static async Task> GatherLibrarySubDependencies /// 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()); + 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)); + 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). /// @@ -191,35 +240,10 @@ public static async Task GetVersionsFromGraph(DependencyGraph IList resultLibraries = new List(); Regex regex = new Regex(@"(\d+\.\d+\.\d+)", RegexOptions.IgnoreCase); - foreach (LibraryDependency library in libraries) - { - GithubRepo repo = Github.GetRepoFromLink(library.name); - SemVersionRange range = SemVersionRange.Parse(library.version); - try - { - var versions = await Github.GetRepoTags(repo); - bool found = false; - //TODO use tryparse to only add valid versions - foreach (RepositoryTag item in versions) - { - Match tagMatch = regex.Match(item.Name); - if (tagMatch.Success && SemVersion.TryParse(tagMatch.Groups[1].Value, out SemVersion? version) && range.Contains(version)) - { - resultLibraries.Add(new PremakeLibrary(version.ToString(),library.name)); - found = true; - break; - } - } - if (found) - continue; - } - catch (Exception) - { - AnsiConsole.WriteLine($"Library not found"); - } - //NO VERSION FOUND FOR RANGE - throw new InvalidOperationException("No valid version found for provided range"); - } + 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/libraries/LibraryManager.cs b/premake-manager-cli/src/libraries/LibraryManager.cs index 7c2063d..8519508 100644 --- a/premake-manager-cli/src/libraries/LibraryManager.cs +++ b/premake-manager-cli/src/libraries/LibraryManager.cs @@ -1,4 +1,5 @@ using Octokit; +using Semver; using Spectre.Console; using src.common_index; using src.config; @@ -9,6 +10,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; +using System.Net.Http; using System.Text; using System.Threading.Tasks; @@ -120,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); @@ -153,7 +170,7 @@ private static async Task ResolveDownloadUrl(GithubRepo repo, string ver public static async Task GetLibraryPath(GithubRepo library) { Config config = ConfigManager.HasConfig() ? ConfigManager.ReadConfig() : new Config(); - return $"{config.Libraries}/{library.name}"; + return $"{config.LibrariesPath ?? "libraries"}/{library.name}"; } } } diff --git a/premake-manager-cli/src/main.cs b/premake-manager-cli/src/main.cs index 36e3a28..8c7e06f 100644 --- a/premake-manager-cli/src/main.cs +++ b/premake-manager-cli/src/main.cs @@ -31,8 +31,6 @@ static async Task Main(string[] args) { // Extracts the part after "--session=" sessionToken = arg.Substring("--session=".Length).Trim('"'); - Console.WriteLine(sessionToken); - await Github.SetSession(sessionToken); } diff --git a/premake-manager-cli/src/modules/ModuleManager.cs b/premake-manager-cli/src/modules/ModuleManager.cs index e854dbb..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,14 +18,14 @@ 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); - 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.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")); } @@ -92,7 +93,7 @@ public static async Task InstallModuleCtx(ProgressContext ctx, string 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) @@ -105,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/utils/CacheUtils.cs b/premake-manager-cli/src/utils/CacheUtils.cs index e19c360..a6ec3d7 100644 --- a/premake-manager-cli/src/utils/CacheUtils.cs +++ b/premake-manager-cli/src/utils/CacheUtils.cs @@ -1,24 +1,140 @@ -using EasyCaching.Core.Serialization; +using EasyCaching.Core; +using EasyCaching.Core.Serialization; using EasyCaching.Disk; -using EasyCaching.Serialization.Json; -using EasyCaching.Serialization.SystemTextJson; // Add this +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 { - internal class CacheUtils + + + 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 static readonly DefaultDiskCachingProvider _provider; - static CacheUtils() + private readonly DefaultDiskCachingProvider _provider; + + public CacheProvider() { - - var serializer = new DefaultJsonSerializer("json", new SystemTextJsonSerializerOptions()); + var serializer = new NewtonsoftEasyCachingSerializer(); var serializers = new List { serializer }; - var options = new DiskDbOptions { BasePath = "app_cache" }; - _provider = new DefaultDiskCachingProvider("default_disk", options); + 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 d178098..64db60c 100644 --- a/premake-manager-cli/src/utils/DownloadUtils.cs +++ b/premake-manager-cli/src/utils/DownloadUtils.cs @@ -45,9 +45,10 @@ 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); @@ -57,6 +58,12 @@ public static async Task DownloadProgressCtx(ProgressContext ctx, string downloa 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 = (double)(response.Content.Headers.ContentLength ?? -1); diff --git a/premake-manager-cli/src/utils/ExtractUtils.cs b/premake-manager-cli/src/utils/ExtractUtils.cs index 8bd8d40..715c538 100644 --- a/premake-manager-cli/src/utils/ExtractUtils.cs +++ b/premake-manager-cli/src/utils/ExtractUtils.cs @@ -143,14 +143,14 @@ public static async Task ExtractZipProgressCtx(ProgressContext ctx, string sourc foreach (var entry in archive.Entries) { if (string.IsNullOrEmpty(entry.Name)) - return; + continue; 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); 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 46da6f5..a84b59d 100644 --- a/premake-manager-cli/src/utils/PathUtils.cs +++ b/premake-manager-cli/src/utils/PathUtils.cs @@ -52,6 +52,11 @@ 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 /// diff --git a/premake-manager-cli/src/utils/PremakeSystem.cs b/premake-manager-cli/src/utils/PremakeSystem.cs index b8e7ebb..639cb37 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,26 +16,14 @@ namespace src.utils internal class PremakeSystemWriter { static IList content = new List(); - public static void Write(Config 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"); - if (config.Modules != null) - { - foreach (var item in config.Modules) - { - AddModule(item.Value.entryPoint ?? item.Key); - } - try - { - File.Delete("premake-system.lua"); - } - catch (Exception) - { - - } - } + AddLibs(libraries); + AddModules(modules); File.WriteAllText("premake-system.lua", string.Join("\n", content)); } static void AddDisclaimer() @@ -44,9 +34,47 @@ 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); + } + AddLibsEnd(); + } + static void AddModules(PremakeModule[] modules) + { + AddModulesStart(); + foreach (var module in modules) + { + AddModule(module); + } + 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/premake5.lua b/premake5.lua index ca2dce3..615af4d 100644 --- a/premake5.lua +++ b/premake5.lua @@ -1,7 +1,5 @@ require "vstudio" - - workspace "premake-manager-cli" architecture "x86_64" configurations { "Debug", "Release" } From 650f7907f465bae2123ec8104a8fd1e12111cb66 Mon Sep 17 00:00:00 2001 From: Beernaert Robbe Date: Fri, 20 Mar 2026 21:18:16 +0100 Subject: [PATCH 28/28] feat: added listing functions --- premake-manager-cli/src/utils/PremakeSystem.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/premake-manager-cli/src/utils/PremakeSystem.cs b/premake-manager-cli/src/utils/PremakeSystem.cs index 639cb37..06b446e 100644 --- a/premake-manager-cli/src/utils/PremakeSystem.cs +++ b/premake-manager-cli/src/utils/PremakeSystem.cs @@ -41,7 +41,7 @@ static void AddLibs(PremakeLibrary[] libraries) { AddLib(lib); } - AddLibsEnd(); + 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) { @@ -50,7 +50,7 @@ static void AddModules(PremakeModule[] modules) { AddModule(module); } - AddModulesEnd(); + 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() {