-
Notifications
You must be signed in to change notification settings - Fork 0
/
NugetConfigReader.cs
95 lines (85 loc) · 2.58 KB
/
NugetConfigReader.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
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
public static class NugetConfigReader
{
public static string GetPackagesPathFromConfig(string currentDirectory)
{
while (true)
{
var packagePath = GetPackagePath(Path.Combine(currentDirectory, "nuget.config"));
if (packagePath != null)
{
return packagePath;
}
packagePath = GetPackagePath(Path.Combine(currentDirectory, ".nuget", "nuget.config"));
if (packagePath != null)
{
return packagePath;
}
try
{
var directoryInfo = Directory.GetParent(currentDirectory);
if (directoryInfo == null)
{
return null;
}
currentDirectory = directoryInfo.FullName;
}
catch
{
// trouble with tree walk. ignore
return null;
}
}
}
public static string GetPackagePath(string nugetConfigPath)
{
var packagePath = Inner(nugetConfigPath);
if (packagePath == null)
{
return null;
}
return Path.GetFullPath(packagePath);
}
static string Inner(string nugetConfigPath)
{
if (!File.Exists(nugetConfigPath))
{
return null;
}
XDocument xDocument;
try
{
xDocument = XDocument.Load(nugetConfigPath);
}
catch (XmlException)
{
return null;
}
var repositoryPath = xDocument.Descendants("repositoryPath")
.Select(x => x.Value)
.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
if (repositoryPath != null)
{
return Path.Combine(Path.GetDirectoryName(nugetConfigPath), repositoryPath);
}
repositoryPath = xDocument.Descendants("add")
.Where(x => string.Equals((string) x.Attribute("key"), "repositoryPath", StringComparison.OrdinalIgnoreCase))
.Select(x => x.Attribute("value"))
.Where(x => x != null)
.Select(x => x.Value)
.FirstOrDefault();
if (repositoryPath == null)
{
return null;
}
if (repositoryPath.StartsWith("$\\"))
{
return repositoryPath.Replace("$", Path.Combine(Path.GetDirectoryName(nugetConfigPath)));
}
return Path.Combine(Path.GetDirectoryName(nugetConfigPath), repositoryPath);
}
}