-
Notifications
You must be signed in to change notification settings - Fork 12
/
Program.fs
1668 lines (1483 loc) · 80.4 KB
/
Program.fs
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
open Femto
open Femto.ProjectCracker
open System
open System.Net.Http
open Serilog
open Npm
open FSharp.Compiler.AbstractIL.Internal.Library
open Fake.Core
open Thoth.Json.Net
open Fake.SystemHelper
open Argu
let logger = LoggerConfiguration().WriteTo.Console().CreateLogger()
type LibraryWithNpmDeps = {
Path : string
Name : string
NpmDependencies : NpmDependency list
}
[<RequireQualifiedAccess>]
type NodeManager =
| Yarn
| Npm
| Pnpm
member this.CommandName =
match this with
| Yarn -> "yarn"
| Npm -> "npm"
| Pnpm -> "pnpm"
let (|NpmCompatible|Yarn|) manager =
match manager with
| NodeManager.Npm | NodeManager.Pnpm -> NpmCompatible
| NodeManager.Yarn -> Yarn
[<RequireQualifiedAccess>]
type ResolveAction =
| Install of library:string * package:string * version:string * range: string
| InstallDev of library:string * package:string * version:string * range: string
| Uninstall of library:string * package: string * version:string
| UninstallDev of library:string * package: string * version:string
| UnableToResolve of library:string * package:string * range:string * error: string
type PackageJson = {
Dependencies : Map<string, string> option
DevDependencies : Map<string, string> option
}
let findLibraryWithNpmDeps (project: CrackedFsproj) =
[ yield project.ProjectFile
yield! project.ProjectReferences
for package in project.PackageReferences do yield package.FsprojPath ]
|> List.map (fun proj ->
let npmDeps = Npm.parseDependencies (Path.normalizeFullPath proj)
{
Path = proj
Name = Path.GetFileNameWithoutExtension proj
NpmDependencies = npmDeps
}
)
|> List.filter (fun projet -> not (List.isEmpty projet.NpmDependencies))
let rec findFile (fileName: string) (project: string) =
let parentDir = IO.Directory.GetParent project
if isNull parentDir then None
else
parentDir.FullName
|> IO.Directory.GetFiles
|> Seq.tryFind (fun file -> Path.GetFileName file = fileName)
|> Option.orElse (findFile fileName parentDir.FullName)
/// Determines the full path of the package.json file by recursively checking every directory and it's parent starting from the path of the project file
let rec findPackageJson = findFile "package.json"
/// Determines which node package manager to use by checking whether the yarn.lock file is present next to package.json
let workspaceCommand (packageJson: string) =
let parentDir = IO.Directory.GetParent packageJson
let siblings = [ yield! IO.Directory.GetFiles parentDir.FullName ]
let yarnLockExists = siblings |> List.exists (fun file -> file.EndsWith "yarn.lock")
let pnpmLockExists = siblings |> List.exists (fun file -> file.EndsWith "pnpm-lock.yaml")
if yarnLockExists
then NodeManager.Yarn
else if pnpmLockExists
then NodeManager.Pnpm
else NodeManager.Npm
/// Determines whether npm packages have been restored by checking the existence of node_modules directory is present next to package.json
let needsNodeModules (packageJson: string) =
let parentDir = IO.Directory.GetParent packageJson
let siblings = IO.Directory.GetDirectories parentDir.FullName
let nodeModulesExists = siblings |> Array.exists (fun file -> file.EndsWith "node_modules")
not nodeModulesExists
let findInstalledPackages (packageJson: string) : ResizeArray<InstalledNpmPackage> =
let file = IO.File.ReadAllText packageJson
let topLevelPackages =
match Decode.Auto.fromString<PackageJson>(file, isCamelCase = true) with
| Ok rawPackage ->
let createInstalledPackages isDevDependency (dependencies: Map<string, string> option) =
dependencies
|> Option.defaultValue Map.empty
|> Seq.map (fun pair -> {
Name = pair.Key;
Range = Some (SemVer.Range(pair.Value));
Installed = None;
DevDependency = isDevDependency
})
ResizeArray [
yield! createInstalledPackages false rawPackage.Dependencies;
yield! createInstalledPackages true rawPackage.DevDependencies
]
| Error errorMessage ->
logger.Error("Couldn't find packages in 'package.json' file. Reason: {Message}", errorMessage)
ResizeArray []
if needsNodeModules packageJson
then
// should have installed node_modules
// return just top-level packages without their exact installed versions
topLevelPackages
else
// node_modules is present
// traverse all packages in there to extract their exact versions
// assumes node_modules is *flattened*
let parentDir = IO.Directory.GetParent packageJson
let siblings = IO.Directory.GetDirectories parentDir.FullName
// using Array.find because we know for sure node_modules is present
let nodeModulePath = siblings |> Array.find (fun dir -> dir.EndsWith "node_modules")
let rec checkPackageJsons nodeModulePath =
for dir in IO.Directory.GetDirectories nodeModulePath do
let dirname = IO.Path.GetFileName(dir)
// Scoped packages
if dirname.StartsWith("@") then
checkPackageJsons dir
else
let pkgJson = IO.Path.Combine(dir, "package.json")
// Some packages create a cache dir in node_modules starting with . like .vite
if not(dirname.StartsWith(".")) && IO.File.Exists pkgJson then
let nameAndVersionDecoder = Decode.object (fun get ->
let name = get.Required.Field "name" Decode.string
let version = get.Required.Field "version" Decode.string
name, version
)
let decoded =
File.readAllTextNonBlocking pkgJson
|> Decode.fromString nameAndVersionDecoder
match decoded with
| Ok (name, version) ->
for package in topLevelPackages do
if package.Name = name
then package.Installed <- Some (SemVer.Version version)
else ()
| Error errorMessage ->
logger.Error("Couldn't decode 'package.json' from {PackageJson}. Reason: {Message}", pkgJson, errorMessage)
()
checkPackageJsons nodeModulePath
topLevelPackages
module CreateProcess =
/// Creates a cross platfrom command from the given program and arguments.
///
/// For example:
///
/// ```fsharp
/// CreateProcess.xplatCommand "npm" [ "install" ]
/// ```
///
/// Will be the following on windows
///
/// ```fsharp
/// CreateProcess.fromRawCommand "cmd" [ "/C"; "npm"; "install" ]
/// ```
/// And the following otherwise
///
/// ```fsharp
/// CreateProcess.fromRawCommand "npm" [ "install" ]
/// ```
let xplatCommand program args =
let program', args' =
if Environment.isWindows
then "cmd", List.concat [ [ "/C"; program ]; args ]
else program, args
CreateProcess.fromRawCommand program' args'
let private getPackageVersions (nodeManager : NodeManager) (pkg : NpmDependency) =
match nodeManager with
| NpmCompatible ->
let res =
// Warning: pnpm does not support show, but you can use npm show
CreateProcess.xplatCommand "npm" [ "show"; pkg.Name; "versions"; "--json" ]
|> CreateProcess.redirectOutput
|> Proc.run
if res.ExitCode = 0 then
let versions = Decode.unsafeFromString (Decode.list Decode.string) res.Result.Output
Some versions
else
None
| Yarn ->
let res =
CreateProcess.xplatCommand nodeManager.CommandName [ "info"; pkg.Name; "versions"; "--json" ]
|> CreateProcess.redirectOutput
|> CreateProcess.ensureExitCode
|> Proc.run
// Yarn returns ExitCode = 0 even if the packge is not found,
// so we need to check using StrErr channel
if String.isNullOrEmpty res.Result.Error || res.Result.Error.Contains "ExperimentalWarning" then
let versions = Decode.unsafeFromString (Decode.field "data" (Decode.list Decode.string)) res.Result.Output
Some versions
else
None
/// Queries the available versions of a package by name and finds the first version that satisfies the version range of the dependency
let getSatisfyingPackageVersion (pkg : NpmDependency) =
pkg.Constraint
|> Option.bind (fun range ->
if pkg.LowestMatching then
pkg.Versions
|> Seq.ofList
|> range.Satisfying
|> Seq.tryHead
else
pkg.Versions
|> Seq.ofList
|> range.MaxSatisfying
|> function
| null -> None
| version -> Some version
)
/// Computes which actions are required for full package resolution of a single library based on the available npm dependency metadata and the currently installed npm packages
let rec autoResolveActions
(nodeManager : NodeManager)
(library : LibraryWithNpmDeps)
(packagesToVerify : NpmDependency list)
(installedPackages : ResizeArray<InstalledNpmPackage>)
(actions: ResolveAction list) =
match packagesToVerify with
| package :: rest ->
let resolveActions =
let installed = installedPackages |> Seq.tryFind (fun p -> p.Name = package.Name)
match installed with
| None ->
// not installed -> needs to be installed
let requiredVersion = getSatisfyingPackageVersion package
match requiredVersion with
| None ->
let error = "Could not find a version that satisfies the required range"
[ ResolveAction.UnableToResolve(library.Name, package.Name, package.RawVersion, error) ]
| Some version ->
if package.DevDependency then
[ ResolveAction.InstallDev(library.Name, package.Name, version, package.RawVersion) ]
else
[ ResolveAction.Install(library.Name, package.Name, version, package.RawVersion) ]
| Some installedPackage ->
// already installed -> check whether it falls under the required constraint
match installedPackage.Installed with
| Some installedVersion ->
// check installed version satisfies package constraint
match package.Constraint with
| Some requiredRange ->
if requiredRange.IsSatisfied installedVersion
then
// versions are correct, check if they are both devDepdendenicies or both dependencies
if package.DevDependency && not installedPackage.DevDependency then
[
// uninstall from "dependencies"
ResolveAction.Uninstall(library.Name, installedPackage.Name, installedVersion.ToString())
// re-install as "devDependency"
ResolveAction.InstallDev(library.Name, package.Name, installedVersion.ToString(), package.RawVersion)
]
elif not package.DevDependency && installedPackage.DevDependency then
[
// uninstall from "devDependencies"
ResolveAction.UninstallDev(library.Name, installedPackage.Name, installedVersion.ToString())
// re-install into "dependencies"
ResolveAction.Install(library.Name, package.Name, installedVersion.ToString(), package.RawVersion)
]
else
// both are either "devDependencies" or "dependencies"
// nothing left to do
[ ]
else
// installed version falls outside of required range
// resolve version from required range
let requiredVersion = getSatisfyingPackageVersion package
match requiredVersion with
| Some resolvedVersion ->
[
// uninstall current
if installedPackage.DevDependency
then yield ResolveAction.UninstallDev(library.Name, installedPackage.Name, installedVersion.ToString())
else yield ResolveAction.Uninstall(library.Name, installedPackage.Name, installedVersion.ToString())
// Re-install using the resolved version
if package.DevDependency
then yield ResolveAction.InstallDev(library.Name, package.Name, resolvedVersion, package.RawVersion)
else yield ResolveAction.Install(library.Name, package.Name, resolvedVersion, package.RawVersion)
]
| None ->
let error = "Could not find a version that satisfies the required range"
[ ResolveAction.UnableToResolve(library.Name, installedPackage.Name, package.RawVersion, error) ]
| None ->
let error = "Required range of npm package was not correctly parsable"
[ ResolveAction.UnableToResolve(library.Name, installedPackage.Name, package.RawVersion, error) ]
| _ ->
[ ]
autoResolveActions nodeManager library rest installedPackages (List.append actions resolveActions)
| [ ] ->
actions
/// Computes the actions required for full package resolution for a list of Fable libraries based on their npm dependency metadata and the installed npm packages
let rec autoResolve
(nodeManager : NodeManager)
(libraries : LibraryWithNpmDeps list)
(installedPackages : ResizeArray<InstalledNpmPackage>)
(resolveActions: ResolveAction list) =
match libraries with
| library :: rest ->
let actions = autoResolveActions nodeManager library library.NpmDependencies installedPackages resolveActions
autoResolve nodeManager rest installedPackages actions
| [ ] ->
resolveActions
type InstallArgs = {
Package: string
Version: string option
}
[<RequireQualifiedAccess>]
type PackageArgs =
| Install of InstallArgs
| Uninstall of package:string
| DoNothing
type FemtoArgs = {
/// The project on which the analysis is performed
Project: string option
/// When set to true, validates the metadata of the npm dependencies of a Fable library
Validate: bool
/// When set to true, performs the required actions for full package resolution
Resolve: bool
/// When set to true, displays the version of Femto
DiplayVersion: bool
LogInitialProjectAnalysis: bool
/// The nuget package to install
PackageArgs: PackageArgs
}
let defaultCliArgs = {
Project = None
Validate = false
Resolve = false
DiplayVersion = false
PackageArgs = PackageArgs.DoNothing
LogInitialProjectAnalysis = true
}
let resolveConflicts (actions: ResolveAction list) =
// remove duplicate uninstall commands
let distinctUninstallActions =
actions
|> List.choose (function
| ResolveAction.Uninstall(library, pkg, version) -> Some(library, pkg, version, false)
| ResolveAction.UninstallDev(library, pkg, version) -> Some (library, pkg, version, true)
| _ -> None)
|> List.distinctBy (fun (lib, pkg, version, isDev) -> pkg)
|> List.map (fun (lib, pkg, version, isDev) ->
if isDev
then ResolveAction.UninstallDev(lib, pkg, version)
else ResolveAction.Uninstall(lib, pkg, version))
let distinctInstallActions =
actions
|> List.choose (function
| ResolveAction.Install(lib, package, version, range) -> Some(lib, package, version, range)
| _ -> None)
// distinct by the combination of package, version and range
|> List.distinctBy (fun (_, pkgName, version, range) -> pkgName, version, range)
// group duplicate package install commands
// try find a version that satisfies all ranges
|> List.groupBy (fun (_, pkg, _, _) -> pkg)
|> List.map (fun (pkgName, packages) ->
match packages with
| [ (lib, _, version, range) ] ->
// make sure the library did not have an unresolvable version
actions
|> List.choose (function
| ResolveAction.UnableToResolve(lib, pkg, range, error) when pkg = pkgName -> Some(SemVer.Range(range))
| _ -> None)
|> List.tryHead
|> function
| None -> ResolveAction.Install(lib, pkgName, version, range)
| Some problematicRange ->
if not (problematicRange.IsSatisfied (SemVer.Version(version)))
then
let errorMsg = sprintf "Resolved version %s satisfies [%s] but not %s" version range (problematicRange.ToString())
ResolveAction.UnableToResolve(lib, pkgName, problematicRange.ToString(), errorMsg)
else
ResolveAction.Install(lib, pkgName, version, range)
| multiplePackages ->
let libName = multiplePackages |> List.map (fun (lib, _, _, _) -> lib) |> List.head
let ranges = multiplePackages |> List.map (fun (_, _, _, range) -> SemVer.Range range)
let versions = multiplePackages |> List.map (fun (_, _, version, _ ) -> SemVer.Version version)
// find a version that satisfies all ranges
versions
|> List.tryFind (fun version -> ranges |> List.forall (fun range -> range.IsSatisfied version))
|> function
| None ->
// could not find a version that satisfies all ranges
// find a sample version that doesn't satisfy a sample range and report them
let rangeStrings = multiplePackages |> List.map (fun (_, _, _, range) -> range)
let errorMsg = sprintf "Could not find a version that satisfies the ranges [%s]" (String.concat ", " rangeStrings)
ResolveAction.UnableToResolve(libName, pkgName, String.concat ", " rangeStrings, errorMsg)
| Some version ->
// found a version that satisfies all versions!
// look ranges that weren't resolved
let rangeStrings = multiplePackages |> List.map (fun (_, _, _, range) -> range)
actions
|> List.choose (function
| ResolveAction.UnableToResolve(lib, pkg, range, error) when pkg = pkgName -> Some(SemVer.Range(range))
| _ -> None)
|> List.tryHead
|> function
| None ->
ResolveAction.Install(libName, pkgName, version.ToString(), String.concat " && " rangeStrings)
| Some problematicRange ->
if not (problematicRange.IsSatisfied version)
then
let errorMsg = sprintf "Resolved version %s satisfies [%s] but not %s" (version.ToString()) (String.concat " && " rangeStrings) (problematicRange.ToString())
ResolveAction.UnableToResolve(libName, pkgName, problematicRange.ToString(), errorMsg)
else
ResolveAction.Install(libName, pkgName, version.ToString(), String.concat " && " rangeStrings)
)
let distinctInstallDevActions =
actions
|> List.choose (function
| ResolveAction.InstallDev(lib, package, version, range) -> Some(lib, package, version, range)
| _ -> None)
// distinct by the combination of package, version and range
|> List.distinctBy (fun (_, pkgName, version, range) -> pkgName, version, range)
// group duplicate package install commands
// try find a version that satisfies all ranges
|> List.groupBy (fun (_, pkg, _, _) -> pkg)
|> List.map (fun (pkgName, packages) ->
match packages with
| [ (lib, _, version, range) ] ->
// make sure the library was did not have an unresolvable version
actions
|> List.choose (function
| ResolveAction.UnableToResolve(lib, pkg, range, error) when pkg = pkgName -> Some(SemVer.Range(range))
| _ -> None)
|> List.tryHead
|> function
| None -> ResolveAction.InstallDev(lib, pkgName, version, range)
| Some problematicRange ->
if not (problematicRange.IsSatisfied (SemVer.Version(version)))
then
let errorMsg = sprintf "Resolved version %s satisfies [%s] but not %s" version range (problematicRange.ToString())
ResolveAction.UnableToResolve(lib, pkgName, problematicRange.ToString(), errorMsg)
else
ResolveAction.InstallDev(lib, pkgName, version, range)
| multiplePackages ->
let libName = multiplePackages |> List.map (fun (lib, _, _, _) -> lib) |> List.head
let ranges = multiplePackages |> List.map (fun (_, _, _, range) -> SemVer.Range range)
let versions = multiplePackages |> List.map (fun (_, _, version, _ ) -> SemVer.Version version)
// find a version that satisfies all ranges
versions
|> List.tryFind (fun version -> ranges |> List.forall (fun range -> range.IsSatisfied version))
|> function
| None ->
// could not find a version that satisfies all ranges
// find a sample version that doesn't satisfy a sample range and report them
let rangeStrings = multiplePackages |> List.map (fun (_, _, _, range) -> range)
let errorMsg = sprintf "Could not find a version that satisfies the ranges [%s]" (String.concat ", " rangeStrings)
ResolveAction.UnableToResolve(libName, pkgName, String.concat ", " rangeStrings, errorMsg)
| Some version ->
// found a version that satisfies all versions!
// look ranges that weren't resolved
let rangeStrings = multiplePackages |> List.map (fun (_, _, _, range) -> range)
actions
|> List.choose (function
| ResolveAction.UnableToResolve(lib, pkg, range, error) when pkg = pkgName -> Some(SemVer.Range(range))
| _ -> None)
|> List.tryHead
|> function
| None ->
ResolveAction.InstallDev(libName, pkgName, version.ToString(), String.concat " && " rangeStrings)
| Some problematicRange ->
if not (problematicRange.IsSatisfied version)
then
let errorMsg = sprintf "Resolved version %s satisfies [%s] but not %s" (version.ToString()) (String.concat " && " rangeStrings) (problematicRange.ToString())
ResolveAction.UnableToResolve(libName, pkgName, problematicRange.ToString(), errorMsg)
else
ResolveAction.InstallDev(libName, pkgName, version.ToString(), String.concat " && " rangeStrings)
)
let unresolvableActions =
actions
|> List.filter (function
| ResolveAction.UnableToResolve (_) -> true
| _ -> false)
List.concat [
distinctUninstallActions
distinctInstallDevActions
distinctInstallActions
unresolvableActions
]
let executeResolutionActions (cwd: string) (manager: NodeManager) (actions: ResolveAction list) =
let actions = resolveConflicts actions
let uninstallPackages =
actions |> List.choose (function
| ResolveAction.Uninstall(_, pkg, _) -> Some pkg
| ResolveAction.UninstallDev(_, pkg, _) -> Some pkg
| _ -> None)
let dependenciesToInstall =
actions |> List.choose (function
| ResolveAction.Install(_, pkg, version, range)-> Some (pkg, version)
| _ -> None)
let devDependenciesToInstall =
actions |> List.choose (function
| ResolveAction.InstallDev(_, pkg, version, range)-> Some (pkg, version)
| _ -> None)
if not (List.isEmpty uninstallPackages) then
// then there some packages we need to uninstall first
let program = manager.CommandName
let args =
match manager with
| NpmCompatible -> [ yield "uninstall"; yield! uninstallPackages ]
| Yarn -> [ yield "remove"; yield! uninstallPackages ]
logger.Information("Uninstalling [{Libraries}]", String.concat ", " uninstallPackages)
CreateProcess.xplatCommand program args
|> CreateProcess.withWorkingDirectory cwd
|> CreateProcess.ensureExitCodeWithMessage (sprintf "Error while uninstalling [%s]" (String.concat ", " uninstallPackages))
|> CreateProcess.redirectOutput
|> Proc.run
|> ignore
if not (List.isEmpty dependenciesToInstall) then
// there are packages that need to be installed
let packagesToInstall =
dependenciesToInstall
|> List.map (fun (package, version) -> sprintf "%s@%s" package version)
let program = manager.CommandName
let args =
match manager with
| NpmCompatible -> [ yield "install"; yield! packagesToInstall; yield "--save" ]
| Yarn -> [ yield "add"; yield! packagesToInstall ]
logger.Information("Installing dependencies [{Libraries}]", String.concat ", " packagesToInstall)
CreateProcess.xplatCommand program args
|> CreateProcess.withWorkingDirectory cwd
|> CreateProcess.ensureExitCodeWithMessage (sprintf "Error while installing %s" (String.concat ", " packagesToInstall))
|> CreateProcess.redirectOutput
|> Proc.run
|> ignore
if not (List.isEmpty devDependenciesToInstall) then
// there are packages that need to be installed
let packagesToInstall =
devDependenciesToInstall
|> List.map (fun (package, version) -> sprintf "%s@%s" package version)
let program = manager.CommandName
let args =
match manager with
| NpmCompatible -> [ yield "install"; yield! packagesToInstall; yield "--save-dev" ]
| Yarn -> [ yield "add"; yield! packagesToInstall; yield "--dev" ]
logger.Information("Installing development dependencies [{Libraries}]", String.concat ", " packagesToInstall)
CreateProcess.xplatCommand program args
|> CreateProcess.withWorkingDirectory cwd
|> CreateProcess.ensureExitCodeWithMessage (sprintf "Error while installing dev %s" (String.concat ", " packagesToInstall))
|> CreateProcess.redirectOutput
|> Proc.run
|> ignore
// print out resolution errors
for action in actions do
match action with
| ResolveAction.UnableToResolve(library, package, version, error) ->
logger.Error("{Library} -> Unable to resolve {Package} {Version}", library, package, version)
logger.Error(error)
| otherwise ->
ignore()
let private validateProject (library : LibraryWithNpmDeps) =
(true, library.NpmDependencies)
||> List.fold (fun (state: bool) (pkg: NpmDependency) ->
logger.Information("{Library} requires npm package {Package}", library.Name, pkg.Name)
logger.Information(" | -- Required range {Range}", pkg.RawVersion)
logger.Information(" | -- Resolution strategy '{Strategy}'", if pkg.LowestMatching then "Min" else "Max")
let isCurrentPkgOk =
match getSatisfyingPackageVersion pkg with
| Some version ->
logger.Information(" | -- ✔ Found version {Version} that satisfies the required range", version)
true
| None ->
logger.Error(" | -- Could not find a version that satisfies the required range {Range}", pkg.RawVersion)
false
state && isCurrentPkgOk
)
let previewResolutionActions
(actions: ResolveAction list)
(installedPackages : InstalledNpmPackage list)
(libraries : LibraryWithNpmDeps list)
(nodeManager: NodeManager) =
// group resolution actions by library/F# project
let actionsByLibrary =
actions
|> List.groupBy (function
| ResolveAction.Install(lib, _, _, _) -> lib
| ResolveAction.InstallDev(lib, _,_,_) -> lib
| ResolveAction.Uninstall(lib, _, _) -> lib
| ResolveAction.UninstallDev(lib, _, _) -> lib
| ResolveAction.UnableToResolve(lib, _, _, _) -> lib)
// libraries without required resolution action will also be logged
// telling the user that everything is OK
let librariesWithoutActions =
let librariesWithActions = List.map fst actionsByLibrary
libraries
|> List.filter (fun lib -> not (librariesWithActions |> List.contains lib.Name))
for library in librariesWithoutActions do
for npmPackage in library.NpmDependencies do
logger.Information("{Library} requires npm package {Package}", library.Name, npmPackage.Name)
logger.Information(" | -- Required range {Range} found in project file", npmPackage.Constraint |> Option.map string |> Option.defaultValue npmPackage.RawVersion)
let installedPackage = installedPackages |> List.tryFind (fun pkg -> pkg.Name = npmPackage.Name)
match installedPackage with
| None ->
// since the library did not require actions, this will never be logged actually
logger.Error(" | -- Missing {package} in package.json", npmPackage.Name)
| Some package ->
match package.Range, package.Installed with
| Some range, Some version ->
logger.Information(" | -- Used range {Range} in package.json", range.ToString())
match npmPackage.Constraint with
| Some requiredRange when range.IsSatisfied version ->
logger.Information(" | -- ✔ Installed version {Version} satisfies required range {Range}", version.ToString(), requiredRange.ToString())
| _ ->
// since the library did not require actions, this will never be logged actually
logger.Error(" | -- Installed version {Version} does not satisfy required range {Range}", version.ToString(), npmPackage.Constraint |> Option.map string |> Option.defaultValue npmPackage.RawVersion)
| _ ->
ignore()
for (library, libActions) in actionsByLibrary do
// group actions required by package
let actionsByPackage =
libActions
|> List.groupBy (function
| ResolveAction.Install(_, pkg, _, _) -> pkg
| ResolveAction.InstallDev(_, pkg,_,_) -> pkg
| ResolveAction.Uninstall(_, pkg, _) -> pkg
| ResolveAction.UninstallDev(_, pkg, _) -> pkg
| ResolveAction.UnableToResolve(_, pkg, _, _) -> pkg)
let currentLibrary = libraries |> List.find (fun lib -> lib.Name = library)
for (package, pkgActions) in actionsByPackage do
// using List.find because we can assume that the dependency was part of the current library
let requiredPackage = currentLibrary.NpmDependencies |> List.find (fun pkg -> pkg.Name = package)
logger.Information("{Library} requires npm package {Package}", library, package)
logger.Information(" | -- Required range {Range} found in project file", requiredPackage.Constraint |> Option.map string |> Option.defaultValue requiredPackage.RawVersion)
let installedPackage = installedPackages |> List.tryFind (fun pkg -> pkg.Name = package)
match installedPackage with
| None ->
logger.Information(" | -- Missing {package} in package.json", package)
| Some installed ->
match installed.Range, installed.Installed with
| Some range, Some version ->
logger.Information(" | -- Used range {Range} in package.json", range.ToString())
logger.Information(" | -- Found installed version {Version}", version.ToString())
| _ ->
ignore()
let nodeCmd npm yarn =
match nodeManager with
| NodeManager.Npm -> npm
| NodeManager.Pnpm -> $"p{npm}"
| NodeManager.Yarn -> yarn
// package actions one of the following
// - Install missing package
// - Uninstall from "devDependencies" and re-install into "dependencies"
// - Uninstall from "dependencies" and re-install "devDependencies"
// - Uninstall old (or "too new") package and re-install based on resolved version
// - Unable to resolve with errors
match pkgActions with
| [ ResolveAction.Install(_, _, version, range) ] ->
if range.Contains "&&"
then logger.Information(" | -- Required version constraint from multiple projects [{Range}]", package, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save" package version)
(sprintf "yarn add %s@%s" package version)
logger.Information(" | -- Resolve manually using '{Command}'", installationCommand)
| [ ResolveAction.InstallDev(_, _, version, range) ] ->
if range.Contains "&&"
then logger.Information(" | -- Required version constraint from multiple projects [{Range}]", package, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save-dev" package version)
(sprintf "yarn add %s@%s --dev" package version)
logger.Information(" | -- Resolve manually using '{Command}'", installationCommand)
// Moving a package from "devDependencies" into "dependencies"
// by means of un-installing it first from the project
// then re-installing it into "dependencies"
| [ ResolveAction.UninstallDev(_); ResolveAction.Install(_, _, version, range) ] ->
logger.Information(" | -- {Package} was installed into \"devDependencies\" instead of \"dependencies\"", package)
logger.Information(" | -- Re-install as a production dependency")
if range.Contains "&&" then logger.Information(" | -- {Packge} specified from multiple projects to satisfy {Range}", package, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save" package version)
(sprintf "yarn add %s@%s" package version)
let uninstallCommand =
nodeCmd
(sprintf "npm uninstall %s" package)
(sprintf "yarn remove %s" package)
logger.Information(" | -- Resolve manually using '{Uninstall}' then '{Install}'", uninstallCommand, installationCommand)
// Moving a package from "dependencies" into "devDependencies"
// by means of un-installing it first from the project
// then re-installing it into "dependencies"
| [ ResolveAction.Uninstall(_); ResolveAction.InstallDev(_, _, version, range) ] ->
logger.Information(" | -- {Package} was installed into \"dependencies\" instead of \"devDependencies\"", package)
logger.Information(" | -- Re-install as a development dependency")
if range.Contains "&&" then logger.Information(" | -- {Package} specified from multiple projects to satisfy {Range}", package, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save-dev" package version)
(sprintf "yarn add %s@%s --dev" package version)
let uninstallCommand =
nodeCmd
(sprintf "npm uninstall %s" package)
(sprintf "yarn remove %s" package)
logger.Information(" | -- Resolve manually using '{Uninstall}' then '{Install}'", uninstallCommand, installationCommand)
// Modifying a package from "dependencies" into a proper version
// that satisfies the requied range
| [ ResolveAction.Uninstall(_, _, installedVersion); ResolveAction.Install(_, _, version, range) ] ->
if range.Contains "&&" then logger.Information(" | -- {Packge} specified from multiple projects to satisfy {Range}", package, range)
logger.Information(" | -- Installed version {Version} does not satisfy [{Range}]", installedVersion, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save" package version)
(sprintf "yarn add %s@%s" package version)
let uninstallCommand =
nodeCmd
(sprintf "npm uninstall %s" package)
(sprintf "yarn remove %s" package)
logger.Information(" | -- Resolve manually using '{Uninstall}' then '{Install}'", uninstallCommand, installationCommand)
// Modifying a package from "devDependencies" into a proper version
// that satisfies the requied range
| [ ResolveAction.UninstallDev(_, _, installedVersion); ResolveAction.InstallDev(_, _, version, range) ] ->
if range.Contains "&&" then logger.Information(" | -- {Packge} specified from multiple projects to satisfy {Range}", package, range)
logger.Information(" | -- Installed version {Version} does not satisfy [{Range}]", installedVersion, range)
let installationCommand =
nodeCmd
(sprintf "npm install %s@%s --save-dev" package version)
(sprintf "yarn add %s@%s --dev" package version)
let uninstallCommand =
nodeCmd
(sprintf "npm uninstall %s" package)
(sprintf "yarn remove %s" package)
logger.Information(" | -- Resolve manually using '{Uninstall}' then '{Install}'", uninstallCommand, installationCommand)
// UnableToResolve can come in pairs: one original and one derived
| [ ResolveAction.UnableToResolve(_, _,_ , error); ResolveAction.UnableToResolve(_) ] ->
logger.Error(" | -- " + error)
// UnableToResolve can come in pairs: one original and one derived
// but sometimes an obsolete "uninstall" action will stay behind as well
| [ (ResolveAction.Uninstall(_) | ResolveAction.UninstallDev(_)); ResolveAction.UnableToResolve(_, _,_ , error); ResolveAction.UnableToResolve(_) ] ->
logger.Error(" | -- " + error)
| [ ResolveAction.UnableToResolve(_, _, _, error) ] ->
logger.Error(" | -- " + error)
| _ ->
ignore()
let private runValidate (libraries : LibraryWithNpmDeps list) =
logger.Information("Ensuring project can be analyzed")
let isValid =
(true, libraries)
||> List.fold (fun (state : bool) (library : LibraryWithNpmDeps) ->
validateProject library && state
)
if isValid then
logger.Information("Validation result: Success")
FemtoResult.ValidationSucceeded
else
logger.Error("Validation result: Failed")
FemtoResult.ValidationFailed
let private restoreNodeModules (packageJson : string) (nodeManager : NodeManager) =
let packageJsonDir = (IO.Directory.GetParent packageJson).FullName
logger.Information("Found package.json in {Dir}", packageJsonDir)
if needsNodeModules packageJson then
logger.Information("Npm packages need to be restored first for project analysis")
let restoreCommand = sprintf "%s install" nodeManager.CommandName
logger.Information("Restoring npm packages using '{Command}' inside {Dir}", restoreCommand, packageJsonDir)
CreateProcess.xplatCommand nodeManager.CommandName [ "install" ]
|> CreateProcess.withWorkingDirectory packageJsonDir
|> CreateProcess.redirectOutput
|> CreateProcess.ensureExitCode
|> Proc.run
|> ignore
let private runResolution (resolve : bool) (packageJson : string option) (nodeManager : NodeManager) (libraries : LibraryWithNpmDeps list) =
match packageJson with
| None ->
for library in libraries do
for pkg in library.NpmDependencies do
logger.Information("{Library} requires npm package {Package} ({Version})", library.Name, pkg.Name, pkg.RawVersion)
logger.Warning "Could not locate package.json file"
FemtoResult.MissingPackageJson
| Some packageJson ->
restoreNodeModules packageJson nodeManager
let installedPackages = findInstalledPackages packageJson
if not resolve then
let resolveActions = autoResolve nodeManager libraries installedPackages []
let simplifiedActions = resolveConflicts resolveActions
previewResolutionActions simplifiedActions (List.ofSeq installedPackages) libraries nodeManager
let allResolutionActionsCanExecute =
simplifiedActions
|> List.exists (function
| ResolveAction.UnableToResolve(_) -> true
| _ -> false)
|> not
if allResolutionActionsCanExecute
then FemtoResult.ValidationSucceeded
else FemtoResult.ValidationFailed
else
let resolveActions = autoResolve nodeManager libraries installedPackages []
if List.isEmpty resolveActions then
logger.Information("✔ Required packages are already resolved")
FemtoResult.ValidationSucceeded
else
logger.Information("Executing required actions for package resolution")
try
let cwd = (IO.Directory.GetParent packageJson).FullName
executeResolutionActions cwd nodeManager resolveActions
logger.Information("✔ Package resolution complete")
FemtoResult.ValidationSucceeded
with
| ex ->
logger.Error(ex.Message)
FemtoResult.UnexpectedError
/// Returns whether paket is installed as a global dotnet tool
let isPaketInstalledGlobally() =
[ "tool"; "list"; "--global" ]
|> CreateProcess.xplatCommand "dotnet"
|> CreateProcess.redirectOutput
|> Proc.run
|> fun result ->
if result.ExitCode <> 0 then
false
else
result.Result.Output
|> String.split '\n'
|> Seq.exists (fun line -> line.StartsWith "paket")
/// Returns whether paket is installed a local dotnet CLI tool
/// This function checks whether the entry "paket" exists in { "tools": [tool entries] }
/// The contents of the JSON is taken from .config/dotnet-tools.json which is the tool manifest
/// for local CLI tools in .NET Core 3 onwards
let isPaketInstalledAsLocalCliTool (paketDependenciesWorkingDir: string) =
try
let toolsConfigPath = IO.Path.Combine(paketDependenciesWorkingDir, ".config", "dotnet-tools.json")
if IO.File.Exists toolsConfigPath then
let toolsContentDecoded =
IO.File.ReadAllText toolsConfigPath
|> Decode.fromString (Decode.at ["tools"; "paket"] Decode.value)
match toolsContentDecoded with
| Ok _ -> true
| Error _ -> false
else
false
with
| ex -> false
let installLocalCliTool name workingDir =
CreateProcess.xplatCommand "dotnet" [ "tool"; "install"; name ]
|> CreateProcess.withWorkingDirectory workingDir
|> CreateProcess.redirectOutput
|> Proc.run
|> fun processInfo ->
if processInfo.ExitCode <> 0 then
Error processInfo.Result.Output
else
Ok()
/// Creates a .config/dotnet-tools.json file if it does not exist
/// This is a tool manifest file which allows us to install paket a local cli tool (starting from .NET Core 3)
/// TODO: Discuss whether it is a good idea to install paket automatically
let installPaketAsLocalCliToll projectRoot =
let directory = IO.Path.Combine(projectRoot, ".config")
let configFilePath = IO.Path.Combine(projectRoot, ".config", "dotnet-tools.json")
if not (IO.Directory.Exists directory) then
IO.Directory.CreateDirectory directory |> ignore
let content = "{ \"version\":1, \"isRoot\":true, \"tools\": { } }"
IO.File.WriteAllText(configFilePath, content)
installLocalCliTool "paket" projectRoot
else
if IO.File.Exists configFilePath then
installLocalCliTool "paket" projectRoot
else
let content = "{ \"version\":1, \"isRoot\":true, \"tools\": { } }"
IO.File.WriteAllText(configFilePath, content)
installLocalCliTool "paket" projectRoot
let installPaketFromBootstrapper projectRoot =
let installation = async {
try
use httpClient = new HttpClient()
let! paketSearchResult = Async.AwaitTask (httpClient.GetStringAsync("https://azuresearch-usnc.nuget.org/query?q=Paket&prerelease=false"))
let dataDecoder =
Decode.object (fun it ->
(it.Required.Field "id" Decode.string,
it.Required.Field "version" Decode.string)
)
|> Decode.list
|> Decode.field "data"
let latestPaketVersion =
match Decode.fromString dataDecoder paketSearchResult with
| Ok packages ->
packages
|> Seq.tryFind (fun (id, _) -> id = "Paket")
|> Option.map (fun (_, version) -> version)
| Error errorMessage ->
logger.Error("Couldn't decode nuget packages. Reason: {Message}", errorMessage)
None