-
Notifications
You must be signed in to change notification settings - Fork 299
/
NugetHelper.cs
1960 lines (1683 loc) · 85.6 KB
/
NugetHelper.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
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
namespace NugetForUnity
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
/// <summary>
/// A set of helper methods that act as a wrapper around nuget.exe
///
/// TIP: It's incredibly useful to associate .nupkg files as compressed folder in Windows (View like .zip files). To do this:
/// 1) Open a command prompt as admin (Press Windows key. Type "cmd". Right click on the icon and choose "Run as Administrator"
/// 2) Enter this command: cmd /c assoc .nupkg=CompressedFolder
/// </summary>
[InitializeOnLoad]
public static class NugetHelper
{
private static bool insideInitializeOnLoad = false;
/// <summary>
/// The path to the nuget.config file.
/// </summary>
public static readonly string NugetConfigFilePath = Path.Combine(Application.dataPath, "./NuGet.config");
/// <summary>
/// The path to the packages.config file.
/// </summary>
private static readonly string PackagesConfigFilePath = Path.Combine(Application.dataPath, "./packages.config");
/// <summary>
/// The path where to put created (packed) and downloaded (not installed yet) .nupkg files.
/// </summary>
public static readonly string PackOutputDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine("NuGet", "Cache"));
/// <summary>
/// The amount of time, in milliseconds, before the nuget.exe process times out and is killed.
/// </summary>
private const int TimeOut = 60000;
/// <summary>
/// The loaded NuGet.config file that holds the settings for NuGet.
/// </summary>
public static NugetConfigFile NugetConfigFile { get; private set; }
/// <summary>
/// Backing field for the packages.config file.
/// </summary>
private static PackagesConfigFile packagesConfigFile;
/// <summary>
/// Gets the loaded packages.config file that hold the dependencies for the project.
/// </summary>
public static PackagesConfigFile PackagesConfigFile
{
get
{
if (packagesConfigFile == null)
{
packagesConfigFile = PackagesConfigFile.Load(PackagesConfigFilePath);
}
return packagesConfigFile;
}
}
/// <summary>
/// The list of <see cref="NugetPackageSource"/>s to use.
/// </summary>
private static List<NugetPackageSource> packageSources = new List<NugetPackageSource>();
/// <summary>
/// The dictionary of currently installed <see cref="NugetPackage"/>s keyed off of their ID string.
/// </summary>
private static Dictionary<string, NugetPackage> installedPackages = new Dictionary<string, NugetPackage>();
/// <summary>
/// The dictionary of cached credentials retrieved by credential providers, keyed by feed URI.
/// </summary>
private static Dictionary<Uri, CredentialProviderResponse?> cachedCredentialsByFeedUri = new Dictionary<Uri, CredentialProviderResponse?>();
/// <summary>
/// The current .NET version being used (2.0 [actually 3.5], 4.6, etc).
/// </summary>
private static ApiCompatibilityLevel DotNetVersion
{
get
{
#if UNITY_5_6_OR_NEWER
return PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup);
#else
return PlayerSettings.apiCompatibilityLevel;
#endif
}
}
/// <summary>
/// Static constructor used by Unity to initialize NuGet and restore packages defined in packages.config.
/// </summary>
static NugetHelper()
{
insideInitializeOnLoad = true;
try
{
// if we are entering playmode, don't do anything
if (EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
// Load the NuGet.config file
LoadNugetConfigFile();
// create the nupkgs directory, if it doesn't exist
if (!Directory.Exists(PackOutputDirectory))
{
Directory.CreateDirectory(PackOutputDirectory);
}
// restore packages - this will be called EVERY time the project is loaded or a code-file changes
Restore();
}
finally
{
insideInitializeOnLoad = false;
}
}
/// <summary>
/// Loads the NuGet.config file.
/// </summary>
public static void LoadNugetConfigFile()
{
if (File.Exists(NugetConfigFilePath))
{
NugetConfigFile = NugetConfigFile.Load(NugetConfigFilePath);
}
else
{
Debug.LogFormat("No NuGet.config file found. Creating default at {0}", NugetConfigFilePath);
NugetConfigFile = NugetConfigFile.CreateDefaultFile(NugetConfigFilePath);
AssetDatabase.Refresh();
}
// parse any command line arguments
//LogVerbose("Command line: {0}", Environment.CommandLine);
packageSources.Clear();
bool readingSources = false;
bool useCommandLineSources = false;
foreach (string arg in Environment.GetCommandLineArgs())
{
if (readingSources)
{
if (arg.StartsWith("-"))
{
readingSources = false;
}
else
{
NugetPackageSource source = new NugetPackageSource("CMD_LINE_SRC_" + packageSources.Count, arg);
LogVerbose("Adding command line package source {0} at {1}", "CMD_LINE_SRC_" + packageSources.Count, arg);
packageSources.Add(source);
}
}
if (arg == "-Source")
{
// if the source is being forced, don't install packages from the cache
NugetConfigFile.InstallFromCache = false;
readingSources = true;
useCommandLineSources = true;
}
}
// if there are not command line overrides, use the NuGet.config package sources
if (!useCommandLineSources)
{
if (NugetConfigFile.ActivePackageSource.ExpandedPath == "(Aggregate source)")
{
packageSources.AddRange(NugetConfigFile.PackageSources);
}
else
{
packageSources.Add(NugetConfigFile.ActivePackageSource);
}
}
}
/// <summary>
/// Runs nuget.exe using the given arguments.
/// </summary>
/// <param name="arguments">The arguments to run nuget.exe with.</param>
/// <param name="logOuput">True to output debug information to the Unity console. Defaults to true.</param>
/// <returns>The string of text that was output from nuget.exe following its execution.</returns>
private static void RunNugetProcess(string arguments, bool logOuput = true)
{
// Try to find any nuget.exe in the package tools installation location
string toolsPackagesFolder = Path.Combine(Application.dataPath, "../Packages");
// create the folder to prevent an exception when getting the files
Directory.CreateDirectory(toolsPackagesFolder);
string[] files = Directory.GetFiles(toolsPackagesFolder, "nuget.exe", SearchOption.AllDirectories);
if (files.Length > 1)
{
Debug.LogWarningFormat("More than one nuget.exe found. Using first one.");
}
else if (files.Length < 1)
{
Debug.LogWarningFormat("No nuget.exe found! Attemping to install the NuGet.CommandLine package.");
InstallIdentifier(new NugetPackageIdentifier("NuGet.CommandLine", "2.8.6"));
files = Directory.GetFiles(toolsPackagesFolder, "nuget.exe", SearchOption.AllDirectories);
if (files.Length < 1)
{
Debug.LogErrorFormat("nuget.exe still not found. Quiting...");
return;
}
}
LogVerbose("Running: {0} \nArgs: {1}", files[0], arguments);
string fileName = string.Empty;
string commandLine = string.Empty;
#if UNITY_EDITOR_OSX
// ATTENTION: you must install mono running on your mac, we use this mono to run `nuget.exe`
fileName = "/Library/Frameworks/Mono.framework/Versions/Current/Commands/mono";
commandLine = " " + files[0] + " " + arguments;
LogVerbose("command: " + commandLine);
#else
fileName = files[0];
commandLine = arguments;
#endif
Process process = Process.Start(
new ProcessStartInfo(fileName, commandLine)
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
// WorkingDirectory = Path.GettargetFramework(files[0]),
// http://stackoverflow.com/questions/16803748/how-to-decode-cmd-output-correctly
// Default = 65533, ASCII = ?, Unicode = nothing works at all, UTF-8 = 65533, UTF-7 = 242 = WORKS!, UTF-32 = nothing works at all
StandardOutputEncoding = Encoding.GetEncoding(850)
});
if (!process.WaitForExit(TimeOut))
{
Debug.LogWarning("NuGet took too long to finish. Killing operation.");
process.Kill();
}
string error = process.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Debug.LogError(error);
}
string output = process.StandardOutput.ReadToEnd();
if (logOuput && !string.IsNullOrEmpty(output))
{
Debug.Log(output);
}
}
/// <summary>
/// Replace all %20 encodings with a normal space.
/// </summary>
/// <param name="directoryPath">The path to the directory.</param>
private static void FixSpaces(string directoryPath)
{
if (directoryPath.Contains("%20"))
{
LogVerbose("Removing %20 from {0}", directoryPath);
Directory.Move(directoryPath, directoryPath.Replace("%20", " "));
directoryPath = directoryPath.Replace("%20", " ");
}
string[] subdirectories = Directory.GetDirectories(directoryPath);
foreach (string subDir in subdirectories)
{
FixSpaces(subDir);
}
string[] files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
if (file.Contains("%20"))
{
LogVerbose("Removing %20 from {0}", file);
File.Move(file, file.Replace("%20", " "));
}
}
}
/// <summary>
/// Checks the file importer settings and disables the export to WSA Platform setting.
/// </summary>
/// <param name="filePath">The path to the .config file.</param>
/// <param name="notifyOfUpdate">Whether or not to log a warning of the update.</param>
public static void DisableWSAPExportSetting(string filePath, bool notifyOfUpdate)
{
string[] unityVersionParts = Application.unityVersion.Split('.');
int unityMajorVersion;
if (int.TryParse(unityVersionParts[0], out unityMajorVersion) && unityMajorVersion <= 2017)
{
return;
}
filePath = Path.GetFullPath(filePath);
string assetsLocalPath = filePath.Replace(Path.GetFullPath(Application.dataPath), "Assets");
PluginImporter importer = AssetImporter.GetAtPath(assetsLocalPath) as PluginImporter;
if (importer == null)
{
if (!insideInitializeOnLoad)
{
Debug.LogError(string.Format("Couldn't get importer for '{0}'.", filePath));
}
return;
}
if (importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer))
{
if (notifyOfUpdate)
{
Debug.LogWarning(string.Format("Disabling WSA platform on asset settings for {0}", filePath));
}
else
{
LogVerbose("Disabling WSA platform on asset settings for {0}", filePath);
}
importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false);
}
}
private static bool FrameworkNamesAreEqual(string tfm1, string tfm2)
{
return tfm1.Equals(tfm2, StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Cleans up a package after it has been installed.
/// Since we are in Unity, we can make certain assumptions on which files will NOT be used, so we can delete them.
/// </summary>
/// <param name="package">The NugetPackage to clean.</param>
private static void Clean(NugetPackageIdentifier package)
{
string packageInstallDirectory = Path.Combine(NugetConfigFile.RepositoryPath, string.Format("{0}.{1}", package.Id, package.Version));
LogVerbose("Cleaning {0}", packageInstallDirectory);
FixSpaces(packageInstallDirectory);
// delete a remnant .meta file that may exist from packages created by Unity
DeleteFile(packageInstallDirectory + "/" + package.Id + ".nuspec.meta");
// delete directories & files that NuGet normally deletes, but since we are installing "manually" they exist
DeleteDirectory(packageInstallDirectory + "/_rels");
DeleteDirectory(packageInstallDirectory + "/package");
DeleteFile(packageInstallDirectory + "/" + package.Id + ".nuspec");
DeleteFile(packageInstallDirectory + "/[Content_Types].xml");
// Unity has no use for the build directory
DeleteDirectory(packageInstallDirectory + "/build");
// For now, delete src. We may use it later...
DeleteDirectory(packageInstallDirectory + "/src");
// Since we don't automatically fix up the runtime dll platforms, remove them until we improve support
// for this newer feature of nuget packages.
DeleteDirectory(Path.Combine(packageInstallDirectory, "runtimes"));
// Delete documentation folders since they sometimes have HTML docs with JavaScript, which Unity tried to parse as "UnityScript"
DeleteDirectory(packageInstallDirectory + "/docs");
// Delete ref folder, as it is just used for compile-time reference and does not contain implementations.
// Leaving it results in "assembly loading" and "multiple pre-compiled assemblies with same name" errors
DeleteDirectory(packageInstallDirectory + "/ref");
if (Directory.Exists(packageInstallDirectory + "/lib"))
{
List<string> selectedDirectories = new List<string>();
// go through the library folders in descending order (highest to lowest version)
IEnumerable<DirectoryInfo> libDirectories = Directory.GetDirectories(packageInstallDirectory + "/lib").Select(s => new DirectoryInfo(s));
var targetFrameworks = libDirectories
.Select(x => x.Name.ToLower());
bool isAlreadyImported = IsAlreadyImportedInEngine(package);
string bestTargetFramework = TryGetBestTargetFrameworkForCurrentSettings(targetFrameworks);
if (!isAlreadyImported && (bestTargetFramework != null))
{
DirectoryInfo bestLibDirectory = libDirectories
.First(x => FrameworkNamesAreEqual(x.Name, bestTargetFramework));
if (bestTargetFramework == "unity" ||
bestTargetFramework == "net35-unity full v3.5" ||
bestTargetFramework == "net35-unity subset v3.5")
{
selectedDirectories.Add(Path.Combine(bestLibDirectory.Parent.FullName, "unity"));
selectedDirectories.Add(Path.Combine(bestLibDirectory.Parent.FullName, "net35-unity full v3.5"));
selectedDirectories.Add(Path.Combine(bestLibDirectory.Parent.FullName, "net35-unity subset v3.5"));
}
else
{
selectedDirectories.Add(bestLibDirectory.FullName);
}
}
foreach (string directory in selectedDirectories)
{
LogVerbose("Using {0}", directory);
}
// delete all of the libaries except for the selected one
foreach (DirectoryInfo directory in libDirectories)
{
bool validDirectory = selectedDirectories
.Where(d => string.Compare(d, directory.FullName, ignoreCase: true) == 0)
.Any();
if (!validDirectory)
{
DeleteDirectory(directory.FullName);
}
}
}
if (Directory.Exists(packageInstallDirectory + "/tools"))
{
// Move the tools folder outside of the Unity Assets folder
string toolsInstallDirectory = Path.Combine(Application.dataPath, string.Format("../Packages/{0}.{1}/tools", package.Id, package.Version));
LogVerbose("Moving {0} to {1}", packageInstallDirectory + "/tools", toolsInstallDirectory);
// create the directory to create any of the missing folders in the path
Directory.CreateDirectory(toolsInstallDirectory);
// delete the final directory to prevent the Move operation from throwing exceptions.
DeleteDirectory(toolsInstallDirectory);
Directory.Move(packageInstallDirectory + "/tools", toolsInstallDirectory);
}
// delete all PDB files since Unity uses Mono and requires MDB files, which causes it to output "missing MDB" errors
DeleteAllFiles(packageInstallDirectory, "*.pdb");
// if there are native DLLs, copy them to the Unity project root (1 up from Assets)
if (Directory.Exists(packageInstallDirectory + "/output"))
{
string[] files = Directory.GetFiles(packageInstallDirectory + "/output");
foreach (string file in files)
{
string newFilePath = Directory.GetCurrentDirectory() + "/" + Path.GetFileName(file);
LogVerbose("Moving {0} to {1}", file, newFilePath);
DeleteFile(newFilePath);
File.Move(file, newFilePath);
}
LogVerbose("Deleting {0}", packageInstallDirectory + "/output");
DeleteDirectory(packageInstallDirectory + "/output");
}
// if there are Unity plugin DLLs, copy them to the Unity Plugins folder (Assets/Plugins)
if (Directory.Exists(packageInstallDirectory + "/unityplugin"))
{
string pluginsDirectory = Application.dataPath + "/Plugins/";
DirectoryCopy(packageInstallDirectory + "/unityplugin", pluginsDirectory);
LogVerbose("Deleting {0}", packageInstallDirectory + "/unityplugin");
DeleteDirectory(packageInstallDirectory + "/unityplugin");
}
// if there are Unity StreamingAssets, copy them to the Unity StreamingAssets folder (Assets/StreamingAssets)
if (Directory.Exists(packageInstallDirectory + "/StreamingAssets"))
{
string streamingAssetsDirectory = Application.dataPath + "/StreamingAssets/";
if (!Directory.Exists(streamingAssetsDirectory))
{
Directory.CreateDirectory(streamingAssetsDirectory);
}
// move the files
string[] files = Directory.GetFiles(packageInstallDirectory + "/StreamingAssets");
foreach (string file in files)
{
string newFilePath = streamingAssetsDirectory + Path.GetFileName(file);
try
{
LogVerbose("Moving {0} to {1}", file, newFilePath);
DeleteFile(newFilePath);
File.Move(file, newFilePath);
}
catch (Exception e)
{
Debug.LogWarningFormat("{0} couldn't be moved. \n{1}", newFilePath, e.ToString());
}
}
// move the directories
string[] directories = Directory.GetDirectories(packageInstallDirectory + "/StreamingAssets");
foreach (string directory in directories)
{
string newDirectoryPath = streamingAssetsDirectory + new DirectoryInfo(directory).Name;
try
{
LogVerbose("Moving {0} to {1}", directory, newDirectoryPath);
if (Directory.Exists(newDirectoryPath))
{
DeleteDirectory(newDirectoryPath);
}
Directory.Move(directory, newDirectoryPath);
}
catch (Exception e)
{
Debug.LogWarningFormat("{0} couldn't be moved. \n{1}", newDirectoryPath, e.ToString());
}
}
// delete the package's StreamingAssets folder and .meta file
LogVerbose("Deleting {0}", packageInstallDirectory + "/StreamingAssets");
DeleteDirectory(packageInstallDirectory + "/StreamingAssets");
DeleteFile(packageInstallDirectory + "/StreamingAssets.meta");
}
}
private static bool IsAlreadyImportedInEngine(NugetPackageIdentifier package)
{
HashSet<string> alreadyImportedLibs = GetAlreadyImportedLibs();
bool isAlreadyImported = alreadyImportedLibs.Contains(package.Id);
LogVerbose("Is package '{0}' already imported? {1}", package.Id, isAlreadyImported);
return isAlreadyImported;
}
private static HashSet<string> alreadyImportedLibs = null;
private static HashSet<string> GetAlreadyImportedLibs()
{
if (alreadyImportedLibs == null)
{
string[] lookupPaths = GetAllLookupPaths();
IEnumerable<string> libNames = lookupPaths
.SelectMany(directory => Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories))
.Select(Path.GetFileName)
.Select(p => Path.ChangeExtension(p, null));
alreadyImportedLibs = new HashSet<string>(libNames);
LogVerbose("Already imported libs: {0}", string.Join(", ", alreadyImportedLibs));
}
return alreadyImportedLibs;
}
private static string[] GetAllLookupPaths()
{
var executablePath = EditorApplication.applicationPath;
var roots = new[] {
// MacOS directory layout
Path.Combine(executablePath, "Contents"),
// Windows directory layout
Path.Combine(Directory.GetParent(executablePath).FullName, "Data")
};
var relativePaths = new[] {
Path.Combine("NetStandard", "compat"),
Path.Combine("MonoBleedingEdge", "lib", "mono")
};
var allPossiblePaths = roots
.SelectMany(root => relativePaths
.Select(relativePath => Path.Combine(root, relativePath)));
var existingPaths = allPossiblePaths
.Where(Directory.Exists)
.ToArray();
LogVerbose("All existing path to dependency lookup are: {0}", string.Join(", ", existingPaths));
return existingPaths;
}
public static NugetFrameworkGroup GetBestDependencyFrameworkGroupForCurrentSettings(NugetPackage package)
{
var targetFrameworks = package.Dependencies
.Select(x => x.TargetFramework);
string bestTargetFramework = TryGetBestTargetFrameworkForCurrentSettings(targetFrameworks);
return package.Dependencies
.FirstOrDefault(x => FrameworkNamesAreEqual(x.TargetFramework, bestTargetFramework)) ?? new NugetFrameworkGroup();
}
public static NugetFrameworkGroup GetBestDependencyFrameworkGroupForCurrentSettings(NuspecFile nuspec)
{
var targetFrameworks = nuspec.Dependencies
.Select(x => x.TargetFramework);
string bestTargetFramework = TryGetBestTargetFrameworkForCurrentSettings(targetFrameworks);
return nuspec.Dependencies
.FirstOrDefault(x => FrameworkNamesAreEqual(x.TargetFramework, bestTargetFramework)) ?? new NugetFrameworkGroup();
}
private struct UnityVersion : IComparable<UnityVersion>
{
public int Major;
public int Minor;
public int Revision;
public char Release;
public int Build;
public static UnityVersion Current = new UnityVersion(Application.unityVersion);
public UnityVersion(string version)
{
Match match = Regex.Match(version, @"(\d+)\.(\d+)\.(\d+)([fpba])(\d+)");
if (!match.Success) { throw new ArgumentException("Invalid unity version"); }
Major = int.Parse(match.Groups[1].Value);
Minor = int.Parse(match.Groups[2].Value);
Revision = int.Parse(match.Groups[3].Value);
Release = match.Groups[4].Value[0];
Build = int.Parse(match.Groups[5].Value);
}
public static int Compare(UnityVersion a, UnityVersion b)
{
if (a.Major < b.Major) { return -1; }
if (a.Major > b.Major) { return 1; }
if (a.Minor < b.Minor) { return -1; }
if (a.Minor > b.Minor) { return 1; }
if (a.Revision < b.Revision) { return -1; }
if (a.Revision > b.Revision) { return 1; }
if (a.Release < b.Release) { return -1; }
if (a.Release > b.Release) { return 1; }
if (a.Build < b.Build) { return -1; }
if (a.Build > b.Build) { return 1; }
return 0;
}
public int CompareTo(UnityVersion other)
{
return Compare(this, other);
}
}
private struct PriorityFramework { public int Priority; public string Framework; }
private static readonly string[] unityFrameworks = new string[] { "unity" };
private static readonly string[] netStandardFrameworks = new string[] {
"netstandard20", "netstandard16", "netstandard15", "netstandard14", "netstandard13", "netstandard12", "netstandard11", "netstandard10" };
private static readonly string[] net4Unity2018Frameworks = new string[] { "net471", "net47" };
private static readonly string[] net4Unity2017Frameworks = new string[] { "net462", "net461", "net46", "net452", "net451", "net45", "net403", "net40", "net4" };
private static readonly string[] net3Frameworks = new string[] { "net35-unity full v3.5", "net35-unity subset v3.5", "net35", "net20", "net11" };
private static readonly string[] defaultFrameworks = new string[] { string.Empty };
public static string TryGetBestTargetFrameworkForCurrentSettings(IEnumerable<string> targetFrameworks)
{
int intDotNetVersion = (int)DotNetVersion; // c
//bool using46 = DotNetVersion == ApiCompatibilityLevel.NET_4_6; // NET_4_6 option was added in Unity 5.6
bool using46 = intDotNetVersion == 3; // NET_4_6 = 3 in Unity 5.6 and Unity 2017.1 - use the hard-coded int value to ensure it works in earlier versions of Unity
bool usingStandard2 = intDotNetVersion == 6; // using .net standard 2.0
var frameworkGroups = new List<string[]> { unityFrameworks };
if (usingStandard2)
{
frameworkGroups.Add(netStandardFrameworks);
}
else if (using46)
{
if (UnityVersion.Current.Major >= 2018)
{
frameworkGroups.Add(net4Unity2018Frameworks);
}
if (UnityVersion.Current.Major >= 2017)
{
frameworkGroups.Add(net4Unity2017Frameworks);
}
frameworkGroups.Add(net3Frameworks);
frameworkGroups.Add(netStandardFrameworks);
}
else
{
frameworkGroups.Add(net3Frameworks);
}
frameworkGroups.Add(defaultFrameworks);
Func<string, int> getTfmPriority = (string tfm) =>
{
for (int i = 0; i < frameworkGroups.Count; ++i)
{
int index = Array.FindIndex(frameworkGroups[i], test =>
{
if (test.Equals(tfm, StringComparison.InvariantCultureIgnoreCase)) { return true; }
if (test.Equals(tfm.Replace(".", string.Empty), StringComparison.InvariantCultureIgnoreCase)) { return true; }
return false;
});
if (index >= 0)
{
return i * 1000 + index;
}
}
return int.MaxValue;
};
// Select the highest .NET library available that is supported
// See here: https://docs.nuget.org/ndocs/schema/target-frameworks
string result = targetFrameworks
.Select(tfm => new PriorityFramework { Priority = getTfmPriority(tfm), Framework = tfm })
.Where(pfm => pfm.Priority != int.MaxValue)
.ToArray() // Ensure we don't search for priorities again when sorting
.OrderBy(pfm => pfm.Priority)
.Select(pfm => pfm.Framework)
.FirstOrDefault();
LogVerbose("Selecting {0} as the best target framework for current settings", result ?? "(null)");
return result;
}
/// <summary>
/// Calls "nuget.exe pack" to create a .nupkg file based on the given .nuspec file.
/// </summary>
/// <param name="nuspecFilePath">The full filepath to the .nuspec file to use.</param>
public static void Pack(string nuspecFilePath)
{
if (!Directory.Exists(PackOutputDirectory))
{
Directory.CreateDirectory(PackOutputDirectory);
}
// Use -NoDefaultExcludes to allow files and folders that start with a . to be packed into the package
// This is done because if you want a file/folder in a Unity project, but you want Unity to ignore it, it must start with a .
// This is especially useful for .cs and .js files that you don't want Unity to compile as game scripts
string arguments = string.Format("pack \"{0}\" -OutputDirectory \"{1}\" -NoDefaultExcludes", nuspecFilePath, PackOutputDirectory);
RunNugetProcess(arguments);
}
/// <summary>
/// Calls "nuget.exe push" to push a .nupkf file to the the server location defined in the NuGet.config file.
/// Note: This differs slightly from NuGet's Push command by automatically calling Pack if the .nupkg doesn't already exist.
/// </summary>
/// <param name="nuspec">The NuspecFile which defines the package to push. Only the ID and Version are used.</param>
/// <param name="nuspecFilePath">The full filepath to the .nuspec file to use. This is required by NuGet's Push command.</param>
/// /// <param name="apiKey">The API key to use when pushing a package to the server. This is optional.</param>
public static void Push(NuspecFile nuspec, string nuspecFilePath, string apiKey = "")
{
string packagePath = Path.Combine(PackOutputDirectory, string.Format("{0}.{1}.nupkg", nuspec.Id, nuspec.Version));
if (!File.Exists(packagePath))
{
LogVerbose("Attempting to Pack.");
Pack(nuspecFilePath);
if (!File.Exists(packagePath))
{
Debug.LogErrorFormat("NuGet package not found: {0}", packagePath);
return;
}
}
string arguments = string.Format("push \"{0}\" {1} -configfile \"{2}\"", packagePath, apiKey, NugetConfigFilePath);
RunNugetProcess(arguments);
}
/// <summary>
/// Recursively copies all files and sub-directories from one directory to another.
/// </summary>
/// <param name="sourceDirectoryPath">The filepath to the folder to copy from.</param>
/// <param name="destDirectoryPath">The filepath to the folder to copy to.</param>
private static void DirectoryCopy(string sourceDirectoryPath, string destDirectoryPath)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirectoryPath);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirectoryPath);
}
// if the destination directory doesn't exist, create it
if (!Directory.Exists(destDirectoryPath))
{
LogVerbose("Creating new directory: {0}", destDirectoryPath);
Directory.CreateDirectory(destDirectoryPath);
}
// get the files in the directory and copy them to the new location
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string newFilePath = Path.Combine(destDirectoryPath, file.Name);
try
{
LogVerbose("Moving {0} to {1}", file.ToString(), newFilePath);
file.CopyTo(newFilePath, true);
}
catch (Exception e)
{
Debug.LogWarningFormat("{0} couldn't be moved to {1}. It may be a native plugin already locked by Unity. Please trying closing Unity and manually moving it. \n{2}", file.ToString(), newFilePath, e.ToString());
}
}
// copy sub-directories and their contents to new location
DirectoryInfo[] dirs = dir.GetDirectories();
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirectoryPath, subdir.Name);
DirectoryCopy(subdir.FullName, temppath);
}
}
/// <summary>
/// Recursively deletes the folder at the given path.
/// NOTE: Directory.Delete() doesn't delete Read-Only files, whereas this does.
/// </summary>
/// <param name="directoryPath">The path of the folder to delete.</param>
private static void DeleteDirectory(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
return;
}
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
// delete any sub-folders first
foreach (FileSystemInfo childInfo in directoryInfo.GetFileSystemInfos())
{
DeleteDirectory(childInfo.FullName);
}
// remove the read-only flag on all files
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
file.Attributes = FileAttributes.Normal;
}
// remove the read-only flag on the directory
directoryInfo.Attributes = FileAttributes.Normal;
// recursively delete the directory
directoryInfo.Delete(true);
}
/// <summary>
/// Deletes a file at the given filepath.
/// </summary>
/// <param name="filePath">The filepath to the file to delete.</param>
private static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
}
/// <summary>
/// Deletes all files in the given directory or in any sub-directory, with the given extension.
/// </summary>
/// <param name="directoryPath">The path to the directory to delete all files of the given extension from.</param>
/// <param name="extension">The extension of the files to delete, in the form "*.ext"</param>
private static void DeleteAllFiles(string directoryPath, string extension)
{
string[] files = Directory.GetFiles(directoryPath, extension, SearchOption.AllDirectories);
foreach (string file in files)
{
DeleteFile(file);
}
}
/// <summary>
/// Uninstalls all of the currently installed packages.
/// </summary>
internal static void UninstallAll()
{
foreach (NugetPackage package in installedPackages.Values.ToList())
{
Uninstall(package);
}
}
/// <summary>
/// "Uninstalls" the given package by simply deleting its folder.
/// </summary>
/// <param name="package">The NugetPackage to uninstall.</param>
/// <param name="refreshAssets">True to force Unity to refesh its Assets folder. False to temporarily ignore the change. Defaults to true.</param>
public static void Uninstall(NugetPackageIdentifier package, bool refreshAssets = true)
{
LogVerbose("Uninstalling: {0} {1}", package.Id, package.Version);
// update the package.config file
PackagesConfigFile.RemovePackage(package);
PackagesConfigFile.Save(PackagesConfigFilePath);
string packageInstallDirectory = Path.Combine(NugetConfigFile.RepositoryPath, string.Format("{0}.{1}", package.Id, package.Version));
DeleteDirectory(packageInstallDirectory);
string metaFile = Path.Combine(NugetConfigFile.RepositoryPath, string.Format("{0}.{1}.meta", package.Id, package.Version));
DeleteFile(metaFile);
string toolsInstallDirectory = Path.Combine(Application.dataPath, string.Format("../Packages/{0}.{1}", package.Id, package.Version));
DeleteDirectory(toolsInstallDirectory);
installedPackages.Remove(package.Id);
if (refreshAssets)
{
AssetDatabase.Refresh();
}
}
/// <summary>
/// Updates a package by uninstalling the currently installed version and installing the "new" version.
/// </summary>
/// <param name="currentVersion">The current package to uninstall.</param>
/// <param name="newVersion">The package to install.</param>
/// <param name="refreshAssets">True to refresh the assets inside Unity. False to ignore them (for now). Defaults to true.</param>
public static bool Update(NugetPackageIdentifier currentVersion, NugetPackage newVersion, bool refreshAssets = true)
{
LogVerbose("Updating {0} {1} to {2}", currentVersion.Id, currentVersion.Version, newVersion.Version);
Uninstall(currentVersion, false);
return InstallIdentifier(newVersion, refreshAssets);
}
/// <summary>
/// Installs all of the given updates, and uninstalls the corresponding package that is already installed.
/// </summary>
/// <param name="updates">The list of all updates to install.</param>
/// <param name="packagesToUpdate">The list of all packages currently installed.</param>
public static void UpdateAll(IEnumerable<NugetPackage> updates, IEnumerable<NugetPackage> packagesToUpdate)
{
float progressStep = 1.0f / updates.Count();
float currentProgress = 0;
foreach (NugetPackage update in updates)
{
EditorUtility.DisplayProgressBar(string.Format("Updating to {0} {1}", update.Id, update.Version), "Installing All Updates", currentProgress);
NugetPackage installedPackage = packagesToUpdate.FirstOrDefault(p => p.Id == update.Id);
if (installedPackage != null)
{
Update(installedPackage, update, false);
}
else
{
Debug.LogErrorFormat("Trying to update {0} to {1}, but no version is installed!", update.Id, update.Version);
}
currentProgress += progressStep;
}
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
}
/// <summary>
/// Gets the dictionary of packages that are actually installed in the project, keyed off of the ID.
/// </summary>
/// <returns>A dictionary of installed <see cref="NugetPackage"/>s.</returns>
public static IEnumerable<NugetPackage> InstalledPackages { get { return installedPackages.Values; } }
/// <summary>
/// Updates the dictionary of packages that are actually installed in the project based on the files that are currently installed.
/// </summary>
public static void UpdateInstalledPackages()
{
LoadNugetConfigFile();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
installedPackages.Clear();
// loops through the packages that are actually installed in the project