Skip to content

Commit

Permalink
Add debug as a CommandLine global option. (#300)
Browse files Browse the repository at this point in the history
* Add debug as a CommandLine global option.

* Update graph cli core
  • Loading branch information
calebkiage authored Jun 16, 2023
1 parent 20e6606 commit 6506a09
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 105 deletions.
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

### Changed

## [1.0.0-preview.1] - 2023-06-16

### Added

- Added overloaded OData functions as commands. Examples of newly added command
paths:
- `mgc drives items workbook worksheets charts image-with-width`
- `mgc drives items workbook worksheets charts image-with-width-with-height`

### Changed

- `--file` has now been split into `--input-file` and `--output-file` to cater
for endpoints that accept a stream and return a stream.
- Fix error when accessing `mgc users direct-reports graph-org-contact`. There
are now 2 similar commands under `mgc users direct-reports graph-org-contact`.
- `mgc users direct-reports graph-org-contact`
- `mgc users direct-reports graph-org-contact-by-id`

## [0.4.0-preview.1] - 2023-05-05

### Added
Expand Down
66 changes: 28 additions & 38 deletions src/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Hosting;
Expand All @@ -24,12 +23,10 @@
using Microsoft.Graph.Cli.Core.Authentication;
using Microsoft.Graph.Cli.Core.Commands.Authentication;
using Microsoft.Graph.Cli.Core.Configuration;
using Microsoft.Graph.Cli.Core.Configuration.Extensions;
using Microsoft.Graph.Cli.Core.Http;
using Microsoft.Graph.Cli.Core.IO;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Cli.Commons.Extensions;
using Microsoft.Kiota.Http.HttpClientLibrary;
using Microsoft.Kiota.Serialization.Form;
Expand All @@ -40,17 +37,17 @@ namespace Microsoft.Graph.Cli
{
class Program
{
private static bool debugEnabled = false;
private static AzureEventSourceListener? listener = null;

static async Task<int> Main(string[] args)
{
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
var builder = BuildCommandLine()
.UseDefaults()
.UseHost(a =>
{
// Pass all the args to avoid system.commandline swallowing them up
return CreateHostBuilder(args);
}).UseRequestAdapter(ic =>
.UseHost(CreateHostBuilder)
.UseRequestAdapter(ic =>
{
var host = ic.GetHost();
var adapter = host.Services.GetRequiredService<IRequestAdapter>();
Expand All @@ -59,16 +56,9 @@ static async Task<int> Main(string[] args)
{
adapter.BaseUrl = client.BaseAddress?.ToString();
}
adapter.BaseUrl = adapter.BaseUrl?.TrimEnd('/');
return adapter;
}).RegisterCommonServices();

builder.AddMiddleware(async (ic, next) =>
{
var op = ic.GetHost().Services.GetService<IOptions<ExtraOptions>>()?.Value;
// Show Azure Identity logs if the --debug option is set
using AzureEventSourceListener? listener = op?.DebugEnabled == true ? AzureEventSourceListener.CreateConsoleLogger(EventLevel.LogAlways) : null;
await next(ic);
});
builder.AddMiddleware(async (ic, next) =>
{
var host = ic.GetHost();
Expand Down Expand Up @@ -108,24 +98,35 @@ static async Task<int> Main(string[] args)
context.ExitCode = exitCode;
});

var parser = builder.Build();

return await parser.InvokeAsync(args);
try
{
var parser = builder.Build();
return await parser.InvokeAsync(args);
}
finally
{
listener?.Dispose();
}
}

static CommandLineBuilder BuildCommandLine()
{
var rootCommand = new GraphClient().BuildRootCommand();
rootCommand.Description = "Microsoft Graph CLI";
// Support specifying additional arguments as configuration arguments
// System.CommandLine might swallow valid config tokens sometimes.
// e.g. if a command has an option --debug and we also want to use
// --debug for configs.
rootCommand.TreatUnmatchedTokensAsErrors = false;

var builder = new CommandLineBuilder(rootCommand);
var debugOption = new Option<bool>("--debug", "Enable debug output");

builder.AddMiddleware(async (ic, next) =>
{
debugEnabled = ic.ParseResult.GetValueForOption<bool>(debugOption);
listener = AzureEventSourceListener.CreateConsoleLogger(debugEnabled ? EventLevel.LogAlways : EventLevel.Warning);
await next(ic);
});

rootCommand.AddCommand(new LoginCommand(builder));
rootCommand.AddCommand(new LogoutCommand());
rootCommand.AddGlobalOption(debugOption);

return builder;
}
Expand All @@ -141,10 +142,6 @@ static IHostBuilder CreateHostBuilder(string[] args) =>
{
var authSection = ctx.Configuration.GetSection(nameof(AuthenticationOptions));
services.Configure<AuthenticationOptions>(authSection);
services.Configure<ExtraOptions>(op =>
{
op.DebugEnabled = ctx.Configuration.GetValue<bool>("Debug");
});
services.AddTransient<LoggingHandler>();
services.AddSingleton<HttpClient>(p =>
{
Expand All @@ -155,8 +152,7 @@ static IHostBuilder CreateHostBuilder(string[] args) =>
GraphServiceLibraryClientVersion = $"{assemblyVersion?.Major ?? 0}.{assemblyVersion?.Minor ?? 0}.{assemblyVersion?.Build ?? 0}",
GraphServiceTargetVersion = "1.0"
};
var loggingHandler = p.GetRequiredService<LoggingHandler>();
return GraphCliClientFactory.GetDefaultClient(options, lowestPriorityMiddlewares: new[] { loggingHandler });
return GraphCliClientFactory.GetDefaultClient(options, loggingHandler: p.GetRequiredService<LoggingHandler>());
});
services.AddSingleton<IAuthenticationProvider>(p =>
{
Expand Down Expand Up @@ -197,13 +193,8 @@ static IHostBuilder CreateHostBuilder(string[] args) =>
}).ConfigureLogging((ctx, logBuilder) =>
{
logBuilder.SetMinimumLevel(LogLevel.Warning);
// If a config is unavailable, troubleshoot using (ctx.Configuration as IConfigurationRoot)?.GetDebugView();
// At this point, the host isn't ready. Get the config option directly.
var debugEnabled = ctx.Configuration.GetValue<bool>("Debug");
if (debugEnabled == true)
{
logBuilder.AddFilter("Microsoft.Graph.Cli", LogLevel.Debug);
}
// Allow runtime selection of log level
logBuilder.AddFilter("Microsoft.Graph.Cli", level => level >= (debugEnabled ? LogLevel.Debug : LogLevel.Warning));
});

static void ConfigureAppConfiguration(IConfigurationBuilder builder, string[] args)
Expand All @@ -217,7 +208,6 @@ static void ConfigureAppConfiguration(IConfigurationBuilder builder, string[] ar
builder.AddJsonFile(userConfigPath, optional: true);
builder.AddJsonFile(authCache.GetAuthenticationCacheFilePath(), optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables(prefix: "MGC_");
builder.AddCommandLine(args.ExpandFlagsForConfiguration());
}
}
}
4 changes: 2 additions & 2 deletions src/msgraph-cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<AssemblyName>mgc</AssemblyName>
<Version>0.4.0-preview.1</Version>
<Version>1.0.0-preview.1</Version>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -26,7 +26,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Graph.Cli.Core" Version="0.2.1-preview.1" />
<PackageReference Include="Microsoft.Graph.Cli.Core" Version="1.0.0-preview.1" />
<PackageReference Include="System.CommandLine.Hosting" Version="0.4.0-alpha.22272.1" />
</ItemGroup>
</Project>
Loading

0 comments on commit 6506a09

Please sign in to comment.