Skip to content
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
12 changes: 12 additions & 0 deletions docs/docs/operator/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,18 @@ All commands support these options:
- `--project`: Regex pattern to filter projects in a solution
- `--target-framework`: Specify target framework for solution projects

### Exit Codes

The CLI returns the exit code of the executed command, so failures can be detected in scripts,
MSBuild `Exec` tasks or CI pipelines:

| Code | Meaning |
| ---- | --------------------------------------------- |
| `0` | Success |
| `1` | Error (an unhandled exception occurred) |
| `2` | Aborted by the user (confirmation prompt) |
| `99` | Usage error (invalid arguments or options) |

### Common Use Cases

1. **Development Setup**:
Expand Down
2 changes: 1 addition & 1 deletion src/KubeOps.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@
errorAction.ShowTypoCorrections = true;
}

await parseResult.InvokeAsync();
return await parseResult.InvokeAsync();
14 changes: 14 additions & 0 deletions src/KubeOps.Cli/Transpilation/AssemblyLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ private static readonly ConditionalWeakTable<MetadataLoadContext, IInheritedAttr
private static readonly ConditionalWeakTable<MetadataLoadContext, OperatorWatchScope>
OperatorWatchScopes = new();

private static readonly string CliDirectory =
AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);

static AssemblyLoader()
{
MSBuildLocator.RegisterDefaults();
Expand Down Expand Up @@ -229,10 +232,21 @@ public static IEnumerable<EntityMetadata> GetConvertedEntities(this MetadataLoad

private static IEnumerable<TypeInfo> GetTypesToInspect(this MetadataLoadContext context) => context
.GetAssemblies()
.Where(a => !IsCliAssembly(a))
.SelectMany(a => a.DefinedTypes)
.Where(t => t is { IsInterface: false, IsAbstract: false, IsGenericType: false })
.OrderBy(t => t.FullName, StringComparer.Ordinal);

// Assemblies next to the CLI only end up in the context because Utilities.GetContextType falls back to
// LoadFromAssemblyPath. Their references (e.g. Microsoft.CodeAnalysis) are not part of the
// PathAssemblyResolver, so inspecting them throws FileNotFoundException.
private static bool IsCliAssembly(Assembly assembly) =>
!string.IsNullOrEmpty(assembly.Location) &&
string.Equals(
Path.GetDirectoryName(assembly.Location)?.TrimEnd(Path.DirectorySeparatorChar),
CliDirectory,
StringComparison.OrdinalIgnoreCase);

[GeneratedRegex(".*")]
private static partial Regex DefaultRegex();
}
79 changes: 79 additions & 0 deletions test/KubeOps.Cli.Test/Transpilation/AssemblyLoader.Test.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

using System.Reflection;

using FluentAssertions;

using k8s.Models;

using KubeOps.Cli.Generators;
using KubeOps.Cli.Transpilation;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace KubeOps.Cli.Test.Transpilation;

[Trait("Area", "Transpilation")]
public sealed class AssemblyLoaderTest
{
[Fact]
public void Should_Not_Inspect_Assemblies_Loaded_From_The_Cli_Directory()
{
using var parser = CreateParser();

// Utilities.GetContextType falls back to LoadFromAssemblyPath for types that only exist in the CLI.
parser.LoadFromAssemblyPath(typeof(RbacGenerator).Assembly.Location);

var inspect = () =>
{
parser.GetRbacAttributes().ToList();
parser.GetValidatedEntities().ToList();
parser.GetMutatedEntities().ToList();
parser.GetConvertedEntities().ToList();
};

inspect.Should().NotThrow();
parser.GetEntities().Should().ContainSingle().Which.Name.Should().Be("AssemblyLoaderTestEntity");
}

private static MetadataLoadContext CreateParser()
{
const string source = """
using k8s.Models;

[KubernetesEntity(Group = "testing.dev", ApiVersion = "v1", Kind = "AssemblyLoaderTestEntity")]
internal sealed class AssemblyLoaderTestEntity;
""";
var syntaxTree = CSharpSyntaxTree.ParseText(source, path: "AssemblyLoaderTestEntity.cs");
var referencePaths = GetReferencePaths().ToList();
var compilation = CSharpCompilation.Create(
$"AssemblyLoaderTestAssembly-{Guid.NewGuid():N}",
[syntaxTree],
referencePaths.Select(path => MetadataReference.CreateFromFile(path)),
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var assemblyStream = new MemoryStream();
compilation.Emit(assemblyStream).Diagnostics
.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)
.Should().BeEmpty();

// The resolver mirrors production: it only knows the inspected project's references, so resolving
// anything the CLI itself is compiled against fails.
var parser = new MetadataLoadContext(new PathAssemblyResolver(referencePaths
.Where(path => !Path.GetFileName(path).StartsWith("Microsoft.CodeAnalysis", StringComparison.Ordinal))));
parser.LoadFromByteArray(assemblyStream.ToArray());
return parser;
}

private static IEnumerable<string> GetReferencePaths()
{
var trustedPlatformAssemblies = (string?)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")
?? throw new InvalidOperationException("Trusted platform assemblies are unavailable.");

return trustedPlatformAssemblies.Split(Path.PathSeparator)
.Concat([typeof(V1Namespace).Assembly.Location])
.Distinct(StringComparer.OrdinalIgnoreCase);
}
}
Loading