This repository has been archived by the owner on Nov 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathProgram.cs
420 lines (361 loc) · 16.6 KB
/
Program.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
using GoCommando;
using GoCommando.Api;
using GoCommando.Attributes;
using NuGetPackageVisualizer.NuGetService;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace NuGetPackageVisualizer
{
public class Program : ICommando
{
[NamedArgument("folder", "l")]
[Description("Path for a folder containing packages.config file(s).")]
[Example("-folder:\"c:\\my projects\\proj\"")]
public string Folder { get; set; }
[NamedArgument("recursive", "r", Default = "true")]
[Description("If set together with folder, a recursive search for packages.config files are made from the specified folder. Default: true.")]
[Example("-recursive:false")]
public bool Recursive { get; set; }
[NamedArgument("file", "f")]
[Description("Path to a packages.config file.")]
[Example("-file:\"c:\\my projects\\proj\\packages.config\"")]
public string File { get; set; }
[NamedArgument("outputtype", "ot", Default = "dgml")]
[Description("Sets the type of the output file. The following file types are supported: dgml, graphviz.")]
[Example("-outputtype:dgml")]
public string OutputType { get; set; }
[NamedArgument("outputpath", "op", Default = "")]
[Description("Sets the root path where output files should be written. Default: \"\" the folder where NuGet Package Visualizer was run.")]
[Example("-outputpath:\"C:\\temp\"")]
public string OutputPath { get; set; }
[NamedArgument("output", "o", Default = "packages")]
[Description("The name of the generated file for the whole source folder. Default: \"packages\".")]
[Example("-output:.\\packages")]
public string Output { get; set; }
[NamedArgument("repositoryuri", "ru", Default = @"http://nuget.org/api/v2/")]
[Description("The URI of the NuGet repository to use for reference. Default: \"http://nuget.org/api/v2/\".")]
[Example("-repositoryuri:\"http://nuget.org/api/v2/\"")]
public string RepositoryUrl { get; set; }
[NamedArgument("wholediagram", "wd", Default = "true")]
[Description("Whether to generate a diagram for the whole source. Default: true.")]
[Example("-wholediagram:true")]
public bool WholeDiagram { get; set; }
[NamedArgument("projectdiagrams", "pd", Default = "false")]
[Description("Whether to generate diagram per project in the source folder. Default: false.")]
[Example("-projectdiagrams:false")]
public bool ProjectDiagrams { get; set; }
[NamedArgument("username", "u", Default = "")]
[Description("The user name for accessing a protected package feed. Default: \"\" (empty).")]
[Example("-username:jdoe")]
public string UserName { get; set; }
[NamedArgument("password", "pw", Default = "")]
[Description("The password for accessing a protected package feed. Default: \"\" (empty).")]
[Example("-password:XYZ")]
public string Password { get; set; }
public static void Main(string[] args)
{
Console.WriteLine("============================");
Console.WriteLine("= NuGet Package Visualizer =");
Console.WriteLine("============================");
Go.Run<Program>(args);
}
public void Run()
{
if (!Valid())
{
Console.WriteLine("Invoke with -? for detailed help.");
return;
}
var packageFiles = GetFiles();
var packages = new ConcurrentBag<PackageViewModel>();
Parallel.ForEach(
packageFiles,
packageFile =>
{
if (!Path.GetDirectoryName(packageFile).EndsWith(".nuget", StringComparison.CurrentCultureIgnoreCase))
{
var projectPackages = GeneratePackages(packageFile);
foreach (
var package in
projectPackages.Where(
package =>
package.LocalVersion != ""
&& !packages.Any(
p => p.NugetId == package.NugetId && p.LocalVersion == package.LocalVersion)))
{
packages.Add(package);
}
if (ProjectDiagrams)
GenerateFile(
projectPackages,
BuildFilePath(Path.GetFileName(Path.GetDirectoryName(packageFile))));
}
});
if (WholeDiagram) GenerateFile(packages.ToList(), BuildFilePath(Output));
}
private IEnumerable<string> GetFiles()
{
var packageFiles = new List<string>();
if (!string.IsNullOrWhiteSpace(File))
packageFiles.Add(File);
else
packageFiles.AddRange(DirSearch(Folder));
Debug.WriteLine($"Found {packageFiles.Count} package files.");
return packageFiles;
}
private List<PackageViewModel> GeneratePackages(string file)
{
Debug.WriteLine($"Processing {file}.");
var packages = new List<PackageViewModel>();
var feedContext = new FeedContext_x0060_1(new Uri(RepositoryUrl))
{
IgnoreMissingProperties = true
};
ApplyCredentials(feedContext);
var packagesConfig = XDocument.Load(file);
var dependencies = new List<DependencyViewModel>();
if (Path.GetFileName(file).Equals("packages.config", StringComparison.CurrentCultureIgnoreCase))
{
foreach (var package in packagesConfig.Descendants("package"))
{
var id = package.Attribute("id").Value;
var version = package.Attribute("version").Value;
// ReSharper disable ReplaceWithSingleCallToFirstOrDefault
var remotePackage =
feedContext
.Packages
.OrderByDescending(x => x.Version)
.Where(x => x.Id == id && x.IsLatestVersion && !x.IsPrerelease)
.FirstOrDefault();
// ReSharper restore ReplaceWithSingleCallToFirstOrDefault
dependencies.Add(new DependencyViewModel { NugetId = id, Version = version });
if (remotePackage == null) continue;
if (packages.Any(p => p.NugetId == id && p.LocalVersion == version)) continue;
packages.Add(
new PackageViewModel
{
RemoteVersion = remotePackage.Version,
LocalVersion = version,
NugetId = id,
Id = Guid.NewGuid().ToString(),
Dependencies = remotePackage.Dependencies
.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
.Select(
x =>
{
var strings = x.Split(new[] { ':' });
return new DependencyViewModel { NugetId = strings[0], Version = strings[1] };
})
.ToArray()
});
foreach (
var pack in
packages
.Last()
.Dependencies
.Select(
dependency =>
dependencies
.FirstOrDefault(
x => x.NugetId == dependency.NugetId && x.Version == dependency.Version))
.Where(pack => pack != null))
{
dependencies.Remove(pack);
}
}
}
if (Path.GetExtension(file).Equals(".csproj", StringComparison.CurrentCultureIgnoreCase))
{
//todo process new format CSProj file. <PackageReference Include="Microsoft.TeamFoundation.DistributedTask.Common" version="15.112.1" />
foreach (var package in packagesConfig.Descendants("PackageReference"))
{
var id = package.Attribute("Include")?.Value;
var version = package.Attribute("Version")?.Value;
// ReSharper disable ReplaceWithSingleCallToFirstOrDefault
var remotePackage =
feedContext
.Packages
.OrderByDescending(x => x.Version)
.Where(x => x.Id == id && x.IsLatestVersion && !x.IsPrerelease)
.FirstOrDefault();
// ReSharper restore ReplaceWithSingleCallToFirstOrDefault
dependencies.Add(new DependencyViewModel { NugetId = id, Version = version });
if (remotePackage == null) continue;
if (packages.Any(p => p.NugetId == id && p.LocalVersion == version)) continue;
packages.Add(
new PackageViewModel
{
RemoteVersion = remotePackage.Version,
LocalVersion = version,
NugetId = id,
Id = Guid.NewGuid().ToString(),
Dependencies = remotePackage.Dependencies
.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
.Select(
x =>
{
var strings = x.Split(new[] { ':' });
return new DependencyViewModel { NugetId = strings[0], Version = strings[1] };
})
.ToArray()
});
foreach (
var pack in
packages
.Last()
.Dependencies
.Select(
dependency =>
dependencies
.FirstOrDefault(
x => x.NugetId == dependency.NugetId && x.Version == dependency.Version))
.Where(pack => pack != null))
{
dependencies.Remove(pack);
}
}
}
packages.Add(
new PackageViewModel
{
RemoteVersion = "",
LocalVersion = "",
NugetId = Path.GetFileName(Path.GetDirectoryName(file)),
Id = Guid.NewGuid().ToString(),
Dependencies = dependencies.ToArray()
});
return packages;
}
private void ApplyCredentials(DataServiceContext dataServiceContext)
{
if (!string.IsNullOrEmpty(UserName))
{
if (string.IsNullOrEmpty(Password))
{
promptForPassword();
}
dataServiceContext.Credentials = new NetworkCredential(UserName, Password);
}
}
private void promptForPassword()
{
Console.WriteLine("You have supplied a username only, please enter the password for accessing the protected feed:");
Console.ResetColor();
//from http://stackoverflow.com/a/3404522/1793
var pass = string.Empty;
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
pass += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
pass = pass.Substring(0, (pass.Length - 1));
Console.Write("\b \b");
}
}
}
// Stops Receiving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("Thank you.");
Password = pass;
}
private void GenerateFile(List<PackageViewModel> packages, string fileName)
{
switch (OutputType)
{
case "dgml":
new DGMLWriter().Write(packages, fileName);
break;
case "graphviz":
new GraphvizWriter().Write(packages, fileName);
break;
}
}
private bool Valid()
{
if (FolderAndFileNotSpecified())
{
Console.WriteLine("You need to specify either folder or file.");
return false;
}
if (FolderAndFileBothSpecified())
{
Console.WriteLine("You cannot specify both folder and file.");
return false;
}
if (WholeDiagramAndProjectDiagramsNotSpecified())
{
Console.WriteLine("You must specify either wholediagram and/or projectdiagrams.");
return false;
}
if (!string.IsNullOrWhiteSpace(File) && !System.IO.File.Exists(File))
{
Console.WriteLine("Could not find file: " + File);
return false;
}
if (!string.IsNullOrWhiteSpace(Folder) && !Directory.Exists(Folder))
{
Console.WriteLine("Could not find folder: " + Folder);
return false;
}
return true;
}
private bool FolderAndFileBothSpecified()
{
return !string.IsNullOrWhiteSpace(Folder) && !string.IsNullOrWhiteSpace(File);
}
private bool FolderAndFileNotSpecified()
{
return string.IsNullOrWhiteSpace(Folder) && string.IsNullOrWhiteSpace(File);
}
private bool WholeDiagramAndProjectDiagramsNotSpecified()
{
return !(WholeDiagram || ProjectDiagrams);
}
private IEnumerable<string> DirSearch(string sDir)
{
var packageFiles = new List<string>();
try
{
foreach (var d in Directory.GetDirectories(sDir))
{
packageFiles.AddRange(Directory.GetFiles(d, "packages.config"));
packageFiles.AddRange(Directory.GetFiles(d, "*.csproj"));
if (Recursive)
packageFiles.AddRange(DirSearch(d));
}
}
catch (Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return packageFiles;
}
private string BuildFilePath(string name)
{
if (OutputPath != string.Empty) Directory.CreateDirectory(OutputPath);
return Path.Combine(OutputPath, string.Format("{0}.{1}", name, GetFileExtension()));
}
private string GetFileExtension()
{
return OutputType == "graphviz" ? "dot" : OutputType;
}
}
}