Skip to content

[Bootstrapper] Fetch information from dotnet feeds #391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
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
30 changes: 8 additions & 22 deletions src/dotnet-bootstrapper/BootstrapperCommandParser.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;
using System.Reflection;
using Microsoft.DotNet.Tools.Bootstrapper.Commands.Search;

namespace Microsoft.DotNet.Tools.Bootstrapper
{
Expand All @@ -15,30 +15,16 @@ internal static class BootstrapperCommandParser
public static Parser BootstrapParser;

public static RootCommand BootstrapperRootCommand = new RootCommand("dotnet bootstrapper");

public static readonly Command VersionCommand = new Command("--version");

private static readonly Lazy<string> _assemblyVersion =
new Lazy<string>(() =>
{
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
var assemblyVersionAttribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (assemblyVersionAttribute == null)
{
return assembly.GetName().Version.ToString();
}
else
{
return assemblyVersionAttribute.InformationalVersion;
}
});
public static readonly Command HelpCommand = new("--help");

static BootstrapperCommandParser()
{
BootstrapperRootCommand.AddCommand(VersionCommand);
VersionCommand.Handler = CommandHandler.Create(() =>
BootstrapperRootCommand.AddCommand(SearchCommandParser.GetCommand());
BootstrapperRootCommand.AddCommand(HelpCommand);

HelpCommand.Handler = CommandHandler.Create(() =>
{
Console.WriteLine(_assemblyVersion.Value);
Console.WriteLine(LocalizableStrings.BootstrapperHelp);
});

BootstrapParser = new CommandLineBuilder(BootstrapperRootCommand)
Expand Down
21 changes: 21 additions & 0 deletions src/dotnet-bootstrapper/Commands/CommandBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.CommandLine.Parsing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.DotNet.Tools.Bootstrapper.Commands
{
public abstract class CommandBase
{
protected ParseResult _parseResult;

protected CommandBase(ParseResult parseResult)
{
_parseResult = parseResult;
}

public abstract int Execute();
}
}
16 changes: 16 additions & 0 deletions src/dotnet-bootstrapper/Commands/Common.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.DotNet.Tools.Bootstrapper.Commands
{
internal static class Common
{
internal static Option<bool> AllowPreviewsOptions = new Option<bool>(
"--allow-previews",
description: "Include pre-release sdk versions");
}
}
66 changes: 66 additions & 0 deletions src/dotnet-bootstrapper/Commands/Search/SearchCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.CommandLine.Parsing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Deployment.DotNet.Releases;
using Spectre.Console;

namespace Microsoft.DotNet.Tools.Bootstrapper.Commands.Search;

internal class SearchCommand(
ParseResult parseResult) : CommandBase(parseResult)
{
private string _channel = parseResult.ValueForArgument(SearchCommandParser.ChannelArgument);
private bool _allowPreviews = parseResult.ValueForOption(SearchCommandParser.AllowPreviewsOption);
public override int Execute()
{
List<Product> productCollection = [.. ProductCollection.GetAsync().Result];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The releases.json only changes about once a month. You should consider caching the file on disk and only update it if there's a new version available.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be using the same etag-based cache invalidation system that @nagilson has for the VSCode extension. ETags are the way to handle cache invalidation of HTTP-delivered resources, and we shouldn't be reinventing the wheel.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does https://github.com/dotnet/deployment-tools cache it? I would hope it does so, but at a glance it looks like it does not. I tis what is interfacing with the web request caller API. I would also hope that it handles proxies well. As well as timeouts. If it does not, I would almost question why that should not be implemented over there instead of here. Definitely wouldn't block on this for this PR but would create another issue from it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what I've seen, I don't think that it does. I do agree that it would make a lot of sense to implement it there

productCollection = [..
productCollection.Where(product => !product.IsOutOfSupport() && (product.SupportPhase != SupportPhase.Preview || _allowPreviews))];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baronfel Did we decide to only support in support installs? I understand why we'd want to do that, but it seems to limit the product use cases. I would rather emit a warning than block the behavior, but maybe that's ill-advised.


if (!string.IsNullOrEmpty(_channel))
{
productCollection = [.. productCollection.Where(product => product.ProductVersion.Equals(_channel, StringComparison.OrdinalIgnoreCase))];
}

foreach (Product product in productCollection)
{
string productHeader = $"{product.ProductName} {product.ProductVersion}";
Console.WriteLine(productHeader);

Table productMetadataTable = new Table()
.AddColumn("Version")
.AddColumn("Release Date")
.AddColumn("Latest SDK")
.AddColumn("Runtime")
.AddColumn("ASP.NET Runtime")
.AddColumn("Windows Desktop Runtime");

List<ProductRelease> releases = product.GetReleasesAsync().Result.ToList()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For future reference in the above issue again: Does this cache, and does it handle no internet/timeouts well? The responsibility of ownership here is interesting. Ideally this command could work offline if it has cached information.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.Where(relase => !relase.IsPreview || _allowPreviews).ToList();

foreach (ProductRelease release in releases)
{
// Get release.Sdks latest version
var latestSdk = release.Sdks
.OrderByDescending(sdk => sdk.Version)
.FirstOrDefault();

productMetadataTable.AddRow(
release.Version.ToString(),
release.ReleaseDate.ToString("d", CultureInfo.CurrentUICulture),
latestSdk?.DisplayVersion ?? "N/A",
release.Runtime?.DisplayVersion ?? "N/A",
release.AspNetCoreRuntime?.DisplayVersion ?? "N/A",
release.WindowsDesktopRuntime?.DisplayVersion ?? "N/A");
}
AnsiConsole.Write(productMetadataTable);
Console.WriteLine();
}

return 0;
}
}
33 changes: 33 additions & 0 deletions src/dotnet-bootstrapper/Commands/Search/SearchCommandParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.Parsing;

namespace Microsoft.DotNet.Tools.Bootstrapper.Commands.Search;

internal class SearchCommandParser
{
internal static Argument<string> ChannelArgument = new Argument<string>(
name: "channel",
description: "The channel to list sdks for. If not specified, all sdks will be listed.")
{
Arity = ArgumentArity.ZeroOrOne
};

internal static Option<bool> AllowPreviewsOption = Common.AllowPreviewsOptions;

private static readonly Command Command = ConstructCommand();
public static Command GetCommand() => Command;
private static Command ConstructCommand()
{
Command command = new("search", "Search for SDKs available for installation.");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: It will be easier to keep these strings in the localize file if we start now, but I also don't want to block on this.

command.AddArgument(ChannelArgument);
command.AddOption(AllowPreviewsOption);

command.Handler = CommandHandler.Create((ParseResult parseResult) =>
{
return new SearchCommand(parseResult).Execute();
});

return command;
}
}
94 changes: 94 additions & 0 deletions src/dotnet-bootstrapper/GlobalJsonUtilities.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.Json;
using Microsoft.Deployment.DotNet.Releases;

namespace Microsoft.DotNet.Tools.Bootstrapper
{
/// <summary>
/// Provides utility methods for working with global.json files in a directory tree.
/// </summary>
internal static class GlobalJsonUtilities
{
/// <summary>
/// Finds the nearest global.json file path by traversing up the directory tree starting from the specified base path.
/// </summary>
/// <param name="basePath">The starting directory path to search for the global.json file.</param>
/// <returns>
/// The full path to the nearest global.json file if found; otherwise, null.
/// </returns>
public static string GetNearestGlobalJsonPath(string basePath)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good for now, I think the runtime implemented some global json logic and it loks like CliTemplateEngineHost also did. We should probably try to share that implementation in the future, and I can create an issue for that.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good for now, I think the runtime implemented some global json logic and it loks like CliTemplateEngineHost also did. We should probably try to share that implementation in the future, and I can create an issue for that.

#393

{
// Example implementation: Traverse up the directory tree to find the nearest global.json file.
string currentPath = basePath;
while (!string.IsNullOrEmpty(currentPath))
{
string globalJsonPath = Path.Combine(currentPath, "global.json");
if (File.Exists(globalJsonPath))
{
return globalJsonPath;
}
currentPath = Directory.GetParent(currentPath)?.FullName;
}
// If no global.json file is found, return null.
return null;
}

/// <summary>
/// Retrieves the contents of the nearest global.json file as a JsonElement by traversing up the directory tree.
/// </summary>
/// <param name="basePath">The starting directory path to search for the global.json file.</param>
/// <returns>
/// A JsonElement representing the contents of the nearest global.json file.
/// </returns>
/// <exception cref="FileNotFoundException">Thrown if no global.json file is found in the directory tree.</exception>
/// <exception cref="JsonException">Thrown if global.json cannot be parsed as json</exception>
public static JsonElement GetNearestGlobalJson(string basePath)
{
string globalJsonPath = GetNearestGlobalJsonPath(basePath);

if (globalJsonPath == null)
{
throw new FileNotFoundException("No global.json file found in the directory tree.");
}

return JsonDocument.Parse(File.ReadAllText(globalJsonPath)).RootElement;
}
/// <summary>
/// Retrieves the major and minor version of the .NET SDK specified in the nearest global.json file
/// within the given base path.
/// </summary>
/// <param name="basePath">The base directory path to search for the global.json file.</param>
/// <returns>
/// A string representing the major and minor version (e.g., "6.0") of the .NET SDK specified
/// in the global.json file.
/// </returns>
/// <exception cref="KeyNotFoundException">
/// Thrown when the required keys ("tools" or "dotnet") are not found in the global.json file.
/// </exception>
public static string GetMajorVersionToInstallInDirectory(string basePath)
{
try
{
// Get the nearest global.json file.
JsonElement globalJson = GlobalJsonUtilities.GetNearestGlobalJson(basePath);
string sdkVersion = globalJson
.GetProperty("tools")
.GetProperty("dotnet")
.ToString();

ReleaseVersion version = ReleaseVersion.Parse(sdkVersion);
Console.WriteLine($"Found version {version.Major}.{version.Minor} in global.json");
return $"{version.Major}.{version.Minor}";
}
catch (KeyNotFoundException e)
{
throw new KeyNotFoundException("The specified key was not found in the global.json", e);
}
}
}
}
72 changes: 72 additions & 0 deletions src/dotnet-bootstrapper/LocalizableStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/dotnet-bootstrapper/LocalizableStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,7 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BootstrapperHelp" xml:space="preserve">
<value>Bootstrapper help text</value>
</data>
</root>
4 changes: 4 additions & 0 deletions src/dotnet-bootstrapper/dotnet-bootstrapper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@
<PropertyGroup>
<LangVersion>preview</LangVersion>
<RootNamespace>Microsoft.DotNet.Tools.Bootstrapper</RootNamespace>
<NoWarn>$(NoWarn);CS8002</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Setup.Configuration.Interop" Version="$(MicrosoftVisualStudioSetupConfigurationPackageVersion)" />
<PackageReference Include="NuGet.Versioning" Version="6.9.1" />
<PackageReference Include="Spectre.Console" Version="0.49.1" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta1.20574.7" />
<PackageReference Include="System.CommandLine.Rendering" Version="0.3.0-alpha.20574.7" />
<PackageReference Include="System.Resources.Extensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Deployment.DotNet.Releases" Version="1.0.1" />
</ItemGroup>

<ItemGroup>
Expand All @@ -39,6 +42,7 @@
<EmbeddedResource Update="LocalizableStrings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>LocalizableStrings.Designer.cs</LastGenOutput>
<CustomToolNamespace>Microsoft.DotNet.Tools.Bootstrapper</CustomToolNamespace>
</EmbeddedResource>
</ItemGroup>

Expand Down
Loading