10000 Merge pull request #466 from filipw/bugfix/nuget · dotnet-script/dotnet-script@139ba2f · GitHub
[go: up one dir, main page]

Skip to content

Commit 139ba2f

Browse files
authored
Merge pull request #466 from filipw/bugfix/nuget
Improved support for local NuGet.Config files.
2 parents 3c96c31 + 22a9555 commit 139ba2f

File tree

15 files changed

+193
-367
lines changed

15 files changed

+193
-367
lines changed

src/Dotnet.Script.DependencyModel/Compilation/CompilationDependencyResolver.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ public CompilationDependencyResolver(LogFactory logFactory)
3535

3636
public IEnumerable<CompilationDependency> GetDependencies(string targetDirectory, IEnumerable<string> scriptFiles, bool enableScriptNugetReferences, string defaultTargetFramework = "net46")
3737
{
38-
var pathToProjectFile = _scriptProjectProvider.CreateProject(targetDirectory, scriptFiles,defaultTargetFramework, enableScriptNugetReferences);
39-
_restorer.Restore(pathToProjectFile, packageSources: Array.Empty<string>());
40-
var pathToAssetsFile = Path.Combine(Path.GetDirectoryName(pathToProjectFile), "obj", "project.assets.json");
38+
var projectFileInfo = _scriptProjectProvider.CreateProject(targetDirectory, scriptFiles, defaultTargetFramework, enableScriptNugetReferences);
39+
_restorer.Restore(projectFileInfo, packageSources: Array.Empty<string>());
40+
var pathToAssetsFile = Path.Combine(Path.GetDirectoryName(projectFileInfo.Path), "obj", "project.assets.json");
4141
var dependencyContext = _scriptDependencyContextReader.ReadDependencyContext(pathToAssetsFile);
4242
var result = new List<CompilationDependency>();
4343
foreach (var scriptDependency in dependencyContext.Dependencies)
@@ -51,7 +51,7 @@ public IEnumerable<CompilationDependency> GetDependencies(string targetDirectory
5151
private static IRestorer CreateRestorer(LogFactory logFactory)
5252
{
5353
var commandRunner = new CommandRunner(logFactory);
54-
return new ProfiledRestorer(new DotnetRestorer(commandRunner, logFactory),logFactory);
54+
return new ProfiledRestorer(new DotnetRestorer(commandRunner, logFactory), logFactory);
5555
}
5656
}
5757
}

src/Dotnet.Script.DependencyModel/Context/CachedRestorer.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,17 @@ public CachedRestorer(IRestorer restorer, LogFactory logFactory)
2828
public bool CanRestore => _restorer.CanRestore;
2929

3030
/// <inheritdoc/>
31-
public void Restore(string pathToProjectFile, string[] packageSources)
31+
public void Restore(ProjectFileInfo projectFileInfo, string[] packageSources)
3232
{
33-
var projectFile = new ProjectFile(File.ReadAllText(pathToProjectFile));
34-
var pathToCachedProjectFile = $"{pathToProjectFile}.cache";
33+
var projectFile = new ProjectFile(File.ReadAllText(projectFileInfo.Path));
34+
var pathToCachedProjectFile = $"{projectFileInfo.Path}.cache";
3535
if (File.Exists(pathToCachedProjectFile))
3636
{
3737
_logger.Debug($"Found cached csproj file at: {pathToCachedProjectFile}");
3838
var cachedProjectFile = new ProjectFile(File.ReadAllText(pathToCachedProjectFile));
3939
if (projectFile.Equals(cachedProjectFile))
4040
{
41-
_logger.Debug($"Skipping restore. {pathToProjectFile} and {pathToCachedProjectFile} are identical.");
41+
_logger.Debug($"Skipping restore. {projectFileInfo.Path} and {pathToCachedProjectFile} are identical.");
4242
return;
4343
}
4444
else
@@ -55,15 +55,15 @@ public void Restore(string pathToProjectFile, string[] packageSources)
5555

5656
void RestoreAndCacheProjectFile()
5757
{
58-
_restorer.Restore(pathToProjectFile, packageSources);
58+
_restorer.Restore(projectFileInfo, packageSources);
5959
if (projectFile.IsCacheable)
6060
{
6161
_logger.Debug($"Caching project file : {pathToCachedProjectFile}");
6262
projectFile.Save(pathToCachedProjectFile);
6363
}
6464
else
6565
{
66-
_logger.Warning($"Unable to cache {pathToProjectFile}. For caching and optimal performance, ensure that the script(s) references Nuget packages with a pinned version.");
66+
_logger.Warning($"Unable to cache {projectFileInfo.Path}. For caching and optimal performance, ensure that the script(s) references Nuget packages with a pinned version.");
6767
}
6868
}
6969
}

src/Dotnet.Script.DependencyModel/Context/DotnetRestorer.cs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Dotnet.Script.DependencyModel.Environment;
22 10000
using Dotnet.Script.DependencyModel.Logging;
33
using Dotnet.Script.DependencyModel.Process;
4+
using Dotnet.Script.DependencyModel.ProjectSystem;
45
using System;
56
using System.Linq;
67

@@ -19,18 +20,18 @@ public DotnetRestorer(CommandRunner commandRunner, LogFactory logFactory)
1920
_scriptEnvironment = ScriptEnvironment.Default;
2021
}
2122

22-
public void Restore(string pathToProjectFile, string[] packageSources)
23+
public void Restore(ProjectFileInfo projectFileInfo, string[] packageSources)
2324
{
2425
var packageSourcesArgument = CreatePackageSourcesArguments();
26+
var configFileArgument = CreateConfigFileArgument();
2527
var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier;
2628

27-
_logger.Debug($"Restoring {pathToProjectFile} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier}");
28-
var exitcode = _commandRunner.Execute("dotnet", $"restore \"{pathToProjectFile}\" -r {runtimeIdentifier} {packageSourcesArgument}");
29-
//var exitcode = _commandRunner.Execute("dotnet", $"restore \"{pathToProjectFile}\" {packageSourcesArgument}");
29+
_logger.Debug($"Restoring {projectFileInfo.Path} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier} NugetConfigFile: {projectFileInfo.NuGetConfigFile}");
30+
var exitcode = _commandRunner.Execute("dotnet", $"restore \"{projectFileInfo.Path}\" -r {runtimeIdentifier} {packageSourcesArgument} {configFileArgument}");
3031
if (exitcode != 0)
3132
{
3233
// We must throw here, otherwise we may incorrectly run with the old 'project.assets.json'
33-
throw new Exception($"Unable to restore packages from '{pathToProjectFile}'. Make sure that all script files contains valid NuGet references");
34+
throw new Exception($"Unable to restore packages from '{projectFileInfo.Path}'. Make sure that all script files contains valid NuGet references");
3435
}
3536

3637
string CreatePackageSourcesArguments()
@@ -40,6 +41,14 @@ string CreatePackageSourcesArguments()
4041
: packageSources.Select(s => $"-s {s}")
4142
.Aggregate((current, next) => $"{current} {next}");
4243
}
44+
45+
string CreateConfigFileArgument()
46+
{
47+
return string.IsNullOrWhiteSpace(projectFileInfo.NuGetConfigFile)
48+
? string.Empty
49+
: $"--configfile {projectFileInfo.NuGetConfigFile}";
50+
51+
}
4352
}
4453

4554
public bool CanRestore => true;

src/Dotnet.Script.DependencyModel/Context/IRestorer.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace Dotnet.Script.DependencyModel.Context
1+
using Dotnet.Script.DependencyModel.ProjectSystem;
2+
3+
namespace Dotnet.Script.DependencyModel.Context
24
{
35
/// <summary>
46
/// Represents a class that is capable of restoring a project file.
@@ -10,7 +12,8 @@ public interface IRestorer
1012
/// </summary>
1113
/// <param name="pathToProjectFile"></param>
1214
/// <param name="packageSources">A list of packages sources to be used when restoring NuGet packages.</param>
13-
void Restore(string pathToProjectFile, string[] packageSources);
15+
/// <param name="configPath">The path to the NuGet config file to be used when restoring.</param>
16+
void Restore(ProjectFileInfo projectFileInfo, string[] packageSources);
1417

1518
/// <summary>
1619
/// Gets a <see cref="bool"/> value that indicates if this <see cref="IRestorer"/> is available on the system.

src/Dotnet.Script.DependencyModel/Context/ProfiledRestorer.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Diagnostics;
22
using Dotnet.Script.DependencyModel.Logging;
3+
using Dotnet.Script.DependencyModel.ProjectSystem;
34

45
namespace Dotnet.Script.DependencyModel.Context
56
{
@@ -16,11 +17,11 @@ public ProfiledRestorer(IRestorer restorer, LogFactory logFactory)
1617

1718
public bool CanRestore => _restorer.CanRestore;
1819

19-
public void Restore(string pathToProjectFile, string[] packageSources)
20+
public void Restore(ProjectFileInfo projectFileInfo, string[] packageSources)
2021
{
2122
var stopwatch = Stopwatch.StartNew();
22-
_restorer.Restore(pathToProjectFile, packageSources);
23-
_logger.Debug($"Restoring {pathToProjectFile} took {stopwatch.ElapsedMilliseconds}ms");
23+
_restorer.Restore(projectFileInfo, packageSources);
24+
_logger.Debug($"Restoring {projectFileInfo.Path} took {stopwatch.ElapsedMilliseconds}ms");
2425
}
2526
}
2627
}
Lines changed: 3 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,14 @@
11
using NuGet.Configuration;
2-
using System.Collections.Generic;
32
using System.Linq;
43

54
namespace Dotnet.Script.DependencyModel.ProjectSystem
65
{
76
internal static class NuGetUtilities
87
{
9-
public static void CreateNuGetConfigFromLocation(string pathToEvaluate, string targetDirectory)
8+
public static string GetNearestConfigPath(string pathToEvaluate)
109
{
11-
var sourceSettings = Settings.LoadDefaultSettings(pathToEvaluate);
12-
var targetSettings = new Settings(targetDirectory);
13-
14-
CopySection(sourceSettings, targetSettings, "config");
15-
CopySection(sourceSettings, targetSettings, "bindingRedirects");
16-
CopySection(sourceSettings, targetSettings, "packageRestore");
17-
CopySection(sourceSettings, targetSettings, "solution");
18-
CopySection(sourceSettings, targetSettings, "packageSources");
19-
CopySection(sourceSettings, targetSettings, "packageSourceCredentials");
20-
CopySection(sourceSettings, targetSettings, "apikeys");
21-
CopySection(sourceSettings, targetSettings, "disabledPackageSources");
22-
CopySection(sourceSettings, targetSettings, "activePackageSource");
23-
24-
targetSettings.SaveToDisk();
25-
}
26-
27-
private static void CopySection(ISettings sourceSettings, ISettings targetSettings, string sectionName)
28-
{
29-
var existingAddItems = sourceSettings.GetSection(sectionName)?.Items.Where(item => item is object && (item is SourceItem || item is AddItem) && item.ElementName.ToLowerInvariant() == "add").Cast<AddItem>();
30-
31-
if (existingAddItems == null)
32-
{
33-
return;
34-
}
35-
36-
foreach (var addItem in existingAddItems)
37-
{
38-
if (ShouldResolvePath(sectionName, addItem.Key))
39-
{
40-
targetSettings.AddOrUpdate(sectionName, new AddItem(addItem.Key, addItem.GetValueAsPath()));
41-
}
42-
else
43-
{
44-
targetSettings.AddOrUpdate(sectionName, addItem);
45-
}
46-
}
47-
}
48-
49-
private static bool ShouldResolvePath(string sectionName, string key)
50-
{
51-
if (sectionName == "packageSources")
52-
{
53-
return true;
54-
}
55-
56-
if (sectionName == "config")
57-
{
58-
return key == "globalPackagesFolder" || key == "repositoryPath";
59-
}
60-
61-
return false;
10+
var settings = Settings.LoadDefaultSettings(pathToEvaluate);
11+
return settings.GetConfigFilePaths().FirstOrDefault();
6212
}
6313
}
6414
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
namespace Dotnet.Script.DependencyModel.ProjectSystem
2+
{
3+
/// <summary>
4+
/// Contains information about the generated project file and
5+
/// where to find the "nearest" NuGet.Config file.
6+
/// </summary>
7+
public class ProjectFileInfo
8+
{
9+
/// <summary>
10+
/// Initializes a new instance of the <see cref="ProjectFileInfo"/> class.
11+
/// </summary>
12+
/// <param name="path">The path to the generated project file to be used during restore.</param>
13+
/// <param name="nugetConfigFile">The path to the nearest NuGet.Config file seen from the target script folder.</param>
14+
public ProjectFileInfo(string path, string nugetConfigFile)
15+
{
16+
Path = path;
17+
NuGetConfigFile = nugetConfigFile;
18+
}
19+
20+
/// <summary>
21+
/// Gets the path of the generated project file to be used during restore.
22+
/// </summary>
23+
public string Path { get; }
24+
25+
/// <summary>
26+
/// Gets the path to the nearest NuGet.Config file seen from the target script folder.
27+
/// </summary>
28+
public string NuGetConfigFile { get; }
29+
}
30+
}

src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ private ScriptProjectProvider(ScriptParser scriptParser, ScriptFilesResolver scr
2727
{
2828
}
2929

30-
public string CreateProjectForRepl(string code, string targetDirectory, string defaultTargetFramework = "net46")
30+
public ProjectFileInfo CreateProjectForRepl(string code, string targetDirectory, string defaultTargetFramework = "net46")
3131
{
3232
var scriptFiles = _scriptFilesResolver.GetScriptFilesFromCode(code);
3333
targetDirectory = Path.Combine(targetDirectory, "interactive");
@@ -61,8 +61,7 @@ public string CreateProjectForRepl(string code, string targetDirectory, string d
6161

6262
LogProjectFileInfo(pathToProjectFile);
6363

64-
EvaluateAndGenerateNuGetConfigFile(targetDirectory, Path.GetDirectoryName(pathToProjectFile));
65-
return pathToProjectFile;
64+
return new ProjectFileInfo(pathToProjectFile, NuGetUtilities.GetNearestConfigPath(targetDirectory));
6665
}
6766

6867
private void LogProjectFileInfo(string pathToProjectFile)
@@ -72,12 +71,12 @@ private void LogProjectFileInfo(string pathToProjectFile)
7271
_logger.Debug(content);
7372
}
7473

75-
public string CreateProject(string targetDirectory, string defaultTargetFramework = "net46", bool enableNuGetScriptReferences = false)
74+
public ProjectFileInfo CreateProject(string targetDirectory, string defaultTargetFramework = "net46", bool enableNuGetScriptReferences = false)
7675
{
7776
return CreateProject(targetDirectory, Directory.GetFiles(targetDirectory, "*.csx", SearchOption.AllDirectories), defaultTargetFramework, enableNuGetScriptReferences);
7877
}
7978

80-
public string CreateProject(string targetDirectory, IEnumerable<string> scriptFiles, string defaultTargetFramework = "net46", bool enableNuGetScriptReferences = false)
79+
public ProjectFileInfo CreateProject(string targetDirectory, IEnumerable<string> scriptFiles, string defaultTargetFramework = "net46", bool enableNuGetScriptReferences = false)
8180
{
8281
if (scriptFiles == null || !scriptFiles.Any())
8382
{
@@ -95,14 +94,14 @@ public string CreateProject(string targetDirectory, IEnumerable<string> scriptFi
9594
return SaveProjectFileFromScriptFiles(targetDirectory, defaultTargetFramework, scriptFiles.ToArray());
9695
}
9796

98-
public string CreateProjectForScriptFile(string scriptFile)
97+
public ProjectFileInfo CreateProjectForScriptFile(string scriptFile)
9998
{
10099
_logger.Debug($"Creating project file for {scriptFile}");
101100
var scriptFiles = _scriptFilesResolver.GetScriptFiles(scriptFile);
102101
return SaveProjectFileFromScriptFiles(Path.GetDirectoryName(scriptFile), _scriptEnvironment.TargetFramework, scriptFiles.ToArray());
103102
}
104103

105-
private string SaveProjectFileFromScriptFiles(string targetDirectory, string defaultTargetFramework, string[] csxFiles)
104+
private ProjectFileInfo SaveProjectFileFromScriptFiles(string targetDirectory, string defaultTargetFramework, string[] csxFiles)
106105
{
107106
ProjectFile projectFile = CreateProjectFileFromScriptFiles(defaultTargetFramework, csxFiles);
108107

@@ -111,8 +110,7 @@ private string SaveProjectFileFromScriptFiles(string targetDirectory, string def
111110

112111
LogProjectFileInfo(pathToProjectFile);
113112

114-
EvaluateAndGenerateNuGetConfigFile(targetDirectory, Path.GetDirectoryName(pathToProjectFile));
115-
return pathToProjectFile;
113+
return new ProjectFileInfo(pathToProjectFile, NuGetUtilities.GetNearestConfigPath(targetDirectory));
116114
}
117115

118116
public ProjectFile CreateProjectFileFromScriptFiles(string defaultTargetFramework, string[] csxFiles)
@@ -130,17 +128,6 @@ public ProjectFile CreateProjectFileFromScriptFiles(string defaultTargetFramewor
130128
return projectFile;
131129
}
132130

133-
private void EvaluateAndGenerateNuGetConfigFile(string targetDirectory, string pathToProjectFileFolder)
134-
{
135-
var pathToDestinationNuGetConfigFile = Path.Combine(pathToProjectFileFolder, Settings.DefaultSettingsFileName);
136-
137-
if (File.Exists(pathToDestinationNuGetConfigFile))
138-
File.Delete(pathToDestinationNuGetConfigFile);
139-
140-
_logger.Debug($"Generating NuGet config evaluated at {targetDirectory} to {pathToDestinationNuGetConfigFile}");
141-
NuGetUtilities.CreateNuGetConfigFromLocation(targetDirectory, pathToProjectFileFolder);
142-
}
143-
144131
public static string GetPathToProjectFile(string targetDirectory)
145132
{
146133
var pathToProjectDirectory = FileUtils.CreateTempFolder(targetDirectory);

0 commit comments

Comments
 (0)
0