Skip to content

Commit

Permalink
Add info command to display key information (#461)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdanish-kh committed Nov 2, 2023
1 parent 23535d2 commit 6f7b2e4
Show file tree
Hide file tree
Showing 17 changed files with 546 additions and 17 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ choco install wingetcreate
| [Token](doc/token.md) | Command for managing cached GitHub personal access tokens |
| [Settings](doc/settings.md) | Command for editing the settings file configurations |
| [Cache](doc/cache.md) | Command for managing downloaded installers stored in cache
| [Info](doc/info.md) | Displays information about the client |
| [-?](doc/help.md) | Displays command line help |

Click on the individual commands to learn more.
Expand Down
7 changes: 7 additions & 0 deletions doc/info.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# info command (Winget-Create)

The **info** command of the [Winget-Create](../README.md) tool is used to show useful information about the client. This information includes the location of the settings file, the local installer cache (download directory) and the logs directory. It also offers links to external resources like the GitHub repository and privacy statement.

## Usage

* Display information related to the client: `wingetcreate.exe info`
16 changes: 15 additions & 1 deletion doc/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ If set to true, the `telemetry.disable` setting will prevent any event from bein

## CleanUp

The `CleanUp` settings determine whether Winget-Create will handle the removal of temporary files (installer cache and logs) generated during the manifest creation process. These settings provide control over the decision to remove files or not and the frequency at which this clean up occurs.
The `CleanUp` settings determine whether Winget-Create will handle the removal of temporary files i.e., installers downloaded and logs generated during the manifest creation process. You can view the location of these files using the [info](./info.md) command. These settings provide control over the decision to remove files or not and the frequency at which this clean up occurs.

### disable

Expand Down Expand Up @@ -60,3 +60,17 @@ The `name` setting specifies the name of the targeted GitHub repository. By defa
"name": "winget-pkgs"
}
```

## Visual

The `Visual` settings control the appearance of the Winget-Create CLI output.

### anonymizePaths

The `anonymizePaths` setting controls whether the paths of files and directories are anonymized in the Winget-Create CLI output. This means that a path such as `C:\Users\user\Documents\manifests\` will be displayed as `%USERPROFILE%\Documents\manifests` (i.e., substitute environment variables where possible). By default, this is set to `true`.

```json
"Visual": {
"anonymizePaths": true
}
```
2 changes: 1 addition & 1 deletion src/WingetCreateCLI/Commands/BaseCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ protected static string SaveManifestDirToLocalPath(
}

Console.WriteLine();
Logger.InfoLocalized(nameof(Resources.ManifestSaved_Message), fullDirPath);
Logger.InfoLocalized(nameof(Resources.ManifestSaved_Message), Common.GetPathForDisplay(fullDirPath, UserSettings.AnonymizePaths));
Console.WriteLine();

return fullDirPath;
Expand Down
81 changes: 81 additions & 0 deletions src/WingetCreateCLI/Commands/InfoCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.

namespace Microsoft.WingetCreateCLI.Commands
{
using System;
using System.IO;
using System.Threading.Tasks;
using CommandLine;
using Microsoft.WingetCreateCLI.Logging;
using Microsoft.WingetCreateCLI.Properties;
using Microsoft.WingetCreateCLI.Telemetry;
using Microsoft.WingetCreateCLI.Telemetry.Events;
using Microsoft.WingetCreateCore;
using Microsoft.WingetCreateCore.Common;

/// <summary>
/// Info command to display general information regarding the tool.
/// </summary>
[Verb("info", HelpText = "InfoCommand_HelpText", ResourceType = typeof(Resources))]
public class InfoCommand : BaseCommand
{
/// <summary>
/// Executes the info command flow.
/// </summary>
/// <returns>Boolean representing success or fail of the command.</returns>
public override async Task<bool> Execute()
{
CommandExecutedEvent commandEvent = new CommandExecutedEvent
{
Command = nameof(InfoCommand),
};

DisplayApplicationHeaderAndCopyright();
Console.WriteLine();
DisplaySystemInformation();
Console.WriteLine();
DisplayInfoTable();

TelemetryManager.Log.WriteEvent(commandEvent);
return await Task.FromResult(commandEvent.IsSuccessful = true);
}

private static void DisplayApplicationHeaderAndCopyright()
{
Console.WriteLine(string.Format(
Resources.Heading,
Utils.GetEntryAssemblyVersion()) +
Environment.NewLine +
Constants.MicrosoftCopyright);
}

private static void DisplaySystemInformation()
{
Logger.DebugLocalized(nameof(Resources.OperatingSystem_Info), Environment.OSVersion.VersionString);
Logger.DebugLocalized(nameof(Resources.SystemArchitecture_Info), System.Runtime.InteropServices.RuntimeInformation.OSArchitecture);
}

private static void DisplayInfoTable()
{
string logsdirectory = Common.GetPathForDisplay(Path.Combine(Common.LocalAppStatePath, Constants.DiagnosticOutputDirectoryFolderName), UserSettings.AnonymizePaths);
string settingsDirectory = Common.GetPathForDisplay(UserSettings.SettingsJsonPath, UserSettings.AnonymizePaths);
string installerCacheDirectory = Common.GetPathForDisplay(PackageParser.InstallerDownloadPath, UserSettings.AnonymizePaths);

new TableOutput(Resources.WingetCreateDirectories_Heading, Resources.Path_Heading)
.AddRow(Resources.Logs_Heading, logsdirectory)
.AddRow(Resources.UserSettings_Heading, settingsDirectory)
.AddRow(Resources.InstallerCache_Heading, installerCacheDirectory)
.Print();

Console.WriteLine();

new TableOutput(Resources.Links_Heading, string.Empty)
.AddRow(Resources.PrivacyStatement_Heading, Constants.PrivacyStatementUrl)
.AddRow(Resources.LicenseAgreement_Heading, Constants.LicenseUrl)
.AddRow(Resources.ThirdPartyNotices_Heading, Constants.ThirdPartyNoticeUrl)
.AddRow(Resources.Homepage_Heading, Constants.HomePageUrl)
.Print();
}
}
}
36 changes: 36 additions & 0 deletions src/WingetCreateCLI/Common.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ namespace Microsoft.WingetCreateCLI
public static class Common
{
private const string ModuleName = "WindowsPackageManagerManifestCreator";
private const string UserProfileEnvironmentVariable = "%USERPROFILE%";
private const string LocalAppDataEnvironmentVariable = "%LOCALAPPDATA%";
private const string TempEnvironmentVariable = "%TEMP%";

private static readonly Lazy<string> AppStatePathLazy = new(() =>
{
Expand Down Expand Up @@ -61,6 +64,39 @@ public static void CleanUpFilesOlderThan(string cleanUpDirectory, int cleanUpDay
}
}

/// <summary>
/// Gets the path for display. This will anonymize the path if caller provides the appropriate flag.
/// </summary>
/// <param name="path">Path to be displayed.</param>
/// <param name="substituteEnvironmentVariables">Whether or not to substitute environment variables.</param>
/// <returns>Anonymized path or original path.</returns>
public static string GetPathForDisplay(string path, bool substituteEnvironmentVariables = true)
{
if (string.IsNullOrEmpty(path) || !substituteEnvironmentVariables)
{
return path;
}

string userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string tempPath = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar);

if (path.StartsWith(tempPath, StringComparison.OrdinalIgnoreCase))
{
return path.Replace(tempPath, TempEnvironmentVariable, StringComparison.OrdinalIgnoreCase);
}
else if (path.StartsWith(localAppDataPath, StringComparison.OrdinalIgnoreCase))
{
return path.Replace(localAppDataPath, LocalAppDataEnvironmentVariable, StringComparison.OrdinalIgnoreCase);
}
else if (path.StartsWith(userProfilePath, StringComparison.OrdinalIgnoreCase))
{
return path.Replace(userProfilePath, UserProfileEnvironmentVariable, StringComparison.OrdinalIgnoreCase);
}

return path;
}

private static bool IsRunningAsUwp()
{
DesktopBridge.Helpers helpers = new DesktopBridge.Helpers();
Expand Down
3 changes: 2 additions & 1 deletion src/WingetCreateCLI/Logger/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace Microsoft.WingetCreateCLI.Logging
using System.Globalization;
using System.IO;
using Microsoft.WingetCreateCLI.Properties;
using Microsoft.WingetCreateCore.Common;
using NLog;
using NLog.Conditions;
using NLog.Config;
Expand All @@ -21,7 +22,7 @@ public static class Logger

private static readonly FileTarget FileTarget = new()
{
FileName = @$"{Path.Combine(Common.LocalAppStatePath, "DiagOutputDir")}\WingetCreateLog-{DateTime.Now:yyyy-MM-dd-HH-mm.fff}.txt",
FileName = @$"{Path.Combine(Common.LocalAppStatePath, Constants.DiagnosticOutputDirectoryFolderName)}\WingetCreateLog-{DateTime.Now:yyyy-MM-dd-HH-mm.fff}.txt",

// Current layout example: 2021-01-01 08:30:59.0000|INFO|Microsoft.WingetCreateCLI.Commands.NewCommand.Execute|Log Message Example
Layout = "${longdate}|${level:uppercase=true}|${callsite}|${message}",
Expand Down
17 changes: 16 additions & 1 deletion src/WingetCreateCLI/Models/SettingsModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ public partial class WindowsPackageManagerRepository
public string Name { get; set; } = "winget-pkgs";


}

/// <summary>Visual settings</summary>
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")]
public partial class Visual
{
/// <summary>Controls whether paths displayed on the console are substituted with environment variables</summary>
[Newtonsoft.Json.JsonProperty("anonymizePaths", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public bool AnonymizePaths { get; set; } = true;


}

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.3.0 (Newtonsoft.Json v11.0.0.0)")]
Expand All @@ -69,6 +80,10 @@ public partial class SettingsManifest
[System.ComponentModel.DataAnnotations.Required]
public WindowsPackageManagerRepository WindowsPackageManagerRepository { get; set; } = new WindowsPackageManagerRepository();

[Newtonsoft.Json.JsonProperty("Visual", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[System.ComponentModel.DataAnnotations.Required]
public Visual Visual { get; set; } = new Visual();


}
}
}
17 changes: 11 additions & 6 deletions src/WingetCreateCLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ private static async Task<int> Main(string[] args)
typeof(TokenCommand),
typeof(CacheCommand),
typeof(ShowCommand),
typeof(InfoCommand),
};
var parserResult = myParser.ParseArguments(args, types);

Expand All @@ -59,9 +60,11 @@ private static async Task<int> Main(string[] args)
return args.Any() ? 1 : 0;
}

if (command is not SettingsCommand && command is not CacheCommand)
bool commandHandlesToken = command is not CacheCommand and not InfoCommand and not SettingsCommand;

// Do not load github client for commands that do not deal with a GitHub token.
if (commandHandlesToken)
{
// Do not load github client for settings or cache command.
if (await command.LoadGitHubClient())
{
try
Expand All @@ -71,7 +74,7 @@ private static async Task<int> Main(string[] args)
if (trimmedVersion != Utils.GetEntryAssemblyVersion())
{
Logger.WarnLocalized(nameof(Resources.OutdatedVersionNotice_Message));
Logger.WarnLocalized(nameof(Resources.GetLatestVersion_Message), latestVersion, "https://github.com/microsoft/winget-create/releases");
Logger.WarnLocalized(nameof(Resources.GetLatestVersion_Message), latestVersion, Constants.GitHubReleasesUrl);
Logger.WarnLocalized(nameof(Resources.UpgradeUsingWinget_Message));
Console.WriteLine();
}
Expand Down Expand Up @@ -113,7 +116,7 @@ private static async Task<int> Main(string[] args)
if (!UserSettings.CleanUpDisabled)
{
Common.CleanUpFilesOlderThan(PackageParser.InstallerDownloadPath, UserSettings.CleanUpDays);
Common.CleanUpFilesOlderThan(Path.Combine(Common.LocalAppStatePath, "DiagOutputDir"), UserSettings.CleanUpDays);
Common.CleanUpFilesOlderThan(Path.Combine(Common.LocalAppStatePath, Constants.DiagnosticOutputDirectoryFolderName), UserSettings.CleanUpDays);
}
}
}
Expand All @@ -126,11 +129,13 @@ private static void DisplayHelp(NotParsed<object> result)
{
h.AddDashesToOption = true;
h.AdditionalNewLineAfterOption = false;
h.Heading = string.Format(Resources.Heading, Utils.GetEntryAssemblyVersion()) + Environment.NewLine;
h.Heading = string.Format(Resources.Heading, Utils.GetEntryAssemblyVersion());
h.Copyright = Constants.MicrosoftCopyright;
h.AddNewLineBetweenHelpSections = true;
h.AddPreOptionsLine(Resources.AppDescription_HelpText);
h.AddPostOptionsLines(new string[] { Resources.MoreHelp_HelpText, Resources.PrivacyStatement_HelpText });
h.AddPreOptionsLine(Environment.NewLine);
h.AddPreOptionsLine(Resources.CommandsAvailable_Message);
h.AddPostOptionsLines(new string[] { Resources.MoreHelp_HelpText, string.Format(Resources.PrivacyStatement_HelpText, Constants.PrivacyStatementUrl) });
h.MaximumDisplayWidth = 100;
h.AutoHelp = false;
h.AutoVersion = false;
Expand Down
Loading

0 comments on commit 6f7b2e4

Please sign in to comment.