-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathVersionHandlerImpl.cs
3128 lines (2898 loc) · 141 KB
/
VersionHandlerImpl.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
// <copyright file="VersionHandlerImpl.cs" company="Google Inc.">
// Copyright (C) 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System;
namespace Google {
[InitializeOnLoad]
public class VersionHandlerImpl : AssetPostprocessor {
/// <summary>
/// A unique class to create the multi-select window to obsolete files.
/// </summary>
private class ObsoleteFilesWindow : MultiSelectWindow {}
/// <summary>
/// Derives metadata from an asset filename.
/// </summary>
public class FileMetadata {
// Splits a filename into components.
private class FilenameComponents
{
// Known multi-component extensions to strip.
private static readonly string[] MULTI_COMPONENT_EXTENSIONS = new [] { ".dll.mdb" };
// Name of the file.
public string filename;
// Directory component.
public string directory;
// Basename (filename with no directory).
public string basename;
// Extension component.
public string extension;
// Basename without an extension.
public string basenameNoExtension;
// Parse a filename into components.
public FilenameComponents(string filename) {
this.filename = filename;
directory = Path.GetDirectoryName(filename);
basename = Path.GetFileName(filename);
// Strip known multi-component extensions from the filename.
extension = null;
foreach (var knownExtension in MULTI_COMPONENT_EXTENSIONS) {
if (basename.ToLower().EndsWith(knownExtension)) extension = knownExtension;
}
if (String.IsNullOrEmpty(extension)) extension = Path.GetExtension(basename);
basenameNoExtension =
basename.Substring(0, basename.Length - extension.Length);
}
}
// Separator for metadata tokens in the supplied filename.
private static char[] FILENAME_TOKEN_SEPARATOR = new char[] { '_' };
// Separator for fields in each metadata token in the supplied
// filename or label.
private static char[] FIELD_SEPARATOR = new char[] { '-' };
// Prefix which identifies the targets metadata in the filename or
// asset label.
public static string[] TOKEN_TARGETS = new [] { "targets-", "t" };
// Prefix which identifies the version metadata in the filename or
// asset label.
public static string[] TOKEN_VERSION = new [] { "version-", "v" };
// Prefix which identifies the .NET version metadata in the filename
// or asset label.
public static string[] TOKEN_DOTNET_TARGETS = new [] { "dotnet-" };
// Prefix which indicates this file is a package manifest.
public static string[] TOKEN_MANIFEST = new [] { "manifest" };
// Prefix which allows a manifest to specify a human readable package name.
// If the name begins with a digit [0-9] the numeric letters at the start of the string
// are used to order the priority of the package alias.
// For example, given the names:
// - "0current name"
// - "1old name"
// - "another alias"
// will create the list of names ["current name", "old name", "another alias"] where
// "current name" is the current display name of the package.
public static string[] TOKEN_MANIFEST_NAME = new[] { "manifestname-"};
// Prefix which identifies the canonical name of this Linux library.
public static string[] TOKEN_LINUX_LIBRARY_BASENAME = new [] { "linuxlibname-" };
// Prefix which identifies the original path of a file when the package was exported.
public static string[] TOKEN_EXPORT_PATH = new [] { "exportpath-" };
// Delimiter for version numbers.
private static char[] VERSION_DELIMITER = new char[] { '.' };
// Maximum number of components parsed from a version number.
private static int MAX_VERSION_COMPONENTS = 4;
// Multiplier applied to each component of the version number,
// see CalculateVersion().
private static long VERSION_COMPONENT_MULTIPLIER = 1000;
// Prefix for labels which encode metadata of an asset.
private static string LABEL_PREFIX = "gvh_";
// Prefix for labels which encode metadata of the asset for 1.2.138 and above.
// These labels are never removed by the version handler.
private static string LABEL_PREFIX_PRESERVE = "gvhp_";
// Initialized depending on the version of unity we are running against
private static HashSet<BuildTarget> targetBlackList = null;
// Initialized by parsing BuildTarget enumeration values from
// BUILD_TARGET_NAME_TO_ENUM_NAME.
private static Dictionary<string, BuildTarget>
buildTargetNameToEnum = null;
/// <summary>
/// Label which flags whether an asset is should be managed by this
/// module.
/// </summary>
public static string ASSET_LABEL = "gvh";
/// <summary>
/// Label which flags whether an asset should be disabled by renaming the file
/// (instead of using the PluginManager).
/// </summary>
public static string ASSET_LABEL_RENAME_TO_DISABLE = "gvh_rename_to_disable";
// Special build target name which enables all platforms / build targets.
public static string BUILD_TARGET_NAME_ANY = "any";
// Map of build target names to BuildTarget enumeration names.
// We don't use BuildTarget enumeration values here as Unity has a
// habit of removing unsupported ones from the API.
static public Dictionary<string, string>
BUILD_TARGET_NAME_TO_ENUM_NAME = new Dictionary<string, string> {
{"osx", "StandaloneOSXUniversal"},
{"osxintel", "StandaloneOSXIntel"},
{"windows", "StandaloneWindows"},
{"ios", "iOS"},
{"ps3", "PS3"},
{"xbox360", "XBOX360"},
{"android", "Android"},
{"linux32", "StandaloneLinux"},
{"windows64", "StandaloneWindows64"},
{"webgl", "WebGL"},
{"linux64", "StandaloneLinux64"},
{"linux", "StandaloneLinuxUniversal"},
{"osxintel64", "StandaloneOSXIntel64"},
{"tizen", "Tizen"},
{"psp2", "PSP2"},
{"ps4", "PS4"},
{"xboxone", "XboxOne"},
{"samsungtv", "SamsungTV"},
{"n3rds", "N3DS"},
{"nintendo3ds", "Nintendo3DS"},
{"wiiu", "WiiU"},
{"tvos", "tvOS"},
{"switch", "Switch"},
};
// Available .NET framework versions.
public const string DOTNET_RUNTIME_VERSION_LEGACY = "3.5";
public const string DOTNET_RUNTIME_VERSION_LATEST = "4.5";
// Matches the .NET framework 3.5 enum value
// UnityEditor.PlayerSettings.scriptingRuntimeVersion in Unity 2017 and beyond.
private const string SCRIPTING_RUNTIME_LEGACY = "Legacy";
// Regular expression which matches valid version strings.
private static Regex VERSION_REGEX = new Regex("^[0-9][0-9.]+$");
// Regular expression which matches valid .NET framework versions.
private static Regex DOTNET_RUNTIME_REGEX =
new Regex("^(" + String.Join("|", (new List<string> {
DOTNET_RUNTIME_VERSION_LEGACY,
DOTNET_RUNTIME_VERSION_LATEST,
SCRIPTING_RUNTIME_LEGACY }).ToArray()) + ")$",
RegexOptions.IgnoreCase);
// Regular expression which matches valid
private static Regex BUILD_TARGET_REGEX =
new Regex("^(editor|" + String.Join(
"|", (new List<string>(BUILD_TARGET_NAME_TO_ENUM_NAME.Keys)).ToArray()) +
")$", RegexOptions.IgnoreCase);
// Regular expression which matches an index in a manifest name field.
private static Regex MANIFEST_NAME_REGEX = new Regex("^([0-9]+)(.*)");
/// <summary>
/// Get a set of build target names mapped to supported BuildTarget
/// enumeration values.
/// </summary>
internal static Dictionary<string, BuildTarget> GetBuildTargetNameToEnum() {
if (buildTargetNameToEnum == null) {
var targetBlackList = GetBlackList();
buildTargetNameToEnum =
new Dictionary<string, BuildTarget>();
foreach (var targetNameEnumName in
BUILD_TARGET_NAME_TO_ENUM_NAME) {
// Attempt to parse the build target name.
// ArgumentException, OverflowException or
// TypeInitializationException
// will be thrown if the build target is no longer
// supported.
BuildTarget target;
try {
target = (BuildTarget)Enum.Parse(
typeof(BuildTarget), targetNameEnumName.Value);
} catch (ArgumentException) {
continue;
} catch (OverflowException) {
continue;
} catch (TypeInitializationException) {
continue;
}
if (!targetBlackList.Contains(target)) {
buildTargetNameToEnum[targetNameEnumName.Key] =
target;
}
}
}
return buildTargetNameToEnum;
}
// Returns a hashset containing blacklisted build targets for the current
// unity environment.
// We need to maintain a separate blacklist as Unity occasionally
// removes BuildTarget display names but does not remove the enumeration
// values associated with the names. This causes a fatal error in
// PluginImporter.GetCompatibleWithPlatform() when provided with a
// BuildTarget that no longer has a display name.
static HashSet<BuildTarget> GetBlackList() {
if (targetBlackList == null) {
targetBlackList = new HashSet<BuildTarget>();
if (VersionHandlerImpl.GetUnityVersionMajorMinor() >= 5.5) {
#pragma warning disable 618
targetBlackList.Add(BuildTarget.PS3);
targetBlackList.Add(BuildTarget.XBOX360);
#pragma warning restore 618
}
}
return targetBlackList;
}
/// <summary>
/// Property that retrieves UnityEditor.PlayerSettings.scriptingRuntimeVersion.
/// </summary>
/// This retrieves UnityEditor.PlayerSettings.scriptingRuntimeVersion using reflection
/// so that this module is compatible with versions of Unity earlier than 2017.
/// <returns>String representation of
/// UnityEditor.PlayerSettings.scriptingRuntimeVersion. If the property isn't
/// available this returns SCRIPTING_RUNTIME_LEGACY.</returns>
private static string ScriptingRuntimeVersion {
get {
var scriptingVersionProperty =
typeof(UnityEditor.PlayerSettings).GetProperty("scriptingRuntimeVersion");
var scriptingVersionValue = scriptingVersionProperty != null ?
scriptingVersionProperty.GetValue(null, null) : null;
var scriptingVersionString = scriptingVersionValue != null ?
scriptingVersionValue.ToString() : SCRIPTING_RUNTIME_LEGACY;
return scriptingVersionString;
}
}
/// <summary>
/// Retrieve the UnityEditor.PlayerSettings.scriptingRuntimeVersion as a version string.
/// </summary>
/// <returns>.NET version string.</returns>
public static string ScriptingRuntimeDotNetVersion {
get {
if (ScriptingRuntimeVersion == SCRIPTING_RUNTIME_LEGACY) {
return FileMetadata.DOTNET_RUNTIME_VERSION_LEGACY;
}
return FileMetadata.DOTNET_RUNTIME_VERSION_LATEST;
}
}
/// <summary>
/// Name of the file use to construct this object.
/// </summary>
public string filename = "";
/// <summary>
/// Name of the file with metadata stripped.
/// </summary>
public string filenameCanonical = "";
/// <summary>
/// Version string parsed from the filename or AssetDatabase label if
/// it's not present in the filename.
/// </summary>
public string versionString = "";
/// <summary>
/// List of target platforms parsed from the filename.
/// </summary>
public HashSet<string> targets = null;
/// <summary>
/// Set if this references an asset manifest.
/// </summary>
public bool isManifest = false;
/// <summary>
/// Offset subtracted from entries inserted in customManifestNames.
/// </summary>
private const int CUSTOM_MANIFEST_NAMES_FIRST_INDEX_OFFSET = Int32.MaxValue / 2;
/// <summary>
/// Backing store for aliases of the manifest name, the current package name is always
/// first in the set. This contains only values parsed from manifestname labels,
/// the ManifestName property is used to retrieve the preferred manifest name.
/// </summary>
public SortedList<int, string> customManifestNames = new SortedList<int, string>();
/// <summary>
/// Set if this references an asset which is handled by PluginManager.
/// </summary>
public bool isHandledByPluginImporter = false;
/// <summary>
/// List of compatible .NET versions parsed from this asset.
/// </summary>
public HashSet<string> dotNetTargets = null;
/// <summary>
/// Basename of a Linux library plugin.
/// </summary>
public string linuxLibraryBasename = null;
/// <summary>
/// Path of the file when it was originally exported as a package.
/// </summary>
public string exportPath = "";
/// <summary>
/// Path of the file when it was originally exported as a package in the project.
/// </summary>
public string ExportPathInProject {
get {
var exportPathInProject = exportPath;
if (!String.IsNullOrEmpty(exportPathInProject)) {
// Remove the assets folder, if specified.
if (FileUtils.IsUnderDirectory(exportPathInProject, FileUtils.ASSETS_FOLDER)) {
exportPathInProject =
exportPath.Substring(FileUtils.ASSETS_FOLDER.Length + 1);
}
// Determine whether this package is installed as a package or asset to
// determine the root directory.
var packageDirectory = FileUtils.GetPackageDirectory(filename);
var installRoot = !String.IsNullOrEmpty(packageDirectory) ?
packageDirectory : FileUtils.ASSETS_FOLDER;
// Translate exportPath into a package relative path.
exportPathInProject = FileUtils.PosixPathSeparators(
Path.Combine(installRoot, exportPathInProject));
}
return exportPathInProject;
}
}
/// <summary>
/// If this is a manifest, get the display name.
/// </summary>
/// <returns>If this file is a manifest, returns the display name of the manifest,
/// null otherwise.</returns>
public string ManifestName {
get {
string name = null;
bool hasManifestNames = customManifestNames != null &&
customManifestNames.Count > 0;
if (isManifest || hasManifestNames) {
if (hasManifestNames) {
name = customManifestNames.Values[0];
} else {
name = (new FilenameComponents(filenameCanonical)).basenameNoExtension;
}
}
return name;
}
}
/// <summary>
/// Whether it's possible to change the asset metadata.
/// </summary>
/// <returns>true if the asset metadata for this file is read-only,
/// false otherwise.</returns>
public bool IsReadOnly {
get {
return FileUtils.IsUnderPackageDirectory(filename);
}
}
/// <summary>
/// Parse metadata from filename and store in this class.
/// </summary>
/// <param name="filename">Name of the file to parse.</param>
public FileMetadata(string filename) {
this.filename = FileUtils.NormalizePathSeparators(filename);
filenameCanonical = ParseMetadataFromFilename(this.filename);
ParseMetadataFromAssetLabels();
// If the export path was specified, override the canonical filename.
var exportPathInProject = ExportPathInProject;
if (!String.IsNullOrEmpty(exportPathInProject)) {
filenameCanonical = ParseMetadataFromFilename(exportPathInProject);
}
UpdateAssetLabels();
}
/// <summary>
/// Parse metadata from the specified filename and store in this class.
/// </summary>
/// <param name="filenameToParse">Parse metadata from the specified filename.</param>
/// <returns>Filename with metadata removed.</returns>
private string ParseMetadataFromFilename(string filenameToParse) {
var filenameComponents = new FilenameComponents(filenameToParse);
// Parse metadata from the filename.
string[] tokens =
filenameComponents.basenameNoExtension.Split(
FILENAME_TOKEN_SEPARATOR);
if (tokens.Length > 1) {
var basenameNoExtension = tokens[0];
for (int i = 1; i < tokens.Length; ++i) {
if (!ParseToken(tokens[i])) {
basenameNoExtension += FILENAME_TOKEN_SEPARATOR[0] + tokens[i];
}
}
filenameComponents.basenameNoExtension = basenameNoExtension;
}
// On Windows the AssetDatabase converts native path separators
// used by the .NET framework '\' to *nix style '/' such that
// System.IO.Path generated paths will not match those looked up
// in the asset database. So we convert the output of Path.Combine
// here to use *nix style paths so that it's possible to perform
// simple string comparisons to check for path equality.
return FileUtils.NormalizePathSeparators(Path.Combine(
filenameComponents.directory,
filenameComponents.basenameNoExtension +
filenameComponents.extension));
}
/// <summary>
/// Parse metadata from asset labels.
/// </summary>
public void ParseMetadataFromAssetLabels() {
// Parse metadata from asset labels if it hasn't been specified in
// the filename.
AssetImporter importer = GetAssetImporter();
if (importer != null) {
foreach (string label in AssetDatabase.GetLabels(importer)) {
ParseLabel(label);
}
isHandledByPluginImporter = typeof(PluginImporter).IsInstanceOfType(importer);
}
}
/// <summary>
/// Determine whether a token matches a set of prefixes extracting the value(s) if it
/// does.
/// </summary>
/// <param name="token">Token to parse.</param>
/// <param name="prefixes">Set of prefixes to compare with the token.</param>
/// <param name="prefix">Added to each item in prefixes before comparing with the token.
/// </param>
/// <returns>Array of values if the token matches the prefixes, null otherwise.</returns>
private string[] MatchPrefixesGetValues(string token, string[] prefixes, string prefix) {
var tokenLower = token.ToLower();
foreach (var item in prefixes) {
var itemWithPrefix = prefix + item;
if (tokenLower.StartsWith(itemWithPrefix)) {
return token.Substring(itemWithPrefix.Length).Split(FIELD_SEPARATOR);
}
}
return null;
}
/// <summary>
/// Determine whether a list of string match a regular expression.
/// </summary>
/// <param name="items">Items to compare against the specific regular expression.</param>
/// <param name="regEx">Regular expression to compare against each item.</param>
/// <returns>true if all items in the list match the regular expression, false otherwise.
/// </returns>
private bool StringListMatchesRegex(IEnumerable<string> items, Regex regEx) {
foreach (var item in items) {
if (!regEx.Match(item).Success) return false;
}
return true;
}
/// <summary>
/// Parse a metadata token and store the value this class.
/// </summary>
/// <param name="token">Token to parse.</param>
/// <param name="prefix">Added as a prefix applied to each prefix compared with the
/// token.</param>
/// <returns>true if the token is parsed, false otherwise.</returns>
private bool ParseToken(string token, string prefix = null) {
prefix = prefix ?? "";
var values = MatchPrefixesGetValues(token, TOKEN_MANIFEST_NAME, prefix);
if (values != null) {
var name = String.Join(FIELD_SEPARATOR[0].ToString(), values);
var nameMatch = MANIFEST_NAME_REGEX.Match(name);
int order = CUSTOM_MANIFEST_NAMES_FIRST_INDEX_OFFSET - customManifestNames.Count;
if (nameMatch.Success) {
int parsedOrder;
if (Int32.TryParse(nameMatch.Groups[1].Value, out parsedOrder)) {
order = parsedOrder - CUSTOM_MANIFEST_NAMES_FIRST_INDEX_OFFSET;
}
name = nameMatch.Groups[2].Value;
}
customManifestNames.Remove(order);
customManifestNames.Add(order, name);
isManifest = true;
return true;
}
values = MatchPrefixesGetValues(token, TOKEN_MANIFEST, prefix);
if (values != null) {
isManifest = true;
return true;
}
values = MatchPrefixesGetValues(token, TOKEN_DOTNET_TARGETS, prefix);
if (values != null && StringListMatchesRegex(values, DOTNET_RUNTIME_REGEX)) {
if(dotNetTargets == null) {
dotNetTargets = new HashSet<string>();
}
dotNetTargets.UnionWith(values);
return true;
}
values = MatchPrefixesGetValues(token, TOKEN_TARGETS, prefix);
if (values != null && StringListMatchesRegex(values, BUILD_TARGET_REGEX)) {
if (targets == null) {
targets = new HashSet<string>();
}
// Convert all target names to lower case.
foreach (var value in values) {
targets.Add(value.ToLower());
}
return true;
}
values = MatchPrefixesGetValues(token, TOKEN_VERSION, prefix);
if (values != null && StringListMatchesRegex(values, VERSION_REGEX)) {
if (values.Length > 0) {
versionString = values[0];
return true;
}
}
values = MatchPrefixesGetValues(token, TOKEN_LINUX_LIBRARY_BASENAME, prefix);
if (values != null) {
linuxLibraryBasename = String.Join(FIELD_SEPARATOR[0].ToString(), values);
return true;
}
values = MatchPrefixesGetValues(token, TOKEN_EXPORT_PATH, prefix);
if (values != null) {
exportPath = FileUtils.PosixPathSeparators(
String.Join(FIELD_SEPARATOR[0].ToString(), values));
return true;
}
return false;
}
/// <summary>
/// Parse a metadata token (from an asset label) and store the value this class.
/// </summary>
/// <param name="label">Asset label to parse.</param>
/// <returns>true if the token is parsed, false otherwise.</returns>
private bool ParseLabel(string label) {
return ParseToken(label, prefix: LABEL_PREFIX_PRESERVE) ||
ParseToken(label, prefix: LABEL_PREFIX);
}
/// <summary>
/// Create a field from a prefix and set of values.
/// </summary>
/// <param name="fieldPrefixes">The first item of this list is used as the prefix.
/// </param>
/// <param name="values">Set of values to store with the field.</param>
private string CreateToken(string[] fieldPrefixes, string[] values) {
return String.Format("{0}{1}", fieldPrefixes[0],
values == null ? "" :
String.Join(Char.ToString(FIELD_SEPARATOR[0]), values));
}
/// <summary>
/// Create an array of asset labels from a prefix and set of values.
/// </summary>
/// <param name="fieldPrefixes">The first item of this list is used as the prefix.
/// </param>
/// <param name="values">Set of values to store with the field.</param>
/// <param name="currentLabels">Labels to search for the suitable prefix.</param>
/// <param name="preserve">Always preserve these labels.</param>
private static string[] CreateLabels(string[] fieldPrefixes, IEnumerable<string> values,
HashSet<string> currentLabels, bool preserve = false) {
string prefix = fieldPrefixes[0];
List<string> labels = new List<string>();
foreach (var value in values) {
labels.Add(CreateLabel(prefix, value, currentLabels, preserve: preserve));
}
return labels.ToArray();
}
/// <summary>
/// Create an asset label from a prefix and a single value
/// </summary>
/// <param name="prefix"> The field prefix to be applied to the label.
/// </param>
/// <param name="value">The value to store in the field</param>
/// <param name="preserve">Whether the label should be preserved.</param>
public static string CreateLabel(string prefix, string value, bool preserve = false) {
return (preserve ? LABEL_PREFIX_PRESERVE : LABEL_PREFIX) + prefix + value;
}
/// <summary>
/// Create an asset label keeping the preservation in the supplied set if it already exists.
/// </summary>
/// <param name="prefix"> The field prefix to be applied to the label.
/// </param>
/// <param name="value">The value to store in the field</param>
/// <param name="currentLabels">Labels to search for the suitable prefix.</param>
/// <param name="preserve">Whether the label should be preserved.</param>
public static string CreateLabel(string prefix, string value, HashSet<string> currentLabels,
bool preserve = false) {
var legacyLabel = CreateLabel(prefix, value, false);
var preservedLabel = CreateLabel(prefix, value, true);
if (currentLabels.Contains(legacyLabel)) return legacyLabel;
if (currentLabels.Contains(preservedLabel)) return preservedLabel;
return preserve ? preservedLabel : legacyLabel;
}
/// <summary>
/// Determine whether this file is compatible with the editor.
/// This is a special case as the editor isn't a "platform" covered
/// by UnityEditor.BuildTarget.
/// </summary>
/// <returns>true if this file targets the editor, false
/// otherwise.</returns>
public bool GetEditorEnabled() {
return targets != null && targets.Contains("editor");
}
/// <summary>
/// Determine whether any build targets have been specified.
/// </summary>
/// <returns>true if targets are specified, false otherwise.</returns>
public bool GetBuildTargetsSpecified() {
return targets != null && targets.Count > 0;
}
/// <summary>
/// Get the list of build targets this file is compatible with.
/// </summary>
/// <returns>Set of BuildTarget (platforms) this is compatible with.
/// </returns>
public HashSet<BuildTarget> GetBuildTargets() {
HashSet<BuildTarget> buildTargetSet = new HashSet<BuildTarget>();
var buildTargetToEnum = GetBuildTargetNameToEnum();
if (targets != null) {
var targetsSet = new HashSet<string>(targets);
if (targetsSet.Contains(BUILD_TARGET_NAME_ANY)) {
buildTargetSet.UnionWith(buildTargetToEnum.Values);
} else {
foreach (string target in targets) {
BuildTarget buildTarget;
if (buildTargetToEnum.TryGetValue(target, out buildTarget)) {
buildTargetSet.Add(buildTarget);
} else if (!target.Equals("editor")) {
Log(filename + " reference to unknown target " +
target + " the version handler may out of date.",
level: LogLevel.Error);
}
}
}
}
return buildTargetSet;
}
/// <summary>
/// Get the set of build targets as strings.
/// </summary>
/// <returns>Set of build targets as strings.</returns>
public HashSet<string> GetBuildTargetStrings() {
var buildTargetStringsSet = new HashSet<string>();
foreach (var buildTarget in GetBuildTargets()) {
buildTargetStringsSet.Add(buildTarget.ToString());
}
return buildTargetStringsSet;
}
/// <summary>
/// Get the list of .NET versions this file is compatible with.
/// </summary>
/// <returns>Set of .NET versions this is compatible with. This returns an empty
/// set if the state of the file should not be modified when the .NET framework
/// version changes.</returns>
public HashSet<string> GetDotNetTargets() {
var dotNetTargetSet = new HashSet<string>();
if (dotNetTargets != null) dotNetTargetSet.UnionWith(dotNetTargets);
return dotNetTargetSet;
}
/// <summary>
/// Save metadata from this class into the asset's labels.
/// </summary>
public void UpdateAssetLabels() {
if (String.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(filename)) || IsReadOnly) {
return;
}
AssetImporter importer = AssetImporter.GetAtPath(filename);
var labels = new HashSet<string>();
var currentLabels = new HashSet<string>();
// Strip labels we're currently managing.
foreach (string label in AssetDatabase.GetLabels(importer)) {
currentLabels.Add(label);
if (!(label.ToLower().StartsWith(LABEL_PREFIX) ||
label.ToLower().Equals(ASSET_LABEL))) {
labels.Add(label);
}
}
// Add / preserve the label that indicates this asset is managed by
// this module.
labels.Add(ASSET_LABEL);
// Add labels for the metadata in this class.
if (!String.IsNullOrEmpty(versionString)) {
labels.Add(CreateLabel(TOKEN_VERSION[0], versionString, currentLabels));
}
if (targets != null && targets.Count > 0) {
labels.UnionWith(CreateLabels(TOKEN_TARGETS, targets, currentLabels));
if (!isHandledByPluginImporter) {
labels.Add(ASSET_LABEL_RENAME_TO_DISABLE);
}
}
if (dotNetTargets != null && dotNetTargets.Count > 0) {
labels.UnionWith(CreateLabels(TOKEN_DOTNET_TARGETS, dotNetTargets, currentLabels));
}
if (!String.IsNullOrEmpty(linuxLibraryBasename)) {
labels.Add(CreateLabel(TOKEN_LINUX_LIBRARY_BASENAME[0], linuxLibraryBasename,
currentLabels));
}
if (!String.IsNullOrEmpty(exportPath)) {
labels.Add(CreateLabel(TOKEN_EXPORT_PATH[0], exportPath, currentLabels,
preserve: true));
}
if (isManifest) {
labels.Add(CreateLabel(TOKEN_MANIFEST[0], null, currentLabels));
}
if (customManifestNames != null && customManifestNames.Count > 0) {
foreach (var indexAndName in customManifestNames) {
int order = indexAndName.Key + CUSTOM_MANIFEST_NAMES_FIRST_INDEX_OFFSET;
var name = indexAndName.Value;
if (order < CUSTOM_MANIFEST_NAMES_FIRST_INDEX_OFFSET) {
labels.Add(CreateLabel(TOKEN_MANIFEST_NAME[0], order.ToString() + name,
currentLabels, preserve: true));
} else {
labels.Add(CreateLabel(TOKEN_MANIFEST_NAME[0], name, currentLabels,
preserve: true));
}
}
}
if (!labels.SetEquals(currentLabels)) {
var sortedLabels = new List<string>(labels);
var sortedCurrentLabels = new List<string>(currentLabels);
sortedCurrentLabels.Sort();
sortedLabels.Sort();
var labelsArray = sortedLabels.ToArray();
Log(String.Format("Changing labels of {0}\n" +
"from: {1}\n" +
"to: {2}\n",
filename,
String.Join(", ", sortedCurrentLabels.ToArray()),
String.Join(", ", labelsArray)),
verbose: true);
AssetDatabase.SetLabels(importer, labelsArray);
}
}
/// <summary>
/// Get the AssetImporter associated with this file.
/// </summary>
/// <returns>AssetImporter instance if one is associated with this
/// file, null otherwise.</returns>
public AssetImporter GetAssetImporter() {
return AssetImporter.GetAtPath(filename);
}
/// <summary>
/// Rename the file associated with this data.
/// </summary>
/// <param name="newFilename">New name of the file.</param>
/// <returns>true if successful, false otherwise.</returns>
public bool RenameAsset(string newFilename) {
// If the source and target filenames are the same, there is nothing to do.
newFilename = FileUtils.NormalizePathSeparators(newFilename);
if (FileUtils.NormalizePathSeparators(filename) == newFilename) {
return true;
}
var filenameComponents = new FilenameComponents(newFilename);
Debug.Assert(filenameComponents.directory ==
Path.GetDirectoryName(filename));
Log(String.Format("Renaming {0} -> {1}", filename, newFilename), verbose: true);
// If the target file exists, delete it.
if (AssetImporter.GetAtPath(newFilename) != null) {
if (!AssetDatabase.MoveAssetToTrash(newFilename)) {
Log("Failed to move asset to trash: " + filename,
level: LogLevel.Error);
return false;
}
}
try {
var targetDir = Path.GetDirectoryName(filename);
if (!String.IsNullOrEmpty(targetDir)) {
Directory.CreateDirectory(targetDir);
}
// This is *really* slow.
string error = AssetDatabase.MoveAsset(filename, newFilename);
if (!String.IsNullOrEmpty(error)) {
string renameError = AssetDatabase.RenameAsset(
filename, filenameComponents.basenameNoExtension);
error = String.IsNullOrEmpty(renameError) ?
renameError : String.Format("{0}, {1}", error, renameError);
}
if (!String.IsNullOrEmpty(error)) {
Log("Failed to rename asset " + filename + " to " +
newFilename + " (" + error + ")",
level: LogLevel.Error);
return false;
}
} catch (Exception) {
// Unity 5.3 and below can end up throw all sorts of
// exceptions here when attempting to reload renamed
// assemblies. Since these are completely harmless as
// everything will be reloaded and exceptions will be
// reported upon AssetDatabase.Refresh(), ignore them.
}
filename = newFilename;
UpdateAssetLabels();
return true;
}
/// <summary>
/// Get a numeric version number. Each component is multiplied by
/// VERSION_COMPONENT_MULTIPLIER^(MAX_VERSION_COMPONENTS -
/// (component_index + 1))
/// and accumulated in the returned value.
/// If the version string contains more than MAX_VERSION_COMPONENTS the
/// remaining components are ignored.
/// </summary>
/// <returns>64-bit version number.</returns>
public long CalculateVersion() {
return CalculateVersion(versionString);
}
/// <summary>
/// Get a numeric version number. Each component is multiplied by
/// VERSION_COMPONENT_MULTIPLIER^(MAX_VERSION_COMPONENTS -
/// (component_index + 1))
/// and accumulated in the returned value.
/// If the version string contains more than MAX_VERSION_COMPONENTS the
/// remaining components are ignored.
/// </summary>
/// <param name="versionString">Version string to parse.</param>
/// <returns>64-bit version number.</returns>
public static long CalculateVersion(string versionString) {
long versionNumber = 0;
if (versionString.Length > 0) {
string[] components = versionString.Split(VERSION_DELIMITER);
int numberOfComponents =
components.Length < MAX_VERSION_COMPONENTS ?
components.Length : MAX_VERSION_COMPONENTS;
for (int i = 0; i < numberOfComponents; ++i) {
versionNumber +=
Convert.ToInt64(components[i]) *
(long)Math.Pow(
(double)VERSION_COMPONENT_MULTIPLIER,
(double)(MAX_VERSION_COMPONENTS - (i + 1)));
}
}
return versionNumber;
}
/// <summary>
/// Convert a numeric version back to a version string.
/// </summary>
/// <param name="versionNumber">Numeric version number.</param>
/// <returns>Version string.</returns>
public static string VersionNumberToString(long versionNumber) {
List<string> components = new List<string>();
for (int i = 0; i < MAX_VERSION_COMPONENTS; ++i) {
long componentDivisor =
(long)Math.Pow((double)VERSION_COMPONENT_MULTIPLIER,
(double)(MAX_VERSION_COMPONENTS - (i + 1)));
components.Add((versionNumber / componentDivisor).ToString());
versionNumber %= componentDivisor;
}
return String.Join(Char.ToString(VERSION_DELIMITER[0]),
components.ToArray());
}
}
/// <summary>
/// Set of FileMetadata ordered by version.
/// </summary>
public class FileMetadataByVersion {
/// <summary>
/// Name of the file with metadata removed.
/// </summary>
public string filenameCanonical = null;
/// <summary>
/// Dictionary of FileMetadata ordered by version.
/// </summary>
private SortedDictionary<long, FileMetadata> metadataByVersion =
new SortedDictionary<long, FileMetadata>();
/// <summary>
/// Get the FileMetadata from this object ordered by version number.
/// </summary>
public SortedDictionary<long, FileMetadata>.ValueCollection Values {
get { return metadataByVersion.Values; }
}
/// <summary>
/// Get FileMetadata from this object given a version number.
/// </summary>
/// <param name="version">Version to search for.</param>
/// <returns>FileMetadata instance if the version is found, null
/// otherwise.</returns>
public FileMetadata this[long version] {
get {
FileMetadata metadata;
if (metadataByVersion.TryGetValue(version, out metadata)) {
return metadata;
}
return null;
}
}
/// <summary>
/// Get the most referenced FileMetadata from this object.
/// </summary>
/// <returns>FileMetadata instance if this object contains at least one version, null
/// otherwise.</returns>
public FileMetadata MostRecentVersion {
get {
var numberOfVersions = metadataByVersion.Count;
return numberOfVersions > 0 ?
(FileMetadata)(
(new ArrayList(metadataByVersion.Values))[numberOfVersions - 1]) : null;
}
}
/// <summary>
/// Backing store for EnabledEditorDlls.
/// </summary>
private HashSet<string> enabledEditorDlls = new HashSet<string>();
/// <summary>
/// Full path of DLLs that should be loaded into the editor application domain.
/// </summary>
public ICollection<string> EnabledEditorDlls { get { return enabledEditorDlls; } }
/// <summary>
/// Determine whether the PluginImporter class is available in
/// UnityEditor. Unity 4 does not have the PluginImporter class so
/// it's not possible to modify asset metadata without hacking the
/// .meta yaml files directly to enable / disable plugin targeting.
/// </summary>
internal static bool PluginImporterAvailable {
get {
return VersionHandler.FindClass("UnityEditor",
"UnityEditor.PluginImporter") != null;
}
}
/// <summary>
/// Construct an instance.
/// </summary>
/// <param name="filenameCanonical">Filename with metadata stripped.
/// </param>
public FileMetadataByVersion(string filenameCanonical) {
this.filenameCanonical = filenameCanonical;
}
/// <summary>
/// Add metadata to the set.
/// </summary>
public void Add(FileMetadata metadata) {
Debug.Assert(
filenameCanonical == null ||
metadata.filenameCanonical.Equals(filenameCanonical));
metadataByVersion[metadata.CalculateVersion()] = metadata;
}
/// <summary>