Skip to content

Commit

Permalink
Splits DockerComposeSettings into standalone settings
Browse files Browse the repository at this point in the history
  • Loading branch information
MihaMarkic committed Feb 24, 2024
1 parent 935fbb3 commit 0bcf83c
Show file tree
Hide file tree
Showing 53 changed files with 1,153 additions and 1,037 deletions.
254 changes: 148 additions & 106 deletions args-parser-2.linq
Original file line number Diff line number Diff line change
@@ -1,128 +1,170 @@
<Query Kind="Statements" />
<Query Kind="Program">
<Namespace>System.Collections.Immutable</Namespace>
</Query>

string path = @"Compose\Run";
string file = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath)!, $@"src\Cake.Docker\{path}\args.txt");
//string file = @"D:\GitProjects\Righthand\Cake\Cake.Docker\src\Cake.Docker\Compose\Up\args.txt";
string[] lines = File.ReadAllLines(file);

Regex regex = new Regex(
"--(?<Argument>[a-z0-9,\\-]+)(?:\\s(?<Type>\\w+))?\\s+(?<Info>.+" +
")",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.CultureInvariant
| RegexOptions.Compiled
);

Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
List<string>? current = null;
foreach (string line in lines.Where(l =>!string.IsNullOrEmpty(l)).Select(l => l.TrimStart()))
void Main()
{
if (line.StartsWith("-"))
string[] commands = new[] { "Build", "Cp", "Create", "Down", "Exec", "Kill", "Logs", "Pause", "Port", "Ps", "Pull", "Push", "Restart", "Rm", "Run", "Scale", "Start", "Stop", "Unpase", "Up" };
foreach (string command in commands)
{
current = new List<string>();
data.Add(line, current);
CreateSettings(@$"Compose\{command}", true);
}
else
}

int CountSpaces(string line)
{
int result = 0;
foreach (char c in line)
{
current.Add(line.Trim());
if (c != ' ')
{
break;
}
result++;
}
return result;
}
string className = path.Replace(@"\", "");
"namespace Cake.Docker".Dump();
"{".Dump();
"/// <summary>".Dump();
$"/// Settings for docker {string.Join(" ", path.Split('\\').Select(p => p.ToLower()))}.".Dump();
"/// </summary>".Dump();
$"public sealed class Docker{className}Settings : DockerComposeSettings".Dump();
"{".Dump();
foreach (var pair in data)

void CreateSettings(string command, bool outputToFile)
{
string line = pair.Key;

var match = regex.Match(line);
if (!match.Success)
string file = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath)!, $@"src\Cake.Docker\{command}\args.txt");
if (!File.Exists(file))
{
("FAILED to match " + line).Dump();
file.Dump("Skipping, does not exist");
return;
}
else
string className = command.Replace(@"\", "");
string settingsFile = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath)!, $@"src\Cake.Docker\{command}\\Docker{className}Settings.cs");
//string file = @"D:\GitProjects\Righthand\Cake\Cake.Docker\src\Cake.Docker\Compose\Up\args.txt";
string[] lines = File.ReadAllLines(file);
//string.Join(Environment.NewLine, lines).Dump();

Regex regex = new Regex(
"--(?<Argument>[a-z0-9,\\-]+)(?:\\s(?<Type>\\w+))?\\s+(?<Info>.+" +
")",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.CultureInvariant
| RegexOptions.Compiled
);

Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
List<string>? current = null;
foreach (string line in lines.Where(l => !string.IsNullOrEmpty(l)))
{
string rawName = match.Groups["Argument"].Value;
string type = match.Groups["Type"].Value;
string info = match.Groups["Info"].Value;
string name = "";
bool upperCase = true;
foreach (char c in rawName)
int offset = CountSpaces(line);
var trimmed = line.AsSpan().Trim();
if (offset < 34 && trimmed.StartsWith("-"))
{
if (upperCase)
{
name += char.ToUpper(c);
upperCase = false;
}
else
{
if (c == '-')
{
upperCase = true;
}
else
{
name += c;
}
}
current = new List<string>();
data.Add(line, current);
}
List<string> comment = new List<string>();
comment.Add(info);
comment.AddRange(pair.Value.Select(l => $"\t{l}"));
"/// <summary>".Dump();
foreach (string commentLine in comment)
current!.Add(trimmed.ToString());
}
StringBuilder sb = new();

sb.AppendLine("namespace Cake.Docker;");
sb.AppendLine("/// <summary>");
sb.AppendLine($"/// Settings for docker {string.Join(" ", command.Split('\\').Select(p => p.ToLower()))}.");
sb.AppendLine("/// </summary>");
sb.AppendLine($"public sealed class Docker{className}Settings : AutoToolSettings");
sb.AppendLine("{");
foreach (var pair in data)
{
string line = pair.Key;

var match = regex.Match(line);
if (!match.Success)
{
("/// " + commentLine
.Replace("<", "&lt;")
.Replace(">", "&gt;"))
.Dump();
("FAILED to match " + line).Dump();
}
"/// </summary>".Dump();
string netType;
switch (type)
else
{
case "duration":
netType = "TimeSpan?";
break;
case "int?":
case "int":
case "uint":
netType = "int?";
break;
case "value":
if (info.EndsWith("[])"))
{
netType = "string[]?";
string rawName = match.Groups["Argument"].Value;
string type = match.Groups["Type"].Value;
string info = match.Groups["Info"].Value;
string name = "";
bool upperCase = true;
foreach (char c in rawName)
{
if (upperCase)
{
name += char.ToUpper(c);
upperCase = false;
}
else
{
netType = "string=";
if (c == '-')
{
upperCase = true;
}
else
{
name += c;
}
}
break;
case "string":
netType = "string?";
break;
case "strings":
netType = "string[]?";
break;
case "stringArray":
netType = "string[]?";
break;
default:
netType = "bool?";
break;
}
if (type == "stringArray")
{
"[AutoProperty(AutoArrayType=AutoArrayType.List)]".Dump();
}
List<string> comment = new List<string>();
comment.Add(info);
comment.AddRange(pair.Value.Skip(1).Select(l => $"{l}"));
sb.AppendLine("\t/// <summary>");
foreach (string commentLine in comment)
{
sb.AppendLine("\t/// " + commentLine
.Replace("<", "&lt;")
.Replace(">", "&gt;"));
}
sb.AppendLine("\t/// </summary>");
string netType;
switch (type)
{
case "duration":
netType = "TimeSpan?";
break;
case "int?":
case "int":
case "uint":
case "bytes":
netType = "int?";
break;
case "value":
if (info.EndsWith("[])"))
{
netType = "string[]?";
}
else
{
netType = "string?=";
}
break;
case "string":
netType = "string?";
break;
case "strings":
netType = "string[]?";
break;
case "stringArray":
netType = "string[]?";
break;
default:
netType = "bool?";
break;
}
if (type == "stringArray")
{
sb.AppendLine("\t[AutoProperty(AutoArrayType=AutoArrayType.List)]");
}
sb.AppendLine($"\tpublic {netType} {name} {{ get; set; }}");
}
$"public {netType} {name} {{ get; set; }}".Dump();
}
}
"}".Dump();
"}".Dump();
sb.AppendLine("}");
if (outputToFile)
{
File.WriteAllText(settingsFile, sb.ToString());
}
else
{
sb.Dump();
}

}
40 changes: 6 additions & 34 deletions src/Cake.Docker.Tests/Compose/Build/DockerComposeBuildFixture.cs
Original file line number Diff line number Diff line change
@@ -1,39 +1,11 @@
using Cake.Core;
using Cake.Core.Configuration;
using Cake.Core.Diagnostics;
using Cake.Core.IO;
using Cake.Testing.Fixtures;
using System;
using Cake.Docker.Tests.Compose;

namespace Cake.Docker.Tests.Build
namespace Cake.Docker.Tests.Build;

public class DockerComposeBuildFixture : DockerComposeFixture<DockerComposeBuildSettings>
{
public class DockerComposeBuildFixture : ToolFixture<DockerComposeBuildSettings>, ICakeContext
protected override void RunTool()
{
public string[] Services { get; set; } = [];

IFileSystem ICakeContext.FileSystem => FileSystem;

ICakeEnvironment ICakeContext.Environment => Environment;

public ICakeLog Log => Log;

ICakeArguments ICakeContext.Arguments => throw new NotImplementedException();

IProcessRunner ICakeContext.ProcessRunner => ProcessRunner;

public IRegistry Registry => Registry;

public ICakeDataResolver Data => throw new NotImplementedException();

ICakeConfiguration ICakeContext.Configuration => throw new NotImplementedException();

public DockerComposeBuildFixture(): base("docker")
{
ProcessRunner.Process.SetStandardOutput(Array.Empty<string>());
}
protected override void RunTool()
{
this.DockerComposeBuild(Settings, Services);
}
this.DockerComposeBuild(Settings, ComposeSettings, Services);
}
}
32 changes: 24 additions & 8 deletions src/Cake.Docker.Tests/Compose/Build/DockerComposeBuildTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ public void WhenParallelFlagIsSet_CommandLineIsCorrect()
{
var fixture = new DockerComposeBuildFixture
{
Settings = new DockerComposeBuildSettings { Parallel = 2 },
ComposeSettings = new DockerComposeSettings { Parallel = 2, },
Settings = new DockerComposeBuildSettings { },
};

var actual = fixture.Run();

Assert.That(actual.Args, Is.EqualTo("compose build --parallel 2"));
Assert.That(actual.Args, Is.EqualTo("compose --parallel 2 build"));
}

[Test]
public void WhenParallelFlagIsSetToFalse_CommandLineDoesNotHaveRm()
{
var fixture = new DockerComposeBuildFixture
{
Settings = new DockerComposeBuildSettings { Parallel = null },
ComposeSettings = new DockerComposeSettings { Parallel = null, },
Settings = new DockerComposeBuildSettings { },
};

var actual = fixture.Run();
Expand All @@ -32,28 +34,42 @@ public void WhenParallelFlagIsSetToFalse_CommandLineDoesNotHaveRm()
}

[Test]
public void WhenFilesFlagIsUsed_CommandLineIncludesIt()
public void WhenFilesAreUsed_CommandLineIncludesIt()
{
var fixture = new DockerComposeBuildFixture
{
Settings = new DockerComposeBuildSettings { File = ["alfa.yaml"] },
ComposeSettings = new DockerComposeSettings { File = ["alfa.yaml"], },
Settings = new DockerComposeBuildSettings { },
};

var actual = fixture.Run();

Assert.That(actual.Args, Is.EqualTo("compose build --file \"alfa.yaml\""));
Assert.That(actual.Args, Is.EqualTo("compose --file \"alfa.yaml\" build"));
}
[Test]
public void WhenTwoFilesAreProvided_CommandLineIncludesThem()
{
var fixture = new DockerComposeBuildFixture
{
Settings = new DockerComposeBuildSettings { File = ["alfa.yaml", "beta.yaml"] },
ComposeSettings = new DockerComposeSettings { File = ["alfa.yaml", "beta.yaml"], },
};

var actual = fixture.Run();

Assert.That(actual.Args, Is.EqualTo("compose build --file \"alfa.yaml\" --file \"beta.yaml\""));
Assert.That(actual.Args, Is.EqualTo("compose --file \"alfa.yaml\" --file \"beta.yaml\" build"));
}
[Test]
public void WhenFilesAreUsedAndMemoryIsSet_CommandLineIncludesIt()
{
var fixture = new DockerComposeBuildFixture
{
ComposeSettings = new DockerComposeSettings { File = ["alfa.yaml"], },
Settings = new DockerComposeBuildSettings { Memory = 1024, },
};

var actual = fixture.Run();

Assert.That(actual.Args, Is.EqualTo("compose --file \"alfa.yaml\" build --memory 1024"));
}
}
}
Loading

0 comments on commit 0bcf83c

Please sign in to comment.