forked from dotnet/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ToolPathCalculator.cs
95 lines (76 loc) · 2.89 KB
/
ToolPathCalculator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// 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.IO;
using System.Collections.Generic;
using NuGet.Frameworks;
using NuGet.Versioning;
namespace Microsoft.DotNet.Cli.Utils
{
public class ToolPathCalculator
{
private readonly string _packagesDirectory;
public ToolPathCalculator(string packagesDirectory)
{
_packagesDirectory = packagesDirectory;
}
public string GetBestLockFilePath(string packageId, VersionRange versionRange, NuGetFramework framework)
{
if (versionRange == null)
{
throw new ArgumentNullException(nameof(versionRange));
}
if (framework == null)
{
throw new ArgumentNullException(nameof(framework));
}
var availableToolVersions = GetAvailableToolVersions(packageId);
var bestVersion = versionRange.FindBestMatch(availableToolVersions);
if (bestVersion == null)
{
throw new GracefulException($"Version for package `{packageId}` could not be resolved.");
}
return GetLockFilePath(packageId, bestVersion, framework);
}
public string GetLockFilePath(string packageId, NuGetVersion version, NuGetFramework framework)
{
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
if (framework == null)
{
throw new ArgumentNullException(nameof(framework));
}
return Path.Combine(
GetBaseToolPath(packageId),
version.ToNormalizedString().ToLowerInvariant(),
framework.GetShortFolderName(),
"project.lock.json");
}
private string GetBaseToolPath(string packageId)
{
return Path.Combine(
_packagesDirectory,
".tools",
packageId.ToLowerInvariant());
}
private IEnumerable<NuGetVersion> GetAvailableToolVersions(string packageId)
{
var availableVersions = new List<NuGetVersion>();
var toolBase = GetBaseToolPath(packageId);
var versionDirectories = Directory.EnumerateDirectories(toolBase);
foreach (var versionDirectory in versionDirectories)
{
var version = Path.GetFileName(versionDirectory);
NuGetVersion nugetVersion = null;
NuGetVersion.TryParse(version, out nugetVersion);
if (nugetVersion != null)
{
availableVersions.Add(nugetVersion);
}
}
return availableVersions;
}
}
}