-
Notifications
You must be signed in to change notification settings - Fork 700
/
Copy pathProjectFactory.cs
1499 lines (1306 loc) · 59.6 KB
/
ProjectFactory.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
extern alias CoreV2;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using System.Threading;
using System.Xml.Linq;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.PackageManagement;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using XElementExtensions = NuGet.Packaging.XElementExtensions;
namespace NuGet.CommandLine
{
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public class ProjectFactory : MSBuildUser, IProjectFactory, CoreV2.NuGet.IPropertyProvider
{
// Its type is Microsoft.Build.Evaluation.Project
private dynamic _project;
private Common.ILogger _logger;
private bool _usingJsonFile;
// Files we want to always exclude from the resulting package
private static readonly HashSet<string> _excludeFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
NuGetConstants.PackageReferenceFile,
"Web.Debug.config",
"Web.Release.config"
};
private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// Packaging folders
private const string ContentFolder = "content";
private const string ReferenceFolder = "lib";
private const string ToolsFolder = "tools";
private const string SourcesFolder = "src";
// Common item types
private const string SourcesItemType = "Compile";
private const string ContentItemType = "Content";
private const string ProjectReferenceItemType = "ProjectReference";
private const string ReferenceOutputAssembly = "ReferenceOutputAssembly";
private const string TransformFileExtension = ".transform";
[Import]
public Configuration.IMachineWideSettings MachineWideSettings { get; set; }
public static IProjectFactory ProjectCreator(PackArgs packArgs, string path)
{
return new ProjectFactory(packArgs.MsBuildDirectory.Value, path, packArgs.Properties)
{
IsTool = packArgs.Tool,
LogLevel = packArgs.LogLevel,
Logger = packArgs.Logger,
MachineWideSettings = packArgs.MachineWideSettings,
Build = packArgs.Build,
IncludeReferencedProjects = packArgs.IncludeReferencedProjects,
SymbolPackageFormat = packArgs.SymbolPackageFormat,
PackagesDirectory = packArgs.PackagesDirectory,
SolutionDirectory = packArgs.SolutionDirectory,
};
}
public ProjectFactory(string msbuildDirectory, string path, IDictionary<string, string> projectProperties)
{
LoadAssemblies(msbuildDirectory);
// Create project, allowing for assembly load failures
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve);
try
{
var project = Activator.CreateInstance(
_projectType,
path,
projectProperties,
null);
Initialize(project);
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(AssemblyResolve);
}
}
public ProjectFactory(string msbuildDirectory, dynamic project)
{
LoadAssemblies(msbuildDirectory);
Initialize(project);
}
private ProjectFactory(
string msbuildDirectory,
Assembly msbuildAssembly,
Assembly frameworkAssembly,
dynamic project)
{
_msbuildDirectory = msbuildDirectory;
_msbuildAssembly = msbuildAssembly;
_frameworkAssembly = frameworkAssembly;
LoadTypes();
Initialize(project);
}
private void Initialize(dynamic project)
{
_project = project;
ProjectProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
AddSolutionDir();
// Get the target framework of the project
string targetFrameworkMoniker = _project.GetPropertyValue("TargetFrameworkMoniker");
if (!String.IsNullOrEmpty(targetFrameworkMoniker))
{
TargetFramework = NuGetFramework.Parse(targetFrameworkMoniker);
}
// This happens before we obtain warning properties, so this Logger is still IConsole.
IConsole console = Logger as IConsole;
switch (LogLevel)
{
case LogLevel.Verbose:
{
console.Verbosity = Verbosity.Detailed;
break;
}
case LogLevel.Information:
{
console.Verbosity = Verbosity.Normal;
break;
}
case LogLevel.Minimal:
{
console.Verbosity = Verbosity.Quiet;
break;
}
}
}
public WarningProperties GetWarningPropertiesForProject()
{
var treatWarningsAsErrors = GetPropertyValue("TreatWarningsAsErrors");
return WarningProperties.GetWarningProperties(treatWarningsAsErrors: string.IsNullOrEmpty(treatWarningsAsErrors) ? "false" : treatWarningsAsErrors,
warningsAsErrors: GetPropertyValue("WarningsAsErrors"),
noWarn: GetPropertyValue("NoWarn"));
}
private string TargetPath
{
get;
set;
}
private NuGetFramework TargetFramework
{
get;
set;
}
public void SetIncludeSymbols(bool includeSymbols)
{
IncludeSymbols = includeSymbols;
}
public bool IncludeSymbols { get; set; }
public bool IncludeReferencedProjects { get; set; }
public bool Build { get; set; }
public Dictionary<string, string> GetProjectProperties()
{
return ProjectProperties;
}
public Dictionary<string, string> ProjectProperties { get; private set; }
public bool IsTool { get; set; }
public LogLevel LogLevel { get; set; }
public SymbolPackageFormat SymbolPackageFormat { get; set; }
public string PackagesDirectory { get; set; }
public string SolutionDirectory { get; set; }
public ILogger Logger
{
get
{
return _logger ?? Common.NullLogger.Instance;
}
set
{
_logger = value;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to continue regardless of any error we encounter extracting metadata.")]
public Packaging.PackageBuilder CreateBuilder(string basePath, NuGetVersion version, string suffix, bool buildIfNeeded, Packaging.PackageBuilder builder = null)
{
if (buildIfNeeded)
{
BuildProject();
}
if (!string.IsNullOrEmpty(TargetPath))
{
Logger.Log(PackagingLogMessage.CreateMessage(string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("PackagingFilesFromOutputPath"),
Path.GetFullPath(Path.GetDirectoryName(TargetPath))), LogLevel.Minimal));
}
builder = new PackageBuilder(false, Logger);
try
{
ExtractMetadata(builder);
}
catch (Exception ex)
{
Logger.Log(PackagingLogMessage.CreateError(string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("UnableToExtractAssemblyMetadata"),
Path.GetFileName(TargetPath)), NuGetLogCode.NU5011));
if (LogLevel == LogLevel.Verbose)
{
Logger.Log(PackagingLogMessage.CreateError(ex.ToString(), NuGetLogCode.NU5011));
}
else
{
Logger.Log(PackagingLogMessage.CreateError(ex.Message, NuGetLogCode.NU5011));
}
return null;
}
var projectAuthor = InitializeProperties(builder);
// Set version based on version argument from console?
if (version != null)
{
// make sure the $version$ placeholder gets populated correctly
_properties["version"] = version.ToFullString();
builder.Version = version;
}
// Only override properties from assembly extracted metadata if they haven't
// been specified also at construction time for the factory (that is,
// console properties always take precedence.
foreach (var key in builder.Properties.Keys)
{
if (!_properties.ContainsKey(key) &&
!ProjectProperties.ContainsKey(key))
{
_properties.Add(key, builder.Properties[key]);
}
}
Packaging.Manifest manifest = null;
// If there is a project.json file, load that and skip any nuspec that may exist
if (!PackCommandRunner.ProcessProjectJsonFile(builder, _project.DirectoryPath as string, builder.Id, version, suffix, GetPropertyValue))
{
// If the package contains a nuspec file then use it for metadata
manifest = ProcessNuspec(builder, basePath);
}
else
{
Logger.Log(
PackagingLogMessage.CreateWarning(
string.Format(NuGetResources.ProjectJsonPack_Deprecated, builder.Id),
NuGetLogCode.NU5126));
_usingJsonFile = true;
}
// Remove the extra author
if (builder.Authors.Count > 1)
{
builder.Authors.Remove(projectAuthor);
}
// Add output files
ApplyAction(p => p.AddOutputFiles(builder));
// Add content files if there are any. They could come from a project or nuspec file
// In order to be compliant with the documented behavior, if the nuspec file has an
// empty <files> element, we do not add any content files at all. If the <files> element
// has one or more files specified, then those files are added to the package along with
// any files of type Content from the csproj file.
if (manifest == null || !manifest.HasFilesNode || manifest.Files.Count > 0)
{
ApplyAction(p => p.AddFiles(builder, ContentItemType, ContentFolder));
}
// Add sources if this is a symbol package
if (IncludeSymbols)
{
if (SymbolPackageFormat == SymbolPackageFormat.SymbolsNupkg)
{
ApplyAction(p => p.AddFiles(builder, SourcesItemType, SourcesFolder));
}
}
ProcessDependencies(builder);
// Set defaults if some required fields are missing
if (String.IsNullOrEmpty(builder.Description))
{
builder.Description = "Description";
Logger.Log(PackagingLogMessage.CreateWarning(string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("Warning_UnspecifiedField"),
"Description",
"Description"), NuGetLogCode.NU5115));
}
if (!builder.Authors.Any())
{
builder.Authors.Add(Environment.UserName);
Logger.Log(PackagingLogMessage.CreateWarning(string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("Warning_UnspecifiedField"),
"Author",
Environment.UserName), NuGetLogCode.NU5115));
}
return builder;
}
public string InitializeProperties(Packaging.IPackageMetadata metadata)
{
// Set the properties that were resolved from the assembly/project so they can be
// resolved by name if the nuspec contains tokens
_properties.Clear();
// Allow Id to be overriden by cmd line properties
if (ProjectProperties.ContainsKey("Id"))
{
_properties.Add("Id", ProjectProperties["Id"]);
}
else
{
_properties.Add("Id", metadata.Id);
}
_properties.Add("Version", metadata.Version.ToFullString());
if (!String.IsNullOrEmpty(metadata.Title))
{
_properties.Add("Title", metadata.Title);
}
if (!String.IsNullOrEmpty(metadata.Description))
{
_properties.Add("Description", metadata.Description);
}
if (!String.IsNullOrEmpty(metadata.Copyright))
{
_properties.Add("Copyright", metadata.Copyright);
}
string projectAuthor = metadata.Authors.FirstOrDefault();
if (!String.IsNullOrEmpty(projectAuthor))
{
_properties.Add("Author", projectAuthor);
}
return projectAuthor;
}
public string GetPropertyValue(string propertyName)
{
string value;
if (!_properties.TryGetValue(propertyName, out value) &&
!ProjectProperties.TryGetValue(propertyName, out value))
{
dynamic property = _project.GetProperty(propertyName);
if (property != null)
{
value = property.EvaluatedValue;
}
}
return value;
}
dynamic CoreV2.NuGet.IPropertyProvider.GetPropertyValue(string propertyName) // used in tests
{
return GetPropertyValue(propertyName);
}
private void BuildProject()
{
if (Build)
{
if (TargetFramework != null)
{
Logger.Log(PackagingLogMessage.CreateMessage(string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("BuildingProjectTargetingFramework"),
_project.FullPath,
TargetFramework), LogLevel.Minimal));
}
BuildProjectWithMsbuild();
}
else
{
TargetPath = ResolveTargetPath();
// Make if the target path doesn't exist, fail
if (!Directory.Exists(TargetPath) && !File.Exists(TargetPath))
{
throw new PackagingException(NuGetLogCode.NU5012, String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("UnableToFindBuildOutput"), TargetPath));
}
}
}
private void BuildProjectWithMsbuild()
{
string properties = string.Empty;
foreach (var property in ProjectProperties)
{
string escapedValue = MsBuildUtility.Escape(property.Value);
properties += $" /p:{property.Key}={escapedValue}";
}
int result = MsBuildUtility.Build(_msbuildDirectory, $"\"{_project.FullPath}\" {properties} /toolsversion:{_project.ToolsVersion}");
if (0 != result) // 0 is msbuild.exe success code
{
// If the build fails, report the error
var error = String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("FailedToBuildProject"), Path.GetFileName(_project.FullPath));
throw new PackagingException(NuGetLogCode.NU5013, error);
}
TargetPath = ResolveTargetPath();
}
private string ResolveTargetPath()
{
// Set the project properties
foreach (var property in ProjectProperties)
{
var existingProperty = _project.GetProperty(property.Key);
if (existingProperty == null || !IsGlobalProperty(existingProperty))
{
// Only set the property if it's not already defined as a global property
// (which those passed in via the ctor are) as trying to set global properties
// with this method throws.
_project.SetProperty(property.Key, property.Value);
}
}
// Re-evaluate the project so that the new property values are applied
_project.ReevaluateIfNecessary();
// Return the new target path
string targetPath = _project.GetPropertyValue("TargetPath");
if (string.IsNullOrEmpty(targetPath))
{
string outputPath = _project.GetPropertyValue("OutputPath");
string configuration = _project.GetPropertyValue("Configuration");
string projectName = Path.GetFileName(Path.GetDirectoryName(_project.FullPath));
targetPath = PathUtility.EnsureTrailingSlash(Path.Combine(outputPath, projectName, "bin", configuration));
}
return targetPath;
}
// The type of projectProperty is Microsoft.Build.Evaluation.ProjectProperty
private static bool IsGlobalProperty(object projectProperty)
{
// This property isn't available on xbuild (mono)
var property = projectProperty.GetType().GetProperty("IsGlobalProperty", BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
return (bool)property.GetValue(projectProperty, null);
}
// REVIEW: Maybe there's something better we can do on mono
// Just return false if the property isn't there
return false;
}
private void ExtractMetadataFromProject(Packaging.PackageBuilder builder)
{
builder.Id = builder.Id ??
_project.GetPropertyValue("AssemblyName") ??
Path.GetFileNameWithoutExtension(_project.FullPath);
string version = _project.GetPropertyValue("Version");
if (builder.Version == null)
{
NuGetVersion parsedVersion;
if (NuGetVersion.TryParse(version, out parsedVersion))
{
builder.Version = parsedVersion;
}
else
{
builder.Version = new NuGetVersion(1, 0, 0);
}
}
}
private static IEnumerable<string> GetFiles(string path, ISet<string> fileNames, SearchOption searchOption)
{
return Directory.EnumerateFiles(path, "*", searchOption)
.Where(filePath => fileNames.Contains(Path.GetFileName(filePath)));
}
private void ApplyAction(Action<ProjectFactory> action)
{
if (IncludeReferencedProjects)
{
RecursivelyApply(action);
}
else
{
action(this);
}
}
/// <summary>
/// Recursively execute the specified action on the current project and
/// projects referenced by the current project.
/// </summary>
/// <param name="action">The action to be executed.</param>
private void RecursivelyApply(Action<ProjectFactory> action)
{
var projectCollection = Activator.CreateInstance(_projectCollectionType) as IDisposable;
using (projectCollection)
{
RecursivelyApply(action, projectCollection);
}
}
/// <summary>
/// Recursively execute the specified action on the current project and
/// projects referenced by the current project.
/// </summary>
/// <param name="action">The action to be executed.</param>
/// <param name="alreadyAppliedProjects">The collection of projects that have been processed.
/// It is used to avoid processing the same project more than once.</param>
private void RecursivelyApply(Action<ProjectFactory> action, dynamic alreadyAppliedProjects)
{
action(this);
foreach (var item in _project.GetItems(ProjectReferenceItemType))
{
if (ShouldExcludeItem(item))
{
continue;
}
string fullPath = item.GetMetadataValue("FullPath");
if (!string.IsNullOrEmpty(fullPath) &&
!NuspecFileExists(fullPath) &&
!File.Exists(ProjectJsonPathUtilities.GetProjectConfigPath(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath))) &&
alreadyAppliedProjects.GetLoadedProjects(fullPath).Count == 0)
{
dynamic project = Activator.CreateInstance(
_projectType,
fullPath,
null,
null,
alreadyAppliedProjects);
var referencedProject = new ProjectFactory(
_msbuildDirectory, _msbuildAssembly, _frameworkAssembly, project);
referencedProject.Logger = _logger;
referencedProject.IncludeSymbols = IncludeSymbols;
referencedProject.Build = Build;
referencedProject.IncludeReferencedProjects = IncludeReferencedProjects;
referencedProject.ProjectProperties = ProjectProperties;
referencedProject.TargetFramework = TargetFramework;
referencedProject.BuildProject();
referencedProject.SymbolPackageFormat = SymbolPackageFormat;
referencedProject.RecursivelyApply(action, alreadyAppliedProjects);
}
}
}
/// <summary>
/// Should the project item be excluded based on the Reference output assembly metadata
/// </summary>
/// <param name="item">Dynamic item which is a project item</param>
/// <returns>true, if the item should be excluded. false, otherwise.</returns>
private static bool ShouldExcludeItem(dynamic item)
{
if (item == null)
{
return true;
}
if (item.HasMetadata(ReferenceOutputAssembly))
{
bool result;
if (bool.TryParse(item.GetMetadataValue("ReferenceOutputAssembly"), out result))
{
if (!result)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns whether a project file has a corresponding nuspec file.
/// </summary>
/// <param name="projectFileFullName">The name of the project file.</param>
/// <returns>True if there is a corresponding nuspec file.</returns>
private static bool NuspecFileExists(string projectFileFullName)
{
var nuspecFile = Path.ChangeExtension(projectFileFullName, NuGetConstants.ManifestExtension);
return File.Exists(nuspecFile);
}
/// <summary>
/// Adds referenced projects that have corresponding nuspec files as dependencies.
/// </summary>
/// <param name="dependencies">The dependencies collection where the new dependencies
/// are added into.</param>
private void AddProjectReferenceDependencies(Dictionary<string, Packaging.Core.PackageDependency> dependencies)
{
var processedProjects = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var projectsToProcess = new Queue<object>();
dynamic projectCollection = Activator.CreateInstance(_projectCollectionType);
using ((IDisposable)projectCollection)
{
projectsToProcess.Enqueue(_project);
while (projectsToProcess.Count > 0)
{
dynamic project = projectsToProcess.Dequeue();
processedProjects.Add(project.FullPath);
foreach (var projectReference in project.GetItems(ProjectReferenceItemType))
{
if (ShouldExcludeItem(projectReference))
{
continue;
}
string fullPath = projectReference.GetMetadataValue("FullPath");
if (string.IsNullOrEmpty(fullPath) ||
processedProjects.Contains(fullPath))
{
continue;
}
var loadedProjects = projectCollection.GetLoadedProjects(fullPath);
var referencedProject = loadedProjects.Count > 0 ?
loadedProjects[0] :
Activator.CreateInstance(
_projectType,
fullPath,
project.GlobalProperties,
null,
projectCollection);
if (NuspecFileExists(fullPath) || File.Exists(ProjectJsonPathUtilities.GetProjectConfigPath(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath))))
{
var dependency = CreateDependencyFromProject(referencedProject, dependencies);
dependencies[dependency.Id] = dependency;
}
else
{
projectsToProcess.Enqueue(referencedProject);
}
}
}
}
}
private bool ProcessJsonFile(PackageBuilder builder, string basePath, string id)
{
return PackCommandRunner.ProcessProjectJsonFile(builder, basePath, id, null, null, GetPropertyValue);
}
// Creates a package dependency from the given project, which has a corresponding
// nuspec file.
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to continue regardless of any error we encounter extracting metadata.")]
private PackageDependency CreateDependencyFromProject(dynamic project, Dictionary<string, Packaging.Core.PackageDependency> dependencies)
{
try
{
var projectFactory = new ProjectFactory(_msbuildDirectory, _msbuildAssembly, _frameworkAssembly, project);
projectFactory.Build = Build;
projectFactory.ProjectProperties = ProjectProperties;
projectFactory.SymbolPackageFormat = SymbolPackageFormat;
projectFactory.BuildProject();
var builder = new Packaging.PackageBuilder();
projectFactory.ExtractMetadata(builder);
projectFactory.InitializeProperties(builder);
if (!projectFactory.ProcessJsonFile(builder, project.DirectoryPath, null))
{
projectFactory.ProcessNuspec(builder, null);
}
else
{
Logger.Log(
PackagingLogMessage.CreateWarning(
string.Format(NuGetResources.ProjectJsonPack_Deprecated, builder.Id),
NuGetLogCode.NU5126));
}
VersionRange versionRange = null;
if (dependencies.ContainsKey(builder.Id))
{
VersionRange nuspecVersion = dependencies[builder.Id].VersionRange;
if (nuspecVersion != null)
{
versionRange = nuspecVersion;
}
}
if (versionRange == null)
{
versionRange = VersionRange.Parse(builder.Version.ToString());
}
return new Packaging.Core.PackageDependency(
builder.Id,
versionRange);
}
catch (Exception ex)
{
var message = string.Format(
CultureInfo.InvariantCulture,
LocalizedResourceManager.GetString("Error_ProcessingNuspecFile"),
project.FullPath,
ex.Message);
throw new PackagingException(NuGetLogCode.NU5014, message, ex);
}
}
private void ExtractMetadata(Packaging.PackageBuilder builder)
{
// If building an xproj, then TargetPath points to the folder where the framework folders will be
// instead of to a single dll. Skip trying to ExtractMetadata from the dll and instead
// use only metadata from the project and json file.
if (!Directory.Exists(TargetPath))
{
// If building a project targeting netstandard, asssembly metadata extraction fails
// because it tries to load system.runtime version 4.1.0 which is not present in the local
// path or the gac. In this case, we should just skip it and extract metadata from the project.
try
{
new AssemblyMetadataExtractor(Logger).ExtractMetadata(builder, TargetPath);
}
catch (Exception ex)
{
Logger.Log(PackagingLogMessage.CreateMessage(ex.Message, LogLevel.Verbose));
ExtractMetadataFromProject(builder);
}
}
else
{
ExtractMetadataFromProject(builder);
}
}
private void AddOutputFiles(Packaging.PackageBuilder builder)
{
// Get the target framework of the project
NuGetFramework nugetFramework;
if (_usingJsonFile && builder.TargetFrameworks.Any())
{
if (builder.TargetFrameworks.Count > 1)
{
var message = string.Format(
CultureInfo.CurrentCulture,
LocalizedResourceManager.GetString("Error_MultipleTargetFrameworks"));
throw new PackagingException(NuGetLogCode.NU5015, message);
}
nugetFramework = builder.TargetFrameworks.First();
}
else
{
nugetFramework = TargetFramework;
}
var projectOutputDirectory = Path.GetDirectoryName(TargetPath);
string targetFileName;
if (Directory.Exists(TargetPath))
{
targetFileName = builder.Id;
}
else
{
targetFileName = Path.GetFileNameWithoutExtension(TargetPath);
}
var outputFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
$"{targetFileName}.dll",
$"{targetFileName}.exe",
$"{targetFileName}.xml",
$"{targetFileName}.winmd"
};
if (IncludeSymbols)
{
// if this is a snupkg package, we don't want any files other than symbol files.
if (SymbolPackageFormat == SymbolPackageFormat.Snupkg)
{
outputFileNames.Clear();
outputFileNames.Add($"{targetFileName}.pdb");
}
else
{
outputFileNames.Add($"{targetFileName}.pdb");
outputFileNames.Add($"{targetFileName}.dll.mdb");
outputFileNames.Add($"{targetFileName}.exe.mdb");
}
}
foreach (var file in GetFiles(projectOutputDirectory, outputFileNames, SearchOption.AllDirectories))
{
string targetFolder;
if (IsTool)
{
targetFolder = ToolsFolder;
}
else
{
if (Directory.Exists(TargetPath))
{
targetFolder = Path.Combine(ReferenceFolder, Path.GetDirectoryName(file.Replace(TargetPath, string.Empty)));
}
else if (nugetFramework == null)
{
targetFolder = ReferenceFolder;
}
else
{
string shortFolderName = nugetFramework.GetShortFolderName();
targetFolder = Path.Combine(ReferenceFolder, shortFolderName);
}
}
var packageFile = new Packaging.PhysicalPackageFile
{
SourcePath = file,
TargetPath = Path.Combine(targetFolder, Path.GetFileName(file))
};
AddFileToBuilder(builder, packageFile);
}
}
private void ProcessDependencies(Packaging.PackageBuilder builder)
{
// get all packages and dependencies, including the ones in project references
var packagesAndDependencies = new Dictionary<String, Tuple<PackageReaderBase, Packaging.Core.PackageDependency>>();
ApplyAction(p => p.AddDependencies(packagesAndDependencies));
// list of all dependency packages
var packages = packagesAndDependencies.Values.Select(t => t.Item1).ToList();
// Add the transform file to the package builder
ProcessTransformFiles(builder, packages.SelectMany(GetTransformFiles));
var dependencies = new Dictionary<string, Packaging.Core.PackageDependency>();
if (!_usingJsonFile)
{
dependencies = builder.DependencyGroups.SelectMany(d => d.Packages)
.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase);
}
// Reduce the set of packages we want to include as dependencies to the minimal set.
// Normally, packages.config has the full closure included, we only add top level
// packages, i.e. packages with in-degree 0
foreach (var package in packages)
{
// Don't add duplicate dependencies
if (dependencies.ContainsKey(package.GetIdentity().Id) || !FindDependency(package.GetIdentity(), packagesAndDependencies.Values))
{
continue;
}
var dependency = packagesAndDependencies[package.GetIdentity().Id].Item2;
dependencies[dependency.Id] = dependency;
}
DisposePackageReaders(packagesAndDependencies);
if (IncludeReferencedProjects)
{
AddProjectReferenceDependencies(dependencies);
}
if (_usingJsonFile)
{
if (dependencies.Any())
{
if (builder.DependencyGroups.Any())
{
var i = 0;
foreach (var group in builder.DependencyGroups.ToList())
{
ISet<Packaging.Core.PackageDependency> newPackagesList = new HashSet<Packaging.Core.PackageDependency>(group.Packages);
foreach (var dependency in dependencies)
{
if (!newPackagesList.Contains(dependency.Value))
{
newPackagesList.Add(dependency.Value);
}
}
var dependencyGroup = new PackageDependencyGroup(group.TargetFramework, newPackagesList);
builder.DependencyGroups.RemoveAt(i);
builder.DependencyGroups.Insert(i, dependencyGroup);
i++;
}
}
else
{
builder.DependencyGroups.Add(new PackageDependencyGroup(NuGetFramework.AnyFramework, new HashSet<Packaging.Core.PackageDependency>(dependencies.Values)));
}
}
}
else
{
// TO FIX: when we persist the target framework into packages.config file,
// we need to pull that info into building the PackageDependencySet object
builder.DependencyGroups.Clear();
// REVIEW: IS NuGetFramework.AnyFramework correct?
builder.DependencyGroups.Add(new PackageDependencyGroup(NuGetFramework.AnyFramework, new HashSet<Packaging.Core.PackageDependency>(dependencies.Values)));
}
}
private bool FindDependency(PackageIdentity projectPackage, IEnumerable<Tuple<PackageReaderBase, Packaging.Core.PackageDependency>> packagesAndDependencies)
{
// returns true if the dependency should be added to the package
// This happens if the dependency is not a dependency of a dependency
// Or if the project dependency version is != the dependency's dependency version
bool found = false;
foreach (var reader in packagesAndDependencies)
{
foreach (var set in reader.Item1.GetPackageDependencies())
{
foreach (var dependency in set.Packages)
{
if (dependency.Id.Equals(projectPackage.Id, StringComparison.OrdinalIgnoreCase))
{
found = true;
if (dependency.VersionRange.MinVersion < projectPackage.Version ||
(!dependency.VersionRange.IsMinInclusive &&
dependency.VersionRange.MinVersion == projectPackage.Version))
{
return true;
}
}
}
}
}
return !found;
}
private void AddDependencies(Dictionary<String, Tuple<PackageReaderBase, Packaging.Core.PackageDependency>> packagesAndDependencies)
{
Dictionary<string, object> props = new Dictionary<string, object>();
foreach (var property in _project.Properties)
{
props.Add(property.Name, property.EvaluatedValue);
}