Skip to content

Commit

Permalink
fix: Remove working directory option and add project deployment tool …
Browse files Browse the repository at this point in the history
…to global options (#665)

* fix: remove working directory option, and add project deployment tool to global options

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove unnecessary directory existence check in KSailLintCommandHandler

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove workingDirectory property from KSail project schema and related test files

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove working directory option from KSailClusterConfigLoader

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove working directory parameter from LoadAsync method in KSailClusterConfigLoader

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove working directory option from ksail configuration files and help documentation

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove working directory option from KSailInitCommandTests and KSailLintCommandTests

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: remove working directory option from KSail configuration files and tests

Signed-off-by: Nikolai Emil Damm <[email protected]>

* fix: simplify SopsConfigLoaderTests by removing unnecessary directory creation

Signed-off-by: Nikolai Emil Damm <[email protected]>

---------

Signed-off-by: Nikolai Emil Damm <[email protected]>
  • Loading branch information
devantler authored Feb 23, 2025
1 parent 31942b7 commit 3ce5b35
Show file tree
Hide file tree
Showing 95 changed files with 524 additions and 601 deletions.
4 changes: 0 additions & 4 deletions schemas/ksail-cluster-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,6 @@
"description": "The options for the KSail project.",
"type": "object",
"properties": {
"workingDirectory": {
"description": "The working directory for the project.",
"type": "string"
},
"configPath": {
"description": "The path to the ksail configuration file.",
"type": "string"
Expand Down
6 changes: 0 additions & 6 deletions src/KSail.Models/Project/KSailProject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@ namespace KSail.Models.Project;
/// </summary>
public class KSailProject
{
/// <summary>
/// The working directory for the project.
/// </summary>
[Description("The working directory for the project.")]
public string WorkingDirectory { get; set; } = ".";

/// <summary>
/// The path to the ksail configuration file.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class DistributionConfigFileGenerator

internal async Task GenerateAsync(KSailCluster config, CancellationToken cancellationToken = default)
{
string configPath = Path.Combine(config.Spec.Project.WorkingDirectory, config.Spec.Project.DistributionConfigPath);
string configPath = Path.Combine(Directory.GetCurrentDirectory(), config.Spec.Project.DistributionConfigPath);
if (File.Exists(configPath))
{
Console.WriteLine($"✔ skipping '{configPath}', as it already exists.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class FluxSystemGenerator
readonly FluxKustomizationGenerator _fluxKustomizationGenerator = new();
internal async Task GenerateAsync(KSailCluster config, CancellationToken cancellationToken = default)
{
string outputDirectory = Path.Combine(config.Spec.Project.WorkingDirectory, "k8s", "clusters", config.Metadata.Name, "flux-system");
string outputDirectory = Path.Combine("k8s", "clusters", config.Metadata.Name, "flux-system");
if (!Directory.Exists(outputDirectory))
_ = Directory.CreateDirectory(outputDirectory);
await GenerateFluxSystemKustomization(config, outputDirectory, cancellationToken).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class KSailClusterConfigGenerator
readonly KSailClusterGenerator _ksailClusterGenerator = new();
internal async Task GenerateAsync(KSailCluster config, CancellationToken cancellationToken = default)
{
string ksailConfigPath = Path.Combine(config.Spec.Project.WorkingDirectory, "ksail-config.yaml");
string ksailConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "ksail-config.yaml");
if (File.Exists(ksailConfigPath))
{
Console.WriteLine($"✔ skipping '{ksailConfigPath}', as it already exists.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal async Task GenerateAsync(KSailCluster config, CancellationToken cancell

async Task GenerateKustomizeFlowHook(KSailCluster config, string currentHook, string currentFlow, CancellationToken cancellationToken = default)
{
string outputPath = Path.Combine(config.Spec.Project.WorkingDirectory, "k8s", currentHook, currentFlow);
string outputPath = Path.Combine("k8s", currentHook, currentFlow);
if (!Directory.Exists(outputPath))
_ = Directory.CreateDirectory(outputPath);
string outputDirectory = Path.Combine(outputPath, "kustomization.yaml");
Expand All @@ -58,8 +58,8 @@ async Task GenerateKustomizeFlowHook(KSailCluster config, string currentHook, st
kustomization = new KustomizeKustomization
{
Resources = [
Path.Combine($"variables.yaml"),
Path.Combine($"variables-sensitive.enc.yaml")
"variables.yaml",
"variables-sensitive.enc.yaml"
]
};
if (!string.IsNullOrEmpty(pathToNextFlow))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class SOPSConfigFileGenerator

internal async Task GenerateAsync(KSailCluster config, CancellationToken cancellationToken = default)
{
string sopsConfigPath = Path.Combine(config.Spec.Project.WorkingDirectory, ".sops.yaml");
string sopsConfigPath = ".sops.yaml";
if (!File.Exists(sopsConfigPath) || string.IsNullOrEmpty(await File.ReadAllTextAsync(sopsConfigPath, cancellationToken).ConfigureAwait(false)))
{
await GenerateNewSOPSConfigFile(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal async Task GenerateAsync(KSailCluster config, CancellationToken cancell
{
foreach (string hook in config.Spec.KustomizeTemplate.Hooks)
{
string hookPath = Path.Combine(config.Spec.Project.WorkingDirectory, "k8s", hook, "variables");
string hookPath = Path.Combine("k8s", hook, "variables");
string name = hook.Replace("/", "-", StringComparison.Ordinal);
await GenerateVariables(hookPath, name, cancellationToken).ConfigureAwait(false);
}
Expand Down
2 changes: 1 addition & 1 deletion src/KSail/Commands/Init/KSailInitCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public KSailInitCommand(GlobalOptions globalOptions) : base("init", "Initialize
config.UpdateConfig("Spec.KustomizeTemplate.Flows", context.ParseResult.GetValueForOption(_kustomizeTemplateKustomizationsOption));
config.UpdateConfig("Spec.KustomizeTemplate.Hooks", context.ParseResult.GetValueForOption(_kustomizeTemplateKustomizationHooksOption));
var handler = new KSailInitCommandHandler(config);
Console.WriteLine($"📁 Initializing new cluster '{config.Metadata.Name}' in '{config.Spec.Project.WorkingDirectory}' with the '{config.Spec.Project.Template}' template.");
Console.WriteLine($"📁 Initializing new cluster '{config.Metadata.Name}' in './' with the '{config.Spec.Project.Template}' template.");
context.ExitCode = await handler.HandleAsync(context.GetCancellationToken()).ConfigureAwait(false);
Console.WriteLine();
}
Expand Down
15 changes: 3 additions & 12 deletions src/KSail/Commands/Lint/Handlers/KSailLintCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Devantler.KubernetesValidator.ClientSide.Schemas;
using Devantler.KubernetesValidator.ClientSide.YamlSyntax;
using KSail.Models;

namespace KSail.Commands.Lint.Handlers;

Expand All @@ -9,20 +8,12 @@ class KSailLintCommandHandler()
readonly YamlSyntaxValidator _yamlSyntaxValidator = new();
readonly SchemaValidator _schemaValidator = new();

internal async Task<bool> HandleAsync(KSailCluster config, CancellationToken cancellationToken = default)
internal async Task<bool> HandleAsync(CancellationToken cancellationToken = default)
{
string kubernetesDirectory = Path.Combine(config.Spec.Project.WorkingDirectory, "k8s");
// if the k8s directory does not exist or is empty, use the working directory instead
string kubernetesDirectory = Path.Combine(Directory.GetCurrentDirectory(), "k8s");
if (!Directory.Exists(kubernetesDirectory) || Directory.GetFiles(kubernetesDirectory, "*.yaml", SearchOption.AllDirectories).Length == 0)
{
Console.WriteLine($"► no manifest files found in '{kubernetesDirectory}', using '{config.Spec.Project.WorkingDirectory}' instead");
kubernetesDirectory = config.Spec.Project.WorkingDirectory;
}

if (!Directory.Exists(kubernetesDirectory) || Directory.GetFiles(kubernetesDirectory, "*.yaml", SearchOption.AllDirectories).Length == 0)
{
Console.WriteLine($"✔ skipping, as '{kubernetesDirectory}' directory does not exist or is empty");
return true;
throw new KSailException($"no manifest files found in '{kubernetesDirectory}'.");
}

Console.WriteLine("► validating yaml syntax");
Expand Down
2 changes: 1 addition & 1 deletion src/KSail/Commands/Lint/KSailLintCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ internal KSailLintCommand(GlobalOptions globalOptions) : base(

Console.WriteLine("🧹 Linting manifest files");
var handler = new KSailLintCommandHandler();
context.ExitCode = await handler.HandleAsync(config, context.GetCancellationToken()).ConfigureAwait(false) ? 0 : 1;
context.ExitCode = await handler.HandleAsync(context.GetCancellationToken()).ConfigureAwait(false) ? 0 : 1;
Console.WriteLine();
}
catch (Exception ex)
Expand Down
2 changes: 1 addition & 1 deletion src/KSail/Commands/Up/Handlers/KSailUpCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ async Task<bool> Lint(KSailCluster config, CancellationToken cancellationToken =
if (config.Spec.CLI.Up.Lint)
{
Console.WriteLine("🔍 Linting manifests");
bool success = await _ksailLintCommandHandler.HandleAsync(config, cancellationToken).ConfigureAwait(false);
bool success = await _ksailLintCommandHandler.HandleAsync(cancellationToken).ConfigureAwait(false);
Console.WriteLine();
return success;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ internal async Task<bool> HandleAsync(CancellationToken cancellationToken = defa
{
return false;
}
string manifestDirectory = Path.Combine(_config.Spec.Project.WorkingDirectory, "k8s");
string manifestDirectory = "k8s";
if (!Directory.Exists(manifestDirectory) || Directory.GetFiles(manifestDirectory, "*.yaml", SearchOption.AllDirectories).Length == 0)
{
throw new KSailException($"a '{manifestDirectory}' directory does not exist or is empty.");
Expand All @@ -42,7 +42,7 @@ internal async Task<bool> HandleAsync(CancellationToken cancellationToken = defa
var ociRegistryFromHost = new Uri($"{scheme}://{host}:{port}{absolutePath}");
Console.WriteLine($"📥 Pushing manifests to '{ociRegistryFromHost}'");
// TODO: Make some form of abstraction around GitOps tools, so it is easier to support apply-based tools like kubectl
await _deploymentTool.PushManifestsAsync(ociRegistryFromHost, Path.Combine(_config.Spec.Project.WorkingDirectory, "k8s"), cancellationToken: cancellationToken).ConfigureAwait(false);
await _deploymentTool.PushManifestsAsync(ociRegistryFromHost, "k8s", cancellationToken: cancellationToken).ConfigureAwait(false);
Console.WriteLine();
if (_config.Spec.CLI.Update.Reconcile)
{
Expand All @@ -64,7 +64,7 @@ async Task<bool> Lint(KSailCluster config, CancellationToken cancellationToken =
if (config.Spec.CLI.Update.Lint)
{
Console.WriteLine("🔍 Linting manifests");
bool success = await _ksailLintCommandHandler.HandleAsync(config, cancellationToken).ConfigureAwait(false);
bool success = await _ksailLintCommandHandler.HandleAsync(cancellationToken).ConfigureAwait(false);
Console.WriteLine();
return success;
}
Expand Down
16 changes: 8 additions & 8 deletions src/KSail/Options/GlobalOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ public class GlobalOptions : IReadOnlyList<Option>
/// </summary>
public List<Option> Options { get; } =
[
new ConnectionContextOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ConnectionKubeconfigOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ConnectionTimeoutOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new MetadataNameOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new PathOption("The path to the ksail configuration file. Default: 'ksail-config.yaml' (G)", ["--config", "-c"]) { Arity = ArgumentArity.ZeroOrOne },
new ProjectDeploymentToolOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ProjectDistributionOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new PathOption($"Path to the distribution configuration file. Default: 'kind-config.yaml' (G)", ["--distribution-config", "-dc"]) { Arity = ArgumentArity.ZeroOrOne },
new ProjectEditorOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ProjectEngineOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ProjectMirrorRegistriesOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ProjectSecretManagerOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new PathOption($"Path to the distribution configuration file. Default: 'kind-config.yaml' (G)", ["--distribution-config", "-dc"]) { Arity = ArgumentArity.ZeroOrOne },
new PathOption("The root directory of the project. Default: '.' (G)", ["--working-directory", "-wd"]) { Arity = ArgumentArity.ZeroOrOne },
new PathOption("The path to the ksail configuration file. Default: 'ksail-config.yaml' (G)", ["--config", "-c"]) { Arity = ArgumentArity.ZeroOrOne },
new ProjectTemplateOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ProjectEditorOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ConnectionKubeconfigOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ConnectionContextOption(new()) { Arity = ArgumentArity.ZeroOrOne },
new ConnectionTimeoutOption(new()) { Arity = ArgumentArity.ZeroOrOne }
new ProjectTemplateOption(new()) { Arity = ArgumentArity.ZeroOrOne }
];


Expand Down
5 changes: 3 additions & 2 deletions src/KSail/Options/ProjectDeploymentToolOption.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.CommandLine;
using KSail.Models;
using KSail.Models.Project;

namespace KSail.Options;

class ProjectDeploymentToolOption() : Option<KSailDeploymentTool>(
class ProjectDeploymentToolOption(KSailCluster config) : Option<KSailDeploymentTool>(
["-dt", "--deployment-tool"],
"The Deployment tool to use for updating the state of the cluster."
$"The Deployment tool to use for updating the state of the cluster. Default: '{config.Spec.Project.DeploymentTool}' (G)"
)
{
}
7 changes: 2 additions & 5 deletions src/KSail/Utils/KSailClusterConfigLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ internal static async Task<KSailCluster> LoadWithGlobalOptionsAsync(GlobalOption
var metadataNameOption = (MetadataNameOption)globalOptions.Options.First(o => o is MetadataNameOption);
var projectConfigOption = (PathOption)globalOptions.Options.First(o => o is PathOption && o.Aliases.Contains("--config"));
var projectDistributionOption = (ProjectDistributionOption)globalOptions.Options.First(o => o is ProjectDistributionOption);
var projectWorkingDirectoryOption = (PathOption)globalOptions.Options.First(o => o is PathOption && o.Aliases.Contains("--working-directory"));
var config = await LoadAsync(
context.ParseResult.GetValueForOption(projectConfigOption),
context.ParseResult.GetValueForOption(projectWorkingDirectoryOption),
context.ParseResult.GetValueForOption(metadataNameOption),
context.ParseResult.GetValueForOption(projectDistributionOption)
).ConfigureAwait(false);
config.UpdateConfig("Metadata.Name", context.ParseResult.GetValueForOption(metadataNameOption));
config.UpdateConfig("Spec.Connection.Kubeconfig", context.ParseResult.GetValueForOption((ConnectionKubeconfigOption)globalOptions.Options.First(o => o is ConnectionKubeconfigOption)));
config.UpdateConfig("Spec.Connection.Context", context.ParseResult.GetValueForOption((ConnectionContextOption)globalOptions.Options.First(o => o is ConnectionContextOption)));
config.UpdateConfig("Spec.Connection.Timeout", context.ParseResult.GetValueForOption((ConnectionTimeoutOption)globalOptions.Options.First(o => o is ConnectionTimeoutOption)));
config.UpdateConfig("Spec.Project.WorkingDirectory", context.ParseResult.GetValueForOption(projectWorkingDirectoryOption));
config.UpdateConfig("Spec.Project.ConfigPath", context.ParseResult.GetValueForOption(projectConfigOption));
config.UpdateConfig("Spec.Project.Distribution", context.ParseResult.GetValueForOption(projectDistributionOption));
config.UpdateConfig("Spec.Project.DistributionConfigPath", context.ParseResult.GetValueForOption((PathOption)globalOptions.Options.First(o => o is PathOption && o.Aliases.Contains("--distribution-config"))));
Expand All @@ -46,15 +43,15 @@ internal static async Task<KSailCluster> LoadWithGlobalOptionsAsync(GlobalOption
return config;
}

internal static async Task<KSailCluster> LoadAsync(string? configFilePath = "ksail-config.yaml", string? directory = default, string? name = default, KSailKubernetesDistribution distribution = default)
internal static async Task<KSailCluster> LoadAsync(string? configFilePath = "ksail-config.yaml", string? name = default, KSailKubernetesDistribution distribution = default)
{
// Create default KSailClusterConfig
var ksailClusterConfig = string.IsNullOrEmpty(name) ?
new KSailCluster(distribution: distribution) :
new KSailCluster(name, distribution: distribution);

// Locate KSail YAML file
string startDirectory = directory ?? Directory.GetCurrentDirectory();
string startDirectory = Directory.GetCurrentDirectory();
string? ksailYaml = string.IsNullOrEmpty(configFilePath) ?
FindConfigFile(startDirectory, "ksail-config.yaml") :
FindConfigFile(startDirectory, configFilePath);
Expand Down
4 changes: 2 additions & 2 deletions src/KSail/Utils/SopsConfigLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ namespace KSail.Utils;
static class SopsConfigLoader
{
static readonly SOPSConfigHelper _sopsConfigHelper = new();
internal static async Task<SOPSConfig> LoadAsync(string? directory = default, CancellationToken cancellationToken = default)
internal static async Task<SOPSConfig> LoadAsync(CancellationToken cancellationToken = default)
{
Console.WriteLine("► searching for a '.sops.yaml' file");
directory ??= Directory.GetCurrentDirectory();
string directory = Directory.GetCurrentDirectory();
string sopsConfigPath = string.Empty;
while (!string.IsNullOrEmpty(directory))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ spec:
context: k3d-my-cluster
timeout: 5m
project:
workingDirectory: .
configPath: ksail-config.yaml
distributionConfigPath: k3d-config.yaml
template: Kustomize
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ spec:
context: kind-ksail-default
timeout: 5m
project:
workingDirectory: .
configPath: ksail-config.yaml
distributionConfigPath: kind-config.yaml
template: Kustomize
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Timeout: 5m
},
Project: {
WorkingDirectory: .,
ConfigPath: ksail-config.yaml,
DistributionConfigPath: k3d-config.yaml,
Template: Kustomize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Timeout: 5m
},
Project: {
WorkingDirectory: .,
ConfigPath: ksail-config.yaml,
DistributionConfigPath: k3d-config.yaml,
Template: Kustomize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Timeout: 5m
},
Project: {
WorkingDirectory: .,
ConfigPath: ksail-config.yaml,
DistributionConfigPath: kind-config.yaml,
Template: Kustomize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Timeout: 5m
},
Project: {
WorkingDirectory: .,
ConfigPath: ksail-config.yaml,
DistributionConfigPath: kind-config.yaml,
Template: Kustomize,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,6 @@
"description": "The options for the KSail project.",
"type": "object",
"properties": {
"workingDirectory": {
"description": "The working directory for the project.",
"type": "string"
},
"configPath": {
"description": "The path to the ksail configuration file.",
"type": "string"
Expand Down
Loading

0 comments on commit 3ce5b35

Please sign in to comment.