Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Align seqcli's environment override handling with Seq's #366

Merged
merged 3 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 13 additions & 103 deletions src/SeqCli/Cli/Commands/ConfigCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,25 @@ protected override Task<int> Run()

try
{
var config = SeqCliConfig.Read();

var config = SeqCliConfig.ReadFromFile(RuntimeConfigurationLoader.DefaultConfigFilename);
if (_key != null)
{
if (_clear)
{
verb = "clear";
Clear(config, _key);
SeqCliConfig.Write(config);
KeyValueSettings.Clear(config, _key);
SeqCliConfig.WriteToFile(config, RuntimeConfigurationLoader.DefaultConfigFilename);
}
else if (_value != null)
{
verb = "update";
Set(config, _key, _value);
SeqCliConfig.Write(config);
KeyValueSettings.Set(config, _key, _value);
SeqCliConfig.WriteToFile(config, RuntimeConfigurationLoader.DefaultConfigFilename);
}
else
{
verb = "print";
Print(config, _key);
}
}
Expand All @@ -78,114 +79,23 @@ protected override Task<int> Run()
return Task.FromResult(1);
}
}

static void Print(SeqCliConfig config, string key)
{
if (config == null) throw new ArgumentNullException(nameof(config));
if (key == null) throw new ArgumentNullException(nameof(key));

var pr = ReadPairs(config).SingleOrDefault(p => p.Key == key);
if (pr.Key == null)
throw new ArgumentException($"Option {key} not found.");

Console.WriteLine(Format(pr.Value));
}

static void Set(SeqCliConfig config, string key, string? value)
{
if (config == null) throw new ArgumentNullException(nameof(config));
if (key == null) throw new ArgumentNullException(nameof(key));

var steps = key.Split('.');
if (steps.Length != 2)
throw new ArgumentException("The format of the key is incorrect; run the command without any arguments to view all keys.");

var first = config.GetType().GetTypeInfo().DeclaredProperties
.Where(p => p.CanRead && p.GetMethod!.IsPublic && !p.GetMethod.IsStatic)
.SingleOrDefault(p => Camelize(p.Name) == steps[0]);

if (first == null)
throw new ArgumentException("The key could not be found; run the command without any arguments to view all keys.");

if (first.PropertyType == typeof(Dictionary<string, SeqCliConnectionConfig>))
throw new NotSupportedException("Use `seqcli profile create` to configure connection profiles.");

var second = first.PropertyType.GetTypeInfo().DeclaredProperties
.Where(p => p.CanRead && p.GetMethod!.IsPublic && !p.GetMethod.IsStatic)
.SingleOrDefault(p => Camelize(p.Name) == steps[1]);

if (second == null)
throw new ArgumentException("The key could not be found; run the command without any arguments to view all keys.");
if (!KeyValueSettings.TryGetValue(config, key, out var value, out _))
throw new ArgumentException($"Option {key} not found");

if (!second.CanWrite || !second.SetMethod!.IsPublic)
throw new ArgumentException("The value is not writeable.");

var targetValue = Convert.ChangeType(value, second.PropertyType, CultureInfo.InvariantCulture);
var configItem = first.GetValue(config);
second.SetValue(configItem, targetValue);
}

static void Clear(SeqCliConfig config, string key)
{
Set(config, key, null);
Console.WriteLine(value);
}

static void List(SeqCliConfig config)
{
foreach (var (key, value) in ReadPairs(config))
{
Console.WriteLine($"{key}:");
Console.WriteLine($" {Format(value)}");
}
}

static IEnumerable<KeyValuePair<string, object?>> ReadPairs(object config)
{
foreach (var property in config.GetType().GetTypeInfo().DeclaredProperties
.Where(p => p.CanRead && p.GetMethod!.IsPublic && !p.GetMethod.IsStatic && !p.Name.StartsWith("Encoded"))
.OrderBy(p => p.Name))
foreach (var (key, value, _) in KeyValueSettings.Inspect(config))
{
var propertyName = Camelize(property.Name);
var propertyValue = property.GetValue(config);

if (propertyValue is IDictionary dict)
{
foreach (var elementKey in dict.Keys)
{
foreach (var elementPair in ReadPairs(dict[elementKey]!))
{
yield return new KeyValuePair<string, object?>(
$"{propertyName}[{elementKey}].{elementPair.Key}",
elementPair.Value);
}
}
}
else if (propertyValue?.GetType().Namespace?.StartsWith("SeqCli.Config") ?? false)
{
foreach (var childPair in ReadPairs(propertyValue))
{
var name = propertyName + "." + childPair.Key;
yield return new KeyValuePair<string, object?>(name, childPair.Value);
}
}
else
{
yield return new KeyValuePair<string, object?>(propertyName, propertyValue);
}
Console.WriteLine($"{key}={value}");
}
}

static string Camelize(string s)
{
if (s.Length < 2)
throw new NotSupportedException("No camel-case support for short names");
return char.ToLowerInvariant(s[0]) + s.Substring(1);
}

static string Format(object? value)
{
return value is IFormattable formattable
? formattable.ToString(null, CultureInfo.InvariantCulture)
: value?.ToString() ?? "";
}
}
4 changes: 2 additions & 2 deletions src/SeqCli/Cli/Commands/Profile/CreateCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ int RunSync()

try
{
var config = SeqCliConfig.Read();
var config = SeqCliConfig.ReadFromFile(RuntimeConfigurationLoader.DefaultConfigFilename);
config.Profiles[_name] = new SeqCliConnectionConfig { ServerUrl = _url, ApiKey = _apiKey };
SeqCliConfig.Write(config);
SeqCliConfig.WriteToFile(config, RuntimeConfigurationLoader.DefaultConfigFilename);
return 0;
}
catch (Exception ex)
Expand Down
2 changes: 1 addition & 1 deletion src/SeqCli/Cli/Commands/Profile/ListCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class ListCommand : Command
{
protected override Task<int> Run()
{
var config = SeqCliConfig.Read();
var config = RuntimeConfigurationLoader.Load();

foreach (var profile in config.Profiles.OrderBy(p => p.Key))
{
Expand Down
4 changes: 2 additions & 2 deletions src/SeqCli/Cli/Commands/Profile/RemoveCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ int RunSync()

try
{
var config = SeqCliConfig.Read();
var config = SeqCliConfig.ReadFromFile(RuntimeConfigurationLoader.DefaultConfigFilename);
if (!config.Profiles.Remove(_name))
{
Log.Error("No profile with name {ProfileName} was found", _name);
return 1;
}

SeqCliConfig.Write(config);
SeqCliConfig.WriteToFile(config, RuntimeConfigurationLoader.DefaultConfigFilename);

return 0;
}
Expand Down
8 changes: 4 additions & 4 deletions src/SeqCli/Cli/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ private static int GetLineEnd (int start, int length, string description)

class OptionValueCollection : IList, IList<string> {

List<string> values = new List<string> ();
List<string> values = new();
OptionContext c;

internal OptionValueCollection (OptionContext c)
Expand Down Expand Up @@ -694,7 +694,7 @@ public Converter<string, string> MessageLocalizer {
get {return localizer;}
}

List<ArgumentSource> sources = new List<ArgumentSource> ();
List<ArgumentSource> sources = new();
ReadOnlyCollection<ArgumentSource> roSources;

public ReadOnlyCollection<ArgumentSource> ArgumentSources {
Expand Down Expand Up @@ -960,7 +960,7 @@ public List<string> Parse (IEnumerable<string> arguments)
}

class ArgumentEnumerator : IEnumerable<string> {
List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
List<IEnumerator<string>> sources = new();

public ArgumentEnumerator (IEnumerable<string> arguments)
{
Expand Down Expand Up @@ -1015,7 +1015,7 @@ private static bool Unprocessed (ICollection<string> extra, Option def, OptionCo
return false;
}

private readonly Regex ValueOption = new Regex (
private readonly Regex ValueOption = new(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");

protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
Expand Down
37 changes: 37 additions & 0 deletions src/SeqCli/Config/EnvironmentOverrides.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace SeqCli.Config;

static class EnvironmentOverrides
{
public static void Apply(string prefix, SeqCliConfig config)
{
var environment = Environment.GetEnvironmentVariables();
Apply(prefix, config, environment.Keys.Cast<string>().ToDictionary(k => k, k => (string?)environment[k]));
}

internal static void Apply(string prefix, SeqCliConfig config, Dictionary<string, string?> environment)
{
if (config == null) throw new ArgumentNullException(nameof(config));
if (environment == null) throw new ArgumentNullException(nameof(environment));

config.DisallowExport();

foreach (var (key, _, _) in KeyValueSettings.Inspect(config))
{
var envVar = ToEnvironmentVariableName(prefix, key);
if (environment.TryGetValue(envVar, out var value))
{
KeyValueSettings.Set(config, key, value ?? "");
}
}
}

internal static string ToEnvironmentVariableName(string prefix, string key)
{
return prefix + key.Replace(".", "_").ToUpperInvariant();
}
}
Loading