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
27 changes: 22 additions & 5 deletions src/Fallout.Build/Execution/BuildManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Fallout.Common.Tooling;
using Fallout.Common.Utilities;
using Fallout.Common.Utilities.Collections;
using Fallout.Common.ValueInjection;
using Serilog;
#pragma warning disable CA2255

Expand All @@ -17,12 +18,12 @@ internal static class BuildManager
{
private const int ErrorExitCode = -1;

private static readonly LinkedList<Action> s_cancellationHandlers = new();
private static readonly LinkedList<Action> cancellationHandlers = new();

public static event Action CancellationHandler
{
add => s_cancellationHandlers.AddFirst(value);
remove => s_cancellationHandlers.Remove(value);
add => cancellationHandlers.AddFirst(value);
remove => cancellationHandlers.Remove(value);
}

[ModuleInitializer]
Expand All @@ -38,11 +39,17 @@ public static int Execute<T>(Expression<Func<T, Target>>[] defaultTargetExpressi
{
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
Console.CancelKeyPress += (_, _) => s_cancellationHandlers.ForEach(x => x());
ToolOptions.Created += (options, _) => VerbosityMapping.Apply((ToolOptions)options);

var build = new T();

// Hold the per-run global subscriptions in locals so the finally can undo exactly them —
// otherwise each Execute in the same process (tests, hosted scenarios) accumulates handlers.
// FT-1 / #306.
ConsoleCancelEventHandler onCancelKeyPress = (_, _) => cancellationHandlers.ForEach(x => x());
EventHandler onToolOptionsCreated = (options, _) => VerbosityMapping.Apply((ToolOptions)options);
Console.CancelKeyPress += onCancelKeyPress;
ToolOptions.Created += onToolOptionsCreated;

try
{
Logging.Configure(build);
Expand Down Expand Up @@ -88,6 +95,16 @@ public static int Execute<T>(Expression<Func<T, Target>>[] defaultTargetExpressi
{
Finish();
Log.CloseAndFlush();

// FT-1 (#306): undo this run's process-global state so a subsequent Execute in the same
// process starts clean — no accumulated handlers, no carried-over log events / caches / config.
CancellationHandler -= Finish;
Console.CancelKeyPress -= onCancelKeyPress;
ToolOptions.Created -= onToolOptionsCreated;
Logging.InMemorySink.Instance.Clear();
ValueInjectionUtility.ClearCache();
NuGetToolPathResolver.Reset();
NpmToolPathResolver.Reset();
}

void Finish()
Expand Down
3 changes: 3 additions & 0 deletions src/Fallout.Build/Execution/ValueInjectionUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ internal static class ValueInjectionUtility
{
private static readonly Dictionary<MemberInfo, object> s_valueCache = new();

/// <summary>Clears the per-run injected-value cache so a subsequent build in the same process re-injects. FT-1 / #306.</summary>
internal static void ClearCache() => s_valueCache.Clear();

public static T TryGetValue<T>(Expression<Func<T>> parameterExpression)
where T : class
{
Expand Down
8 changes: 7 additions & 1 deletion src/Fallout.Build/Logging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,16 @@ public void Emit(LogEvent logEvent)
_logEvents.Add(logEvent);
}

public void Dispose()
/// <summary>Drops accumulated events so a subsequent build in the same process starts clean. FT-1 / #306.</summary>
public void Clear()
{
_logEvents.Clear();
}

public void Dispose()
{
Clear();
}
}

internal class ExecutingTargetLogEventEnricher : ILogEventEnricher
Expand Down
6 changes: 6 additions & 0 deletions src/Fallout.Tooling/NpmToolPathResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ public static class NpmToolPathResolver
{
public static AbsolutePath NpmPackageJsonFile;

/// <summary>Resets the per-run package.json location so a subsequent build in the same process starts from defaults. FT-1 / #306.</summary>
public static void Reset()
{
NpmPackageJsonFile = null;
}

public static string GetNpmExecutable(string npmExecutable)
{
Assert.FileExists(NpmPackageJsonFile);
Expand Down
9 changes: 9 additions & 0 deletions src/Fallout.Tooling/NuGetToolPathResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ public static class NuGetToolPathResolver
public static string NuGetAssetsConfigFile;
public static string PaketPackagesConfigFile;

/// <summary>Resets the per-run package-location config so a subsequent build in the same process starts from defaults. FT-1 / #306.</summary>
public static void Reset()
{
EmbeddedPackagesDirectory = null;
NuGetPackagesConfigFile = null;
NuGetAssetsConfigFile = null;
PaketPackagesConfigFile = null;
}

public static string GetPackageExecutable(string packageId, string packageExecutable, string version = null, string framework = null)
{
Assert.True(packageId != null && packageExecutable != null);
Expand Down
67 changes: 67 additions & 0 deletions tests/Fallout.Build.Specs/InMemorySinkSpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using FluentAssertions;
using Fallout.Common.Execution;
using Serilog.Events;
using Serilog.Parsing;
using Xunit;

namespace Fallout.Common.Specs;

/// <summary>
/// Covers <see cref="Logging.InMemorySink"/>'s reset added in FT-1 / #306. The sink is a
/// process-wide singleton, so <c>BuildManager.Execute</c>'s <c>finally</c> calls <c>Clear()</c> to
/// stop one run's warnings/errors bleeding into the next build in the same process; <c>Dispose()</c>
/// delegates to the same reset.
/// </summary>
public class InMemorySinkSpecs
{
private static readonly Logging.InMemorySink Sink = Logging.InMemorySink.Instance;

public InMemorySinkSpecs()
{
// Normalize the shared singleton before each case — prior runs (or a real logging pipeline)
// may have left events behind.
Sink.Clear();
}

[Fact]
public void Clear_drops_accumulated_events()
{
Sink.Emit(CreateLogEvent("first"));
Sink.Emit(CreateLogEvent("second"));
Sink.LogEvents.Should().HaveCount(2);

Sink.Clear();

Sink.LogEvents.Should().BeEmpty();
}

[Fact]
public void Dispose_drops_accumulated_events()
{
Sink.Emit(CreateLogEvent("only"));
Sink.LogEvents.Should().ContainSingle();

Sink.Dispose();

Sink.LogEvents.Should().BeEmpty();
}

[Fact]
public void Clear_on_an_empty_sink_is_a_no_op()
{
Sink.LogEvents.Should().BeEmpty();

Sink.Clear();

Sink.LogEvents.Should().BeEmpty();
}

private static LogEvent CreateLogEvent(string message) =>
new(
timestamp: DateTimeOffset.UnixEpoch,
level: LogEventLevel.Warning,
exception: null,
messageTemplate: new MessageTemplateParser().Parse(message),
properties: Array.Empty<LogEventProperty>());
}
65 changes: 65 additions & 0 deletions tests/Fallout.Build.Specs/ValueInjectionUtilitySpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System.Reflection;
using FluentAssertions;
using Fallout.Common.ValueInjection;
using Xunit;

namespace Fallout.Common.Specs;

/// <summary>
/// Covers <see cref="ValueInjectionUtility.ClearCache"/> added in FT-1 / #306. The injected-value
/// cache is keyed by member and lives for the process, so <c>BuildManager.Execute</c>'s <c>finally</c>
/// clears it — otherwise a second build in the same process would re-serve the first run's injected
/// values instead of re-computing them.
///
/// A counting attribute makes the cache observable: the injected value is the running call count, so
/// a cached read repeats the previous value while a post-<c>ClearCache</c> read re-injects a fresh one.
/// </summary>
public class ValueInjectionUtilitySpecs
{
[Fact]
public void Value_is_cached_after_the_first_injection()
{
ValueInjectionUtility.ClearCache();
CountingInjectionAttribute.Reset();
var subject = new Subject();

var first = ValueInjectionUtility.TryGetValue(() => subject.Value);
var second = ValueInjectionUtility.TryGetValue(() => subject.Value);

first.Should().Be("1");
second.Should().Be("1", "the second read is served from the cache, not re-injected");
CountingInjectionAttribute.Invocations.Should().Be(1);
}

[Fact]
public void ClearCache_forces_re_injection_on_the_next_read()
{
ValueInjectionUtility.ClearCache();
CountingInjectionAttribute.Reset();
var subject = new Subject();

var first = ValueInjectionUtility.TryGetValue(() => subject.Value);

ValueInjectionUtility.ClearCache();
var afterClear = ValueInjectionUtility.TryGetValue(() => subject.Value);

first.Should().Be("1");
afterClear.Should().Be("2", "clearing the cache re-runs the injection");
CountingInjectionAttribute.Invocations.Should().Be(2);
}

private sealed class Subject
{
[CountingInjection]
public string Value;
}

private sealed class CountingInjectionAttribute : ValueInjectionAttributeBase
{
public static int Invocations { get; private set; }

public static void Reset() => Invocations = 0;

public override object GetValue(MemberInfo member, object instance) => (++Invocations).ToString();
}
}
68 changes: 68 additions & 0 deletions tests/Fallout.Tooling.Specs/ToolPathResolverResetSpecs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using FluentAssertions;
using Fallout.Common.IO;
using Fallout.Common.Tooling;
using Xunit;

namespace Fallout.Common.Specs;

/// <summary>
/// Covers the per-run <c>Reset()</c> hooks added in FT-1 / #306: <see cref="BuildManager"/>'s
/// <c>finally</c> calls these so a subsequent build in the same process starts from default
/// package-location config instead of inheriting the previous run's residue.
///
/// Shares the resolvers' process-global static fields with <see cref="ToolTasksToolPathSpecs"/>,
/// so both classes live in a non-parallelized collection — otherwise a concurrent test could
/// observe a field mid-reset.
/// </summary>
[Collection(ToolPathResolverStateCollection.Name)]
public class ToolPathResolverResetSpecs : IDisposable
{
private readonly string _embeddedPackagesDirectory = NuGetToolPathResolver.EmbeddedPackagesDirectory;
private readonly string _nuGetPackagesConfigFile = NuGetToolPathResolver.NuGetPackagesConfigFile;
private readonly string _nuGetAssetsConfigFile = NuGetToolPathResolver.NuGetAssetsConfigFile;
private readonly string _paketPackagesConfigFile = NuGetToolPathResolver.PaketPackagesConfigFile;
private readonly AbsolutePath _npmPackageJsonFile = NpmToolPathResolver.NpmPackageJsonFile;

[Fact]
public void NuGetToolPathResolver_Reset_clears_every_package_location_field()
{
NuGetToolPathResolver.EmbeddedPackagesDirectory = "/packages";
NuGetToolPathResolver.NuGetPackagesConfigFile = "/packages.config";
NuGetToolPathResolver.NuGetAssetsConfigFile = "/project.assets.json";
NuGetToolPathResolver.PaketPackagesConfigFile = "/paket.dependencies";

NuGetToolPathResolver.Reset();

NuGetToolPathResolver.EmbeddedPackagesDirectory.Should().BeNull();
NuGetToolPathResolver.NuGetPackagesConfigFile.Should().BeNull();
NuGetToolPathResolver.NuGetAssetsConfigFile.Should().BeNull();
NuGetToolPathResolver.PaketPackagesConfigFile.Should().BeNull();
}

[Fact]
public void NpmToolPathResolver_Reset_clears_the_package_json_location()
{
NpmToolPathResolver.NpmPackageJsonFile = "/tmp/package.json";

NpmToolPathResolver.Reset();

NpmToolPathResolver.NpmPackageJsonFile.Should().BeNull();
}

// Restore whatever the ambient environment had so these mutations don't leak into sibling tests.
public void Dispose()
{
NuGetToolPathResolver.EmbeddedPackagesDirectory = _embeddedPackagesDirectory;
NuGetToolPathResolver.NuGetPackagesConfigFile = _nuGetPackagesConfigFile;
NuGetToolPathResolver.NuGetAssetsConfigFile = _nuGetAssetsConfigFile;
NuGetToolPathResolver.PaketPackagesConfigFile = _paketPackagesConfigFile;
NpmToolPathResolver.NpmPackageJsonFile = _npmPackageJsonFile;
}
}

[CollectionDefinition(Name, DisableParallelization = true)]
public class ToolPathResolverStateCollection
{
public const string Name = "ToolPathResolverState";
}
1 change: 1 addition & 0 deletions tests/Fallout.Tooling.Specs/ToolTasksToolPathSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace Fallout.Common.Specs;

[Collection(ToolPathResolverStateCollection.Name)]
public class ToolTasksToolPathSpecs
{
public ToolTasksToolPathSpecs()
Expand Down
Loading