forked from nblockchain/conventions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanityCheckNuget.fsx
executable file
·624 lines (507 loc) · 21.7 KB
/
sanityCheckNuget.fsx
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#!/usr/bin/env -S dotnet fsi
open System
open System.IO
open System.Linq
open System.Diagnostics
open System.Text
open System.Text.RegularExpressions
#r "System.Core.dll"
open System.Xml
#r "System.Xml.Linq.dll"
open System.Xml.Linq
open System.Xml.XPath
#r "nuget: Fsdk, Version=0.6.0--date20230214-0422.git-1ea6f62"
open Fsdk
open Fsdk.Process
#r "nuget: Microsoft.Build, Version=16.11.0"
open Microsoft.Build.Construction
type ScriptTarget =
| Solution of FileInfo
| Folder of DirectoryInfo
let args = Misc.FsxOnlyArguments()
let currentDirectory = Directory.GetCurrentDirectory()
if args.Length > 1 then
printf "Usage: %s [example.sln(optional)]" __SOURCE_FILE__
Environment.Exit 1
let target =
if args.IsEmpty then
currentDirectory |> DirectoryInfo |> ScriptTarget.Folder
else
let singleArg = args.[0]
if Directory.Exists singleArg then
failwithf "Use an .sln file insted of directory."
elif not(File.Exists singleArg) then
failwithf "'%s' does not exist." singleArg
elif singleArg.EndsWith ".sln" then
singleArg |> FileInfo |> ScriptTarget.Solution
else
failwithf
"'%s' argument is invalid. You should enter an .sln file or run this script on current directory"
singleArg
let nugetSolutionPackagesDir =
Path.Combine(currentDirectory, "packages") |> DirectoryInfo
let nugetPackageConfigDir =
Path.Combine(currentDirectory, "NuGet.config") |> FileInfo
if not nugetPackageConfigDir.Exists || not nugetSolutionPackagesDir.Exists then
failwithf
"NuGet.config not found in '%s', please create it with the `globalPackagesFolder` key as `packages`."
nugetPackageConfigDir.FullName
module MapHelper =
let GetKeysOfMap(map: Map<'Key, 'Value>) : seq<'Key> =
map |> Map.toSeq |> Seq.map fst
let MergeIntoMap<'Key, 'Value when 'Key: comparison>
(from: seq<'Key * 'Value>)
: Map<'Key, seq<'Value>> =
let keys = from.Select(fun (key, _value) -> key)
let keyValuePairs =
seq {
for theKey in keys do
let valsForKey =
(from.Where(fun (aKey, aValue) -> theKey = aKey))
.Select(fun (aKey, aValue) -> aValue)
|> seq
yield theKey, valsForKey
}
keyValuePairs |> Map.ofSeq
[<StructuralEquality; StructuralComparison>]
type private PackageInfo =
{
PackageId: string
PackageVersion: string
ReqReinstall: Option<bool>
}
type private DependencyHolder =
{
Name: string
}
[<CustomComparison; CustomEquality>]
type private ComparableFileInfo =
{
File: FileInfo
}
member self.DependencyHolderName: DependencyHolder =
if self.File.FullName.ToLower().EndsWith ".nuspec" then
{
Name = self.File.Name
}
else
{
Name =
self.File.Directory.Name
+ (Path.DirectorySeparatorChar.ToString())
}
interface IComparable with
member self.CompareTo obj =
match obj with
| null -> self.File.FullName.CompareTo null
| :? ComparableFileInfo as other ->
self.File.FullName.CompareTo other.File.FullName
| _ -> invalidArg "obj" "not a ComparableFileInfo"
override self.Equals obj =
match obj with
| :? ComparableFileInfo as other ->
self.File.FullName.Equals other.File.FullName
| _ -> false
override self.GetHashCode() =
self.File.FullName.GetHashCode()
let SanityCheckNugetPackages() =
let notPackagesFolder
(solutionDir: DirectoryInfo)
(dir: DirectoryInfo)
: bool =
dir.FullName <> nugetSolutionPackagesDir.FullName
let notSubmodule(dir: DirectoryInfo) : bool =
let getSubmoduleDirsForThisRepo() : seq<DirectoryInfo> =
if File.Exists ".gitmodules" then
let regex = Regex("path\s*=\s*([^\s]+)")
seq {
for regexMatch in
regex.Matches(File.ReadAllText ".gitmodules") do
let submoduleFolderRelativePath =
regexMatch.Groups.[1].ToString()
let submoduleFolder =
DirectoryInfo(
Path.Combine(
currentDirectory,
submoduleFolderRelativePath
)
)
yield submoduleFolder
}
else
Seq.empty
not(
getSubmoduleDirsForThisRepo()
.Any(fun d -> dir.FullName = d.FullName)
)
// this seems to be a bug in Microsoft.Build nuget library, FIXME: report
let normalizeDirSeparatorsPaths(path: string) : string =
path
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar)
let sanityCheckNugetPackagesFromSolution(sol: FileInfo) =
let rec findProjectFiles() : seq<FileInfo> =
let parsedSolution = SolutionFile.Parse sol.FullName
seq {
for projPath in
(parsedSolution
.ProjectsInOrder
.Select(fun proj ->
normalizeDirSeparatorsPaths proj.AbsolutePath
)
.ToList()) do
if projPath.ToLower().EndsWith ".fsproj"
|| projPath.ToLower().EndsWith ".csproj" then
yield (FileInfo projPath)
}
let rec findNuspecFiles(dir: DirectoryInfo) : seq<FileInfo> =
dir.Refresh()
seq {
for file in dir.EnumerateFiles() do
if (file.Name.ToLower()).EndsWith ".nuspec" then
yield file
for subdir in
dir
.EnumerateDirectories()
.Where(notSubmodule)
.Where(notPackagesFolder sol.Directory) do
for file in findNuspecFiles subdir do
yield file
}
let getPackageTree
(sol: FileInfo)
: Map<ComparableFileInfo, seq<PackageInfo>> =
let projectFiles = findProjectFiles()
let projectElements =
seq {
for projectFile in projectFiles do
let xmlDoc = XDocument.Load projectFile.FullName
let query = "//PackageReference"
let pkgReferences = xmlDoc.XPathSelectElements query
for pkgReference in pkgReferences do
let id =
pkgReference
.Attributes()
.Single(fun attr ->
attr.Name.LocalName = "Include"
|| attr.Name.LocalName = "Update"
)
.Value
let version =
pkgReference
.Attributes()
.Single(fun attr ->
attr.Name.LocalName = "Version"
)
.Value
yield
{
File = projectFile
},
{
PackageId = id
PackageVersion = version
ReqReinstall = None
}
}
|> List.ofSeq
let solDir = sol.Directory
solDir.Refresh()
let nuspecFiles = findNuspecFiles solDir
let nuspecFileElements =
seq {
for nuspecFile in nuspecFiles do
let xmlDoc = XDocument.Load nuspecFile.FullName
let nsOpt =
let nsString = xmlDoc.Root.Name.Namespace.ToString()
if String.IsNullOrEmpty nsString then
None
else
let nsManager = XmlNamespaceManager(NameTable())
let nsPrefix = "x"
nsManager.AddNamespace(nsPrefix, nsString)
if nsString
<> "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd" then
Console.Error.WriteLine
"Warning: the namespace URL doesn't match expectations, nuspec's XPath query may result in no elements"
Some(nsManager, sprintf "%s:" nsPrefix)
let query = "//{0}dependency"
let dependencies =
match nsOpt with
| None ->
let fixedQuery =
String.Format(query, String.Empty)
xmlDoc.XPathSelectElements fixedQuery
| Some(nsManager, nsPrefix) ->
let fixedQuery = String.Format(query, nsPrefix)
xmlDoc.XPathSelectElements(
fixedQuery,
nsManager
)
for dependency in dependencies do
let id =
dependency
.Attributes()
.Single(fun attr ->
attr.Name.LocalName = "id"
)
.Value
let version =
dependency
.Attributes()
.Single(fun attr ->
attr.Name.LocalName = "version"
)
.Value
yield
{
File = nuspecFile
},
{
PackageId = id
PackageVersion = version
ReqReinstall = None
}
}
|> List.ofSeq
let allElements = Seq.append projectElements nuspecFileElements
allElements |> MapHelper.MergeIntoMap
let getAllPackageIdsAndVersions
(packageTree: Map<ComparableFileInfo, seq<PackageInfo>>)
: Map<PackageInfo, seq<DependencyHolder>> =
seq {
for KeyValue(dependencyHolderFile, pkgs) in packageTree do
for pkg in pkgs do
yield pkg, dependencyHolderFile.DependencyHolderName
}
|> MapHelper.MergeIntoMap
let getDirectoryNamesForPackagesSet
(packages: Map<PackageInfo, seq<DependencyHolder>>)
: Map<string, seq<DependencyHolder>> =
seq {
for KeyValue(package, prjs) in packages do
let dirForPackage =
sprintf
"%s%s%s"
(package.PackageId.ToLower())
(Path.DirectorySeparatorChar.ToString())
package.PackageVersion
yield dirForPackage, prjs
}
|> Map.ofSeq
let findMissingPackageDirs
(solDir: DirectoryInfo)
(idealPackageDirs: Map<string, seq<DependencyHolder>>)
: Map<string, seq<DependencyHolder>> =
solDir.Refresh()
if not nugetSolutionPackagesDir.Exists then
failwithf
"'%s' subdir under solution dir %s doesn't exist, run `make` first"
nugetSolutionPackagesDir.Name
nugetSolutionPackagesDir.FullName
let packageDirsAbsolutePaths =
nugetSolutionPackagesDir
.EnumerateDirectories()
.Select(fun dir -> dir.FullName)
if not(packageDirsAbsolutePaths.Any()) then
Console.Error.WriteLine(
sprintf
"'%s' subdir under solution dir %s doesn't contain any packages"
nugetSolutionPackagesDir.Name
nugetSolutionPackagesDir.FullName
)
Console.Error.WriteLine
"Maybe you forgot to issue the commands `git submodule sync --recursive && git submodule update --init --recursive`?"
Environment.Exit 1
seq {
for KeyValue(packageDirNameThatShouldExist, prjs) in
idealPackageDirs do
let pkgDirToLookFor =
Path.Combine(
nugetSolutionPackagesDir.FullName,
packageDirNameThatShouldExist
)
|> DirectoryInfo
if not pkgDirToLookFor.Exists then
yield packageDirNameThatShouldExist, prjs
}
|> Map.ofSeq
let findExcessPackageDirs
(solDir: DirectoryInfo)
(idealPackageDirs: Map<string, seq<DependencyHolder>>)
: seq<string> =
solDir.Refresh()
if not(nugetSolutionPackagesDir.Exists) then
failwithf
"'%s' subdir under solution dir %s doesn't exist, run `make` first"
nugetSolutionPackagesDir.Name
nugetSolutionPackagesDir.FullName
// "src" is a directory for source codes and build scripts,
// not for packages, so we need to exclude it from here
let packageDirNames =
nugetSolutionPackagesDir
.EnumerateDirectories()
.Select(fun dir -> dir.Name)
.Except([ "src" ])
if not(packageDirNames.Any()) then
failwithf
"'%s' subdir under solution dir %s doesn't contain any packages"
nugetSolutionPackagesDir.Name
nugetSolutionPackagesDir.FullName
let packageDirsThatShouldExist =
MapHelper.GetKeysOfMap idealPackageDirs
seq {
for packageDirThatExists in packageDirNames do
if
not
(
packageDirsThatShouldExist.Contains
packageDirThatExists
)
then
yield packageDirThatExists
}
let findPackagesWithMoreThanOneVersion
(packageTree: Map<ComparableFileInfo, seq<PackageInfo>>)
: Map<string, seq<ComparableFileInfo * PackageInfo>> =
let getAllPackageInfos
(packages: Map<ComparableFileInfo, seq<PackageInfo>>)
=
let pkgInfos =
seq {
for KeyValue(_, pkgs) in packages do
for pkg in pkgs do
yield pkg
}
Set pkgInfos
let getAllPackageVersionsForPackageId
(packages: seq<PackageInfo>)
(packageId: string)
=
seq {
for package in packages do
if package.PackageId = packageId then
yield package.PackageVersion
}
|> Set
let packageInfos = getAllPackageInfos packageTree
let packageIdsWithMoreThan1Version =
seq {
for packageId in
packageInfos.Select(fun pkg -> pkg.PackageId) do
let versions =
getAllPackageVersionsForPackageId
packageInfos
packageId
if versions.Count > 1 then
yield packageId
}
if not(packageIdsWithMoreThan1Version.Any()) then
Map.empty
else
seq {
for pkgId in packageIdsWithMoreThan1Version do
let pkgs =
seq {
for KeyValue(file, packageInfos) in packageTree do
for pkg in packageInfos do
if pkg.PackageId = pkgId then
yield file, pkg
}
yield pkgId, pkgs
}
|> Map.ofSeq
let packageTree = getPackageTree sol
let packages = getAllPackageIdsAndVersions packageTree
Console.WriteLine(
sprintf
"%i nuget packages found for solution %s"
packages.Count
sol.Name
)
let idealDirList = getDirectoryNamesForPackagesSet packages
let solDir = sol.Directory
solDir.Refresh()
let missingPackageDirs = findMissingPackageDirs solDir idealDirList
if missingPackageDirs.Any() then
for KeyValue(missingPkg, depHolders) in missingPackageDirs do
let depHolderNames =
String.Join(",", depHolders.Select(fun dh -> dh.Name))
Console.Error.WriteLine(
sprintf
"Missing folder for nuget package in submodule: %s (referenced from %s)"
missingPkg
depHolderNames
)
Environment.Exit 1
let pkgWithMoreThan1VersionPrint
(key: string)
(packageInfos: seq<ComparableFileInfo * PackageInfo>)
=
Console.Error.WriteLine(
sprintf
"Package found with more than one version: %s. All occurrences:"
key
)
for file, pkgInfo in packageInfos do
Console.Error.WriteLine(
sprintf
"* Version: %s. Dependency holder: %s"
pkgInfo.PackageVersion
file.DependencyHolderName.Name
)
let packagesWithMoreThanOneVersion =
findPackagesWithMoreThanOneVersion packageTree
if packagesWithMoreThanOneVersion.Any() then
Map.iter pkgWithMoreThan1VersionPrint packagesWithMoreThanOneVersion
Environment.Exit 1
let findPackagesWithSomeReqReinstallAttrib
(packageTree: Map<ComparableFileInfo, seq<PackageInfo>>)
: seq<ComparableFileInfo * PackageInfo> =
seq {
for KeyValue(file, packageInfos) in packageTree do
for pkg in packageInfos do
match pkg.ReqReinstall with
| Some true -> yield file, pkg
| _ -> ()
}
let packagesWithWithSomeReqReinstallAttrib =
findPackagesWithSomeReqReinstallAttrib packageTree
if packagesWithWithSomeReqReinstallAttrib.Any() then
Console.Error.WriteLine(
sprintf
"Packages found with some RequireReinstall attribute (please reinstall it before pushing):"
)
for file, pkg in packagesWithWithSomeReqReinstallAttrib do
Console.Error.WriteLine(
sprintf
"* Name: %s. Project: %s"
pkg.PackageId
file.DependencyHolderName.Name
)
Environment.Exit 1
Console.WriteLine(
sprintf
"Nuget sanity check succeeded for solution dir %s"
solDir.FullName
)
let rec findSolutions(dir: DirectoryInfo) : seq<FileInfo> =
dir.Refresh()
seq {
// FIXME: avoid returning duplicates? (in case there are 2 .sln files in the same dir...)
for file in dir.EnumerateFiles() do
if file.Name.ToLower().EndsWith ".sln" then
yield file
for subdir in dir.EnumerateDirectories().Where notSubmodule do
for solution in findSolutions subdir do
yield solution
}
match target with
| Solution solution -> sanityCheckNugetPackagesFromSolution solution
| Folder folder ->
let solutions = findSolutions folder
if Seq.isEmpty solutions then
failwithf "There is no *.sln file located in: '%s'" folder.FullName
for sol in solutions do
sanityCheckNugetPackagesFromSolution sol
SanityCheckNugetPackages()