示例#1
0
	/// <summary>
	/// Builds UnrealHeaderTool for the specified platform.
	/// </summary>
	/// <param name="Command"></param>
	/// <param name="InPlatform"></param>
	public static void BuildUnrealHeaderTool(BuildCommand Command, UnrealBuildTool.UnrealTargetPlatform InPlatform)
	{
		BuildProduct(Command, new UE4Build.BuildTarget()
		{
			ProjectName = "",
			TargetName = "UnrealHeaderTool",
			Platform = InPlatform,
			Config = UnrealBuildTool.UnrealTargetConfiguration.Development,
		});
	}
	/// <summary>
	/// Builds BuildPatchTool for the specified platform.
	/// </summary>
	/// <param name="Command"></param>
	/// <param name="InPlatform"></param>
	public static void BuildBuildPatchTool(BuildCommand Command, UnrealBuildTool.UnrealTargetPlatform InPlatform)
	{
		BuildProduct(Command, new UE4Build.BuildTarget()
			{
				UprojectPath = null,
				TargetName = "BuildPatchTool",
				Platform = InPlatform,
				Config = UnrealBuildTool.UnrealTargetConfiguration.Shipping,
			});
	}
示例#3
0
    /// <summary>
    /// Builds BuildPatchTool for the specified platform.
    /// </summary>
    /// <param name="Command"></param>
    /// <param name="InPlatform"></param>
    public static void BuildBuildPatchTool(BuildCommand Command, UnrealBuildTool.UnrealTargetPlatform InPlatform)
    {
        Log("Building BuildPatchTool");

        var UE4Build = new UE4Build(Command);

        var Agenda = new UE4Build.BuildAgenda();
        Agenda.Targets.Add(new UE4Build.BuildTarget()
        {
            ProjectName = "",
            TargetName = "BuildPatchTool",
            Platform = InPlatform,
            Config = UnrealBuildTool.UnrealTargetConfiguration.Development,
        });

        UE4Build.Build(Agenda, InDeleteBuildProducts: true, InUpdateVersionFiles: true);
        UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);
    }
示例#4
0
	private static void BuildProduct(BuildCommand Command, UE4Build.BuildTarget Target)
	{
		if (Target == null)
		{
			throw new AutomationException("Target is required when calling UE4BuildUtils.BuildProduct");
		}

		LogConsole("Building {0}", Target.TargetName);

		if (Command == null)
		{
			Command = new UE4BuildUtilDummyBuildCommand();
		}

		var UE4Build = new UE4Build(Command);

		var Agenda = new UE4Build.BuildAgenda();
		Agenda.Targets.Add(Target);

		UE4Build.Build(Agenda, InDeleteBuildProducts: true, InUpdateVersionFiles: true);
		UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);
	}
        public IExecutable ManageCommand(string[] inputArgs)
        {
            IExecutable command = null;

            switch (inputArgs[0])
            {
                case "build":
                    command = new BuildCommand(inputArgs[1], this.Engine);
                    break;
                case "skip":
                    command = new SkipCommand();
                    break;
                case "empire-status":
                    command = new StatusCommand(this.Engine);
                    break;
                case "armistice":
                    command = new EndCommand();
                    break;
            }

            return command;
        }
        public static BaseCommand getCommand(string[] commandLine)
        {
            BaseCommand command = null;

            if (commandLine.Length != 0) {
                switch (commandLine[0].ToUpper()) {
                    case "DECOMPOSE":
                        command = new DecomposeCommand(commandLine);
                        break;
                    case "BUILD":
                        command = new BuildCommand(commandLine);
                        break;
                    default:
                        command = new HelpCommand(commandLine);
                        break;
                }
            }

            if (command == null || !command.argsAreOk()) {
                command = new HelpCommand(commandLine);
            }

            return command;
        }
		public ElectricCommander(BuildCommand InCommand)
		{
			Command = InCommand;
		}
    public static void Build(BuildCommand Command, ProjectParams Params, int WorkingCL = -1, ProjectBuildTargets TargetMask = ProjectBuildTargets.All)
	{
		Params.ValidateAndLog();

		if (!Params.Build)
		{
			return;
		}

		Log("********** BUILD COMMAND STARTED **********");

		var UE4Build = new UE4Build(Command);
		var Agenda = new UE4Build.BuildAgenda();
		var CrashReportPlatforms = new HashSet<UnrealTargetPlatform>();

		// Setup editor targets
		if (Params.HasEditorTargets && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.Editor) == ProjectBuildTargets.Editor)
		{
			// @todo Mac: proper platform detection
			UnrealTargetPlatform EditorPlatform = HostPlatform.Current.HostEditorPlatform;
			const UnrealTargetConfiguration EditorConfiguration = UnrealTargetConfiguration.Development;

			CrashReportPlatforms.Add(EditorPlatform);
            Agenda.AddTargets(Params.EditorTargets.ToArray(), EditorPlatform, EditorConfiguration, Params.CodeBasedUprojectPath);
			if (Params.EditorTargets.Contains("UnrealHeaderTool") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealHeaderTool" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.EditorTargets.Contains("ShaderCompileWorker") == false)
			{
				Agenda.AddTargets(new string[] { "ShaderCompileWorker" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.Pak && Params.EditorTargets.Contains("UnrealPak") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealPak" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.FileServer && Params.EditorTargets.Contains("UnrealFileServer") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealFileServer" }, EditorPlatform, EditorConfiguration);
			}
		}

		// Setup cooked targets
		if (Params.HasClientCookedTargets && (TargetMask & ProjectBuildTargets.ClientCooked) == ProjectBuildTargets.ClientCooked)
		{
            List<UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
			{
                foreach (var ClientPlatformType in UniquePlatformTypes)
				{
                    string ScriptPluginArgs = GetBlueprintPluginPathArgument(Params, true, ClientPlatformType);
                    CrashReportPlatforms.Add(ClientPlatformType);
					Agenda.AddTargets(Params.ClientCookedTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: ScriptPluginArgs + " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
				}
			}
		}
		if (Params.HasServerCookedTargets && (TargetMask & ProjectBuildTargets.ServerCooked) == ProjectBuildTargets.ServerCooked)
		{
            List<UnrealTargetPlatform> UniquePlatformTypes = Params.ServerTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ServerConfigsToBuild)
			{
				foreach (var ServerPlatformType in UniquePlatformTypes)
				{
                    string ScriptPluginArgs = GetBlueprintPluginPathArgument(Params, false, ServerPlatformType);
                    CrashReportPlatforms.Add(ServerPlatformType);
					Agenda.AddTargets(Params.ServerCookedTargets.ToArray(), ServerPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: ScriptPluginArgs + " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
				}
			}
		}
		if (!Params.NoBootstrapExe && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.Bootstrap) == ProjectBuildTargets.Bootstrap)
		{
			UnrealBuildTool.UnrealTargetPlatform[] BootstrapPackagedGamePlatforms = { UnrealBuildTool.UnrealTargetPlatform.Win32, UnrealBuildTool.UnrealTargetPlatform.Win64 };
			foreach(UnrealBuildTool.UnrealTargetPlatform BootstrapPackagedGamePlatformType in BootstrapPackagedGamePlatforms)
			{
				if(Params.ClientTargetPlatforms.Contains(new TargetPlatformDescriptor(BootstrapPackagedGamePlatformType)))
				{
					Agenda.AddTarget("BootstrapPackagedGame", BootstrapPackagedGamePlatformType, UnrealBuildTool.UnrealTargetConfiguration.Shipping);
				}
			}
		}
		if (Params.CrashReporter && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.CrashReporter) == ProjectBuildTargets.CrashReporter)
		{
			foreach (var CrashReportPlatform in CrashReportPlatforms)
			{
				if (UnrealBuildTool.UnrealBuildTool.PlatformSupportsCrashReporter(CrashReportPlatform))
				{
					Agenda.AddTarget("CrashReportClient", CrashReportPlatform, UnrealTargetConfiguration.Shipping);
				}
			}
		}
		if (Params.HasProgramTargets && (TargetMask & ProjectBuildTargets.Programs) == ProjectBuildTargets.Programs)
		{
            List<UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
			{
				foreach (var ClientPlatformType in UniquePlatformTypes)
				{
					Agenda.AddTargets(Params.ProgramTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath);
				}
			}
		}
		UE4Build.Build(Agenda, InDeleteBuildProducts: Params.Clean, InUpdateVersionFiles: WorkingCL > 0);

		if (WorkingCL > 0) // only move UAT files if we intend to check in some build products
		{
			UE4Build.AddUATFilesToBuildProducts();
		}
		UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);

		if (WorkingCL > 0)
		{
			// Sign everything we built
			CodeSign.SignMultipleIfEXEOrDLL(Command, UE4Build.BuildProductFiles);

			// Open files for add or edit
			UE4Build.AddBuildProductsToChangelist(WorkingCL, UE4Build.BuildProductFiles);
		}

		Log("********** BUILD COMMAND COMPLETED **********");
	}
        public void It_can_build_with_dynamic_loading_enabled(string targetFramework, string rollForwardValue, bool shouldSetRollForward, bool?copyLocal, bool shouldCopyLocal)
        {
            var testProject = new TestProject()
            {
                Name             = "EnableDynamicLoading",
                TargetFrameworks = targetFramework,
            };

            testProject.AdditionalProperties["EnableDynamicLoading"] = "true";
            if (!string.IsNullOrEmpty(rollForwardValue))
            {
                testProject.AdditionalProperties["RollForward"] = rollForwardValue;
            }

            testProject.PackageReferences.Add(new TestPackageReference("Newtonsoft.Json", "13.0.1"));
            if (copyLocal.HasValue)
            {
                testProject.AdditionalProperties["CopyLocalLockFileAssemblies"] = copyLocal.ToString().ToLower();
            }

            var identifier = targetFramework + shouldSetRollForward + shouldCopyLocal + (rollForwardValue == null? "Null" : rollForwardValue);
            var testAsset  = _testAssetsManager.CreateTestProject(testProject, identifier: identifier);

            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            string runtimeConfigName = $"{testProject.Name}.runtimeconfig.json";
            var    outputDirectory   = buildCommand.GetOutputDirectory(testProject.TargetFrameworks);

            outputDirectory.Should().HaveFiles(new[] {
                runtimeConfigName,
                $"{testProject.Name}.runtimeconfig.dev.json"
            });

            if (shouldCopyLocal)
            {
                outputDirectory.Should().HaveFile("Newtonsoft.Json.dll");
            }
            else
            {
                outputDirectory.Should().NotHaveFile("Newtonsoft.Json.dll");
            }

            string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, runtimeConfigName);
            string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
            JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);
            JToken  rollForward           = runtimeConfig["runtimeOptions"]["rollForward"];

            if (shouldSetRollForward)
            {
                rollForward.Value <string>().Should().Be(string.IsNullOrEmpty(rollForwardValue) ? "LatestMinor" : rollForwardValue);
            }
            else
            {
                rollForward.Should().BeNull();
            }
        }
        public void It_can_use_implicitly_defined_compilation_constants(string targetFramework, string[] expectedOutput, string targetPlatformIdentifier = null, string targetPlatformVersion = null)
        {
            var testProj = new TestProject()
            {
                Name             = "CompilationConstants",
                TargetFrameworks = targetFramework,
                IsExe            = true,
            };

            if (targetPlatformIdentifier != null)
            {
                testProj.AdditionalProperties["TargetPlatformIdentifier"] = targetPlatformIdentifier;
                testProj.AdditionalProperties["TargetPlatformVersion"]    = targetPlatformVersion;
            }
            var testAsset = _testAssetsManager.CreateTestProject(testProj, targetFramework);

            File.WriteAllText(Path.Combine(testAsset.Path, testProj.Name, $"{testProj.Name}.cs"), @"
using System;
class Program
{
    static void Main(string[] args)
    {
        #if NETCOREAPP
            Console.WriteLine(""NETCOREAPP"");
        #endif
        #if NETCOREAPP2_1
            Console.WriteLine(""NETCOREAPP2_1"");
        #endif
        #if NETCOREAPP3_1
            Console.WriteLine(""NETCOREAPP3_1"");
        #endif
        #if NETCOREAPP3_1_OR_GREATER
            Console.WriteLine(""NETCOREAPP3_1_OR_GREATER"");
        #endif
        #if NET
            Console.WriteLine(""NET"");
        #endif
        #if NET5_0
            Console.WriteLine(""NET5_0"");
        #endif
        #if NET5_0_OR_GREATER
            Console.WriteLine(""NET5_0_OR_GREATER"");
        #endif
        #if WINDOWS
            Console.WriteLine(""WINDOWS"");
        #endif
        #if WINDOWS7_0
            Console.WriteLine(""WINDOWS7_0"");
        #endif
        #if WINDOWS7_0_OR_GREATER
            Console.WriteLine(""WINDOWS7_0_OR_GREATER"");
        #endif
        #if IOS
            Console.WriteLine(""IOS"");
        #endif
    }
}");

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.Path, testProj.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var runCommand = new RunExeCommand(Log, Path.Combine(buildCommand.GetOutputDirectory(targetFramework).FullName, $"{testProj.Name}.exe"));
            var stdOut     = runCommand.Execute().StdOut.Split(Environment.NewLine.ToCharArray()).Where(line => !string.IsNullOrWhiteSpace(line));

            stdOut.Should().BeEquivalentTo(expectedOutput);
        }
        public void It_resolves_conflicts(bool isSdk, bool usePackagesConfig)
        {
            var successMessage = "No conflicts found for support libs";

            var testAsset = _testAssetsManager
                            .CopyTestAsset(GetTemplateName(isSdk, usePackagesConfig))
                            .WithSource()
                            .WithProjectChanges((projectPath, project) =>
            {
                if (IsAppProject(projectPath))
                {
                    var ns = project.Root.Name.Namespace;

                    AddReferenceToLibrary(project, ReferenceScenario.ProjectReference);

                    var itemGroup = new XElement(ns + "ItemGroup");
                    project.Root.Add(itemGroup);

                    // packages.config template already has a reference to NETStandard.Library 1.6.1
                    if (!usePackagesConfig)
                    {
                        // Reference the old package based NETStandard.Library.
                        itemGroup.Add(new XElement(ns + "PackageReference",
                                                   new XAttribute("Include", "NETStandard.Library"),
                                                   new XAttribute("Version", "1.6.1")));
                    }

                    // Add a target to validate that no conflicts are from support libs
                    var target = new XElement(ns + "Target",
                                              new XAttribute("Name", "CheckForConflicts"),
                                              new XAttribute("AfterTargets", "_HandlePackageFileConflicts"));
                    project.Root.Add(target);

                    target.Add(new XElement(ns + "FindUnderPath",
                                            new XAttribute("Files", "@(_ConflictPackageFiles)"),
                                            new XAttribute("Path", RepoInfo.BuildExtensionsMSBuildPath),
                                            new XElement(ns + "Output",
                                                         new XAttribute("TaskParameter", "InPath"),
                                                         new XAttribute("ItemName", "_ConflictsInSupportLibs"))
                                            ));
                    target.Add(new XElement(ns + "Message",
                                            new XAttribute("Condition", "'@(_ConflictsInSupportLibs)' == ''"),
                                            new XAttribute("Importance", "High"),
                                            new XAttribute("Text", successMessage)));
                    target.Add(new XElement(ns + "Error",
                                            new XAttribute("Condition", "'@(_ConflictsInSupportLibs)' != ''"),
                                            new XAttribute("Text", "Found conflicts under support libs: @(_ConflictsInSupportLibs)")));
                }
            });

            if (usePackagesConfig)
            {
                testAsset.NuGetRestore(Log, relativePath: AppName);
                testAsset.Restore(Log, relativePath: LibraryName);
            }
            else
            {
                testAsset.Restore(Log, relativePath: AppName);
            }

            // build should succeed without duplicates
            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, AppName));

            buildCommand
            .Execute()
            .Should()
            .Pass()
            .And
            .NotHaveStdOutContaining("warning")
            .And
            .HaveStdOutContainingIgnoreCase(successMessage);

            var outputDirectory = isSdk ?
                                  buildCommand.GetOutputDirectory("net461") :
                                  buildCommand.GetNonSDKOutputDirectory();

            outputDirectory.Should().HaveFiles(new[] {
                "netstandard.dll",
                $"{AppName}.exe.config"
            });
        }
示例#12
0
        public void It_resolves_runtimepack_from_packs_folder()
        {
            var testProject = new TestProject()
            {
                IsExe             = true,
                TargetFrameworks  = ToolsetInfo.CurrentTargetFramework,
                RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid()
            };

            //  Use separate packages download folder for this project so that we can verify whether it had to download runtime packs
            testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packages";

            var testAsset = _testAssetsManager.CreateTestProject(testProject);

            var getValuesCommand = new GetValuesCommand(testAsset, "RuntimePack", GetValuesCommand.ValueType.Item);

            getValuesCommand.MetadataNames = new List <string>()
            {
                "NuGetPackageId", "NuGetPackageVersion"
            };
            getValuesCommand.DependsOnTargets = "ProcessFrameworkReferences";
            getValuesCommand.ShouldRestore    = false;

            getValuesCommand.Execute()
            .Should()
            .Pass();

            var runtimePacks = getValuesCommand.GetValuesWithMetadata();

            var packageDownloadProject = new TestProject()
            {
                Name             = "PackageDownloadProject",
                TargetFrameworks = testProject.TargetFrameworks
            };

            //  Add PackageDownload items for runtime packs which will be needed
            foreach (var runtimePack in runtimePacks)
            {
                packageDownloadProject.AddItem("PackageDownload",
                                               new Dictionary <string, string>()
                {
                    { "Include", runtimePack.metadata["NuGetPackageId"] },
                    { "Version", "[" + runtimePack.metadata["NuGetPackageVersion"] + "]" }
                });
            }

            //  Download runtime packs into separate folder under test assets
            packageDownloadProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\packs";

            var packageDownloadAsset = _testAssetsManager.CreateTestProject(packageDownloadProject);

            new RestoreCommand(packageDownloadAsset)
            .Execute()
            .Should()
            .Pass();

            //  Package download folders use lowercased package names, but pack folders use mixed case
            //  So change casing of the downloaded runtime pack folders to match what is expected
            //  for packs folders
            foreach (var runtimePack in runtimePacks)
            {
                string oldCasing = Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name, "packs", runtimePack.metadata["NuGetPackageId"].ToLowerInvariant());
                string newCasing = Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name, "packs", runtimePack.metadata["NuGetPackageId"]);
                Directory.Move(oldCasing, newCasing);
            }

            //  Now build the original test project with the packs folder with the runtime packs we just downloaded
            var buildCommand = new BuildCommand(testAsset)
                               .WithEnvironmentVariable(EnvironmentVariableNames.WORKLOAD_PACK_ROOTS, Path.Combine(packageDownloadAsset.TestRoot, packageDownloadProject.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            //  Verify that runtime packs weren't downloaded to test project's packages folder
            var packagesFolder = Path.Combine(testAsset.TestRoot, testProject.Name, "packages");

            foreach (var runtimePack in runtimePacks)
            {
                var path = Path.Combine(packagesFolder, runtimePack.metadata["NuGetPackageId"].ToLowerInvariant());
                new DirectoryInfo(path).Should().NotExist("Runtime Pack should have been resolved from packs folder");
            }
        }
        void TestPackagesNotDownloaded(bool referenceAspNet, bool selfContained, [CallerMemberName] string testName = null)
        {
            string nugetPackagesFolder = _testAssetsManager.CreateTestDirectory(testName, identifier: "packages_" + referenceAspNet).Path;

            var testProject = new TestProject(testName)
            {
                TargetFrameworks = ToolsetInfo.CurrentTargetFramework,
                IsExe            = true,
            };

            if (selfContained)
            {
                testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid();
                testProject.AdditionalProperties["SelfContained"] = "true";
            }
            else
            {
                //  Don't use AppHost in order to avoid additional download to packages folder
                testProject.AdditionalProperties["UseAppHost"] = "False";
            }

            if (referenceAspNet)
            {
                testProject.FrameworkReferences.Add("Microsoft.AspNetCore.App");
            }

            testProject.AdditionalProperties["DisableTransitiveFrameworkReferenceDownloads"] = "True";
            testProject.AdditionalProperties["RestorePackagesPath"] = nugetPackagesFolder;

            //  Set packs folder to nonexistant folder so the project won't use installed targeting or runtime packs
            testProject.AdditionalProperties["NetCoreTargetingPackRoot"] = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testName, identifier: referenceAspNet.ToString());

            var buildCommand = new BuildCommand(testAsset);

            buildCommand.Execute()
            .Should()
            .Pass();

            var expectedPackages = new List <string>()
            {
                "microsoft.netcore.app.ref"
            };

            if (selfContained)
            {
                expectedPackages.Add("microsoft.netcore.app.runtime.**RID**");
                expectedPackages.Add("microsoft.netcore.app.host.**RID**");
            }

            if (referenceAspNet)
            {
                expectedPackages.Add("microsoft.aspnetcore.app.ref");
            }

            Directory.EnumerateDirectories(nugetPackagesFolder)
            .Select(Path.GetFileName)
            .Select(package =>
            {
                if (package.Contains(".runtime.") || (package.Contains(".host.")))
                {
                    //  Replace RuntimeIdentifier, which should be the last dotted segment in the package name, with "**RID**"
                    package = package.Substring(0, package.LastIndexOf('.') + 1) + "**RID**";
                }

                return(package);
            })
            .Should().BeEquivalentTo(expectedPackages);
        }
        public void It_can_use_HttpClient_and_exchange_the_type_with_a_NETStandard_library()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return;
            }

            var netStandardLibrary = new TestProject()
            {
                Name             = "NETStandardLibrary",
                TargetFrameworks = "netstandard1.4",
                IsSdkProject     = true
            };

            netStandardLibrary.SourceFiles["NETStandard.cs"] = @"
using System.Net.Http;
public class NETStandard
{
    public static HttpClient GetHttpClient()
    {
        return new HttpClient();
    }
}
";

            var netFrameworkLibrary = new TestProject()
            {
                Name             = "NETFrameworkLibrary",
                TargetFrameworks = "net461",
                IsSdkProject     = true
            };

            netFrameworkLibrary.ReferencedProjects.Add(netStandardLibrary);

            netFrameworkLibrary.SourceFiles["NETFramework.cs"] = @"
using System.Net.Http;
public class NETFramework
{
    public void Method1()
    {
        System.Net.Http.HttpClient client = NETStandard.GetHttpClient();
    }
}
";

            var testAsset = _testAssetsManager.CreateTestProject(netFrameworkLibrary, "ExchangeHttpClient")
                            .WithProjectChanges((projectPath, project) =>
            {
                if (Path.GetFileName(projectPath).Equals(netFrameworkLibrary.Name + ".csproj", StringComparison.OrdinalIgnoreCase))
                {
                    var ns = project.Root.Name.Namespace;

                    var itemGroup = new XElement(ns + "ItemGroup");
                    project.Root.Add(itemGroup);

                    itemGroup.Add(new XElement(ns + "Reference", new XAttribute("Include", "System.Net.Http")));
                }
            })
                            .Restore(Log, netFrameworkLibrary.Name);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, netFrameworkLibrary.Name));

            buildCommand
            .Execute()
            .Should()
            .Pass();
        }
        public void It_trims_conflicts_from_the_deps_file(string targetFramework)
        {
            TestProject project = new TestProject()
            {
                Name             = "NetCore2App",
                TargetFrameworks = targetFramework,
                IsExe            = true,
                IsSdkProject     = true
            };

            project.SourceFiles["Program.cs"] = @"
using System;
public static class Program
{
    public static void Main()
    {
        TestConflictResolution();
        Console.WriteLine(""Hello, World!"");
    }
" + ConflictResolutionAssets.ConflictResolutionTestMethod + @"
}
";

            var testAsset = _testAssetsManager.CreateTestProject(project, identifier: targetFramework)
                            .WithProjectChanges(p =>
            {
                var ns = p.Root.Name.Namespace;

                var itemGroup = new XElement(ns + "ItemGroup");
                p.Root.Add(itemGroup);

                foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies)
                {
                    itemGroup.Add(new XElement(ns + "PackageReference",
                                               new XAttribute("Include", dependency.Item1),
                                               new XAttribute("Version", dependency.Item2)));
                }
            })
                            .Restore(Log, project.Name);

            string projectFolder = Path.Combine(testAsset.Path, project.Name);

            var buildCommand = new BuildCommand(Log, projectFolder);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            string outputFolder = buildCommand.GetOutputDirectory(project.TargetFrameworks).FullName;

            using (var depsJsonFileStream = File.OpenRead(Path.Combine(outputFolder, $"{project.Name}.deps.json")))
            {
                var dependencyContext = new DependencyContextJsonReader().Read(depsJsonFileStream);
                dependencyContext.Should()
                .OnlyHaveRuntimeAssemblies("", project.Name)
                .And
                .HaveNoDuplicateRuntimeAssemblies("")
                .And
                .HaveNoDuplicateNativeAssets("");;
            }
        }
        private void RunAppFromOutputFolder(string testName, bool useRid, bool includeConflicts,
                                            string targetFramework = "netcoreapp2.0")
        {
            var runtimeIdentifier = useRid ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null;

            TestProject project = new TestProject()
            {
                Name              = testName,
                IsSdkProject      = true,
                TargetFrameworks  = targetFramework,
                RuntimeIdentifier = runtimeIdentifier,
                IsExe             = true,
            };

            string outputMessage = $"Hello from {project.Name}!";

            project.SourceFiles["Program.cs"] = @"
using System;
public static class Program
{
    public static void Main()
    {
        TestConflictResolution();
        Console.WriteLine(""" + outputMessage + @""");
    }
" + ConflictResolutionAssets.ConflictResolutionTestMethod + @"
}
";
            var testAsset = _testAssetsManager.CreateTestProject(project, project.Name)
                            .WithProjectChanges(p =>
            {
                if (includeConflicts)
                {
                    var ns = p.Root.Name.Namespace;

                    var itemGroup = new XElement(ns + "ItemGroup");
                    p.Root.Add(itemGroup);

                    foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies)
                    {
                        itemGroup.Add(new XElement(ns + "PackageReference",
                                                   new XAttribute("Include", dependency.Item1),
                                                   new XAttribute("Version", dependency.Item2)));
                    }
                }
            })
                            .Restore(Log, project.Name);

            string projectFolder = Path.Combine(testAsset.Path, project.Name);

            var buildCommand = new BuildCommand(Log, projectFolder);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            string outputFolder = buildCommand.GetOutputDirectory(project.TargetFrameworks, runtimeIdentifier: runtimeIdentifier ?? "").FullName;

            Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { Path.Combine(outputFolder, project.Name + ".dll") })
            .CaptureStdOut()
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining(outputMessage);
        }
        private void It_targets_the_right_framework(
            string testIdentifier,
            string targetFramework,
            string runtimeFrameworkVersion,
            bool selfContained,
            bool isExe,
            string expectedPackageVersion,
            string expectedRuntimeVersion,
            string extraMSBuildArguments = null)
        {
            string runtimeIdentifier = null;

            if (selfContained)
            {
                runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework);
            }

            var testProject = new TestProject()
            {
                Name                    = "FrameworkTargetTest",
                TargetFrameworks        = targetFramework,
                RuntimeFrameworkVersion = runtimeFrameworkVersion,
                IsSdkProject            = true,
                IsExe                   = isExe,
                RuntimeIdentifier       = runtimeIdentifier
            };

            var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>();

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier)
                            .Restore(Log, testProject.Name, extraArgs);

            NuGetConfigWriter.Write(testAsset.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand
            .Execute(extraArgs)
            .Should()
            .Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier);

            if (isExe)
            {
                //  Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps
                if (!selfContained)
                {
                    string  runtimeConfigFile     = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json");
                    string  runtimeConfigContents = File.ReadAllText(runtimeConfigFile);
                    JObject runtimeConfig         = JObject.Parse(runtimeConfigContents);

                    string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>();
                    actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion);
                }

                var runtimeconfigDevFileName = testProject.Name + ".runtimeconfig.dev.json";
                outputDirectory.Should()
                .HaveFile(runtimeconfigDevFileName);

                string  devruntimeConfigContents = File.ReadAllText(Path.Combine(outputDirectory.FullName, runtimeconfigDevFileName));
                JObject devruntimeConfig         = JObject.Parse(devruntimeConfigContents);

                var additionalProbingPaths = ((JArray)devruntimeConfig["runtimeOptions"]["additionalProbingPaths"]).Values <string>();
                // can't use Path.Combine on segments with an illegal `|` character
                var expectedPath = $"{Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|";
                additionalProbingPaths.Should().Contain(expectedPath);
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance);

            var target            = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null);
            var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App");

            netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion);
        }
示例#18
0
        public void TestPreviewFeatures(bool enablePreviewFeatures, bool generateRequiresPreviewFeaturesAttribute, string targetFramework)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("HelloWorld", identifier: $"{enablePreviewFeatures}${generateRequiresPreviewFeaturesAttribute}${targetFramework}")
                            .WithSource()
                            .WithTargetFramework(targetFramework)
                            .WithProjectChanges((path, project) =>
            {
                var ns = project.Root.Name.Namespace;

                project.Root.Add(
                    new XElement(ns + "PropertyGroup",
                                 new XElement(ns + "EnablePreviewFeatures", $"{enablePreviewFeatures}")));

                if (enablePreviewFeatures && !generateRequiresPreviewFeaturesAttribute)
                {
                    project.Root.Add(
                        new XElement(ns + "PropertyGroup",
                                     new XElement(ns + "GenerateRequiresPreviewFeaturesAttribute", $"False")));
                }
            });

            var buildCommand = new BuildCommand(testAsset);

            buildCommand.Execute().Should().Pass();

            var assemblyPath = Path.Combine(buildCommand.GetOutputDirectory(targetFramework).FullName, "HelloWorld.dll");

            var  parameterlessAttributes = AssemblyInfo.GetParameterlessAttributes(assemblyPath);
            bool contains = false;

            foreach (var attribute in parameterlessAttributes)
            {
                if (attribute.Equals("RequiresPreviewFeaturesAttribute", System.StringComparison.Ordinal))
                {
                    contains = true;
                    break;
                }
            }

            var getValuesCommand = new GetValuesCommand(testAsset, "LangVersion", targetFramework: targetFramework);

            getValuesCommand.Execute().Should().Pass();

            var values      = getValuesCommand.GetValues();
            var langVersion = values.FirstOrDefault() ?? string.Empty;

            if (enablePreviewFeatures && generateRequiresPreviewFeaturesAttribute)
            {
                if (targetFramework == ToolsetInfo.CurrentTargetFramework)
                {
                    Assert.Equal("Preview", langVersion);
                    Assert.True(contains);
                }
                else
                {
                    // The assembly level attribute is generated only for the latest TFM for the given sdk
                    Assert.False(contains);
                    Assert.NotEqual("Preview", langVersion);
                }
            }

            if (!generateRequiresPreviewFeaturesAttribute)
            {
                Assert.False(contains);
            }
        }
        public void AoT_Publish_HostedAppWithScopedCss_VisualStudio()
        {
            // Simulates publishing the same way VS does by setting BuildProjectReferences=false.
            var testAppName  = "BlazorHosted";
            var testInstance = CreateAspNetSdkTestAssetWithAot(testAppName, new [] { "blazorwasm", "blazorhosted" });

            File.WriteAllText(Path.Combine(testInstance.TestRoot, "blazorwasm", "App.razor.css"), "h1 { font-size: 16px; }");

            // VS builds projects individually and then a publish with BuildDependencies=false, but building the main project is a close enough approximation for this test.
            var buildCommand = new BuildCommand(testInstance, "blazorwasm");

            buildCommand.Execute("/p:BuildInsideVisualStudio=true /p:Configuration=Release").Should().Pass();

            // Publish
            var publishCommand = new PublishCommand(Log, Path.Combine(testInstance.TestRoot, "blazorhosted"));

            publishCommand.Execute("/p:BuildProjectReferences=false /p:BuildInsideVisualStudio=true /p:Configuration=Release").Should().Pass();

            var publishDirectory       = publishCommand.GetOutputDirectory(DefaultTfm);
            var blazorPublishDirectory = Path.Combine(publishDirectory.ToString(), "wwwroot");

            // Make sure the main project exists
            new FileInfo(Path.Combine(publishDirectory.ToString(), "blazorhosted.dll")).Should().Exist();

            // Verification for https://github.com/dotnet/aspnetcore/issues/19926. Verify binaries for projects
            // referenced by the Hosted project appear in the publish directory
            publishDirectory.Should().HaveFiles(new[]
            {
                "RazorClassLibrary.dll",
                "blazorwasm.dll"
            });

            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/_framework/blazor.boot.json",
                "wwwroot/_framework/blazor.webassembly.js",
                "wwwroot/_framework/dotnet.wasm",
                "wwwroot/_framework/blazorwasm.dll",
                "wwwroot/_framework/System.Text.Json.dll"
            });

            // Verify project references appear as static web assets
            // Also verify project references to the server project appear in the publish output
            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/_framework/RazorClassLibrary.dll",
                "RazorClassLibrary.dll"
            });

            // Verify static assets are in the publish directory
            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/index.html"
            });

            // Verify scoped css
            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/blazorwasm.styles.css"
            });

            // Verify static web assets from referenced projects are copied.
            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/_content/RazorClassLibrary/wwwroot/exampleJsInterop.js",
                "wwwroot/_content/RazorClassLibrary/styles.css",
            });

            // Verify web.config
            publishDirectory.Should().HaveFiles(new[]
            {
                "web.config"
            });

            VerifyBootManifestHashes(testInstance, Path.Combine(publishDirectory.ToString(), "wwwroot"));

            // Verify compression works
            publishDirectory.Should().HaveFiles(new[]
            {
                "wwwroot/_framework/dotnet.wasm.br",
                "wwwroot/_framework/blazorwasm.dll.br",
                "wwwroot/_framework/RazorClassLibrary.dll.br",
                "wwwroot/_framework/System.Text.Json.dll.br"
            });

            VerifyBootManifestHashes(testInstance, blazorPublishDirectory);
            VerifyServiceWorkerFiles(testInstance, blazorPublishDirectory,
                                     serviceWorkerPath: Path.Combine("serviceworkers", "my-service-worker.js"),
                                     serviceWorkerContent: "// This is the production service worker",
                                     assetsManifestPath: "custom-service-worker-assets.js");
        }
示例#20
0
        static async Task Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintUsageHeader();
                PrintUsage();
                Environment.Exit(-1);
            }

            Console.CancelKeyPress += (s, e) =>
            {
                ProcessHelper.KillActive();
                Environment.Exit(-1);
            };

            ICommand command = null;

            switch (args[0])
            {
            case StartElectronCommand.COMMAND_NAME:
                command = new StartElectronCommand(args.Skip(1).ToArray());
                break;

            case BuildCommand.COMMAND_NAME:
                command = new BuildCommand(args.Skip(1).ToArray());
                break;

            case InitCommand.COMMAND_NAME:
                command = new InitCommand(args.Skip(1).ToArray());
                break;

            case AddCommand.COMMAND_NAME:
                command = new AddCommand(args.Skip(1).ToArray());
                break;

            case VersionCommand.COMMAND_NAME:
                command = new VersionCommand(args.Skip(1).ToArray());
                break;

            case "--help":
            case "--h":
            case "help":
                PrintUsageHeader();

                if (args.Length > 1)
                {
                    PrintUsage(args[1]);
                }
                else
                {
                    PrintUsage();
                }
                break;

            default:
                Console.Error.WriteLine($"Unknown command {args[0]}");
                PrintUsage();
                Environment.Exit(-1);
                break;
            }

            if (command != null)
            {
                var success = await command.ExecuteAsync();

                if (!success)
                {
                    Environment.Exit(-1);
                }
            }
        }
示例#21
0
 /// <summary>
 /// Basic constructor with staging dir suffix override, basically to avoid having platform concatenated
 /// </summary>
 public BuildPatchToolStagingInfo(BuildCommand InOwnerCommand, string InAppName, string InMcpConfigKey, int InAppID, string InBuildVersion, MCPPlatform platform, string stagingDirRelativePath, string stagingDirSuffix)
 {
     OwnerCommand = InOwnerCommand;
     AppName = InAppName;
     McpConfigKey = InMcpConfigKey;
     AppID = InAppID;
     BuildVersion = InBuildVersion;
     Platform = platform;
     var BuildRootPath = GetBuildRootPath();
     StagingDir = CommandUtils.CombinePaths(BuildRootPath, stagingDirRelativePath, BuildVersion, stagingDirSuffix);
     CloudDirRelativePath = CommandUtils.CombinePaths(stagingDirRelativePath, "CloudDir");
     CloudDir = CommandUtils.CombinePaths(BuildRootPath, CloudDirRelativePath);
 }
示例#22
0
        private void DownloadLatestPOFile(XLocApiClient XLocApiClient, string AuthToken, string Culture, ProjectImportExportInfo ProjectImportInfo)
        {
            var XLocFilename = GetXLocFilename(ProjectImportInfo.PortableObjectName);

            // This will throw if the requested culture is invalid, but we don't want to let that kill the whole gather
            var LatestBuildXml = "";

            try
            {
                var EpicCultureToXLocLanguageId = GetEpicCultureToXLocLanguageId();
                LatestBuildXml = RequestLatestBuild(XLocApiClient, AuthToken, EpicCultureToXLocLanguageId[Culture], XLocFilename);
            }
            catch (Exception Ex)
            {
                BuildCommand.LogWarning("RequestLatestBuild failed for {0}. {1}", Culture, Ex);
                return;
            }
            if (String.IsNullOrEmpty(LatestBuildXml))
            {
                Console.WriteLine("[IGNORED] '{0}' has no build data ({1})", XLocFilename, Culture);
                return;
            }

            var POFileUri    = "";
            var BuildsXmlDoc = new XmlDocument();

            BuildsXmlDoc.LoadXml(LatestBuildXml);

            var BuildElem = BuildsXmlDoc["Build"];

            if (BuildElem != null)
            {
                var BuildFilesElem = BuildElem["BuildFiles"];
                if (BuildFilesElem != null)
                {
                    foreach (XmlNode BuildFile in BuildFilesElem)
                    {
                        bool IsCorrectFile = false;

                        // Is this the file we want?
                        var GameFileElem = BuildFile["GameFile"];
                        if (GameFileElem != null)
                        {
                            var GameFileNameElem = GameFileElem["Name"];
                            if (GameFileNameElem != null && GameFileNameElem.InnerText == XLocFilename)
                            {
                                IsCorrectFile = true;
                            }
                        }

                        if (IsCorrectFile)
                        {
                            var BuildFileDownloadUriElem = BuildFile["DownloadUri"];
                            if (BuildFileDownloadUriElem != null)
                            {
                                POFileUri = BuildFileDownloadUriElem.InnerText;
                                break;
                            }
                        }
                    }
                }
            }

            if (!String.IsNullOrEmpty(POFileUri))
            {
                var DestinationDirectory = new DirectoryInfo(CommandUtils.CombinePaths(RootWorkingDirectory, ProjectImportInfo.DestinationPath));
                var CultureDirectory     = (ProjectImportInfo.bUseCultureDirectory) ? new DirectoryInfo(Path.Combine(DestinationDirectory.FullName, Culture)) : DestinationDirectory;
                if (!CultureDirectory.Exists)
                {
                    CultureDirectory.Create();
                }

                var HTTPRequest = WebRequest.Create(POFileUri);
                HTTPRequest.Method = "GET";
                using (var Response = (HttpWebResponse)XLocUtils.GetWebResponse(HTTPRequest))
                {
                    if (Response.StatusCode != HttpStatusCode.OK)
                    {
                        BuildCommand.LogWarning("HTTP Request to '{0}' failed. {1}", POFileUri, Response.StatusDescription);
                        return;
                    }

                    using (var ResponseStream = Response.GetResponseStream())
                    {
                        var ExportFile = new FileInfo(Path.Combine(CultureDirectory.FullName, ProjectImportInfo.PortableObjectName));

                        // Write out the updated PO file so that the gather commandlet will import the new data from it
                        {
                            var ExportFileWasReadOnly = false;
                            if (ExportFile.Exists)
                            {
                                // We're going to clobber the existing PO file, so make sure it's writable (it may be read-only if in Perforce)
                                ExportFileWasReadOnly = ExportFile.IsReadOnly;
                                ExportFile.IsReadOnly = false;
                            }

                            using (var FileStream = ExportFile.Open(FileMode.Create))
                            {
                                ResponseStream.CopyTo(FileStream);
                                Console.WriteLine("[SUCCESS] Exporting: '{0}' as '{1}' ({2})", XLocFilename, ExportFile.FullName, Culture);
                            }

                            if (ExportFileWasReadOnly)
                            {
                                ExportFile.IsReadOnly = true;
                            }
                        }

                        // Also update the back-up copy so we can diff against what we got from XLoc, and what the gather commandlet produced
                        {
                            var ExportFileCopy = new FileInfo(Path.Combine(ExportFile.DirectoryName, String.Format("{0}_FromXLoc{1}", Path.GetFileNameWithoutExtension(ExportFile.Name), ExportFile.Extension)));

                            var ExportFileCopyWasReadOnly = false;
                            if (ExportFileCopy.Exists)
                            {
                                // We're going to clobber the existing PO file, so make sure it's writable (it may be read-only if in Perforce)
                                ExportFileCopyWasReadOnly = ExportFileCopy.IsReadOnly;
                                ExportFileCopy.IsReadOnly = false;
                            }

                            ExportFile.CopyTo(ExportFileCopy.FullName, true);

                            if (ExportFileCopyWasReadOnly)
                            {
                                ExportFileCopy.IsReadOnly = true;
                            }

                            // Add/check out backed up POs from OneSky.
                            if (CommandUtils.P4Enabled)
                            {
                                UE4Build.AddBuildProductsToChangelist(PendingChangeList, new List <string>()
                                {
                                    ExportFileCopy.FullName
                                });
                            }
                        }
                    }
                }
            }
        }
示例#23
0
        public void COMReferenceProperlyPublish()
        {
            var targetFramework = "netcoreapp3.0";

            var testProject = new TestProject
            {
                Name             = "MultiComReference",
                TargetFrameworks = targetFramework,
                IsExe            = true,
                SourceFiles      =
                {
                    ["Program.cs"] = @"
                            class Program
                            {
                                static void Main(string[] args)
                                {
                                }
                            }
                        "
                }
            };

            var vslangProj70ComRef = "VSLangProj.dll";
            var reference1         = new XElement("ItemGroup",
                                                  new XElement("COMReference",
                                                               new XAttribute("Include", vslangProj70ComRef),
                                                               new XElement("Guid", "49a1950e-3e35-4595-8cb9-920c64c44d67"),
                                                               new XElement("VersionMajor", "7"),
                                                               new XElement("VersionMinor", "0"),
                                                               new XElement("WrapperTool", "tlbimp"),
                                                               new XElement("Lcid", "0"),
                                                               new XElement("Isolated", "false"),
                                                               new XElement("EmbedInteropTypes", "false")));

            var vslangProj80ComRef = "VSLangProj80.dll";
            var reference2         = new XElement("ItemGroup",
                                                  new XElement("COMReference",
                                                               new XAttribute("Include", vslangProj80ComRef),
                                                               new XElement("Guid", "307953c0-7973-490a-a4a7-25999e023be8"),
                                                               new XElement("VersionMajor", "8"),
                                                               new XElement("VersionMinor", "0"),
                                                               new XElement("WrapperTool", "tlbimp"),
                                                               new XElement("Lcid", "0"),
                                                               new XElement("Isolated", "false"),
                                                               new XElement("EmbedInteropTypes", "false")));

            var testAsset = _testAssetsManager
                            .CreateTestProject(testProject)
                            .WithProjectChanges(doc => doc.Root.Add(new[] { reference1, reference2 }));

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, testProject.Name));

            buildCommand.Execute().Should().Pass();

            var outputDirectory = buildCommand.GetOutputDirectory(targetFramework);

            // COM References by default adds the 'Interop.' prefix.
            Assert.True(outputDirectory.File($"Interop.{vslangProj70ComRef}").Exists);
            Assert.True(outputDirectory.File($"Interop.{vslangProj80ComRef}").Exists);

            var publishCommand = new PublishCommand(testAsset);

            publishCommand.Execute().Should().Pass();

            outputDirectory = publishCommand.GetOutputDirectory(targetFramework);

            // COM References by default adds the 'Interop.' prefix.
            Assert.True(outputDirectory.File($"Interop.{vslangProj70ComRef}").Exists);
            Assert.True(outputDirectory.File($"Interop.{vslangProj80ComRef}").Exists);
        }
        private void TestZipFileSharing(bool useSdk, [CallerMemberName] string callingMethod = "")
        {
            var testProject = new TestProject()
            {
                Name         = "Net471ZipFileTest",
                IsExe        = true,
                IsSdkProject = useSdk
            };

            if (useSdk)
            {
                testProject.TargetFrameworks = "net471";
            }
            else
            {
                testProject.TargetFrameworkVersion = "v4.7.1";
            }

            testProject.PackageReferences.AddRange(new[]
            {
                new TestPackageReference("System.IO.Compression.ZipFile", "4.3.0")
            });


            var netStandardProject = new TestProject()
            {
                Name             = "NetStandard16_Library",
                TargetFrameworks = "netstandard1.6",
                IsSdkProject     = true
            };

            netStandardProject.PackageReferences.AddRange(new[]
            {
                new TestPackageReference("System.IO.Compression.ZipFile", "4.3.0")
            });

            testProject.ReferencedProjects.Add(netStandardProject);

            testProject.SourceFiles["Program.cs"] = $@"
using System;
public static class Program
{{
    public static int Main()
    {{
        bool success = true;

        Type[] nsTypes = NS16LibClass.GetTypes();
        Type[] appTypes = new Type[]
        {{
            typeof(System.IO.Compression.ZipArchive),
            typeof(System.IO.Compression.ZipArchiveEntry),
            typeof(System.IO.Compression.ZipArchiveMode),
            typeof(System.IO.Compression.ZipFile),
            typeof(System.IO.Compression.ZipFileExtensions),
        }};

        if (nsTypes.Length != appTypes.Length)
        {{
            Console.WriteLine($""Error: Types count in NS library {{ nsTypes.Length}} is not equal to the types count in the app {{ appTypes.Length}} "");
            return 1;
        }}

        for (int i = 0; i < nsTypes.Length; i++)
        {{
            if (!nsTypes[i].Equals(appTypes[i]))
            {{
                Console.WriteLine($""{{nsTypes[i].FullName}}"");
                success = false;
            }}
        }}

        if (success)
        {{
            Console.WriteLine(""Success"");
            return 0;
        }}
        return 1;
    }}
}}
";

            netStandardProject.SourceFiles["NSTypes.cs"] = $@"
using System;
public static class NS16LibClass
{{
    public static Type [] GetTypes()
    {{
        return new Type[]
        {{
            typeof(System.IO.Compression.ZipArchive),
            typeof(System.IO.Compression.ZipArchiveEntry),
            typeof(System.IO.Compression.ZipArchiveMode),
            typeof(System.IO.Compression.ZipFile),
            typeof(System.IO.Compression.ZipFileExtensions),
        }};
    }}
}}
";
            var testAsset = _testAssetsManager.CreateTestProject(testProject, callingMethod: callingMethod, identifier: useSdk ? "_sdk" : string.Empty)
                            .WithProjectChanges((projectPath, project) =>
            {
                if (Path.GetFileNameWithoutExtension(projectPath) == testProject.Name)
                {
                    string folder = Path.GetDirectoryName(projectPath);

                    //  Adding this binding redirect is the workaround for ZipFile on .NET 4.7.1
                    //  See https://github.com/Microsoft/dotnet/blob/master/releases/net471/KnownIssues/623552-BCL%20Higher%20assembly%20versions%20that%204.0.0.0%20for%20System.IO.Compression.ZipFile%20cannot%20be%20loaded%20without%20a%20binding%20redirect.md
                    File.WriteAllText(Path.Combine(folder, "app.config"),
                                      @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <runtime>
    <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
      <dependentAssembly>
        <assemblyIdentity name=""System.IO.Compression.ZipFile"" publicKeyToken=""b77a5c561934e089"" culture=""neutral"" />
        <bindingRedirect oldVersion=""0.0.0.0-4.0.2.0"" newVersion=""4.0.0.0"" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
");
                    var ns = project.Root.Name.Namespace;

                    project.Root.Elements(ns + "ItemGroup").Last().Add(
                        new XElement(ns + "None", new XAttribute("Include", "app.config")));
                }
            });

            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute("/v:m")
            .Should()
            .Pass()
            .And
            //  warning MSB3836: The explicit binding redirect on "System.IO.Compression.ZipFile, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            //  conflicts with an autogenerated binding redirect. Consider removing it from the application configuration file or disabling
            //  autogenerated binding redirects. The build will replace it with: "<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0"
            //  xmlns="urn:schemas-microsoft-com:asm.v1" />"
            .NotHaveStdOutContaining("MSB3836");

            var exePath = Path.Combine(buildCommand.GetOutputDirectory(testProject.TargetFrameworks).FullName, testProject.Name + ".exe");

            new RunExeCommand(Log, exePath)
            .Execute()
            .Should()
            .Pass();
        }
示例#25
0
        public void It_builds_a_runnable_output(string targetFramework, bool dependenciesIncluded)
        {
            if (!EnvironmentInfo.SupportsTargetFramework(targetFramework))
            {
                return;
            }

            var runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework);
            var testAsset         = _testAssetsManager
                                    .CopyTestAsset("HelloWorld", identifier: targetFramework)
                                    .WithSource()
                                    .WithTargetFramework(targetFramework)
                                    .WithProjectChanges(project =>
            {
                var ns            = project.Root.Name.Namespace;
                var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
                propertyGroup.Add(new XElement(ns + "RuntimeIdentifier", runtimeIdentifier));
            });

            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var outputDirectory         = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier);
            var selfContainedExecutable = $"HelloWorld{Constants.ExeSuffix}";

            string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable);

            string[] expectedFiles = new[] {
                selfContainedExecutable,
                "HelloWorld.dll",
                "HelloWorld.pdb",
                "HelloWorld.deps.json",
                "HelloWorld.runtimeconfig.dev.json",
                "HelloWorld.runtimeconfig.json",
                $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}",
                $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}",
            };

            if (dependenciesIncluded)
            {
                outputDirectory.Should().HaveFiles(expectedFiles);
            }
            else
            {
                outputDirectory.Should().OnlyHaveFiles(expectedFiles);
            }

            outputDirectory.Should().NotHaveFiles(new[] {
                $"apphost{Constants.ExeSuffix}",
            });

            new RunExeCommand(Log, selfContainedExecutableFullPath)
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("Hello World!");
        }
        public void HttpClient_can_be_used_in_project_references()
        {
            var referencedProject = new TestProject()
            {
                Name                   = "ReferencedHttpClientProject",
                IsExe                  = false,
                IsSdkProject           = false,
                TargetFrameworkVersion = "v4.7.1"
            };

            referencedProject.PackageReferences.Add(new TestPackageReference("dotless.Core", "1.6.4"));
            referencedProject.PackageReferences.Add(new TestPackageReference("Microsoft.Owin.Security.Facebook", "4.0.0"));

            referencedProject.SourceFiles["FacebookHandler.cs"] = @"
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public class FacebookHandler : HttpClientHandler
{
	protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
	{
        return await base.SendAsync(request, cancellationToken);
    }
}";

            var testProject = new TestProject()
            {
                Name                   = "Net471HttpClientTest",
                IsExe                  = true,
                IsSdkProject           = false,
                TargetFrameworkVersion = "v4.7.1"
            };

            testProject.AdditionalProperties["RestoreProjectStyle"] = "PackageReference";

            testProject.ReferencedProjects.Add(referencedProject);
            testProject.SourceFiles["Program.cs"] = @"
using Microsoft.Owin.Security.Facebook;
using Owin;

public class Startup
{
    public static void Main(string [] args)
    {
    }

    public void Configuration(IAppBuilder app)
    {
        var facebookOptions = new FacebookAuthenticationOptions
        {
            BackchannelHttpHandler = new FacebookHandler()
        };
    }
}
";

            var testAsset = _testAssetsManager.CreateTestProject(testProject)
                            .WithProjectChanges((projectPath, project) =>
            {
                if (Path.GetFileNameWithoutExtension(projectPath) == testProject.Name)
                {
                    var ns = project.Root.Name.Namespace;

                    //  Add target which helped trigger the error case.  A target like this was provided as
                    //  a workaround to a different issue: https://github.com/dotnet/sdk/pull/1582#issuecomment-329571228
                    var reproTarget = XElement.Parse(@"
  <Target Name=""AddAdditionalReference"" AfterTargets=""ImplicitlyExpandNETStandardFacades"">
    <ItemGroup>
      <Reference Include = ""@(_NETStandardLibraryNETFrameworkLib)"" Condition = ""'%(FileName)' == 'system.net.http'"">
        <Private>true</Private>
      </Reference>
    </ItemGroup>
  </Target> ");
                    foreach (var element in reproTarget.DescendantsAndSelf())
                    {
                        element.Name = ns + element.Name.LocalName;
                    }
                    project.Root.Add(reproTarget);
                }
            });

            var buildCommand = new BuildCommand(testAsset);

            buildCommand.Execute().Should().Pass();
        }
        public void It_does_not_include_netstandard_when_inbox(bool isSdk)
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset(GetTemplateName(isSdk))
                            .WithSource()
                            .WithProjectChanges((projectPath, project) =>
            {
                if (IsAppProject(projectPath))
                {
                    AddReferenceToLibrary(project, ReferenceScenario.ProjectReference);

                    // Add a target that replaces the facade folder with the set of netstandard support assemblies
                    // this can be replaced by targeting the version of .NETFramework that includes netstandard inbox,
                    // once available
                    var facadesDir = Path.Combine(RepoInfo.BuildExtensionsMSBuildPath, "net461", "ref\\");
                    var ns         = project.Root.Name.Namespace;
                    var target     = new XElement(ns + "Target",
                                                  new XAttribute("Name", "ReplaceDesignTimeFacadeDirectories"),
                                                  new XAttribute("AfterTargets", "GetReferenceAssemblyPaths"));
                    project.Root.Add(target);

                    var itemGroup = new XElement(ns + "ItemGroup");
                    target.Add(itemGroup);

                    itemGroup.Add(new XElement(ns + "_UpdateTargetFrameworkDirectory",
                                               new XAttribute("Include", "$(TargetFrameworkDirectory);" + facadesDir),
                                               new XAttribute("Exclude", "@(DesignTimeFacadeDirectories)")));

                    itemGroup.Add(new XElement(ns + "DesignTimeFacadeDirectories",
                                               new XAttribute("Remove", "@(DesignTimeFacadeDirectories)")));
                    itemGroup.Add(new XElement(ns + "DesignTimeFacadeDirectories",
                                               new XAttribute("Include", facadesDir)));

                    var propertyGroup = new XElement(ns + "PropertyGroup");
                    target.Add(propertyGroup);

                    propertyGroup.Add(new XElement(ns + "TargetFrameworkDirectory", "@(_UpdateTargetFrameworkDirectory)"));

                    // currently RAR doesn't detect when netstandard is referenced, directly set _HasReferenceToSystemRuntime
                    // this will be fixed once netstandard is inbox
                    // ISSUE: https://github.com/Microsoft/msbuild/issues/2199
                    propertyGroup.Add(new XElement(ns + "_HasReferenceToSystemRuntime", "True"));
                }
            });

            testAsset.Restore(Log, relativePath: AppName);

            var buildCommand = new BuildCommand(Log, Path.Combine(testAsset.TestRoot, AppName));

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var outputDirectory = isSdk ?
                                  buildCommand.GetOutputDirectory("net461") :
                                  buildCommand.GetNonSDKOutputDirectory();

            outputDirectory.Should().OnlyHaveFiles(new[] {
                "TestApp.exe",
                "TestApp.pdb",
                "TestLibrary.dll",
                "TestLibrary.pdb"
            });
        }
        public void It_builds_the_project_successfully()
        {
            var testAsset = _testAssetsManager
                            .CopyTestAsset("AppWithLibrary")
                            .WithSource();

            testAsset.Restore("TestApp");
            testAsset.Restore("TestLibrary");

            var appProjectDirectory = Path.Combine(testAsset.TestRoot, "TestApp");

            var buildCommand = new BuildCommand(Stage0MSBuild, appProjectDirectory);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            var outputDirectory = buildCommand.GetOutputDirectory("netcoreapp1.0");

            outputDirectory.Should().OnlyHaveFiles(new[] {
                "TestApp.dll",
                "TestApp.pdb",
                "TestApp.deps.json",
                "TestApp.runtimeconfig.json",
                "TestApp.runtimeconfig.dev.json",
                "TestLibrary.dll",
                "TestLibrary.pdb",
            });

            Command.Create(RepoInfo.DotNetHostPath, new[] { Path.Combine(outputDirectory.FullName, "TestApp.dll") })
            .CaptureStdOut()
            .Execute()
            .Should()
            .Pass()
            .And
            .HaveStdOutContaining("This string came from the test library!");

            var appInfo = FileVersionInfo.GetVersionInfo(Path.Combine(outputDirectory.FullName, "TestApp.dll"));

            appInfo.CompanyName.Should().Be("Test Authors");
            appInfo.FileVersion.Should().Be("1.2.3.0");
            appInfo.FileDescription.Should().Be("Test AssemblyTitle");
            appInfo.LegalCopyright.Should().Be("Copyright (c) Test Authors");
            appInfo.ProductName.Should().Be("Test Product");

            // This check is blocked from working on non-Windows by https://github.com/dotnet/corefx/issues/11163
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                appInfo.ProductVersion.Should().Be("1.2.3-beta");
            }

            var libInfo = FileVersionInfo.GetVersionInfo(Path.Combine(outputDirectory.FullName, "TestLibrary.dll"));

            libInfo.CompanyName.Trim().Should().Be("TestLibrary");
            libInfo.FileVersion.Should().Be("42.43.44.45");
            libInfo.FileDescription.Should().Be("TestLibrary");
            libInfo.LegalCopyright.Trim().Should().BeEmpty();
            libInfo.ProductName.Should().Be("TestLibrary");

            // This check is blocked from working on non-Windows by https://github.com/dotnet/corefx/issues/11163
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                libInfo.ProductVersion.Should().Be("42.43.44.45-alpha");
            }
        }
        private void TestInvalidTargetFramework(string testName, string targetFramework, bool useSolution, string expectedOutput)
        {
            var testProject = new TestProject()
            {
                Name             = testName,
                TargetFrameworks = targetFramework,
            };

            string identifier = ((useSolution ? "_Solution" : "") + targetFramework + expectedOutput).GetHashCode().ToString();
            var    testAsset  = _testAssetsManager.CreateTestProject(testProject, testProject.Name, identifier);

            if (targetFramework.Contains(";"))
            {
                //  The TestProject class doesn't differentiate between TargetFramework and TargetFrameworks, and helpfully selects
                //  which property to use based on whether there's a semicolon.
                //  For this test, we need to override this behavior
                testAsset = testAsset.WithProjectChanges(project =>
                {
                    var ns = project.Root.Name.Namespace;

                    project.Root.Element(ns + "PropertyGroup")
                    .Element(ns + "TargetFrameworks")
                    .Name = ns + "TargetFramework";
                });
            }

            RestoreCommand restoreCommand;
            BuildCommand   buildCommand;

            if (useSolution)
            {
                var dotnetCommand = new DotnetCommand(Log)
                {
                    WorkingDirectory = testAsset.TestRoot
                };

                dotnetCommand.Execute("new", "sln")
                .Should()
                .Pass();

                var relativePathToProject = Path.Combine(testProject.Name, testProject.Name + ".csproj");
                dotnetCommand.Execute($"sln", "add", relativePathToProject)
                .Should()
                .Pass();

                var relativePathToSln = Path.GetFileName(testAsset.Path) + ".sln";

                restoreCommand = testAsset.GetRestoreCommand(Log, relativePathToSln);
                buildCommand   = new BuildCommand(testAsset, relativePathToSln);
            }
            else
            {
                restoreCommand = testAsset.GetRestoreCommand(Log, testProject.Name);
                buildCommand   = new BuildCommand(testAsset);
            }

            //  Set RestoreContinueOnError=ErrorAndContinue to force failure on error
            //  See https://github.com/NuGet/Home/issues/5309
            var restore = restoreCommand.Execute("/p:RestoreContinueOnError=ErrorAndContinue");

            // Intentionally not checking the error message on restore here as we can't put ourselves in front of
            // restore and customize the message for invalid target frameworks as that would break restoring packages
            // like MSBuild.Sdk.Extras that add support for extra TFMs.
            restore.Should().Fail();

            buildCommand
            .ExecuteWithoutRestore()
            .Should()
            .Fail()
            .And
            .HaveStdOutContaining(expectedOutput)
            .And.NotHaveStdOutContaining(">=");     // old error about comparing empty string to version when TargetFramework was blank;
        }
    public static void Build(BuildCommand Command, ProjectParams Params, int WorkingCL = -1, ProjectBuildTargets TargetMask = ProjectBuildTargets.All)
    {
        Params.ValidateAndLog();

        if (!Params.Build)
        {
            return;
        }

        Log("********** BUILD COMMAND STARTED **********");

        var UE4Build             = new UE4Build(Command);
        var Agenda               = new UE4Build.BuildAgenda();
        var CrashReportPlatforms = new HashSet <UnrealTargetPlatform>();

        // Setup editor targets
        if (Params.HasEditorTargets && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.Editor) == ProjectBuildTargets.Editor)
        {
            // @todo Mac: proper platform detection
            UnrealTargetPlatform            EditorPlatform      = HostPlatform.Current.HostEditorPlatform;
            const UnrealTargetConfiguration EditorConfiguration = UnrealTargetConfiguration.Development;

            CrashReportPlatforms.Add(EditorPlatform);
            Agenda.AddTargets(Params.EditorTargets.ToArray(), EditorPlatform, EditorConfiguration, Params.CodeBasedUprojectPath);
            if (Params.EditorTargets.Contains("UnrealHeaderTool") == false)
            {
                Agenda.AddTargets(new string[] { "UnrealHeaderTool" }, EditorPlatform, EditorConfiguration);
            }
            if (Params.EditorTargets.Contains("ShaderCompileWorker") == false)
            {
                Agenda.AddTargets(new string[] { "ShaderCompileWorker" }, EditorPlatform, EditorConfiguration);
            }
            if (Params.Pak && Params.EditorTargets.Contains("UnrealPak") == false)
            {
                Agenda.AddTargets(new string[] { "UnrealPak" }, EditorPlatform, EditorConfiguration);
            }
            if (Params.FileServer && Params.EditorTargets.Contains("UnrealFileServer") == false)
            {
                Agenda.AddTargets(new string[] { "UnrealFileServer" }, EditorPlatform, EditorConfiguration);
            }
        }

        // Setup cooked targets
        if (Params.HasClientCookedTargets && (TargetMask & ProjectBuildTargets.ClientCooked) == ProjectBuildTargets.ClientCooked)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
            {
                foreach (var ClientPlatformType in UniquePlatformTypes)
                {
                    string ScriptPluginArgs = GetBlueprintPluginPathArgument(Params, true, ClientPlatformType);
                    CrashReportPlatforms.Add(ClientPlatformType);
                    Agenda.AddTargets(Params.ClientCookedTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: ScriptPluginArgs + " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
                }
            }
        }
        if (Params.HasServerCookedTargets && (TargetMask & ProjectBuildTargets.ServerCooked) == ProjectBuildTargets.ServerCooked)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ServerTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ServerConfigsToBuild)
            {
                foreach (var ServerPlatformType in UniquePlatformTypes)
                {
                    string ScriptPluginArgs = GetBlueprintPluginPathArgument(Params, false, ServerPlatformType);
                    CrashReportPlatforms.Add(ServerPlatformType);
                    Agenda.AddTargets(Params.ServerCookedTargets.ToArray(), ServerPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: ScriptPluginArgs + " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
                }
            }
        }
        if (!Params.NoBootstrapExe && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.Bootstrap) == ProjectBuildTargets.Bootstrap)
        {
            UnrealBuildTool.UnrealTargetPlatform[] BootstrapPackagedGamePlatforms = { UnrealBuildTool.UnrealTargetPlatform.Win32, UnrealBuildTool.UnrealTargetPlatform.Win64 };
            foreach (UnrealBuildTool.UnrealTargetPlatform BootstrapPackagedGamePlatformType in BootstrapPackagedGamePlatforms)
            {
                if (Params.ClientTargetPlatforms.Contains(new TargetPlatformDescriptor(BootstrapPackagedGamePlatformType)))
                {
                    Agenda.AddTarget("BootstrapPackagedGame", BootstrapPackagedGamePlatformType, UnrealBuildTool.UnrealTargetConfiguration.Shipping);
                }
            }
        }
        if (Params.CrashReporter && !Automation.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.CrashReporter) == ProjectBuildTargets.CrashReporter)
        {
            foreach (var CrashReportPlatform in CrashReportPlatforms)
            {
                if (PlatformSupportsCrashReporter(CrashReportPlatform))
                {
                    Agenda.AddTarget("CrashReportClient", CrashReportPlatform, UnrealTargetConfiguration.Shipping, InAddArgs: " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
                }
            }
        }
        if (Params.HasProgramTargets && (TargetMask & ProjectBuildTargets.Programs) == ProjectBuildTargets.Programs)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
            {
                foreach (var ClientPlatformType in UniquePlatformTypes)
                {
                    Agenda.AddTargets(Params.ProgramTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath);
                }
            }
        }
        UE4Build.Build(Agenda, InDeleteBuildProducts: Params.Clean, InUpdateVersionFiles: WorkingCL > 0);

        if (WorkingCL > 0)         // only move UAT files if we intend to check in some build products
        {
            UE4Build.AddUATFilesToBuildProducts();
        }
        UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);

        if (WorkingCL > 0)
        {
            // Sign everything we built
            CodeSign.SignMultipleIfEXEOrDLL(Command, UE4Build.BuildProductFiles);

            // Open files for add or edit
            UE4Build.AddBuildProductsToChangelist(WorkingCL, UE4Build.BuildProductFiles);
        }

        Log("********** BUILD COMMAND COMPLETED **********");
    }
示例#31
0
    public static void Build(BuildCommand Command, ProjectParams Params, int WorkingCL = -1, ProjectBuildTargets TargetMask = ProjectBuildTargets.All)
    {
        Params.ValidateAndLog();

        if (!Params.Build)
        {
            return;
        }
        if (CommandUtils.IsEngineInstalled() && !Params.IsCodeBasedProject)
        {
            return;
        }

        LogInformation("********** BUILD COMMAND STARTED **********");

        var UE4Build             = new UE4Build(Command);
        var Agenda               = new UE4Build.BuildAgenda();
        var CrashReportPlatforms = new HashSet <UnrealTargetPlatform>();

        // Setup editor targets
        if (Params.HasEditorTargets && (!Params.SkipBuildEditor) && (TargetMask & ProjectBuildTargets.Editor) == ProjectBuildTargets.Editor)
        {
            // @todo Mac: proper platform detection
            UnrealTargetPlatform            EditorPlatform      = HostPlatform.Current.HostEditorPlatform;
            const UnrealTargetConfiguration EditorConfiguration = UnrealTargetConfiguration.Development;

            Agenda.AddTargets(Params.EditorTargets.ToArray(), EditorPlatform, EditorConfiguration, Params.CodeBasedUprojectPath);

            if (!CommandUtils.IsEngineInstalled())
            {
                CrashReportPlatforms.Add(EditorPlatform);
                if (Params.EditorTargets.Contains("UnrealHeaderTool") == false)
                {
                    Agenda.AddTargets(new string[] { "UnrealHeaderTool" }, EditorPlatform, EditorConfiguration);
                    Agenda.AddTargets(new string[] { "UnrealHeaderTool" }, EditorPlatform, EditorConfiguration, Params.CodeBasedUprojectPath);
                }
                if (Params.EditorTargets.Contains("ShaderCompileWorker") == false)
                {
                    Agenda.AddTargets(new string[] { "ShaderCompileWorker" }, EditorPlatform, EditorConfiguration);
                }
                if (Params.FileServer && Params.EditorTargets.Contains("UnrealFileServer") == false)
                {
                    Agenda.AddTargets(new string[] { "UnrealFileServer" }, EditorPlatform, EditorConfiguration);
                }
            }
        }

        // allow all involved platforms to hook into the agenda
        HashSet <UnrealTargetPlatform> UniquePlatforms = new HashSet <UnrealTargetPlatform>();

        UniquePlatforms.UnionWith(Params.ClientTargetPlatforms.Select(x => x.Type));
        UniquePlatforms.UnionWith(Params.ServerTargetPlatforms.Select(x => x.Type));
        foreach (UnrealTargetPlatform TargetPlatform in UniquePlatforms)
        {
            Platform.GetPlatform(TargetPlatform).PreBuildAgenda(UE4Build, Agenda, Params);
        }

        // Build any tools we need to stage
        if ((TargetMask & ProjectBuildTargets.UnrealPak) == ProjectBuildTargets.UnrealPak && !CommandUtils.IsEngineInstalled())
        {
            if (Params.EditorTargets.Contains("UnrealPak") == false)
            {
                Agenda.AddTargets(new string[] { "UnrealPak" }, HostPlatform.Current.HostEditorPlatform, UnrealTargetConfiguration.Development, Params.CodeBasedUprojectPath);
            }
        }

        // Additional compile arguments
        string AdditionalArgs = "";

        if (string.IsNullOrEmpty(Params.UbtArgs) == false)
        {
            string Arg = Params.UbtArgs;
            Arg             = Arg.TrimStart(new char[] { '\"' });
            Arg             = Arg.TrimEnd(new char[] { '\"' });
            AdditionalArgs += " " + Arg;
        }

        if (Params.MapFile)
        {
            AdditionalArgs += " -mapfile";
        }

        if (Params.Deploy || Params.Package)
        {
            AdditionalArgs += " -skipdeploy";             // skip deploy step in UBT if we going to do it later anyway
        }

        if (Params.Distribution)
        {
            AdditionalArgs += " -distribution";
        }

        // Config overrides (-ini)
        foreach (string ConfigOverrideParam in Params.ConfigOverrideParams)
        {
            AdditionalArgs += " -";
            AdditionalArgs += ConfigOverrideParam;
        }

        // Setup cooked targets
        if (Params.HasClientCookedTargets && (!Params.SkipBuildClient) && (TargetMask & ProjectBuildTargets.ClientCooked) == ProjectBuildTargets.ClientCooked)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
            {
                foreach (var ClientPlatformType in UniquePlatformTypes)
                {
                    CrashReportPlatforms.Add(ClientPlatformType);
                    Agenda.AddTargets(Params.ClientCookedTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"" + AdditionalArgs);
                }
            }
        }
        if (Params.HasServerCookedTargets && (TargetMask & ProjectBuildTargets.ServerCooked) == ProjectBuildTargets.ServerCooked)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ServerTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ServerConfigsToBuild)
            {
                foreach (var ServerPlatformType in UniquePlatformTypes)
                {
                    CrashReportPlatforms.Add(ServerPlatformType);
                    Agenda.AddTargets(Params.ServerCookedTargets.ToArray(), ServerPlatformType, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"" + AdditionalArgs);
                }
            }
        }
        if (!Params.NoBootstrapExe && !CommandUtils.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.Bootstrap) == ProjectBuildTargets.Bootstrap)
        {
            UnrealBuildTool.UnrealTargetPlatform[] BootstrapPackagedGamePlatforms = { UnrealBuildTool.UnrealTargetPlatform.Win32, UnrealBuildTool.UnrealTargetPlatform.Win64 };
            foreach (UnrealBuildTool.UnrealTargetPlatform BootstrapPackagedGamePlatformType in BootstrapPackagedGamePlatforms)
            {
                if (Params.ClientTargetPlatforms.Contains(new TargetPlatformDescriptor(BootstrapPackagedGamePlatformType)))
                {
                    Agenda.AddTarget("BootstrapPackagedGame", BootstrapPackagedGamePlatformType, UnrealBuildTool.UnrealTargetConfiguration.Shipping);
                }
            }
        }
        if (Params.CrashReporter && !CommandUtils.IsEngineInstalled() && (TargetMask & ProjectBuildTargets.CrashReporter) == ProjectBuildTargets.CrashReporter)
        {
            foreach (var CrashReportPlatform in CrashReportPlatforms)
            {
                if (PlatformSupportsCrashReporter(CrashReportPlatform))
                {
                    Agenda.AddTarget("CrashReportClient", CrashReportPlatform, UnrealTargetConfiguration.Shipping, InAddArgs: " -remoteini=\"" + Params.RawProjectPath.Directory.FullName + "\"");
                }
            }
        }
        if (Params.HasProgramTargets && (TargetMask & ProjectBuildTargets.Programs) == ProjectBuildTargets.Programs)
        {
            List <UnrealTargetPlatform> UniquePlatformTypes = Params.ClientTargetPlatforms.ConvertAll(x => x.Type).Distinct().ToList();

            foreach (var BuildConfig in Params.ClientConfigsToBuild)
            {
                foreach (var ClientPlatformType in UniquePlatformTypes)
                {
                    Agenda.AddTargets(Params.ProgramTargets.ToArray(), ClientPlatformType, BuildConfig, Params.CodeBasedUprojectPath);
                }
            }
        }
        UE4Build.Build(Agenda, InDeleteBuildProducts: Params.Clean, InUpdateVersionFiles: WorkingCL > 0);

        if (WorkingCL > 0)         // only move UAT files if we intend to check in some build products
        {
            UE4Build.AddUATFilesToBuildProducts();
        }
        UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);

        if (WorkingCL > 0)
        {
            // Sign everything we built
            CodeSign.SignMultipleIfEXEOrDLL(Command, UE4Build.BuildProductFiles);

            // Open files for add or edit
            UE4Build.AddBuildProductsToChangelist(WorkingCL, UE4Build.BuildProductFiles);
        }

        LogInformation("********** BUILD COMMAND COMPLETED **********");
    }
示例#32
0
        private void TestProject(string projectFolderOrFile, string testName, ProjectPerfOperation perfOperation, string restoreSources = null)
        {
            string testProjectPath;
            string testProjectDirectory;
            bool   projectFileSpecified;

            if (File.Exists(projectFolderOrFile))
            {
                projectFileSpecified = true;
                testProjectPath      = projectFolderOrFile;
                testProjectDirectory = Path.GetDirectoryName(projectFolderOrFile);
            }
            else
            {
                projectFileSpecified = false;
                testProjectPath      = Directory.GetFiles(projectFolderOrFile, "*.sln", SearchOption.AllDirectories).SingleOrDefault();
                if (testProjectPath == null)
                {
                    testProjectPath = Directory.GetFiles(projectFolderOrFile, "*.csproj", SearchOption.AllDirectories).SingleOrDefault();
                    if (testProjectPath == null)
                    {
                        throw new ArgumentException("Could not find project file to test in folder: " + projectFolderOrFile);
                    }
                }
                testProjectDirectory = Path.GetDirectoryName(testProjectPath);
            }

            TestCommand commandToTest;
            var         perfTest = new PerfTest();

            perfTest.ScenarioName = testName;

            if (perfOperation == ProjectPerfOperation.NoOpRestore)
            {
                TestCommand restoreCommand;

                if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild)
                {
                    restoreCommand = new RestoreCommand(Log, testProjectPath);
                }
                else
                {
                    restoreCommand = new RestoreCommand(Log, testProjectPath);
                    restoreCommand = new DotnetCommand(Log, "restore");
                    if (projectFileSpecified)
                    {
                        restoreCommand.Arguments.Add(testProjectPath);
                    }
                }
                if (!string.IsNullOrEmpty(restoreSources))
                {
                    restoreCommand.Arguments.Add($"/p:RestoreSources={restoreSources}");
                }
                restoreCommand.WorkingDirectory = testProjectDirectory;

                restoreCommand.Execute().Should().Pass();

                commandToTest     = restoreCommand;
                perfTest.TestName = "Restore (No-op)";
            }
            else
            {
                if (TestContext.Current.ToolsetUnderTest.ShouldUseFullFrameworkMSBuild)
                {
                    commandToTest = new BuildCommand(Log, projectFileSpecified ? testProjectPath : testProjectDirectory);
                    commandToTest.Arguments.Add("/restore");
                }
                else
                {
                    commandToTest = new DotnetCommand(Log, "build");
                    if (projectFileSpecified)
                    {
                        commandToTest.Arguments.Add(testProjectPath);
                    }
                }
                if (!string.IsNullOrEmpty(restoreSources))
                {
                    commandToTest.Arguments.Add($"/p:RestoreSources={restoreSources}");
                }
                commandToTest.WorkingDirectory = testProjectDirectory;

                if (perfOperation == ProjectPerfOperation.CleanBuild)
                {
                    perfTest.TestName = "Build";
                }
                else if (perfOperation == ProjectPerfOperation.BuildWithNoChanges)
                {
                    //  Build once before taking folder snapshot
                    commandToTest.Execute().Should().Pass();

                    perfTest.TestName = "Build (no changes)";
                }
                else
                {
                    throw new ArgumentException("Unexpected perf operation: " + perfOperation);
                }
            }

            perfTest.ProcessToMeasure = commandToTest.GetProcessStartInfo();
            perfTest.TestFolder       = testProjectDirectory;

            perfTest.Run();
        }
        public void The_default_configuration_can_be_set_to_release()
        {
            TestProject project = new TestProject()
            {
                Name             = "DirectoryBuildPropsTest",
                TargetFrameworks = "netstandard1.4",
                IsSdkProject     = true
            };

            var testAsset = _testAssetsManager.CreateTestProject(project);

            string directoryBuildPropsPath = Path.Combine(testAsset.Path, "Directory.Build.props");

            var directoryBuildPropsContent = @"
<Project>
  <PropertyGroup>
    <Configuration Condition="" '$(Configuration)' == '' "">Release</Configuration>
  </PropertyGroup>
</Project>
";

            File.WriteAllText(directoryBuildPropsPath, directoryBuildPropsContent);

            var restoreCommand = testAsset.GetRestoreCommand(Log, project.Name);

            restoreCommand
            .Execute()
            .Should()
            .Pass();

            string projectFolder = Path.Combine(testAsset.Path, project.Name);

            var buildCommand = new BuildCommand(Log, projectFolder);

            buildCommand
            .Execute()
            .Should()
            .Pass();

            string GetPropertyValue(string propertyName)
            {
                var getValuesCommand = new GetValuesCommand(Log, projectFolder,
                                                            project.TargetFrameworks, propertyName, GetValuesCommand.ValueType.Property)
                {
                    Configuration = "Release"
                };

                getValuesCommand
                .Execute()
                .Should()
                .Pass();

                var values = getValuesCommand.GetValues();

                values.Count.Should().Be(1);
                return(values[0]);
            }

            GetPropertyValue("Configuration").Should().Be("Release");
            GetPropertyValue("Optimize").Should().Be("true");
        }
示例#34
0
        public void It_discovers_assembly_parts(string aspnetVersion)
        {
            var testProject = new TestProject()
            {
                Name             = "AssemblyPartDiscovery",
                TargetFrameworks = "net462",
                IsExe            = true
            };

            testProject.SourceFiles["Program.cs"] = @"
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.Extensions.DependencyModel;
using System.IO;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(""" + testProject.Name + @""");
        foreach (var item in parts)
        {
            System.Console.WriteLine(item.Name);
        }
    }
}";

            TestProject referencedProjectWithPart = new TestProject()
            {
                Name             = "ReferencedProjectWithPart",
                TargetFrameworks = "net462",
                IsExe            = false
            };


            referencedProjectWithPart.References.Add("System.ServiceModel");

            referencedProjectWithPart.SourceFiles["Class1.cs"] = @"
class Class1
{
    public string X => typeof(System.ServiceModel.AddressFilterMode).ToString();
}";

            TestProject referencedProjectWithMvc = new TestProject()
            {
                Name             = "ReferencedProjectWithMVC",
                ProjectSdk       = "Microsoft.NET.Sdk.Web",
                TargetFrameworks = "net462",
                IsExe            = false
            };

            referencedProjectWithMvc.PackageReferences.Add(new TestPackageReference("Microsoft.AspNetCore.Mvc", aspnetVersion));

            testProject.ReferencedProjects.Add(referencedProjectWithPart);
            testProject.ReferencedProjects.Add(referencedProjectWithMvc);

            var testProjectInstance = _testAssetsManager
                                      .CreateTestProject(testProject, identifier: aspnetVersion);

            var buildCommand = new BuildCommand(testProjectInstance);

            buildCommand.Execute()
            .Should()
            .Pass();

            string outputPath = buildCommand.GetOutputDirectory(testProject.TargetFrameworks).FullName;

            string exePath = Path.Combine(outputPath, testProject.Name + ".exe");

            var toolCommandSpec = new SdkCommandSpec()
            {
                FileName = exePath
            };

            TestContext.Current.AddTestEnvironmentVariables(toolCommandSpec);

            ICommand toolCommand = toolCommandSpec.ToCommand().CaptureStdOut();

            var toolResult = toolCommand.Execute();

            toolResult.Should().Pass();
        }
        public void It_checks_for_valid_references(string referencerTarget, bool referencerIsSdkProject,
                                                   string dependencyTarget, bool dependencyIsSdkProject,
                                                   bool restoreSucceeds, bool buildSucceeds)
        {
            string identifier = referencerTarget.ToString() + " " + dependencyTarget.ToString();

            //  MSBuild isn't happy with semicolons in the path when doing file exists checks
            identifier = identifier.Replace(';', '_');

            TestProject referencerProject = GetTestProject("Referencer", referencerTarget, referencerIsSdkProject);
            TestProject dependencyProject = GetTestProject("Dependency", dependencyTarget, dependencyIsSdkProject);

            referencerProject.ReferencedProjects.Add(dependencyProject);

            //  Set the referencer project as an Exe unless it targets .NET Standard
            if (!referencerProject.TargetFrameworkIdentifiers.Contains(ConstantStringValues.NetstandardTargetFrameworkIdentifier))
            {
                referencerProject.IsExe = true;
            }

            //  Skip running test if not running on Windows
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (!referencerProject.BuildsOnNonWindows || !dependencyProject.BuildsOnNonWindows)
                {
                    return;
                }
            }

            var testAsset = _testAssetsManager.CreateTestProject(referencerProject, nameof(It_checks_for_valid_references), identifier);

            var restoreCommand = testAsset.GetRestoreCommand(Log, relativePath: "Referencer");

            if (restoreSucceeds)
            {
                restoreCommand
                .Execute()
                .Should()
                .Pass();
            }
            else
            {
                restoreCommand
                .Execute()
                .Should()
                .Fail();
            }

            if (!referencerProject.IsSdkProject)
            {
                //  The Restore target currently seems to be a no-op for non-SDK projects,
                //  so we need to explicitly restore the dependency
                testAsset.GetRestoreCommand(Log, relativePath: "Dependency")
                .Execute()
                .Should()
                .Pass();
            }

            var buildCommand = new BuildCommand(testAsset, "Referencer");
            var result       = buildCommand.Execute();

            if (buildSucceeds)
            {
                result.Should().Pass();
            }
            else if (referencerIsSdkProject)
            {
                result.Should().Fail().And.HaveStdOutContaining("NU1201");
            }
            else
            {
                result.Should().Fail()
                .And.HaveStdOutContaining("It cannot be referenced by a project that targets");
            }
        }
	public static void Build(BuildCommand Command, ProjectParams Params, int WorkingCL = -1)
	{

		Params.ValidateAndLog();

		if (!Params.Build)
		{
			return;
		}

		Log("********** BUILD COMMAND STARTED **********");

		var UE4Build = new UE4Build(Command);
		var Agenda = new UE4Build.BuildAgenda();
		var CrashReportPlatforms = new HashSet<UnrealTargetPlatform>();

		// Setup editor targets
		if (Params.HasEditorTargets && !Params.Rocket)
		{
			// @todo Mac: proper platform detection
			UnrealTargetPlatform EditorPlatform = HostPlatform.Current.HostEditorPlatform;
			const UnrealTargetConfiguration EditorConfiguration = UnrealTargetConfiguration.Development;

			CrashReportPlatforms.Add(EditorPlatform);
			Agenda.AddTargets(Params.EditorTargets.ToArray(), EditorPlatform, EditorConfiguration, Params.CodeBasedUprojectPath);
			if (Params.EditorTargets.Contains("UnrealHeaderTool") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealHeaderTool" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.EditorTargets.Contains("ShaderCompileWorker") == false)
			{
				Agenda.AddTargets(new string[] { "ShaderCompileWorker" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.Pak && Params.EditorTargets.Contains("UnrealPak") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealPak" }, EditorPlatform, EditorConfiguration);
			}
			if (Params.FileServer && Params.EditorTargets.Contains("UnrealFileServer") == false)
			{
				Agenda.AddTargets(new string[] { "UnrealFileServer" }, EditorPlatform, EditorConfiguration);
			}
		}

		// Setup cooked targets
		if (Params.HasClientCookedTargets)
		{
			foreach (var BuildConfig in Params.ClientConfigsToBuild)
			{
				foreach (var ClientPlatform in Params.ClientTargetPlatforms)
				{
					CrashReportPlatforms.Add(ClientPlatform);
					Agenda.AddTargets(Params.ClientCookedTargets.ToArray(), ClientPlatform, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: " -remoteini=\""+Path.GetDirectoryName(Params.RawProjectPath)+"\"");
				}
			}
		}
		if (Params.HasServerCookedTargets)
		{
			foreach (var BuildConfig in Params.ServerConfigsToBuild)
			{
				foreach (var ServerPlatform in Params.ServerTargetPlatforms)
				{
					CrashReportPlatforms.Add(ServerPlatform);
					Agenda.AddTargets(Params.ServerCookedTargets.ToArray(), ServerPlatform, BuildConfig, Params.CodeBasedUprojectPath, InAddArgs: " -remoteini=\""+Path.GetDirectoryName(Params.RawProjectPath)+"\"");
				}
			}
		}
		if (Params.CrashReporter && !Params.Rocket)
		{
			var CrashReportClientTarget = new[] { "CrashReportClient" };
			foreach (var CrashReportPlatform in CrashReportPlatforms)
			{
				if (UnrealBuildTool.UnrealBuildTool.PlatformSupportsCrashReporter(CrashReportPlatform))
				{
					Agenda.AddTargets(CrashReportClientTarget, CrashReportPlatform, UnrealTargetConfiguration.Development);
				}
			}
		}
		if (Params.HasProgramTargets && !Params.Rocket)
		{
			foreach (var BuildConfig in Params.ClientConfigsToBuild)
			{
				foreach (var ClientPlatform in Params.ClientTargetPlatforms)
				{
					Agenda.AddTargets(Params.ProgramTargets.ToArray(), ClientPlatform, BuildConfig, Params.CodeBasedUprojectPath);
				}
			}
		}
		UE4Build.Build(Agenda, InDeleteBuildProducts: Params.Clean, InUpdateVersionFiles: WorkingCL > 0);

		if (WorkingCL > 0) // only move UAT files if we intend to check in some build products
		{
			UE4Build.AddUATFilesToBuildProducts();
		}
		UE4Build.CheckBuildProducts(UE4Build.BuildProductFiles);

		if (WorkingCL > 0)
		{
			// Sign everything we built
			CodeSign.SignMultipleIfEXEOrDLL(Command, UE4Build.BuildProductFiles);

			// Open files for add or edit
			UE4Build.AddBuildProductsToChangelist(WorkingCL, UE4Build.BuildProductFiles);
		}

		Log("********** BUILD COMMAND COMPLETED **********");
	}
示例#37
0
 /// <summary>
 /// Basic constructor with staging dir suffix override, basically to avoid having platform concatenated
 /// </summary>
 public BuildPatchToolStagingInfo(BuildCommand InOwnerCommand, string InAppName, string InMcpConfigKey, int InAppID, string InBuildVersion, UnrealTargetPlatform platform, string stagingDirRelativePath, string stagingDirSuffix)
     : this(InOwnerCommand, InAppName, InMcpConfigKey, InAppID, InBuildVersion, ToMCPPlatform(platform), stagingDirRelativePath, stagingDirSuffix)
 {
 }
示例#38
0
        public void TestGetConfig_WithNoInputAndDocfxJsonExists()
        {
            const string documentsBaseDir = "documents";
            const string outputBaseDir = "output";
            const string templateDir = "template";
            if (Directory.Exists(documentsBaseDir))
            {
                Directory.Delete(documentsBaseDir, true);
            }
            if (Directory.Exists(outputBaseDir))
            {
                Directory.Delete(outputBaseDir, true);
            }
            if (Directory.Exists(templateDir))
            {
                Directory.Delete(templateDir, true);
            }

            // Create default template
            var defaultTemplate = @"
{{{conceptual}}}
";
            Directory.CreateDirectory(Path.Combine(templateDir, "default"));
            Directory.CreateDirectory(documentsBaseDir);
            Directory.CreateDirectory(outputBaseDir);
            File.WriteAllText(Path.Combine(templateDir, "default", "Conceptual.html.tmpl"), defaultTemplate);

            // use `/` as it will be used in glob pattern
            // In glob pattern, `/` is considered as file separator while `\` is considered as escape character
            var conceptualFile = documentsBaseDir + "/test.md";
            File.WriteAllLines(
                conceptualFile,
                new[]
                {
                    "---",
                    "a: b",
                    "b:",
                    "  c: e",
                    "---",
                    "# Hello World",
                    "Test XRef: @XRef1",
                    "Test link: [link text](../documents/test.md)",
                    "<p>",
                    "test",
                });

            ParseResult result = new BuildCommand(new Options
            {
                CurrentSubCommand = CommandType.Build,
                BuildCommand = new BuildCommandOptions
                {
                    Content = new List<string> { conceptualFile },
                    OutputFolder = Path.Combine(Environment.CurrentDirectory, outputBaseDir),
                    Templates = new List<string> { Path.Combine(templateDir, "default") }
                }
            }
            , null).Exec(null);

            Assert.Equal(ResultLevel.Success, result.ResultLevel);
            var file = Path.Combine(outputBaseDir, Path.ChangeExtension(conceptualFile, ".html"));
            Assert.True(File.Exists(file));
            // TODO: Update when XREF is implemented by @zhyan
            Assert.Equal<string>(
                new string[]
                {
                    "",
                    "<h1 id=\"hello-world\">Hello World</h1>",
                    "<p>Test XRef: <span class=\"xref\">XRef1</span>",
                    "Test link: <a href=\"test.html\">link text</a></p>",
                    "<p><p>",
                    "test</p>",
                    ""
                },
                File.ReadAllLines(file));
        }
示例#39
0
 public UE4Build(BuildCommand Command)
 {
     OwnerCommand = Command;
     BuildProductFiles.Clear();
 }
示例#40
0
        public void When_TargetPlatformVersion_is_set_higher_than_10_It_can_reference_cswinrt_api()
        {
            const string ProjectName = "WindowsDesktopSdkTest_without_ProjectSdk_set";

            const string tfm = "net5.0";

            var testProject = new TestProject()
            {
                Name             = ProjectName,
                TargetFrameworks = tfm,
                IsWinExe         = true,
            };

            testProject.SourceFiles.Add("Program.cs", _useCsWinrtApi);
            testProject.AdditionalProperties.Add("TargetPlatformIdentifier", "Windows");
            testProject.AdditionalProperties.Add("TargetPlatformVersion", "10.0.17763");

            var asset = _testAssetsManager.CreateTestProject(testProject);

            var buildCommand = new BuildCommand(Log, Path.Combine(asset.Path, ProjectName));

            buildCommand.Execute()
            .Should()
            .Pass();

            void Assert(DirectoryInfo outputDir)
            {
                outputDir.File("Microsoft.Windows.SDK.NET.dll").Exists.Should().BeTrue("The output has cswinrt dll");
                outputDir.File("WinRT.Runtime.dll").Exists.Should().BeTrue("The output has cswinrt dll");
                var runtimeconfigjson = File.ReadAllText(outputDir.File(ProjectName + ".runtimeconfig.json").FullName);

                runtimeconfigjson.Contains(@"""name"": ""Microsoft.NETCore.App""").Should().BeTrue("runtimeconfig.json only reference Microsoft.NETCore.App");
                runtimeconfigjson.Contains("Microsoft.Windows.SDK.NET").Should().BeFalse("runtimeconfig.json does not reference windows SDK");
            }

            Assert(buildCommand.GetOutputDirectory(tfm));

            var publishCommand    = new PublishCommand(asset);
            var runtimeIdentifier = "win-x64";

            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}")
            .Should()
            .Pass();

            Assert(publishCommand.GetOutputDirectory(tfm, runtimeIdentifier: runtimeIdentifier));

            var filesCopiedToPublishDirCommand = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "FilesCopiedToPublishDir",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "ComputeFilesCopiedToPublishDir",
                MetadataNames    = { "RelativePath" },
            };

            filesCopiedToPublishDirCommand.Execute().Should().Pass();
            var filesCopiedToPublishDircommandItems
                = from item in filesCopiedToPublishDirCommand.GetValuesWithMetadata()
                  select new
                {
                Identity     = item.value,
                RelativePath = item.metadata["RelativePath"]
                };

            filesCopiedToPublishDircommandItems
            .Should().Contain(i => i.RelativePath == "Microsoft.Windows.SDK.NET.dll" && Path.GetFileName(i.Identity) == "Microsoft.Windows.SDK.NET.dll",
                              because: "wapproj should copy cswinrt dlls");
            filesCopiedToPublishDircommandItems
            .Should()
            .Contain(i => i.RelativePath == "WinRT.Runtime.dll" && Path.GetFileName(i.Identity) == "WinRT.Runtime.dll",
                     because: "wapproj should copy cswinrt dlls");

            var publishItemsOutputGroupOutputsCommand = new GetValuesCommand(
                Log,
                Path.Combine(asset.Path, testProject.Name),
                testProject.TargetFrameworks,
                "PublishItemsOutputGroupOutputs",
                GetValuesCommand.ValueType.Item)
            {
                DependsOnTargets = "Publish",
                MetadataNames    = { "OutputPath" },
            };

            publishItemsOutputGroupOutputsCommand.Execute().Should().Pass();
            var publishItemsOutputGroupOutputsItems =
                from item in publishItemsOutputGroupOutputsCommand.GetValuesWithMetadata()
                select new
            {
                FullAssetPath = Path.GetFullPath(Path.Combine(asset.Path, testProject.Name, item.metadata["OutputPath"]))
            };

            publishItemsOutputGroupOutputsItems
            .Should().Contain(i => Path.GetFileName(Path.GetFullPath(i.FullAssetPath)) == "WinRT.Runtime.dll" && File.Exists(i.FullAssetPath),
                              because: (string)"as the replacement for FilesCopiedToPublishDir, wapproj should copy cswinrt dlls");
            publishItemsOutputGroupOutputsItems
            .Should()
            .Contain(i => Path.GetFileName(Path.GetFullPath(i.FullAssetPath)) == "WinRT.Runtime.dll" && File.Exists(i.FullAssetPath),
                     because: "as the replacement for FilesCopiedToPublishDir, wapproj should copy cswinrt dlls");

            // ready to run is supported
            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}", $"-p:PublishReadyToRun=true")
            .Should()
            .Pass();

            // PublishSingleFile is supported
            publishCommand.Execute("-p:SelfContained=true", $"-p:RuntimeIdentifier={runtimeIdentifier}", $"-p:PublishSingleFile=true")
            .Should()
            .Pass();
        }
示例#41
0
        public void It_appends_rid_to_outdir_correctly(string identifier, string rid, bool useAppendOption, bool shouldAppend)
        {
            foreach (bool multiTarget in new[] { false, true })
            {
                var testAsset = _testAssetsManager
                                .CopyTestAsset("DesktopMinusRid", identifier: Path.DirectorySeparatorChar + identifier + (multiTarget ? "Multi" : ""))
                                .WithSource()
                                .WithProjectChanges(project =>
                {
                    var ns            = project.Root.Name.Namespace;
                    var propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
                    propertyGroup.Add(new XElement(ns + "RuntimeIdentifier", rid));
                    propertyGroup.Add(new XElement(ns + "AppendRuntimeIdentifierToOutputPath", useAppendOption.ToString()));

                    if (multiTarget)
                    {
                        propertyGroup.Element(ns + "RuntimeIdentifier").Add(new XAttribute("Condition", "'$(TargetFramework)' == 'net46'"));
                        propertyGroup.Element(ns + "TargetFramework").Remove();
                        propertyGroup.Add(new XElement(ns + "TargetFrameworks", "net46;netcoreapp1.1"));
                    }
                });

                var buildCommand = new BuildCommand(testAsset);
                buildCommand
                .Execute()
                .Should()
                .Pass();

                var publishCommand = new PublishCommand(testAsset);
                publishCommand
                .Execute(multiTarget ? new[] { "/p:TargetFramework=net46" } : Array.Empty <string>())
                .Should()
                .Pass();

                string expectedOutput;
                switch (rid)
                {
                case "":
                    expectedOutput = "Native code was not used (MSIL)";
                    break;

                case "win7-x86":
                    expectedOutput = "Native code was not used (X86)";
                    break;

                case "win7-x64":
                    expectedOutput = "Native code was not used (Amd64)";
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(rid));
                }

                var outputDirectory  = buildCommand.GetOutputDirectory("net46", runtimeIdentifier: shouldAppend ? rid : "");
                var publishDirectory = publishCommand.GetOutputDirectory("net46", runtimeIdentifier: rid);

                foreach (var directory in new[] { outputDirectory, publishDirectory })
                {
                    var exe = Path.Combine(directory.FullName, "DesktopMinusRid.exe");

                    var runCommand = new RunExeCommand(Log, exe);
                    runCommand
                    .Execute()
                    .Should()
                    .Pass()
                    .And
                    .HaveStdOutContaining(expectedOutput);
                }
            }
        }
示例#42
0
 /// <summary>
 /// Basic constructor with staging dir suffix override, basically to avoid having platform concatenated
 /// </summary>
 public BuildPatchToolStagingInfo(BuildCommand InOwnerCommand, string InAppName, string InMcpConfigKey, int InAppID, string InBuildVersion, UnrealTargetPlatform platform, string stagingDirRelativePath, string stagingDirSuffix, string InManifestFilename)
     : this(InOwnerCommand, InAppName, InMcpConfigKey, InAppID, InBuildVersion, ToMCPPlatform(platform), stagingDirRelativePath, stagingDirSuffix, InManifestFilename)
 {
 }
示例#43
0
        public static List<UnrealTargetPlatform> GetTargetPlatforms(BuildCommand Command, UnrealTargetPlatform HostPlatform)
        {
            List<UnrealTargetPlatform> TargetPlatforms = new List<UnrealTargetPlatform>();
            if(!Command.ParseParam("NoTargetPlatforms"))
            {
                // Always support the host platform
                TargetPlatforms.Add(HostPlatform);

                // Add other target platforms for each host platform
                if(HostPlatform == UnrealTargetPlatform.Win64)
                {
                    TargetPlatforms.Add(UnrealTargetPlatform.Win32);
                }
                if(HostPlatform == UnrealTargetPlatform.Win64 || HostPlatform == UnrealTargetPlatform.Mac)
                {
                    TargetPlatforms.Add(UnrealTargetPlatform.Android);
                }
                if(HostPlatform == UnrealTargetPlatform.Win64 || HostPlatform == UnrealTargetPlatform.Mac)
                {
                    TargetPlatforms.Add(UnrealTargetPlatform.IOS);
                }
                if(HostPlatform == UnrealTargetPlatform.Win64)
                {
                    TargetPlatforms.Add(UnrealTargetPlatform.Linux);
                }
                if(HostPlatform == UnrealTargetPlatform.Win64 || HostPlatform == UnrealTargetPlatform.Mac )
                {
                    TargetPlatforms.Add(UnrealTargetPlatform.HTML5);
                }

                // Remove any platforms that aren't enabled on the command line
                string TargetPlatformFilter = Command.ParseParamValue("TargetPlatforms", null);
                if(TargetPlatformFilter != null)
                {
                    List<UnrealTargetPlatform> NewTargetPlatforms = new List<UnrealTargetPlatform>();
                    foreach (string TargetPlatformName in TargetPlatformFilter.Split(new char[]{ '+' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        UnrealTargetPlatform TargetPlatform;
                        if(!Enum.TryParse(TargetPlatformName, out TargetPlatform))
                        {
                            throw new AutomationException("Unknown target platform '{0}' specified on command line");
                        }
                        else if(TargetPlatforms.Contains(TargetPlatform))
                        {
                            NewTargetPlatforms.Add(TargetPlatform);
                        }
                    }
                    TargetPlatforms = NewTargetPlatforms;
                }
            }
            return TargetPlatforms;
        }
示例#44
0
        void Test_inbox_assembly_wins_conflict_resolution(bool useSdkProject, string httpPackageVersion, bool useAlias = false)
        {
            var testProject = new TestProject()
            {
                Name  = "DesktopInBoxConflictResolution",
                IsExe = true
            };

            if (useSdkProject)
            {
                testProject.TargetFrameworks = "net472";
            }
            else
            {
                testProject.IsSdkProject           = false;
                testProject.TargetFrameworkVersion = "v4.7.2";
            }

            testProject.PackageReferences.Add(new TestPackageReference("System.Net.Http", httpPackageVersion));

            testProject.SourceFiles["Program.cs"] =
                (useAlias ? "extern alias snh;" + Environment.NewLine : "") +

                @"using System;


class Program
{
    static void Main(string[] args)
    {
" +
                (useAlias ? "var client = new snh::System.Net.Http.HttpClient();" :
                 "var client = new System.Net.Http.HttpClient();") +
                @"
    }
}";

            string identifier = (useSdkProject ? "_SDK_" : "_") +
                                (useAlias ? "alias" : "") +
                                httpPackageVersion;

            var testAsset = _testAssetsManager.CreateTestProject(testProject, testProject.Name, identifier)
                            .WithProjectChanges(p =>
            {
                var ns        = p.Root.Name.Namespace;
                var itemGroup = new XElement(ns + "ItemGroup");
                p.Root.Add(itemGroup);

                var httpReference = new XElement(ns + "Reference",
                                                 new XAttribute("Include", "System.Net.Http"));

                if (useAlias)
                {
                    httpReference.SetAttributeValue("Aliases", "snh");
                }

                itemGroup.Add(httpReference);
            });

            var buildCommand = new BuildCommand(testAsset);

            buildCommand
            .Execute("/v:normal")
            .Should()
            .Pass()
            .And.NotHaveStdOutContaining("MSB3277")     // MSB3277: Found conflicts between different versions of the same dependent assembly that could not be resolved.
            .And.NotHaveStdOutContaining("MSB3243")     // MSB3243: No way to resolve conflict between...
            .And.NotHaveStdOutContaining("Could not determine");
        }