using System.CommandLine.Binding; using System.CommandLine.Parsing; namespace Duplicati.CommandLine.ServerUtil; /// /// An abstract binder class for managing a singleton instance of . /// /// /// This class ensures that only one instance of is associated with a given . /// public abstract class OutputInterceptorBinder : BinderBase { private static OutputInterceptor? _instance; /// /// Gets the current instance of . /// /// Thrown when the instance has not been initialized. public static OutputInterceptor? Instance => _instance; /// /// Retrieves or creates a instance for the specified binding context. /// /// The binding context to associate with the interceptor. Must not be null. /// The existing or newly created instance. /// Thrown when is null. public static OutputInterceptor GetConsoleInterceptor(BindingContext bindingContext) { ArgumentNullException.ThrowIfNull(bindingContext, nameof(bindingContext)); if (_instance is not null && ReferenceEquals(_instance.BindingContext, bindingContext)) { return _instance; } _instance = CreateInterceptor(bindingContext); return _instance; } /// /// Gets the bound value for the specified binding context. /// /// The binding context to retrieve the interceptor for. /// The associated instance. protected override OutputInterceptor GetBoundValue(BindingContext bindingContext) { return GetConsoleInterceptor(bindingContext); } /// /// Creates a new instance with the specified binding context. /// /// The binding context to initialize the interceptor with. /// A new instance. private static OutputInterceptor CreateInterceptor(BindingContext bindingContext) { var interceptor = new OutputInterceptor(bindingContext.ParseResult.Tokens.Any(x => x is { Type: TokenType.Option, Value: "--json" }), bindingContext); interceptor.SetCommand(bindingContext.ParseResult.CommandResult.Command.Name); return interceptor; } }