Skip to content

Commit

Permalink
Merge pull request #28548 from nagilson/nagilson-internal-msrc-mirror
Browse files Browse the repository at this point in the history
[Internal to External Port] Templating Nuget Config Changes, MSBuild
  • Loading branch information
nagilson authored Oct 13, 2022
2 parents 44582f5 + 76edff1 commit cf48680
Show file tree
Hide file tree
Showing 23 changed files with 187 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using FluentAssertions;
using Microsoft.Build.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -117,15 +116,11 @@ public void It_does_not_error_on_duplicate_package_names()
new CacheWriter(task); // Should not error
}

[Fact]
public void It_warns_on_invalid_culture_codes_of_resources()
{
string projectAssetsJsonPath = Path.GetTempFileName();
var assetsContent = @"
private static string AssetsFileWithInvalidLocale(string tfm, string locale) => @"
{
`version`: 3,
`targets`: {
`net7.0`: {
`{tfm}`: {
`JavaScriptEngineSwitcher.Core/3.3.0`: {
`type`: `package`,
`compile`: {
Expand All @@ -136,59 +131,65 @@ public void It_warns_on_invalid_culture_codes_of_resources()
},
`resource`: {
`lib/netstandard2.0/ru-ru/JavaScriptEngineSwitcher.Core.resources.dll`: {
`locale`: `what is this even`
`locale`: `{locale}`
}
}
}
}
},
`project`: {
`version`: `1.0.0`,
`frameworks`: {
`{tfm}`: {
`targetAlias`: `{tfm}`
}
}
}
}".Replace("`", "\"");
}".Replace("`", "\"").Replace("{tfm}", tfm).Replace("{locale}", locale);

[InlineData("net7.0", true)]
[InlineData("net6.0", false)]
[Theory]
public void It_warns_on_invalid_culture_codes_of_resources(string tfm, bool shouldHaveWarnings)
{
string projectAssetsJsonPath = Path.GetTempFileName();
var assetsContent = AssetsFileWithInvalidLocale(tfm, "what is this even");
File.WriteAllText(projectAssetsJsonPath, assetsContent);
var task = InitializeTask(out _);
task.ProjectAssetsFile = projectAssetsJsonPath;
task.TargetFramework = "net7.0";
var writer = new CacheWriter(task);
writer.WriteToCacheFile();
var messages = (task.BuildEngine as MockBuildEngine).Warnings;
var invalidContextMessages = messages.Where(msg => msg.Code == "NETSDK1188");
invalidContextMessages.Should().HaveCount(1);
task.TargetFramework = tfm;
var writer = new CacheWriter(task, new MockPackageResolver());
writer.WriteToMemoryStream();
var engine = task.BuildEngine as MockBuildEngine;

var invalidContextWarnings = engine.Warnings.Where(msg => msg.Code == "NETSDK1188");
invalidContextWarnings.Should().HaveCount(shouldHaveWarnings ? 1 : 0);

var invalidContextMessages = engine.Messages.Where(msg => msg.Code == "NETSDK1188");
invalidContextMessages.Should().HaveCount(shouldHaveWarnings ? 0 : 1);

}

[Fact]
public void It_warns_on_incorrectly_cased_culture_codes_of_resources()

[InlineData("net7.0", true)]
[InlineData("net6.0", false)]
[Theory]
public void It_warns_on_incorrectly_cased_culture_codes_of_resources(string tfm, bool shouldHaveWarnings)
{
string projectAssetsJsonPath = Path.GetTempFileName();
var assetsContent = @"
{
`version`: 3,
`targets`: {
`net7.0`: {
`JavaScriptEngineSwitcher.Core/3.3.0`: {
`type`: `package`,
`compile`: {
`lib/netstandard2.0/JavaScriptEngineSwitcher.Core.dll`: {}
},
`runtime`: {
`lib/netstandard2.0/JavaScriptEngineSwitcher.Core.dll`: {}
},
`resource`: {
`lib/netstandard2.0/ru-ru/JavaScriptEngineSwitcher.Core.resources.dll`: {
`locale`: `ru-ru`
}
}
}
}
}
}".Replace("`", "\"");
var assetsContent = AssetsFileWithInvalidLocale(tfm, "ru-ru");
File.WriteAllText(projectAssetsJsonPath, assetsContent);
var task = InitializeTask(out _);
task.ProjectAssetsFile = projectAssetsJsonPath;
task.TargetFramework = "net7.0";
var writer = new CacheWriter(task);
writer.WriteToCacheFile();
var messages = (task.BuildEngine as MockBuildEngine).Warnings;
var invalidContextMessages = messages.Where(msg => msg.Code == "NETSDK1187");
invalidContextMessages.Should().HaveCount(1);
task.TargetFramework = tfm;
var writer = new CacheWriter(task, new MockPackageResolver());
writer.WriteToMemoryStream();
var engine = task.BuildEngine as MockBuildEngine;

var invalidContextWarnings = engine.Warnings.Where(msg => msg.Code == "NETSDK1187");
invalidContextWarnings.Should().HaveCount(shouldHaveWarnings ? 1 : 0);

var invalidContextMessages = engine.Messages.Where(msg => msg.Code == "NETSDK1187");
invalidContextMessages.Should().HaveCount(shouldHaveWarnings ? 0 : 1);
}

private ResolvePackageAssets InitializeTask(out IEnumerable<PropertyInfo> inputProperties)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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 NuGet.ProjectModel;
using NuGet.Versioning;
using System.IO;

Expand All @@ -24,5 +25,7 @@ public string GetPackageDirectory(string packageId, NuGetVersion version, out st
packageRoot = _root;
return Path.Combine(_root, packageId, version.ToNormalizedString(), "path");
}

public string ResolvePackageAssetPath(LockFileTargetLibrary package, string relativePath) => Path.Combine(GetPackageDirectory(package.Name, package.Version), relativePath);
}
}
}
2 changes: 2 additions & 0 deletions src/Tasks/Microsoft.NET.Build.Tasks/IPackageResolver.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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 NuGet.ProjectModel;
using NuGet.Versioning;

namespace Microsoft.NET.Build.Tasks
Expand All @@ -9,5 +10,6 @@ internal interface IPackageResolver
{
string GetPackageDirectory(string packageId, NuGetVersion version);
string GetPackageDirectory(string packageId, NuGetVersion version, out string packageRoot);
string ResolvePackageAssetPath(LockFileTargetLibrary package, string relativePath);
}
}
33 changes: 29 additions & 4 deletions src/Tasks/Microsoft.NET.Build.Tasks/ResolvePackageAssets.cs
Original file line number Diff line number Diff line change
Expand Up @@ -657,8 +657,8 @@ internal sealed class CacheWriter : IDisposable
private ResolvePackageAssets _task;
private BinaryWriter _writer;
private LockFile _lockFile;
private NuGetPackageResolver _packageResolver;
private LockFileTarget _compileTimeTarget;
private IPackageResolver _packageResolver;
private LockFileTarget _runtimeTarget;
private Dictionary<string, int> _stringTable;
private List<string> _metadataStrings;
Expand All @@ -677,6 +677,15 @@ internal sealed class CacheWriter : IDisposable

private const char RelatedPropertySeparator = ';';

/// <summary>
/// This constructor should only be used for testing - IPackgeResolver carries a lot of
/// state so using mocks really help with testing this component.
/// </summary>
public CacheWriter(ResolvePackageAssets task, IPackageResolver resolver) : this(task)
{
_packageResolver = resolver;
}

public CacheWriter(ResolvePackageAssets task)
{
_targetFramework = task.TargetFramework;
Expand Down Expand Up @@ -1425,14 +1434,30 @@ private void WriteResourceAssemblies()
var normalizedLocale = System.Globalization.CultureInfo.GetCultureInfo(locale).Name;
if (normalizedLocale != locale)
{
_task.Log.LogWarning(Strings.PackageContainsIncorrectlyCasedLocale, package.Name, package.Version.ToNormalizedString(), locale, normalizedLocale);
var tfm = _lockFile.GetTargetAndThrowIfNotFound(_targetFramework, null).TargetFramework;
if (tfm.Version.Major >= 7)
{
_task.Log.LogWarning(Strings.PackageContainsIncorrectlyCasedLocale, package.Name, package.Version.ToNormalizedString(), locale, normalizedLocale);
}
else
{
_task.Log.LogMessage(Strings.PackageContainsIncorrectlyCasedLocale, package.Name, package.Version.ToNormalizedString(), locale, normalizedLocale);
}
}
locale = normalizedLocale;
}
catch (System.Globalization.CultureNotFoundException cnf)
{
_task.Log.LogWarning(Strings.PackageContainsUnknownLocale, package.Name, package.Version.ToNormalizedString(), cnf.InvalidCultureName);
// We could potentially strip this unknown locales at this point, but we do not.
var tfm = _lockFile.GetTargetAndThrowIfNotFound(_targetFramework, null).TargetFramework;
if (tfm.Version.Major >= 7)
{
_task.Log.LogWarning(Strings.PackageContainsUnknownLocale, package.Name, package.Version.ToNormalizedString(), cnf.InvalidCultureName);
} else
{
_task.Log.LogMessage(Strings.PackageContainsUnknownLocale, package.Name, package.Version.ToNormalizedString(), cnf.InvalidCultureName);
}

// We could potentially strip this unknown locale at this point, but we do not.
// Locale data can change over time (it's typically an OS database that's kept updated),
// and the data on the system running the build may not be the same data as
// the system executing the built code. So we should be permissive for this case.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Copyright (c) .NET Foundation. All rights reserved.
receive servicing updates and security fixes.
-->
<ItemGroup>
<_EolNetCoreTargetFrameworkVersions Include="1.0;1.1;2.0;2.1;2.2;3.0" />
<_EolNetCoreTargetFrameworkVersions Include="1.0;1.1;2.0;2.1;2.2;3.0;5.0" />
</ItemGroup>

<Target Name="_CheckForEolTargetFrameworks" AfterTargets="_CheckForUnsupportedNETCoreVersion"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public GivenThatWeWantToTargetEolFrameworks(ITestOutputHelper log) : base(log)
[InlineData("netcoreapp1.0")]
[InlineData("netcoreapp3.0")]
[InlineData("netcoreapp2.1")]
[InlineData("net5.0")]
public void It_warns_that_framework_is_out_of_support(string targetFrameworks)
{
var testProject = new TestProject()
Expand Down
46 changes: 45 additions & 1 deletion src/Tests/dotnet-new.Tests/CommonTemplatesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.NET.TestFramework.Assertions;
using Microsoft.NET.TestFramework.Commands;
using Microsoft.TemplateEngine.TestHelper;
using Xunit.Abstractions;

namespace Microsoft.DotNet.Cli.New.IntegrationTests
Expand Down Expand Up @@ -191,7 +194,7 @@ public void AllCommonItemsCreate(string expectedTemplateName, string templateSho
.Should()
.ExitWith(0)
.And.NotHaveStdErr()
.And.HaveStdOut($@"The template ""{expectedTemplateName}"" was created successfully.");
.And.HaveStdOutContaining($@"The template ""{expectedTemplateName}"" was created successfully.");

Directory.Delete(workingDir, true);
}
Expand Down Expand Up @@ -274,6 +277,47 @@ public void GlobalJsonTests(string expectedContent, params string[] parameters)
Directory.Delete(workingDir, true);
}

[Fact]
public void NuGetConfigPermissions()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
//runs only on Unix
return;
}

string templateShortName = "nugetconfig";
string expectedTemplateName = "NuGet Config";
string workingDir = TestUtils.CreateTemporaryFolder();

new DotnetNewCommand(_log, templateShortName)
.WithCustomHive(_fixture.HomeDirectory)
.WithWorkingDirectory(workingDir)
.Execute()
.Should()
.ExitWith(0)
.And.NotHaveStdErr()
.And.HaveStdOutContaining($@"The template ""{expectedTemplateName}"" was created successfully.");

var process = Process.Start(new ProcessStartInfo()
{
FileName = "/bin/sh",
Arguments = "-c \"ls -la\"",
WorkingDirectory = workingDir
});

new Command(process)
.WorkingDirectory(workingDir)
.CaptureStdOut()
.CaptureStdErr()
.Execute()
.Should()
.ExitWith(0)
.And.HaveStdOutMatching("^-rw-------.*nuget.config$", RegexOptions.Multiline);

Directory.Delete(workingDir, true);
}

#region Project templates language features tests

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "Konfigurace NuGet",
"description": "Soubor pro konfiguraci umístění, ve kterých bude NuGet hledat balíčky",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Otevře nuget.config v editoru."
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "NuGet-Konfig.",
"description": "Eine Datei zum Konfigurieren der Speicherorte, in denen NuGet nach Paketen suchen wird",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Öffnet „nuget.config“ im Editor"
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@
"author": "Microsoft",
"name": "NuGet Config",
"description": "A file for configuring the locations NuGet will search for packages",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Opens nuget.config in the editor"
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "Configuración de NuGet",
"description": "Un archivo para configurar las ubicaciones en las que NuGet buscará paquetes",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Abre nuget.config en el editor"
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "Configuration NuGet",
"description": "Un fichier permettant de configurer les emplacements où NuGet recherche des packages",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Ouvre nuget.config dans l’éditeur"
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "Configurazione NuGet",
"description": "Un file per la configurazione del NuGet dei percorsi eseguirà la ricerca dei pacchetti",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "Apre nuget.config nell'editor"
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "NuGet Config",
"description": "NuGet がパッケージが検索する場所を構成するためのファイル",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "エディターで nuget.config を開く"
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
{
"author": "Microsoft",
"name": "NuGet 구성",
"description": "NuGet 패키지를 검색할 위치를 구성하는 파일",
"postActions/chmod/description": "Apply permissions",
"postActions/chmod/manualInstructions/default/text": "Run 'chmod 600 nuget.config'",
"postActions/open-file/description": "편집기에서 nuget.config를 엽니다"
}
Loading

0 comments on commit cf48680

Please # to comment.