Exemplo n.º 1
0
        public bool Run(string solutionFile, BuildConfiguration configuration = BuildConfiguration.Release, string target = "Build")
        {
            if (string.IsNullOrEmpty(solutionFile))
                throw new ArgumentNullException("solutionFile");

            if (string.IsNullOrEmpty(target))
                throw new ArgumentNullException("target");

            var results = BuilderCapability.Call(solutionFile, configuration);

            foreach (var targetResult in results.TargetResults)
            {
                switch (targetResult.Result)
                {
                    case ResultCode.Failure:
                        Logger.Error(targetResult.Component, targetResult.Exception);
                        break;
                    case ResultCode.Success:
                    case ResultCode.Skipped:
                        Logger.Info(targetResult.Component, targetResult.Result.ToString());
                        break;
                }
            }

            return results.ExitCode == ResultCode.Success;
        }
Exemplo n.º 2
0
        public static ConfigurationSettings GetSettings(BuildConfiguration configuration)
        {
            //#if (DEBUG)
            //            return new LocalSettings();
            //#elif (TEST)
            //              return new TestSettings();
            //#elif (DEVELOPMENT)
            //              return new DevSettings();
            //#elif (RELEASE)
            //              return new TestSettings();
            //#endif

            switch (configuration)
            {
                case (BuildConfiguration.Debug):
                    return new LocalSettings();
                    break;

                case (BuildConfiguration.Development):
                    return new DevSettings();
                    break;

                case (BuildConfiguration.Release):
                    return new ReleaseSettings();
                    break;

                case (BuildConfiguration.Test):
                    return new TestSettings();
                    break;
            }
            return null;
        }
Exemplo n.º 3
0
        public void FromXml(System.Xml.XmlNode node)
        {
            _lastBuildConfiguration = AGS.Types.BuildConfiguration.Unknown;

            // Allow for earlier versions of the XML
            if (node != null && node.SelectSingleNode("WorkspaceState") != null)
                SerializeUtils.DeserializeFromXML(this, node);
        }
        private void ExecuteBuildNuGetPackages(BuildConfiguration configuration)
        {
            foreach (var buildNuGetPackage in configuration.BuildNuGetPackages)
            {
                try
                {
                    var properties = new PropertyProvider();

                    string version = buildNuGetPackage.Version;

                    if (version == null)
                        version = VersionRetriever.GetVersion(TargetPath);

                    properties.Properties["version"] = version;

                    string manifest = TranslatePath(buildNuGetPackage.Manifest);

                    var builder = new PackageBuilder(
                        manifest,
                        buildNuGetPackage.BasePath ?? TargetDir,
                        properties,
                        false
                    );

                    string target =
                        buildNuGetPackage.Target != null
                        ? TranslatePath(buildNuGetPackage.Target)
                        : Path.Combine(TargetDir, Path.GetFileNameWithoutExtension(manifest) + "." + version + ".nupkg");

                    bool isExistingPackage = File.Exists(target);
                    try
                    {
                        using (Stream stream = File.Create(target))
                        {
                            builder.Save(stream);
                        }
                    }
                    catch
                    {
                        if (!isExistingPackage && File.Exists(target))
                            File.Delete(target);

                        throw;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogErrorFromException(ex);
                }
            }
        }
Exemplo n.º 5
0
        private void ExecuteCreateContext(BuildConfiguration configuration)
        {
            if (configuration.CreateContext == null)
                return;

            string target =
                configuration.CreateContext.Target ??
                TargetDir;

            using (var key = PackageRegistry.OpenRegistryRoot(true, new ContextName(configuration.CreateContext.Context, true)))
            {
                key.SetValue("InstallationPath", target);
            }
        }
Exemplo n.º 6
0
        public IBuildResult Call(string solutionFile, BuildConfiguration buildConfiguration)
        {
            var projectCollection = new ProjectCollection();
            var properties = new Dictionary<string, string> { { "Configuration", buildConfiguration.ToString() } };

            var buildRequest = new BuildRequestData(solutionFile, properties, null, new[] { "Build" }, null);

            var result = BuildManager.DefaultBuildManager.Build(new BuildParameters(projectCollection), buildRequest);

            return new BuildResult
                       {
                           ExitCode = Convert(result.OverallResult),
                           TargetResults = result.ResultsByTarget.Select(c => new Build.TargetResult
                                                                                  {
                                                                                      Component = c.Key,
                                                                                      Exception = c.Value.Exception,
                                                                                      Result = Convert(c.Value.ResultCode)
                                                                                  })
                                                                                  .ToArray()
                       };
        }
Exemplo n.º 7
0
        private void ExecuteInstallPackages(BuildConfiguration configuration)
        {
            using (new AssemblyResolver())
            {
                foreach (var installPackage in configuration.InstallPackages)
                {
                    try
                    {
                        var installer = new PackageInstaller(
                            new ContextName(installPackage.Context, true),
                            TranslatePath(installPackage.Package)
                        );

                        installer.Execute();
                    }
                    catch (Exception ex)
                    {
                        Log.LogErrorFromException(ex);
                    }
                }
            }
        }
Exemplo n.º 8
0
 public Build(long id, string number, BuildStatus? status, DateTime startDate, DateTime finishDate,
     DateTime queuedDate, BuildConfiguration buildConfiguration, Agent agent, List<Change> changes, string webUrl,
     Properties properties, ITestOccurrences testOccurrences, BuildState? state)
 {
     m_Id = id;
     m_Number = number;
     m_Status = status;
     m_State = state;
     m_StartDate = startDate;
     m_FinishDate = finishDate;
     m_QueuedDate = queuedDate;
     m_BuildConfiguration = buildConfiguration;
     m_Agent = agent;
     m_TestOccurrences = testOccurrences;
     m_Changes = changes;
     m_WebUrl = webUrl;
     m_Properties = properties;
 }
Exemplo n.º 9
0
        public void TestToBuildConfiguration()
        {
            RegistryImage targetImage =
                RegistryImage.Named(ImageReference.Of("gcr.io", "my-project/my-app", null))
                .AddCredential("username", "password");
            IContainerizer containerizer =
                Containerizer.To(targetImage)
                .SetBaseImageLayersCache(Paths.Get("base/image/layers"))
                .SetApplicationLayersCache(Paths.Get("application/layers"))
                .AddEventHandler(mockFibEventConsumer);

            RegistryImage baseImage =
                RegistryImage.Named("base/image").AddCredentialRetriever(mockCredentialRetriever);
            FibContainerBuilder fibContainerBuilder =
                new FibContainerBuilder(baseImage, buildConfigurationBuilder)
                .SetLayers(new[] { mockLayerConfiguration1, mockLayerConfiguration2 });
            BuildConfiguration buildConfiguration =
                fibContainerBuilder.ToBuildConfiguration(
                    containerizer);

            Assert.AreEqual(
                buildConfigurationBuilder.Build().GetContainerConfiguration(),
                buildConfiguration.GetContainerConfiguration());

            Assert.AreEqual(
                "base/image", buildConfiguration.GetBaseImageConfiguration().GetImage().ToString());
            Assert.AreEqual(
                new[] { mockCredentialRetriever },
                buildConfiguration.GetBaseImageConfiguration().GetCredentialRetrievers());

            Assert.AreEqual(
                "gcr.io/my-project/my-app",
                buildConfiguration.GetTargetImageConfiguration().GetImage().ToString());
            Assert.AreEqual(
                1, buildConfiguration.GetTargetImageConfiguration().GetCredentialRetrievers().Length);
            Assert.AreEqual(
                Credential.From("username", "password"),
                buildConfiguration
                .GetTargetImageConfiguration()
                .GetCredentialRetrievers()
                [0]
                .Retrieve()
                .OrElseThrow(() => new AssertionException("")));

            Assert.AreEqual(ImmutableHashSet.Create("latest"), buildConfiguration.GetAllTargetImageTags());

            Assert.AreEqual(
                new[] { mockLayerConfiguration1, mockLayerConfiguration2 },
                buildConfiguration.GetLayerConfigurations());

            buildConfiguration.GetEventHandlers().Dispatch(mockFibEvent);
            Mock.Get(mockFibEventConsumer).Verify(m => m(mockFibEvent));

            Assert.AreEqual("fibdotnet-core", buildConfiguration.GetToolName());

            Assert.AreEqual(ManifestFormat.V22, buildConfiguration.GetTargetFormat());

            Assert.AreEqual("fibdotnet-core", buildConfiguration.GetToolName());

            // Changes fibContainerBuilder.
            buildConfiguration =
                fibContainerBuilder
                .SetFormat(ImageFormat.OCI)
                .ToBuildConfiguration(
                    containerizer
                    .WithAdditionalTag("tag1")
                    .WithAdditionalTag("tag2")
                    .SetToolName("toolName"));
            Assert.AreEqual(ManifestFormat.OCI, buildConfiguration.GetTargetFormat());
            Assert.AreEqual(
                ImmutableHashSet.Create("latest", "tag1", "tag2"), buildConfiguration.GetAllTargetImageTags());
            Assert.AreEqual("toolName", buildConfiguration.GetToolName());
        }
Exemplo n.º 10
0
        public static void SetUp()
        {
            s_Assets.SetUp();

            var assetGuids = new List<GUID>();
            try
            {
                {
                    string path = s_Assets.GetNextPath(".asset");
                    AssetDatabase.CreateAsset(s_TempTexture = new Texture2D(64, 64), path);
                    s_TempTextureGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempTextureGuid);
                }
                {
                    string path = s_Assets.GetNextPath(".mat");
                    AssetDatabase.CreateAsset(s_TempMaterial = new Material(Shader.Find("Standard")), path);
                    s_TempMaterialGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                    assetGuids.Add(s_TempMaterialGuid);
                    s_TempMaterial.mainTexture = s_TempTexture;
                }

                var tempScenePath = s_Assets.GetNextPath(".unity");
                s_TempScene = SubSceneTestsHelper.CreateScene(tempScenePath);
                s_SubSceneWithSections = SubSceneTestsHelper.CreateSubSceneInSceneFromObjects("SubScene", false, s_TempScene, () =>
                {
                    var go1 = new GameObject();
                    go1.AddComponent<SceneSectionComponent>().SectionIndex = 0;
                    var go2 = new GameObject();
                    go2.AddComponent<SceneSectionComponent>().SectionIndex = 2;
                    go2.AddComponent<TestComponentAuthoring>().Material = s_TempMaterial;
                    return new List<GameObject> { go1, go2 };
                });

                {
                    var path = s_Assets.GetNextPath("LiveLinkBuildConfig.buildconfiguration");
                    BuildConfiguration.CreateAsset(path, config =>
                    {
                        config.SetComponent(new SceneList
                        {
                            SceneInfos = new List<SceneList.SceneInfo>
                            {
                                new SceneList.SceneInfo
                                {
                                    Scene = GlobalObjectId.GetGlobalObjectIdSlow(AssetDatabase.LoadAssetAtPath<SceneAsset>(tempScenePath))
                                }
                            }
                        });
                    });
                    s_LiveLinkBuildConfigGuid = new GUID(AssetDatabase.AssetPathToGUID(path));
                }
            }
            catch
            {
                s_Assets.TearDown();
                throw;
            }

            // This call ensures that the asset worker is already running and no test times out because we're still
            // waiting for the asset worker. Effectively this doesn't change the runtime that much since we will have
            // to wait for the import to finish in most of the tests anyway.
            GeEntitySceneArtifactHash(s_SubSceneWithSections.SceneGUID, s_LiveLinkBuildConfigGuid, ImportMode.Synchronous);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            s_TempAssetGuids = assetGuids.ToArray();
            DefaultWorldInitialization.DefaultLazyEditModeInitialize();
            s_Connection = new LiveLinkTestConnection();
            EditorSceneLiveLinkToPlayerSendSystem.instance.SetConnection(s_Connection);
            LiveLinkAssetBundleBuildSystem.instance.SetConnection(s_Connection);
        }
Exemplo n.º 11
0
 public virtual void BeforeBuildStarted(BuildConfiguration data)
 {
     IsFinished = false;
 }
Exemplo n.º 12
0
 public TestContextBase(BuildPipelineBase pipeline, BuildConfiguration config) : base(pipeline, config)
 {
 }
Exemplo n.º 13
0
        public static LiveLinkChangeSet UpdateLiveLink(Scene scene, Hash128 sceneGUID, ref LiveLinkDiffGenerator liveLinkData, int sceneDirtyID, LiveLinkMode mode, BuildConfiguration config)
        {
            //Debug.Log("ApplyLiveLink: " + scene.SceneName);

            int framesToRetainBlobAssets = RetainBlobAssetsSetting.GetFramesToRetainBlobAssets(config);

            var liveLinkEnabled = mode != LiveLinkMode.Disabled;

            if (liveLinkData != null && liveLinkData._LiveLinkEnabled != liveLinkEnabled)
            {
                liveLinkData.Dispose();
                liveLinkData = null;
            }

            var unloadAllPreviousEntities = liveLinkData == null;

            if (liveLinkData == null)
            {
                liveLinkData = new LiveLinkDiffGenerator(sceneGUID, liveLinkEnabled);
            }

            if (!liveLinkEnabled)
            {
                return(new LiveLinkChangeSet
                {
                    UnloadAllPreviousEntities = unloadAllPreviousEntities,
                    SceneName = scene.name,
                    SceneGUID = sceneGUID,
                    FramesToRetainBlobAssets = framesToRetainBlobAssets
                });
            }

            var flags = GameObjectConversionUtility.ConversionFlags.AddEntityGUID | GameObjectConversionUtility.ConversionFlags.AssignName | GameObjectConversionUtility.ConversionFlags.GameViewLiveLink;

            if (mode == LiveLinkMode.LiveConvertSceneView)
            {
                flags |= GameObjectConversionUtility.ConversionFlags.SceneViewLiveLink;
            }

            liveLinkData.Convert(scene, sceneGUID, flags, config);

            var convertedEntityManager = liveLinkData._ConvertedWorld.EntityManager;

            // We don't know the scene tag of the destination world, so we create a null Scene Tag.
            // In the patching code this will be translated into the final scene entity.
            convertedEntityManager.AddSharedComponentData(liveLinkData._MissingSceneQuery, new SceneTag {
                SceneEntity = Entity.Null
            });

#if UNITY_2020_1_OR_NEWER
            convertedEntityManager.AddSharedComponentData(liveLinkData._MissingRenderDataQuery, new EditorRenderData {
                SceneCullingMask = UnityEditor.SceneManagement.SceneCullingMasks.GameViewObjects, PickableObject = null
            });
#else
            convertedEntityManager.AddSharedComponentData(liveLinkData._MissingRenderDataQuery, new EditorRenderData {
                SceneCullingMask = EditorRenderData.LiveLinkEditGameViewMask, PickableObject = null
            });
#endif

            var options = EntityManagerDifferOptions.IncludeForwardChangeSet |
                          EntityManagerDifferOptions.FastForwardShadowWorld |
                          EntityManagerDifferOptions.ValidateUniqueEntityGuid |
                          EntityManagerDifferOptions.ClearMissingReferences;

            var changes = new LiveLinkChangeSet
            {
                Changes = liveLinkData._LiveLinkDiffer.GetChanges(options, Allocator.TempJob).ForwardChangeSet,
                UnloadAllPreviousEntities = unloadAllPreviousEntities,
                SceneName = scene.name,
                SceneGUID = sceneGUID,
                FramesToRetainBlobAssets = framesToRetainBlobAssets
            };


            liveLinkData.LiveLinkDirtyID = sceneDirtyID;
            // convertedEntityManager.Debug.CheckInternalConsistency();

            return(changes);
        }
 public SolutionConfigurationPlatform(BuildConfiguration buildConfiguration, CpuConfiguration cpuConfiguration)
 {
     BuildConfiguration = buildConfiguration;
     CpuConfiguration   = cpuConfiguration;
 }
Exemplo n.º 15
0
        private List <WordDocumentGenerator.Client.Entities.BuildDetail> GetDataContext()
        {
            var buildDetails = new List <BuildDetail>();

            foreach (var build in this.Builds)
            {
                var buildDetail = new BuildDetail()
                {
                    DocumentDetail              = new DocumentDetail(),
                    Build                       = new Build(),
                    BuildConfigurations         = new List <BuildConfiguration>(),
                    BuildConfigurationSolutions = new List <BuildConfigurationSolution>(),
                    Changesets                  = new List <WordDocumentGenerator.Client.Entities.Changeset>(),
                    ChangesetChangeDetails      = new List <ChangesetChangeDetail>(),
                    WorkItems                   = new List <WordDocumentGenerator.Client.Entities.WorkItem>(),
                    TestResult                  = new TestResult(),
                    TestResultPassedItems       = new List <TestResultPassedItem>(),
                    TestResultFailedItems       = new List <TestResultFailedItem>(),
                    TestResultInconclusiveItems = new List <TestResultInconclusiveItem>()
                };

                // Load Document Details into BuildDetails
                buildDetail.DocumentDetail.Title     = build.BuildNumber;
                buildDetail.DocumentDetail.CreatedOn = DateTime.Now.ToLongDateString();
                buildDetail.DocumentDetail.CreatedBy = Environment.UserName;

                // Load Build Details into BuildDetails
                buildDetail.Build.BuildDefinition = !string.IsNullOrEmpty(build.BuildDefinition.Name) ? build.BuildDefinition.Name : string.Empty;              // "Tailspin Toys";
                // Null check - only if the build controller was removed & the builds not deleted will the controller be null
                buildDetail.Build.BuildController  = build.BuildDefinition.BuildController != null ? build.BuildDefinition.BuildController.Name : "Unavilable"; // "WIN-GS9GMUJITS8 - Controller";
                buildDetail.Build.BuildNumber      = !string.IsNullOrEmpty(build.BuildNumber) ? build.BuildNumber : "Unavilable";                               // "Tailspin Toys - Iteration 2_20100318.2";
                buildDetail.Build.BuildQuality     = !string.IsNullOrEmpty(build.Quality) ? build.Quality : "Not Set";
                buildDetail.Build.BuildState       = build.Status.ToString();                                                                                   // "Succeeded";
                buildDetail.Build.BuildTeamProject = build.TeamProject;                                                                                         // "Tailspin Toys";
                buildDetail.Build.BuildTestStatus  = build.TestStatus.ToString();                                                                               // "Passed";

                // TODO: Add a new function to create this from start and finish time
                buildDetail.Build.BuildTotalExecutionTimeInSeconds = CalculateTotalBuildExecutionTime(build.StartTime, build.FinishTime);          // "86 seconds";

                buildDetail.Build.BuildUri                = build.Uri;                                                                             // new Uri(@"vstfs:///VersionControl/Build/17");
                buildDetail.Build.BuildStartTime          = build.StartTime.ToString("dd MM YYYY hh:mm:ss");                                       // "01-01-2011 12:09:07";
                buildDetail.Build.BuildSourceGetVersion   = !string.IsNullOrEmpty(build.SourceGetVersion) ? build.SourceGetVersion : "Unavilable"; // "70";
                buildDetail.Build.BuildShelvesetName      = !string.IsNullOrEmpty(build.ShelvesetName) ? build.ShelvesetName : "Not Shelved";      // @"Tailspin Toys\@2_20100318.2";
                buildDetail.Build.BuildRetainIndefinitely = build.KeepForever.ToString();                                                          // "false";
                buildDetail.Build.BuildRequestedBy        = !string.IsNullOrEmpty(build.RequestedBy) ? build.RequestedBy : "Unavilable";           // @"WIN-GS9GMUJITS8\abuobe";
                buildDetail.Build.BuildReason             = build.Reason.ToString();                                                               // "CI";
                buildDetail.Build.BuildLogLocation        = !string.IsNullOrEmpty(build.LogLocation) ? build.LogLocation : "Unavailable";          // @"\\Log\\Folder\abc\TailSpin Toys\Tailspin Toys - Iteration 2_20100318.2";
                buildDetail.Build.BuildLastChangedOn      = build.LastChangedOn.ToString();                                                        // "05-01-2012 13:01:37";
                buildDetail.Build.BuildLastChangedBy      = build.LastChangedBy;                                                                   // @"UK\tarora";

                // Todo: create a new function to generate the string for the last modified duration
                buildDetail.Build.BuildLastModifiedNoOfDaysAgo = CalculateTotalBuildExecutionTime(build.LastChangedOn, DateTime.Now);

                buildDetail.Build.BuildLabelName = !string.IsNullOrEmpty(build.LabelName) ? build.LabelName : "Not Labeled"; // @"Tailspin Toys@\Label\2_20100318.2";
                buildDetail.Build.BuildIsDeleted = build.IsDeleted.ToString();                                               // "false";
                buildDetail.Build.BuildEndTime   = build.FinishTime.ToString();                                              // "01-01-2011 12:10:35";

                // ToDo: create a new function to generate the string for the completed no of days ago
                buildDetail.Build.BuildCompletedNoOfDaysAgo = CalculateTotalBuildExecutionTime(build.FinishTime, DateTime.Now);

                buildDetail.Build.BuildDropLocation = !string.IsNullOrEmpty(build.DropLocation) ? build.DropLocation : "Unavailable"; // @"\\Drop\\Folder\abc\TailSpin Toys\Tailspin Toys - Iteration 2_20100318.2";

                if (!this.Exclusions.Contains("BuildConfiguration"))
                {
                    // Load Build Configuration into BuildDetails
                    foreach (IConfigurationSummary configSummary in InformationNodeConverters.GetConfigurationSummaries(build))
                    {
                        var buildConfigSummary = new BuildConfiguration();
                        buildConfigSummary.BuildConfigFlavor        = configSummary.Flavor;                              // "Mixed Platform";
                        buildConfigSummary.BuildConfigPlatform      = configSummary.Platform;                            // "Debug";
                        buildConfigSummary.BuildConfigTotalErrors   = configSummary.TotalCompilationErrors.ToString();   // "0";
                        buildConfigSummary.BuildConfigTotalWarnings = configSummary.TotalCompilationWarnings.ToString(); // "1";

                        buildDetail.BuildConfigurations.Add(buildConfigSummary);
                    }

                    // Load Build Configuration Solutions into BuildDetails
                    foreach (IBuildProjectNode buildConfig in InformationNodeConverters.GetTopLevelProjects(build.Information))
                    {
                        var buildConfigurationSolution = new BuildConfigurationSolution();
                        buildConfigurationSolution.BuildRootNodeSolutionServerPath = buildConfig.ServerPath;
                        buildConfigurationSolution.BuildRootNodeErrorCount         = buildConfig.CompilationErrors.ToString();
                        buildConfigurationSolution.BuildRootNodeWarningCount       = buildConfig.CompilationWarnings.ToString();
                        buildConfigurationSolution.BuildRootNodeLogFile            = buildConfig.LogFile != null ? buildConfig.LogFile.Url.AbsolutePath : string.Empty;

                        buildDetail.BuildConfigurationSolutions.Add(buildConfigurationSolution);
                    }
                }

                if (!this.Exclusions.Contains("Changesets"))
                {
                    // check if the user selected Changesets, Load changesets into BuildDetails
                    foreach (IChangesetSummary changesetInfo in InformationNodeConverters.GetAssociatedChangesets(build.Information))
                    {
                        var changesetDetail = this.VersionControlServer.GetChangeset(changesetInfo.ChangesetId);
                        buildDetail.Changesets.Add(new WordDocumentGenerator.Client.Entities.Changeset
                        {
                            ChangesetId          = changesetDetail.ChangesetId.ToString(),
                            ChangesetUri         = changesetDetail.ArtifactUri,             // new Uri(@"vstfs:///VersionControl/Changeset/63"),
                            ChangesetCommittedOn = changesetDetail.CreationDate.ToString(), // "01-01-2011 12:05:01",
                            ChangesetCommittedBy = changesetDetail.Owner,                   // @"UK\tarora",
                            ChangesetComment     = changesetDetail.Comment                  // "Refactoring code improvements"
                        });

                        var changes = new List <string>();
                        foreach (var ch in changesetDetail.Changes)
                        {
                            changes.Add(ch.Item.ServerItem);
                        }

                        buildDetail.ChangesetChangeDetails.Add(new ChangesetChangeDetail
                        {
                            ChangesetChangeId          = changesetDetail.ChangesetId.ToString(),
                            ChangesetChangeServerPaths = changes
                        });
                    }
                }

                if (!this.Exclusions.Contains("WorkItems"))
                {
                    // check if the user selected WorkItems
                    // Load workItems into BuildDetails
                    foreach (IWorkItemSummary workItemInfo in InformationNodeConverters.GetAssociatedWorkItems(build))
                    {
                        var workItemDetail = WorkItemStore.GetWorkItem(workItemInfo.WorkItemId);
                        buildDetail.WorkItems.Add(new WordDocumentGenerator.Client.Entities.WorkItem()
                        {
                            WorkItemId            = workItemDetail.Id.ToString(),
                            WorkItemUri           = workItemDetail.Uri,
                            WorkItemType          = workItemDetail.Type.Name,
                            WorkItemTitle         = workItemDetail.Title,
                            WorkItemState         = workItemDetail.State,
                            WorkItemIterationPath = workItemDetail.IterationPath,
                            WorkItemAreaPath      = workItemDetail.AreaPath,
                            WorkItemAssignedTo    = workItemInfo.AssignedTo
                        });
                    }

                    string introduction = string.Empty;
                    foreach (var wiT in buildDetail.WorkItems.Select(d => d.WorkItemType).Distinct())
                    {
                        introduction = string.Format("{0} {1}, ", buildDetail.WorkItems.Where(wi => wi.WorkItemType == wiT).ToList().Count, string.Format("{0}(s)", wiT));
                    }

                    if (introduction.Length != 0)
                    {
                        introduction = introduction.Remove(introduction.Length - 2);
                    }

                    buildDetail.WorkItemIntroduction = introduction;
                }

                if (!this.Exclusions.Contains("TestResults"))
                {
                    // check if user selected Test Results
                    // Load test results into BuildDetails
                    foreach (var tr in TestManagementService.GetTeamProject(buildDetail.Build.BuildTeamProject).TestRuns.ByBuild(build.Uri))
                    {
                        buildDetail.TestResult.TestResultId                    = tr.Id.ToString();
                        buildDetail.TestResult.TestResultTitle                 = tr.Title;
                        buildDetail.TestResult.TestResultStatus                = tr.State.ToString();                        // "Complete";
                        buildDetail.TestResult.TestResultTotalTest             = tr.Statistics.TotalTests.ToString();        // "24";
                        buildDetail.TestResult.TestResultTotalTestCompleted    = tr.Statistics.CompletedTests.ToString();    // "24";
                        buildDetail.TestResult.TestResultTotalTestPassed       = tr.Statistics.PassedTests.ToString();       // "22";
                        buildDetail.TestResult.TestResultTotalTestFailed       = tr.Statistics.FailedTests.ToString();       // "1";
                        buildDetail.TestResult.TestResultTotalTestInconclusive = tr.Statistics.InconclusiveTests.ToString(); // "1";

                        double result = 0.0;
                        if (tr.Statistics.TotalTests != 0)
                        {
                            // var passPerc = decimal.MinValue;
                            result = tr.Statistics.PassedTests * 100 / tr.Statistics.TotalTests;
                        }

                        buildDetail.TestResult.TestResultTotalTestPassRate = result.ToString();
                        buildDetail.TestResult.TestResultIsAutomated       = tr.IsAutomated.ToString(); // "false";

                        // Load testResultPassedItems into BuildDetails
                        // Check for passed tests
                        foreach (ITestCaseResult lp in tr.QueryResultsByOutcome(TestOutcome.Passed))
                        {
                            buildDetail.TestResultPassedItems.Add(new WordDocumentGenerator.Client.Entities.TestResultPassedItem()
                            {
                                TestResultPassedListStatus = "Passed",
                                TestResultPassedListTitle  = lp.TestCaseTitle
                            });
                        }

                        // Load testResultsFailedItems into BuildDetails
                        foreach (ITestCaseResult lf in tr.QueryResultsByOutcome(TestOutcome.Failed))
                        {
                            buildDetail.TestResultFailedItems.Add(new WordDocumentGenerator.Client.Entities.TestResultFailedItem()
                            {
                                TestResultFailedListStatus = "Failed",
                                TestResultFailedListTitle  = lf.TestCaseTitle,
                                TestResultFailedListReason = lf.ErrorMessage
                            });
                        }

                        // Load testResultsInconclusiveItems into BuildDetails
                        foreach (ITestCaseResult li in tr.QueryResultsByOutcome(TestOutcome.Inconclusive))
                        {
                            buildDetail.TestResultInconclusiveItems.Add(new WordDocumentGenerator.Client.Entities.TestResultInconclusiveItem()
                            {
                                TestResultInconclusiveListStatus = "Inconclusive",
                                TestResultInconclusiveListTitle  = li.TestCaseTitle
                            });
                        }
                    }
                }

                buildDetails.Add(buildDetail);
            }

            return(buildDetails);
        }
Exemplo n.º 16
0
 public void BuildStepStart(BuildConfiguration pConfiguration)
 {
     PlayerSettings.productName = pConfiguration.Params;
 }
Exemplo n.º 17
0
 public void OneTimeSetup()
 {
     m_BuildPipeline = new TestBuildPipeline();
     m_BuildConfiguration = BuildConfiguration.CreateInstance(config => config.name = "TestConfiguration");
 }
Exemplo n.º 18
0
 public TizenToolChain(Unity.IL2CPP.Building.Architecture architecture, BuildConfiguration buildConfiguration) : base(architecture, buildConfiguration)
 {
 }
Exemplo n.º 19
0
        private void Install(PackageKeyDiff pck, PackageDependency originalDependency, BuildConfiguration configuration)
        {
            var repository = _cacheRepositories.First(r => r.Type == pck.PackageType);

            using (var s = repository.Download(pck))
                using (var reader = _packageReaderFactory.Get(pck.PackageType, s))
                {
                    BeginInstallPackage?.Invoke(this, new PackageKeyDiffEventArgs(pck, true));
                    reader.InstallTo(_rootDirectory, originalDependency, configuration);
                }

            _index.Install(pck);

            FinishInstallPackage?.Invoke(this, new PackageKeyDiffEventArgs(pck, true));
        }
Exemplo n.º 20
0
        private void ResetFiles(BuildConfiguration configuration)
        {
            ClearAllFolders();

            _index = _installedPackagesManager.GetNew(_rootDirectory, configuration);
        }
Exemplo n.º 21
0
        private bool DependenciesChanged(IEnumerable <PackageKey> currentDependencies, BuildConfiguration configuration)
        {
            if (configuration != _index.Configuration)
            {
                return(true);
            }

            if (currentDependencies.Count() != _index.TotalPackagesCount)
            {
                return(true);
            }

            return(currentDependencies.Any(pck => !_index.IsInstalled(pck)));
        }
Exemplo n.º 22
0
        public override bool Initialize(string region)
        {
            var versions = new Versions(Game.ProgramCode);
            var cdns     = new CDNs(Game.ProgramCode);

            if (!cdns.Records.TryGetValue(region, out ServerInfo))
            {
                return(false);
            }

            Versions.Record versionInfo;
            if (!versions.Records.TryGetValue(region, out versionInfo))
            {
                return(false);
            }

            BuildConfig   = new BuildConfiguration(ServerInfo.Hosts[0], versionInfo.BuildConfig);
            ContentConfig = new ContentConfiguration(ServerInfo.Hosts[0], versionInfo.CDNConfig);

            _rootKey     = BuildConfig.Root.ToByteArray();
            _encodingKey = BuildConfig.Encoding[1].ToByteArray();

            using (var encodingClient = new AsyncClient(ServerInfo.Hosts[0]))
            {
                encodingClient.Send($"/{ServerInfo.Path}/data/{_encodingKey[0]:x2}/{_encodingKey[1]:x2}/{_encodingKey}");
                if (!encodingClient.Failed)
                {
                    using (var encodingPack = new BLTE(encodingClient.Stream, 0, encodingClient.ContentLength))
                        if (!LoadEncoding(encodingPack))
                        {
                            throw new InvalidOperationException("Unable to find encoding!");
                        }
                }
            }

            for (var i = 0; i < ContentConfig.Archives.Length; ++i)
            {
                var archiveHash = ContentConfig.Archives[i];

                using (var archiveClient = new AsyncClient(ServerInfo.Hosts[0]))
                {
                    archiveClient.Send($"/{ServerInfo.Path}/data/{archiveHash[0]:x2}/{archiveHash[1]:x2}/{archiveHash.ToHexString()}.index");
                    if (!archiveClient.Failed)
                    {
                        LoadIndex(archiveClient.Stream, archiveClient.ContentLength, i);
                    }
                }
            }

            if (!_encodingEntries.ContainsKey(_rootKey))
            {
                throw new InvalidOperationException("Root entry not found in encoding!");
            }

            var encodingEntry = _encodingEntries[_rootKey];

            foreach (var rootEncodingEntry in encodingEntry)
            {
                using (var rootClient = new AsyncClient(ServerInfo.Hosts[0]))
                {
                    rootClient.Send($"/{ServerInfo.Path}/data/{rootEncodingEntry.Item2[0]:x2}/{rootEncodingEntry.Item2[1]:x2}/{rootEncodingEntry.Item2.ToHexString()}");
                    if (rootClient.Failed)
                    {
                        continue;
                    }

                    using (var rootBlte = new BLTE(rootClient.Stream, 0, rootClient.ContentLength))
                        if (LoadRoot(rootBlte))
                        {
                            break;
                        }
                }
            }

            return(_rootEntries.Count != 0);
        }
 public override RunStepResult Start(BuildConfiguration settings)
 {
     return(Success(settings, null));
 }
 public override CppToolChain MakeCppToolChain(Unity.IL2CPP.Building.Architecture architecture, BuildConfiguration buildConfiguration, bool treatWarningsAsErrors) =>
 new TizenToolChain(architecture, buildConfiguration);
 public override bool CanRun(BuildConfiguration settings, out string reason)
 {
     reason = null;
     return(true);
 }
 public AssemblyCompilationAttribute(BuildConfiguration buildConfiguration)
 {
     BuildConfiguration = buildConfiguration;
 }
Exemplo n.º 27
0
 /// <summary>
 /// Starts building game for the specified platform.
 /// </summary>
 /// <param name="platform">The target platform.</param>
 /// <param name="configuration">The build configuration.</param>
 /// <param name="outputPath">The output path (output directory).</param>
 /// <param name="options">The build options.</param>
 /// <param name="defines">Scripts compilation define symbols (macros).</param>
 public static void Build(BuildPlatform platform, BuildConfiguration configuration, string outputPath, BuildOptions options, string[] defines)
 {
     Internal_Build(platform, configuration, outputPath, options, defines);
 }
Exemplo n.º 28
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            try
            {
                var sceneWithBuildConfiguration = SceneWithBuildConfigurationGUIDs.ReadFromFile(ctx.assetPath);

                // Ensure we have as many dependencies as possible registered early in case an exception is thrown
                EditorEntityScenes.AddEntityBinaryFileDependencies(ctx, sceneWithBuildConfiguration.BuildConfiguration);
                EditorEntityScenes.DependOnSceneGameObjects(sceneWithBuildConfiguration.SceneGUID, ctx);

                var config = BuildConfiguration.LoadAsset(sceneWithBuildConfiguration.BuildConfiguration);

                var scenePath = AssetDatabaseCompatibility.GuidToPath(sceneWithBuildConfiguration.SceneGUID);
                var scene     = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
                try
                {
                    EditorSceneManager.SetActiveScene(scene);

                    var settings = new GameObjectConversionSettings();

                    settings.SceneGUID = sceneWithBuildConfiguration.SceneGUID;
                    if (!sceneWithBuildConfiguration.IsBuildingForEditor)
                    {
                        settings.ConversionFlags |= GameObjectConversionUtility.ConversionFlags.IsBuildingForPlayer;
                    }

                    settings.BuildConfiguration = config;
                    settings.AssetImportContext = ctx;
                    settings.FilterFlags        = WorldSystemFilterFlags.HybridGameObjectConversion;

                    WriteEntitySceneSettings writeEntitySettings = new WriteEntitySceneSettings();
                    if (config != null && config.TryGetComponent <DotsRuntimeBuildProfile>(out var profile))
                    {
                        if (config.TryGetComponent <DotsRuntimeRootAssembly>(out var rootAssembly))
                        {
                            writeEntitySettings.Codec              = Codec.LZ4;
                            writeEntitySettings.IsDotsRuntime      = true;
                            writeEntitySettings.BuildAssemblyCache = new BuildAssemblyCache()
                            {
                                BaseAssemblies = rootAssembly.RootAssembly.asset,
                                PlatformName   = profile.Target.UnityPlatformName
                            };
                            settings.FilterFlags = WorldSystemFilterFlags.DotsRuntimeGameObjectConversion;

                            //Updating the root asmdef references or its references should re-trigger conversion
                            ctx.DependsOnArtifact(AssetDatabase.GetAssetPath(rootAssembly.RootAssembly.asset));
                            foreach (var assemblyPath in writeEntitySettings.BuildAssemblyCache.AssembliesPath)
                            {
                                ctx.DependsOnArtifact(assemblyPath);
                            }
                        }
                    }

                    var sectionRefObjs = new List <ReferencedUnityObjects>();
                    var sectionData    = EditorEntityScenes.ConvertAndWriteEntityScene(scene, settings, sectionRefObjs, writeEntitySettings);

                    WriteAssetDependencyGUIDs(sectionRefObjs, sectionData, ctx);

                    foreach (var objRefs in sectionRefObjs)
                    {
                        DestroyImmediate(objRefs);
                    }
                }
                finally
                {
                    EditorSceneManager.CloseScene(scene, true);
                }
            }
            // Currently it's not acceptable to let the asset database catch the exception since it will create a default asset without any dependencies
            // This means a reimport will not be triggered if the scene is subsequently modified
            catch (Exception e)
            {
                Debug.Log($"Exception thrown during SubScene import: {e}");
            }
        }
Exemplo n.º 29
0
 internal static extern void Internal_Build(BuildPlatform platform, BuildConfiguration configuration, string outputPath, BuildOptions options, string[] defines);
Exemplo n.º 30
0
                    /// <summary>
                    /// Runs the MSVC compiliation task for all given
                    /// configurations and architecture targets.
                    /// </summary>
                    /// <param name="config">
                    /// The configurations to compile against.
                    /// </param>
                    /// <param name="arch">
                    /// The architectures to use in assembly generation.
                    /// </param>
                    /// <returns>
                    /// True if the build task succeeded, false otherwise.
                    /// </returns>
                    public override bool Run(BuildConfiguration config, Architecture arch)
                    {
                        // Clean exceptions first.
                        Errors.Clear();

                        // First thing is to ensure that an acceptable version of MSVC is installed.
                        if (!InstalledToolVersions.ContainsKey(MinimumRequiredToolVersion))
                        {
                            Errors.Add(new Exception(string.Format("An installation of MSVC meeting the minimum required version of {0} could not be found.", MinimumRequiredToolVersion.ToString())));
                            return(false);
                        }

                        // Ensure that we have an output directory.
                        Debug.Assert(!string.IsNullOrEmpty(OutputDirectory) && !string.IsNullOrWhiteSpace(OutputDirectory), "No output directory defined.");
                        if (string.IsNullOrEmpty(OutputDirectory) || string.IsNullOrWhiteSpace(OutputDirectory))
                        {
                            Errors.Add(new Exception("No output directory defined."));
                            return(false);
                        }

                        // Ensure that we have an output file name.
                        Debug.Assert(!string.IsNullOrEmpty(OutputFileName) && !string.IsNullOrWhiteSpace(OutputFileName), "No output file name defined.");
                        if (string.IsNullOrEmpty(OutputFileName) || string.IsNullOrWhiteSpace(OutputFileName))
                        {
                            Errors.Add(new Exception("No output fine name defined."));
                            return(false);
                        }

                        // Ensure we have sources to compile.
                        Debug.Assert(Sources.Count > 0, "No sources defined.");
                        if (Sources.Count <= 0)
                        {
                            Errors.Add(new Exception("No sources defined."));
                            return(false);
                        }

                        // Make clones of all the various falgs. The reason for this
                        // is because the user might have specified non-target, non-plat
                        // specific flags, which we want to apply after we clear/reset
                        // them ever time we compile for a config.
                        var originalGlobalCompilerFlags = new List <string>(GlobalCompilerFlags);
                        var originalGlobalLinkerFlags   = new List <string>(GlobalLinkerFlags);

                        var originalReleaseCompilerFlags = new List <string>(ReleaseCompilerFlags);
                        var originalDebugCompilerFlags   = new List <string>(DebugCompilerFlags);

                        var originalReleaseLinkerFlags = new List <string>(ReleaseLinkerFlags);
                        var originalDebugLinkerFlags   = new List <string>(DebugLinkerFlags);

                        // Keep track of number of configs/archs we build for. Use
                        // these counts to determine success.
                        int totalCompilationAttempts = 0;
                        int totalCompilationSuccess  = 0;

                        // Iterate over set configuration flags. Then iterate over set
                        // arch flags, build out ENV for each configuration and run the
                        // build with that environment.
                        foreach (BuildConfiguration cfg in Enum.GetValues(typeof(BuildConfiguration)))
                        {
                            if (config.HasFlag(cfg))
                            {
                                foreach (Architecture a in Enum.GetValues(typeof(Architecture)))
                                {
                                    if (arch.HasFlag(a))
                                    {
                                        // Begin a compilation attempt for config/arch.
                                        ++totalCompilationAttempts;

                                        Console.WriteLine(string.Format("Running MSVC Compilation for config: {0} and arch: {1}.", cfg.ToString(), a.ToString()));

                                        // Reset flags to defaults.
                                        GlobalCompilerFlags  = new List <string>(originalGlobalCompilerFlags);
                                        GlobalLinkerFlags    = new List <string>(originalGlobalLinkerFlags);
                                        ReleaseCompilerFlags = new List <string>(originalReleaseCompilerFlags);
                                        DebugCompilerFlags   = new List <string>(originalDebugCompilerFlags);
                                        ReleaseLinkerFlags   = new List <string>(originalReleaseLinkerFlags);
                                        DebugLinkerFlags     = new List <string>(originalDebugLinkerFlags);

                                        // Add debug/release flags depending on current CFG.
                                        switch (cfg)
                                        {
                                        case BuildConfiguration.Debug:
                                        {
                                            GlobalCompilerFlags = GlobalCompilerFlags.Concat(DebugCompilerFlags).ToList();
                                        }
                                        break;

                                        case BuildConfiguration.Release:
                                        {
                                            GlobalCompilerFlags = GlobalCompilerFlags.Concat(ReleaseCompilerFlags).ToList();
                                        }
                                        break;
                                        }

                                        // Build intermediary directory
                                        string fullIntermediaryDir = string.Empty;

                                        if (!string.IsNullOrEmpty(IntermediaryDirectory) && !string.IsNullOrWhiteSpace(IntermediaryDirectory))
                                        {
                                            fullIntermediaryDir = IntermediaryDirectory.ConvertToHostOsPath();
                                        }
                                        else
                                        {
                                            // If not specified, use working directory.
                                            fullIntermediaryDir = WorkingDirectory;
                                        }

                                        // Build out so that it's Debug/Release x86/x64
                                        fullIntermediaryDir = fullIntermediaryDir + Path.DirectorySeparatorChar + string.Format("{0} {1}", cfg.ToString(), a.ToString());

                                        // Now we need the ENV vars for our tool version.
                                        var envVars = GetEnvironmentForVersion(MinimumRequiredToolVersion, a);

                                        // Force creation of intermediaries directory.
                                        Directory.CreateDirectory(fullIntermediaryDir);

                                        // Force creation of output directory for arch/config.
                                        string configArchOutDir = string.Format("{0}{1} {2}",
                                                                                OutputDirectory.ConvertToHostOsPath() + Path.DirectorySeparatorChar + "msvc" + Path.DirectorySeparatorChar,
                                                                                cfg.ToString(), a.ToString());

                                        // Set the intermediary output directory. We use a trailing slash
                                        // here because if we don't, the params won't parse properly when
                                        // passed to CL.exe.
                                        GlobalCompilerFlags.Add(string.Format("/Fo\"{0}/\"", fullIntermediaryDir));

                                        switch (a)
                                        {
                                        case Architecture.x86:
                                        {
                                            GlobalLinkerFlags.Add("/MACHINE:x86");
                                        }
                                        break;

                                        case Architecture.x64:
                                        {
                                            GlobalLinkerFlags.Add("/MACHINE:x64");
                                        }
                                        break;
                                        }

                                        // Whether we're merging the link command.
                                        bool isStaticLibrary = false;

                                        // Setup final output path. Create it first.
                                        Directory.CreateDirectory(configArchOutDir);
                                        string finalOutputPath = configArchOutDir + Path.DirectorySeparatorChar + OutputFileName;


                                        switch (OutputAssemblyType)
                                        {
                                        case AssemblyType.Unspecified:
                                        {
                                            Errors.Add(new Exception("No output assembly type specified."));
                                            return(false);
                                        }

                                        case AssemblyType.SharedLibrary:
                                        {
                                            // Define User/Win DLL.
                                            GlobalCompilerFlags.Add("/D_USRDLL");
                                            GlobalCompilerFlags.Add("/D_WINDLL");

                                            GlobalLinkerFlags.Add("/DLL");

                                            isStaticLibrary = true;

                                            // Add appropriate file extension.
                                            finalOutputPath += ".dll";
                                        }
                                        break;

                                        case AssemblyType.StaticLibrary:
                                        {
                                            // /c flag means don't link
                                            if (!GlobalCompilerFlags.Contains("/c"))
                                            {
                                                GlobalCompilerFlags.Add("/c");
                                            }

                                            // Add appropriate file extension.
                                            finalOutputPath += ".lib";
                                        }
                                        break;

                                        case AssemblyType.Executable:
                                        {
                                            isStaticLibrary = true;

                                            // Add appropriate file extension.
                                            finalOutputPath += ".exe";
                                        }
                                        break;
                                        }

                                        // Specify full output path. Spaces escaped later.
                                        GlobalLinkerFlags.Add(string.Format("/OUT:\"{0}\"", finalOutputPath));

                                        // Add debug/release flags to linker depending on current CFG.
                                        switch (cfg)
                                        {
                                        case BuildConfiguration.Debug:
                                        {
                                            GlobalLinkerFlags = GlobalLinkerFlags.Concat(DebugLinkerFlags).ToList();
                                        }
                                        break;

                                        case BuildConfiguration.Release:
                                        {
                                            GlobalLinkerFlags = GlobalLinkerFlags.Concat(ReleaseLinkerFlags).ToList();
                                        }
                                        break;
                                        }

                                        // Clone compile flags.
                                        var finalArgs = new List <string>(GlobalCompilerFlags);

                                        // Append includes.
                                        foreach (var inclPath in IncludePaths)
                                        {
                                            // Escape spaces in path.
                                            finalArgs.Add("/I");
                                            finalArgs.Add(inclPath.Replace(" ", @"\\ "));
                                        }

                                        // Append sources.
                                        finalArgs = finalArgs.Concat(Sources).ToList();

                                        if (isStaticLibrary)
                                        {
                                            // Add linker call if applicable.
                                            finalArgs.Add("/link");
                                            finalArgs = finalArgs.Concat(GlobalLinkerFlags).ToList();
                                        }
                                        else
                                        {
                                            // Add debug/release DLL flags depending on current CFG.
                                            // Shared runtime, as long as this isn't a static lib.
                                            switch (cfg)
                                            {
                                            case BuildConfiguration.Debug:
                                            {
                                                finalArgs.Add("/MDd");
                                            }
                                            break;

                                            case BuildConfiguration.Release:
                                            {
                                                finalArgs.Add("/MD");
                                            }
                                            break;
                                            }
                                        }

                                        // Run compiler.
                                        string clExe = "cl.exe";
                                        var    paths = envVars["PATH"].Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                                        // Need to obtain a full path to cl.exe
                                        var fullClPath = paths.Select(x => Path.Combine(x, clExe))
                                                         .Where(x => File.Exists(x))
                                                         .FirstOrDefault();

                                        if (!string.IsNullOrEmpty(fullClPath) && !string.IsNullOrWhiteSpace(fullClPath))
                                        {
                                            clExe = fullClPath;
                                        }
                                        else
                                        {
                                            Errors.Add(new Exception("Could not find absolute path to cl.exe"));
                                            return(false);
                                        }

                                        // Print final args.
                                        //Console.WriteLine(string.Join(" ", finalArgs));

                                        int compileReturnCode = RunProcess(WorkingDirectory, clExe, finalArgs, Timeout.Infinite, envVars);

                                        // If no auto linking, run LIB.
                                        if (!isStaticLibrary && compileReturnCode == 0)
                                        {
                                            // Basically means static library. So, we need to run
                                            // LIB tool.
                                            string libExe = "lib.exe";

                                            // Need to obtain a full path to lib.exe
                                            var fullLibPath = paths.Select(x => Path.Combine(x, libExe))
                                                              .Where(x => File.Exists(x))
                                                              .FirstOrDefault();

                                            if (!string.IsNullOrEmpty(fullLibPath) && !string.IsNullOrWhiteSpace(fullLibPath))
                                            {
                                                libExe = fullLibPath;
                                            }
                                            else
                                            {
                                                Errors.Add(new Exception("Could not find absolute path to lib.exe"));
                                                return(false);
                                            }

                                            var finalLibArgs = new List <string>();

                                            foreach (var libDir in LibraryPaths)
                                            {
                                                // Add all lib dirs with escaped spaces.
                                                finalLibArgs.Add(string.Format("/LIBPATH {0}", libDir.Replace(" ", @"\\ ")));
                                            }

                                            // Add all of our generated objects
                                            foreach (var objFile in Directory.GetFiles(fullIntermediaryDir))
                                            {
                                                finalLibArgs.Add(string.Format("\"{0}\"", objFile));
                                            }

                                            foreach (var linkerArg in GlobalLinkerFlags)
                                            {
                                                // Add all linker args with escaped spaces.
                                                finalLibArgs.Add(linkerArg);
                                            }

                                            // Print all final linker args.
                                            // Console.WriteLine(string.Join(" ", finalLibArgs));

                                            int libReturnCode = RunProcess(WorkingDirectory, libExe, finalLibArgs, Timeout.Infinite, envVars);

                                            if (libReturnCode != 0)
                                            {
                                                return(false);
                                            }
                                        }

                                        // CL always returns 0 for success. Any other value is failure:
                                        // Source:
                                        // https://msdn.microsoft.com/en-us/library/ebh0y918.aspx
                                        if (compileReturnCode != 0)
                                        {
                                            return(false);
                                        }
                                        else
                                        {
                                            ++totalCompilationSuccess;
                                        }
                                    } // End of if building for arch.
                                }     // End of foreach architecture.
                            }         // End of if building for config.
                        }             // End of foreach config.

                        bool success = totalCompilationAttempts > 0 && totalCompilationSuccess == totalCompilationAttempts;

                        if (success)
                        {
                            // Copy includes if we've successfully built a library and includes is specified.
                            switch (OutputAssemblyType)
                            {
                            case AssemblyType.SharedLibrary:
                            case AssemblyType.StaticLibrary:
                            {
                                // Only if auto copy is true.
                                if (AutoCopyIncludes)
                                {
                                    // Copy all .h, .hpp, .hxx etc.
                                    HashSet <string> exclusions = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                                    exclusions.Add(".c");
                                    exclusions.Add(".cpp");
                                    exclusions.Add(".cxx");

                                    foreach (var includePath in IncludePaths)
                                    {
                                        CopyDirectory(includePath, OutputDirectory + Path.DirectorySeparatorChar + "include", true, true, null, exclusions);
                                    }
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        // Always assume failure first.
                        return(success);
                    }
Exemplo n.º 31
0
 public IStepsRunner CreateStepsRunner(BuildConfiguration buildConfiguration)
 {
     return(stepsRunnerFactory(buildConfiguration));
 }
Exemplo n.º 32
0
 public Project()
 {
     Repositories              = new List <Repository>();
     Configurations            = new List <BuildConfiguration>();
     DefaultBuildConfiguration = new BuildConfiguration();
 }
Exemplo n.º 33
0
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            if (!ConfigureTools())
            {
                Errors.Add(new Exception("Failed to discover and or download git for boost modular build."));
                return false;
            }

            // Build out the base path to zlib.
            StringBuilder zlibBasePath = new StringBuilder(WorkingDirectory);
            zlibBasePath.Append(Path.DirectorySeparatorChar);
            zlibBasePath.Append("deps");
            zlibBasePath.Append(Path.DirectorySeparatorChar);
            zlibBasePath.Append("zlib");

            // Build out the base path to bzip2.
            StringBuilder bzip2BasePath = new StringBuilder(WorkingDirectory);
            bzip2BasePath.Append(Path.DirectorySeparatorChar);
            bzip2BasePath.Append("deps");
            bzip2BasePath.Append(Path.DirectorySeparatorChar);
            bzip2BasePath.Append("bzip2");

            // Build out the base path to the boost source directory.
            StringBuilder boostBasePath = new StringBuilder(WorkingDirectory);
            boostBasePath.Append(Path.DirectorySeparatorChar);
            boostBasePath.Append("deps");
            boostBasePath.Append(Path.DirectorySeparatorChar);
            boostBasePath.Append("boost");

            var boostWorkingDirectory = boostBasePath.ToString().ConvertToHostOsPath();
            
            if (!InitializeSubmodules(boostWorkingDirectory))
            {
                Errors.Add(new Exception("Failed to initialize boost submodules."));
                return false;
            }            

            if (!InitializeBoostBuild(boostWorkingDirectory))
            {
                Errors.Add(new Exception("Failed to initialize boost build engine."));
                return false;
            }
            
            // Do build for each config + arch.
            foreach (BuildConfiguration cfg in Enum.GetValues(typeof(BuildConfiguration)))
            {
                if (config.HasFlag(cfg))
                {
                    foreach (Architecture a in Enum.GetValues(typeof(Architecture)))
                    {
                        if (arch.HasFlag(a))
                        {
                            var firstPassBuildArgs = new List<string>();
                            firstPassBuildArgs.Add("-a");
                            firstPassBuildArgs.Add(string.Format("-j{0}", Environment.ProcessorCount));
                            firstPassBuildArgs.Add("--toolset=msvc");
                            firstPassBuildArgs.Add("--layout=system");
                            firstPassBuildArgs.Add("cxxflags=\"-D_WIN32_WINNT=0x0600\"");
                            firstPassBuildArgs.Add("cflags=\"-D_WIN32_WINNT=0x0600\"");
                            firstPassBuildArgs.Add("link=shared");
                            firstPassBuildArgs.Add("threading=multi");
                            
                            switch(a)
                            {
                                case Architecture.x86:
                                {
                                    firstPassBuildArgs.Add("address-model=32");
                                }
                                break;

                                case Architecture.x64:
                                {
                                    firstPassBuildArgs.Add("address-model=64");
                                }
                                break;
                            }

                            firstPassBuildArgs.Add("--stagedir=\"stage" + Path.DirectorySeparatorChar + "msvc" + Path.DirectorySeparatorChar + String.Format("{0} {1}", cfg.ToString(), a.ToString()) + "\"");
                            
                            var secondPassArgs = new List<string>(firstPassBuildArgs);

                            // Add debug/release to args.
                            firstPassBuildArgs.Add(cfg.ToString().ToLower());

                            firstPassBuildArgs.Add("stage");

                            WriteLineToConsole(string.Join(" ", firstPassBuildArgs));

                            secondPassArgs.Add("--with-iostreams");
                            secondPassArgs.Add("-sNO_COMPRESSION=0");
                            secondPassArgs.Add("-sNO_ZLIB=0");                            
                            secondPassArgs.Add(string.Format("-sBZIP2_SOURCE={0}", bzip2BasePath.ToString()));
                            secondPassArgs.Add(string.Format("-sZLIB_SOURCE={0}", zlibBasePath.ToString()));                            

                            // Add debug/release to args.
                            secondPassArgs.Add(cfg.ToString().ToLower());

                            secondPassArgs.Add("stage");

                            var b2Path = boostWorkingDirectory + Path.DirectorySeparatorChar + "b2.exe";

                            if(RunProcess(boostWorkingDirectory, b2Path, firstPassBuildArgs) != 0)
                            {
                                Errors.Add(new Exception(string.Format("Failed first pass build of boost for configuration {0} and arch {1}.", cfg.ToString(), a.ToString())));
                                return false;
                            }

                            if(RunProcess(boostWorkingDirectory, b2Path, secondPassArgs) != 0)
                            {
                                Errors.Add(new Exception(string.Format("Failed second pass build of boost for configuration {0} and arch {1}.", cfg.ToString(), a.ToString())));
                                return false;
                            }
                        }
                    }
                }
            }

            return true;
        }
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            // Clear errors before trying.
            Errors.Clear();

            if (!SupportedArchitectures.HasFlag(arch))
            {
                Errors.Add(new Exception("Unsupported architecture specified for build task."));
                return false;
            }

            if (!ConfigureDirectories())
            {
                Errors.Add(new Exception("Failed to configure arch specific directories for openSSL build."));
                return false;
            }

            // We need to get the environment for a the MSVC compiler and
            // associated build tools.
            var installedMsvcVersions = MSVCCompilerTask.InstalledToolVersions;

            if (installedMsvcVersions.Count == 0)
            {
                Errors.Add(new Exception("Could not detect a compatible installation of MSVC."));
                return false;
            }

            // Get a reversed list of tool versions and iterate over them, until we find
            // an installed version. This way we're always working with the latest
            // version available.
            var allVersions = Enum.GetValues(typeof(ToolVersions)).Cast<ToolVersions>().Reverse();

            ToolVersions versionToUse = ToolVersions.v11;

            foreach (var msvcVersion in allVersions)
            {
                if (installedMsvcVersions.ContainsKey(msvcVersion))
                {
                    versionToUse = msvcVersion;
                    WriteLineToConsole(string.Format("Discovered and using MSVC {0} for compilation.", versionToUse.ToString()));
                    break;
                }
            }

            // Build out the base path to the openSSL source directory.
            StringBuilder opensslBasePath = new StringBuilder(WorkingDirectory);
            opensslBasePath.Append(Path.DirectorySeparatorChar);
            opensslBasePath.Append("deps");
            opensslBasePath.Append(Path.DirectorySeparatorChar);
            opensslBasePath.Append("openssl");

            int numCompilationAttempts = 0;
            int numSuccessfulCompilations = 0;

            // We're only going to iterate over arches. We're not going to build a debug
            // version of openSSL, just release versions for each arch.
            foreach (Architecture a in Enum.GetValues(typeof(Architecture)))
            {
                if (arch.HasFlag(a))
                {
                    ++numCompilationAttempts;

                    var finalBuildEnvironment = MSVCCompilerTask.GetEnvironmentForVersion(versionToUse, a);

                    // Add perl path if it doesn't already exist.
                    if (finalBuildEnvironment["PATH"].IndexOf(m_perlDir) == -1)
                    {
                        finalBuildEnvironment["PATH"] += (Path.PathSeparator + m_perlDir);
                    }

                    var configArgs = new List<string>();

                    configArgs.Add("no-idea");
                    configArgs.Add("no-mdc2");
                    configArgs.Add("no-rc5");
                    configArgs.Add("no-comp");

                    // XXX TODO - Remove this option when upgrading to openSSL 1.1.0
                    configArgs.Add("no-ssl2");

                    configArgs.Add("no-ssl3");
                    configArgs.Add("no-weak-ssl-ciphers");
                    configArgs.Add("threads");

                    // The working dir. This will either be the x86 or x64 openSSL source dir.
                    string workingDirectory = string.Empty;

                    // We need to include nasm regardless of rater arch because
                    // the openSSL configuration system will whine and quit if
                    // we don't. We should be guaranteed to have a PATH variable
                    // here unless something went horribly wrong.
                    finalBuildEnvironment["PATH"] += (Path.PathSeparator + m_nasmDir);

                    // XXX TODO - This needs to go away when we bump to OpenSSL 1.1.0
                    string whichAsmCall = string.Empty;

                    string openSslInstallDir = string.Empty;

                    switch (a)
                    {
                        case Architecture.x86:
                            {

                                // Build inside the x86 dir
                                workingDirectory = m_openSslx86Dir;

                                // Set x86 release build.
                                configArgs.Insert(0, "VC-WIN32");

                                whichAsmCall = "ms" + Path.DirectorySeparatorChar + "do_nasm.bat";

                                openSslInstallDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                            Path.DirectorySeparatorChar +
                                            "msvc" +
                                            Path.DirectorySeparatorChar +
                                            "Releasex86";
                            }
                            break;

                        case Architecture.x64:
                            {
                                // Build inside the x64 dir
                                workingDirectory = m_openSslx64Dir;

                                whichAsmCall = "ms" + Path.DirectorySeparatorChar + "do_win64a.bat";

                                // Set x64 release build.
                                configArgs.Insert(0, "VC-WIN64A");

                                openSslInstallDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                            Path.DirectorySeparatorChar +
                                            "msvc" +
                                            Path.DirectorySeparatorChar +
                                            "Releasex64";                                
                            }
                            break;

                        default:
                            {
                                WriteLineToConsole(string.Format("Dont have arch: {0}", a.ToString()));
                                continue;
                            }
                    }

                    // Setup prefix (output) path to deps/openssl/msvc/ReleaseX64
                                configArgs.Add(
                                    string.Format(
                                        "--prefix={0}",
                                       openSslInstallDir)
                                            );

                                // Setup config path to deps/openssl/msvc/ReleaseX86
                                configArgs.Add(
                                    string.Format(
                                        "--openssldir={0}",
                                        openSslInstallDir)
                                            );


                    WriteLineToConsole(string.Format("Configuring for arch: {0}", a.ToString()));

                    WriteLineToConsole(workingDirectory);

                    WriteLineToConsole(string.Format("Config Path: {0}", workingDirectory + Path.DirectorySeparatorChar + "Configure"));

                    // Push configure script to front of args.
                    configArgs.Insert(0, "Configure");

                    WriteLineToConsole(string.Join(" ", configArgs));

                    // Run the configuration process.
                    var perlExitCode = RunProcess(workingDirectory, m_perlDir + Path.DirectorySeparatorChar + "perl.exe", configArgs, Timeout.Infinite, finalBuildEnvironment);

                    // Now run the actual build process.

                    // Example of the call string expanded/populated:
                    // call "ms\do_nasm.bat" && nmake -f ms\ntdll.mak && nmake -f ms\ntdll.mak install
                    
                    string callArgs = string.Format("/C \"{0}\" && {1} && {2}", whichAsmCall, "nmake -f ms" + Path.DirectorySeparatorChar + "ntdll.mak", "nmake -f ms" + Path.DirectorySeparatorChar + "ntdll.mak install");

                    // XXX TODO - This is way to do it when we jump up to OpenSSL 1.1.0
                    //string callArgs = string.Format("/C {0} && {1}", "nmake", "nmake install");

                    // Running cmd.exe with these batch commands will build openSSL.
                    var buildExitCode = RunProcess(workingDirectory, "cmd.exe", new List<string> { callArgs }, Timeout.Infinite, finalBuildEnvironment);

                    if(perlExitCode == 0 && buildExitCode == 0)
                    {
                        // Was a success. Move the output folder now.
                        var destBaseDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                            Path.DirectorySeparatorChar +
                                            "msvc" +
                                            Path.DirectorySeparatorChar;

                        var destReleaseDir = destBaseDir + string.Format("{0} {1}", BuildConfiguration.Release.ToString(), a.ToString());
                        var destDebugDir = destBaseDir + string.Format("{0} {1}", BuildConfiguration.Debug.ToString(), a.ToString());

                        // If we don't delete old stuff, Directory.Move will fail.
                        if(Directory.Exists(destReleaseDir))
                        {
                            Directory.Delete(destReleaseDir, true);
                        }

                        // Move aka rename the directory to have a space.
                        try
						{
							Directory.Move(openSslInstallDir, destReleaseDir);
						}
						catch 
						{
							// Sometimes getting access denied. Perhaps parts of the build
							// process are still hanging. Try and give them a few seconds
							// to wrap up, then try again.
							Thread.Sleep(3000);
							
							Directory.Move(openSslInstallDir, destReleaseDir);
						}
                        
                        // Simply copy the release folder for arch to a debug folder.
                        CopyDirectory(destReleaseDir, destDebugDir, true);

                        ++numSuccessfulCompilations;
                    }
                }
            }

            var wasSuccess = numCompilationAttempts > 0 && numCompilationAttempts == numSuccessfulCompilations;

            return wasSuccess;
        }
Exemplo n.º 35
0
 public abstract CppToolChain MakeCppToolChain(Unity.IL2CPP.Building.Architecture architecture, BuildConfiguration buildConfiguration, bool treatWarningsAsErrors);
Exemplo n.º 36
0
 private static Project CreateProject(string projectId, Project[] childProjects,
     BuildConfiguration[] buildConfigurations)
 {
     return new Project
     {
         Id = projectId,
         BuildTypes = new BuildTypeWrapper {BuildType = new List<BuildConfiguration>(buildConfigurations)},
         Projects = new ProjectWrapper {Project = new List<Project>(childProjects)}
     };
 }
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            // All we're gonna do here is make sure we've got all of our submodules
            // present and ready to go.

            if (!ConfigureTools())
            {
                Errors.Add(new Exception("Failed to discover and or download git."));
                return false;
            }

            // Build out the base path to our submodules.
            StringBuilder submoduleBasePath = new StringBuilder(WorkingDirectory);
            submoduleBasePath.Append(Path.DirectorySeparatorChar);
            submoduleBasePath.Append("deps");

			var fullGitPath = m_gitDir + Path.DirectorySeparatorChar + "git.exe";
			
			WriteLineToConsole("Initializing submodules ...");

            if (RunProcess(WorkingDirectory, fullGitPath, new List<string>(new[] { "submodule update --init"})) != 0)
            {				
				WriteLineToConsole("Failed to initialize submodules."); 
				return false;
            }
			
            var submoduleDirs = Directory.GetDirectories(submoduleBasePath.ToString(), "*.*", SearchOption.TopDirectoryOnly);

            var checkoutAttempts = 0;
            var successfulCheckouts = 0;            

			// Now we do recursive init on each submodule, except boost.
            foreach (var submodulePath in submoduleDirs)
            {
                ++checkoutAttempts;

                var dirInfo = new DirectoryInfo(submodulePath);

                string checkoutCommand = string.Empty;
                string submoduleIdentifier = "deps" + Path.DirectorySeparatorChar + dirInfo.Name;

                // We want to recursively init everything EXCEPT boost.
                if (!dirInfo.Name.Equals("boost", StringComparison.OrdinalIgnoreCase))
                {
                    checkoutCommand += "--recursive";
                }

                checkoutCommand += " " + submoduleIdentifier;

                WriteLineToConsole(string.Format("Initializing submodule {0} ...", submoduleIdentifier));

                if (RunProcess(WorkingDirectory, fullGitPath, new List<string>(new[] { "submodule update --init " + checkoutCommand })) == 0)
                {
                    ++successfulCheckouts;
                    WriteLineToConsole(string.Format("Submodule {0} successfully initialized.", submoduleIdentifier));
                }
                else
                {
                    WriteLineToConsole(string.Format("Failed to initialize submodule {0}.", submoduleIdentifier));
                }
            }

            return checkoutAttempts > 0 && successfulCheckouts == checkoutAttempts;
        }
Exemplo n.º 38
0
 public void SetBuildConfiguration(BuildConfiguration buildConfiguration)
 {
     m_BuildConfiguration = buildConfiguration;
 }
Exemplo n.º 39
0
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            // Means we didn't find git.
            var    toolsPath = WorkingDirectory + Path.DirectorySeparatorChar + "tools";
            string portableGitDownloadUri = string.Empty;
            string portableGitSha256      = string.Empty;

            portableGitDownloadUri = @"https://github.com/basil00/Divert/releases/download/v1.2.0-rc/WinDivert-1.2.0-rc-MSVC.zip";
            portableGitSha256      = @"7A194D5066C4093A370E3EA474371A4CF9976D28763C253D9DDF312BC2B33715";

            var portableGitZipName = "WinDivert.zip";

            var fullZipPath = toolsPath + Path.DirectorySeparatorChar + portableGitZipName;

            bool zipAlreadyExists = File.Exists(fullZipPath);

            if (zipAlreadyExists)
            {
                WriteLineToConsole("Discovered previous download. Verifying integrity.");

                // Just let it revert to false if hash doesn't match. The file
                // would simply be overwritten.
                zipAlreadyExists = VerifyFileHash(HashAlgorithmName.SHA256, fullZipPath, portableGitSha256);

                if (!zipAlreadyExists)
                {
                    WriteLineToConsole("Integrity check failed. Attempting clean download.");
                }
                else
                {
                    WriteLineToConsole("Integrity check passed. Using cached download.");
                }
            }

            if (!zipAlreadyExists)
            {
                var downloadTask = DownloadFile(portableGitDownloadUri, toolsPath, null, portableGitZipName);
                downloadTask.Wait();

                if (!VerifyFileHash(HashAlgorithmName.SHA256, fullZipPath, portableGitSha256))
                {
                    throw new Exception("Downloaded file does not match expected hash.");
                }
            }

            // Before decompressing again, let's see if we can find an already
            // decompressed perl.exe.
            var decompressedPath = WorkingDirectory + Path.DirectorySeparatorChar + "deps" + Path.DirectorySeparatorChar + "windivert" + Path.DirectorySeparatorChar + "msvc";

            string[] existingGitPaths = new string[0];

            if (Directory.Exists(decompressedPath))
            {
                existingGitPaths = Directory.GetFiles(decompressedPath, "WinDivert.dll", SearchOption.AllDirectories);

                if (existingGitPaths.Length > 0)
                {
                    return(true);
                }
            }

            // If we reached here, then we need to decompress.
            DecompressArchive(fullZipPath, decompressedPath);

            // Collapse the top directory which contains version
            // info and rename the 64 bit folder from amd64 to x64.
            var amd64Path = Directory.GetDirectories(decompressedPath, "amd64", SearchOption.AllDirectories);

            if (amd64Path.Length != 1)
            {
                WriteLineToConsole("Failed to find WinDivert 64 bit library in extracted package.");
                return(false);
            }

            var parentDir = Directory.GetParent(amd64Path[0]);

            var allDirs = Directory.GetDirectories(parentDir.FullName, "*.*", SearchOption.TopDirectoryOnly);

            foreach (var dir in allDirs)
            {
                var dirInfo = new DirectoryInfo(dir);
                if (dirInfo.Name.Equals("amd64", StringComparison.OrdinalIgnoreCase))
                {
                    Directory.Move(dir, decompressedPath + Path.DirectorySeparatorChar + "x64");
                }
                else
                {
                    Directory.Move(dir, decompressedPath + Path.DirectorySeparatorChar + dirInfo.Name);
                }
            }

            // Delete the now empty, version specific folder.
            Directory.Delete(parentDir.FullName, true);

            existingGitPaths = Directory.GetFiles(decompressedPath, "WinDivert.dll", SearchOption.AllDirectories);

            if (existingGitPaths.Length == 0)
            {
                WriteLineToConsole("Failed to find WinDivert library in extracted package.");
                return(false);
            }

            return(true);
        }
Exemplo n.º 40
0
        private void SaveGeneratedPart(LDD.Parts.PartWrapper part, BuildConfiguration buildConfig)
        {
            if (buildConfig.InternalFlag == 1)
            {
                part.SaveToLdd(LDDEnvironment.Current);
                MessageBox.Show("Part files generated!");
                return;
            }
            string targetPath = buildConfig.OutputPath;

            if (targetPath.Contains("$"))
            {
                targetPath = ProjectManager.ExpandVariablePath(targetPath);
            }

            if (buildConfig.InternalFlag == 2 || string.IsNullOrEmpty(buildConfig.OutputPath))
            {
                using (var sfd = new SaveFileDialog())
                {
                    if (!string.IsNullOrEmpty(targetPath) &&
                        FileHelper.IsValidDirectory(targetPath))
                    {
                        sfd.InitialDirectory = targetPath;
                    }

                    sfd.FileName = part.PartID.ToString();
                    //if (buildConfig.CreateZip)
                    //{
                    //    sfd.FileName += ".zip";
                    //    sfd.DefaultExt = ".zip";
                    //}

                    if (sfd.ShowDialog() != DialogResult.OK)
                    {
                        //show canceled message
                        return;
                    }

                    //if (buildConfig.CreateZip)
                    //    targetPath = sfd.FileName;
                    //else
                    targetPath = Path.GetDirectoryName(sfd.FileName);
                }
            }

            Directory.CreateDirectory(targetPath);
            part.SavePrimitive(targetPath);

            if (!buildConfig.LOD0Subdirectory)
            {
                part.SaveMeshes(targetPath);
            }
            else
            {
                targetPath = Path.Combine(targetPath, "LOD0");
                Directory.CreateDirectory(targetPath);
                part.SaveMeshes(targetPath);
            }

            MessageBox.Show("Part files generated!");
        }
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            // Means we didn't find git.
            var toolsPath = WorkingDirectory + Path.DirectorySeparatorChar + "tools";
            string portableGitDownloadUri = string.Empty;
            string portableGitSha256 = string.Empty;

            portableGitDownloadUri = @"https://github.com/basil00/Divert/releases/download/v1.2.0-rc/WinDivert-1.2.0-rc-MSVC.zip";
            portableGitSha256 = @"7A194D5066C4093A370E3EA474371A4CF9976D28763C253D9DDF312BC2B33715";

            var portableGitZipName = "WinDivert.zip";

            var fullZipPath = toolsPath + Path.DirectorySeparatorChar + portableGitZipName;

            bool zipAlreadyExists = File.Exists(fullZipPath);

            if (zipAlreadyExists)
            {
                WriteLineToConsole("Discovered previous download. Verifying integrity.");

                // Just let it revert to false if hash doesn't match. The file
                // would simply be overwritten.
                zipAlreadyExists = VerifyFileHash(HashAlgorithmName.SHA256, fullZipPath, portableGitSha256);

                if (!zipAlreadyExists)
                {
                    WriteLineToConsole("Integrity check failed. Attempting clean download.");
                }
                else
                {
                    WriteLineToConsole("Integrity check passed. Using cached download.");
                }
            }

            if (!zipAlreadyExists)
            {
                var downloadTask = DownloadFile(portableGitDownloadUri, toolsPath, null, portableGitZipName);
                downloadTask.Wait();

                if (!VerifyFileHash(HashAlgorithmName.SHA256, fullZipPath, portableGitSha256))
                {
                    throw new Exception("Downloaded file does not match expected hash.");
                }
            }

            // Before decompressing again, let's see if we can find an already
            // decompressed perl.exe.
            var decompressedPath = WorkingDirectory + Path.DirectorySeparatorChar + "deps" + Path.DirectorySeparatorChar + "windivert" + Path.DirectorySeparatorChar + "msvc";

            string[] existingGitPaths = new string[0];

            if (Directory.Exists(decompressedPath))
            {
                existingGitPaths = Directory.GetFiles(decompressedPath, "WinDivert.dll", SearchOption.AllDirectories);

                if (existingGitPaths.Length > 0)
                {
                    return true;
                }
            }

            // If we reached here, then we need to decompress.
            DecompressArchive(fullZipPath, decompressedPath);

            // Collapse the top directory which contains version 
            // info and rename the 64 bit folder from amd64 to x64.
            var amd64Path = Directory.GetDirectories(decompressedPath, "amd64", SearchOption.AllDirectories);

            if(amd64Path.Length != 1)
            {
                WriteLineToConsole("Failed to find WinDivert 64 bit library in extracted package.");
                return false;
            }

            var parentDir = Directory.GetParent(amd64Path[0]);

            var allDirs = Directory.GetDirectories(parentDir.FullName, "*.*", SearchOption.TopDirectoryOnly);

            foreach(var dir in allDirs)
            {
                var dirInfo = new DirectoryInfo(dir);
                if(dirInfo.Name.Equals("amd64", StringComparison.OrdinalIgnoreCase))
                {
                    Directory.Move(dir, decompressedPath + Path.DirectorySeparatorChar + "x64");
                }
                else
                {
                    Directory.Move(dir, decompressedPath + Path.DirectorySeparatorChar + dirInfo.Name);
                }
            }

            // Delete the now empty, version specific folder.
            Directory.Delete(parentDir.FullName, true);

            existingGitPaths = Directory.GetFiles(decompressedPath, "WinDivert.dll", SearchOption.AllDirectories);

            if (existingGitPaths.Length == 0)
            {
                WriteLineToConsole("Failed to find WinDivert library in extracted package.");
                return false;
            }

            return true;
        
        }        
 public override CppToolChain MakeCppToolChain(Unity.IL2CPP.Building.Architecture architecture, BuildConfiguration buildConfiguration, bool treatWarningsAsErrors)
 {
     return new AndroidToolChain(architecture, buildConfiguration, treatWarningsAsErrors, new NPath(""));
 }
Exemplo n.º 43
0
        public override bool Run(BuildConfiguration config, Architecture arch)
        {
            // Clear errors before trying.
            Errors.Clear();

            if (!SupportedArchitectures.HasFlag(arch))
            {
                Errors.Add(new Exception("Unsupported architecture specified for build task."));
                return(false);
            }

            if (!ConfigureDirectories())
            {
                Errors.Add(new Exception("Failed to configure arch specific directories for openSSL build."));
                return(false);
            }

            // We need to get the environment for a the MSVC compiler and
            // associated build tools.
            var installedMsvcVersions = MSVCCompilerTask.InstalledToolVersions;

            if (installedMsvcVersions.Count == 0)
            {
                Errors.Add(new Exception("Could not detect a compatible installation of MSVC."));
                return(false);
            }

            // Get a reversed list of tool versions and iterate over them, until we find
            // an installed version. This way we're always working with the latest
            // version available.
            var allVersions = Enum.GetValues(typeof(ToolVersions)).Cast <ToolVersions>().Reverse();

            ToolVersions versionToUse = ToolVersions.v11;

            foreach (var msvcVersion in allVersions)
            {
                if (installedMsvcVersions.ContainsKey(msvcVersion))
                {
                    versionToUse = msvcVersion;
                    WriteLineToConsole(string.Format("Discovered and using MSVC {0} for compilation.", versionToUse.ToString()));
                    break;
                }
            }

            // Build out the base path to the openSSL source directory.
            StringBuilder opensslBasePath = new StringBuilder(WorkingDirectory);

            opensslBasePath.Append(Path.DirectorySeparatorChar);
            opensslBasePath.Append("deps");
            opensslBasePath.Append(Path.DirectorySeparatorChar);
            opensslBasePath.Append("openssl");

            int numCompilationAttempts    = 0;
            int numSuccessfulCompilations = 0;

            // We're only going to iterate over arches. We're not going to build a debug
            // version of openSSL, just release versions for each arch.
            foreach (Architecture a in Enum.GetValues(typeof(Architecture)))
            {
                if (arch.HasFlag(a))
                {
                    ++numCompilationAttempts;

                    var finalBuildEnvironment = MSVCCompilerTask.GetEnvironmentForVersion(versionToUse, a);

                    // Add perl path if it doesn't already exist.
                    if (finalBuildEnvironment["PATH"].IndexOf(m_perlDir) == -1)
                    {
                        finalBuildEnvironment["PATH"] += (Path.PathSeparator + m_perlDir);
                    }

                    var configArgs = new List <string>();

                    configArgs.Add("no-idea");
                    configArgs.Add("no-mdc2");
                    configArgs.Add("no-rc5");
                    configArgs.Add("no-comp");

                    // XXX TODO - Remove this option when upgrading to openSSL 1.1.0
                    configArgs.Add("no-ssl2");

                    configArgs.Add("no-ssl3");
                    configArgs.Add("no-weak-ssl-ciphers");
                    configArgs.Add("threads");

                    // The working dir. This will either be the x86 or x64 openSSL source dir.
                    string workingDirectory = string.Empty;

                    // We need to include nasm regardless of rater arch because
                    // the openSSL configuration system will whine and quit if
                    // we don't. We should be guaranteed to have a PATH variable
                    // here unless something went horribly wrong.
                    finalBuildEnvironment["PATH"] += (Path.PathSeparator + m_nasmDir);

                    // XXX TODO - This needs to go away when we bump to OpenSSL 1.1.0
                    string whichAsmCall = string.Empty;

                    string openSslInstallDir = string.Empty;

                    switch (a)
                    {
                    case Architecture.x86:
                    {
                        // Build inside the x86 dir
                        workingDirectory = m_openSslx86Dir;

                        // Set x86 release build.
                        configArgs.Insert(0, "VC-WIN32");

                        whichAsmCall = "ms" + Path.DirectorySeparatorChar + "do_nasm.bat";

                        openSslInstallDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                            Path.DirectorySeparatorChar +
                                            "msvc" +
                                            Path.DirectorySeparatorChar +
                                            "Releasex86";
                    }
                    break;

                    case Architecture.x64:
                    {
                        // Build inside the x64 dir
                        workingDirectory = m_openSslx64Dir;

                        whichAsmCall = "ms" + Path.DirectorySeparatorChar + "do_win64a.bat";

                        // Set x64 release build.
                        configArgs.Insert(0, "VC-WIN64A");

                        openSslInstallDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                            Path.DirectorySeparatorChar +
                                            "msvc" +
                                            Path.DirectorySeparatorChar +
                                            "Releasex64";
                    }
                    break;

                    default:
                    {
                        WriteLineToConsole(string.Format("Dont have arch: {0}", a.ToString()));
                        continue;
                    }
                    }

                    // Setup prefix (output) path to deps/openssl/msvc/ReleaseX64
                    configArgs.Add(
                        string.Format(
                            "--prefix={0}",
                            openSslInstallDir)
                        );

                    // Setup config path to deps/openssl/msvc/ReleaseX86
                    configArgs.Add(
                        string.Format(
                            "--openssldir={0}",
                            openSslInstallDir)
                        );


                    WriteLineToConsole(string.Format("Configuring for arch: {0}", a.ToString()));

                    WriteLineToConsole(workingDirectory);

                    WriteLineToConsole(string.Format("Config Path: {0}", workingDirectory + Path.DirectorySeparatorChar + "Configure"));

                    // Push configure script to front of args.
                    configArgs.Insert(0, "Configure");

                    WriteLineToConsole(string.Join(" ", configArgs));

                    // Run the configuration process.
                    var perlExitCode = RunProcess(workingDirectory, m_perlDir + Path.DirectorySeparatorChar + "perl.exe", configArgs, Timeout.Infinite, finalBuildEnvironment);

                    // Now run the actual build process.

                    // Example of the call string expanded/populated:
                    // call "ms\do_nasm.bat" && nmake -f ms\ntdll.mak && nmake -f ms\ntdll.mak install

                    string callArgs = string.Format("/C \"{0}\" && {1} && {2}", whichAsmCall, "nmake -f ms" + Path.DirectorySeparatorChar + "ntdll.mak", "nmake -f ms" + Path.DirectorySeparatorChar + "ntdll.mak install");

                    // XXX TODO - This is way to do it when we jump up to OpenSSL 1.1.0
                    //string callArgs = string.Format("/C {0} && {1}", "nmake", "nmake install");

                    // Running cmd.exe with these batch commands will build openSSL.
                    var buildExitCode = RunProcess(workingDirectory, "cmd.exe", new List <string> {
                        callArgs
                    }, Timeout.Infinite, finalBuildEnvironment);

                    if (perlExitCode == 0 && buildExitCode == 0)
                    {
                        // Was a success. Move the output folder now.
                        var destBaseDir = opensslBasePath.ToString().ConvertToHostOsPath() +
                                          Path.DirectorySeparatorChar +
                                          "msvc" +
                                          Path.DirectorySeparatorChar;

                        var destReleaseDir = destBaseDir + string.Format("{0} {1}", BuildConfiguration.Release.ToString(), a.ToString());
                        var destDebugDir   = destBaseDir + string.Format("{0} {1}", BuildConfiguration.Debug.ToString(), a.ToString());

                        // If we don't delete old stuff, Directory.Move will fail.
                        if (Directory.Exists(destReleaseDir))
                        {
                            Directory.Delete(destReleaseDir, true);
                        }

                        // Move aka rename the directory to have a space.
                        try
                        {
                            Directory.Move(openSslInstallDir, destReleaseDir);
                        }
                        catch
                        {
                            // Sometimes getting access denied. Perhaps parts of the build
                            // process are still hanging. Try and give them a few seconds
                            // to wrap up, then try again.
                            Thread.Sleep(3000);

                            Directory.Move(openSslInstallDir, destReleaseDir);
                        }

                        // Simply copy the release folder for arch to a debug folder.
                        CopyDirectory(destReleaseDir, destDebugDir, true);

                        ++numSuccessfulCompilations;
                    }
                }
            }

            var wasSuccess = numCompilationAttempts > 0 && numCompilationAttempts == numSuccessfulCompilations;

            return(wasSuccess);
        }
 public BuildConfiguration Copy()
 {
     BuildConfiguration bc = new BuildConfiguration(target, options);
     bc.scenes = scenes;
     bc.scenesToggle = scenesToggle;
     bc.enabled = enabled;
     bc.name = name;
     bc.customDefineSymbols = customDefineSymbols;
     return bc;
 }
Exemplo n.º 45
0
        public static void BuildTo(BuildConfiguration buildConfiguration, string path)
        {
            var buildTarget      = EditorUserBuildSettings.activeBuildTarget;
            var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);

            /*
             * Debug
             * Develop
             * Release
             */
            void ProfileConfiguration(ClassicBuildProfile profile, string s) => profile.Configuration = (BuildType)Enum.Parse(typeof(BuildType), s, true);

            SetBuildComponentValue <ClassicBuildProfile>(buildConfiguration, "-BUILD_PROFILE_CONFIGURATION", ProfileConfiguration);

            /*
             * Mono2x
             * IL2CPP
             * WinRTDotNET
             */
            void ScriptingBackend(ClassicScriptingSettings profile, string s) => profile.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), s, true);

            SetBuildComponentValue <ClassicScriptingSettings>(buildConfiguration, "-BUILD_SCRIPTING_BACKEND", ScriptingBackend);

            /*
             * Debug
             * Release
             * Master
             */
            void Il2CppCompilerConfiguration(ClassicScriptingSettings profile, string s) => profile.Il2CppCompilerConfiguration = (Il2CppCompilerConfiguration)Enum.Parse(typeof(Il2CppCompilerConfiguration), s, true);;
            SetBuildComponentValue <ClassicScriptingSettings>(buildConfiguration, "-BUILD_SCRIPTING_IL2CPP_CONFIGURATION", Il2CppCompilerConfiguration);

            var graphicsJobs = PlayerSettings.graphicsJobs;

            try {
                PlayerSettings.graphicsJobs = bool.Parse(CommandLineArguments.ReadArgValue("-GRAPHICS_JOBS"));
                Debug.Log($"[{typeof(ScriptableBuildPipeline)}] PlayerSettings.graphicsJobs = {PlayerSettings.graphicsJobs}");
            } catch (CommandLineArguments.CommandLineArgumentNotFoundException) { /*Ignore*/ }

            try {
                var version = CommandLineArguments.ReadArgValue("-BUILD_NUMBER");
                PlayerSettings.bundleVersion = version;

                if (buildTarget == BuildTarget.iOS || Application.platform == RuntimePlatform.OSXPlayer)
                {
                    PlayerSettings.iOS.buildNumber = version;
                }

                if (buildTarget == BuildTarget.Android)
                {
                    var match = new Regex(@"^(\d{1})\.(\d{1})\.(\d{1,3})$").Match(version);
                    if (!match.Success)
                    {
                        throw new InvalidOperationException($"BUILD_NUMBER {version} is not in the format #{{1}}.#{{1}}.#{{1-3}} for conversion to Android bundleVersionCode");
                    }
                    int bundleVersionCode = 0;
                    bundleVersionCode += int.Parse(match.Groups[1].Value) * 10000;
                    bundleVersionCode += int.Parse(match.Groups[2].Value) * 1000;
                    bundleVersionCode += int.Parse(match.Groups[3].Value);
                    PlayerSettings.Android.bundleVersionCode = bundleVersionCode;
                }
            } catch (CommandLineArguments.CommandLineArgumentNotFoundException) { /*Ignore*/ }

            var additionalil2CppArgs = PlayerSettings.GetAdditionalIl2CppArgs();

            try {
                if (CommandLineArguments.IsArgumentPresent("-BUILD_SCRIPTING_IL2CPP_DISABLE_JUMP_THREADING_OPTIMISER"))
                {
                    PlayerSettings.SetAdditionalIl2CppArgs(additionalil2CppArgs + " --compiler-flags=-d2ssa-cfg-jt-");
                    Debug.Log($"[{typeof(ScriptableBuildPipeline)}] PlayerSettings.additionalIl2CppArgs = {PlayerSettings.GetAdditionalIl2CppArgs()}");
                }
            } catch (CommandLineArguments.CommandLineArgumentNotFoundException) { /*Ignore*/ }

            var applicationIdentifier = PlayerSettings.applicationIdentifier;

            try {
                PlayerSettings.SetApplicationIdentifier(buildTargetGroup, CommandLineArguments.ReadArgValue("-APPLICATION_IDENTIFIER"));
                Debug.Log($"[{typeof(ScriptableBuildPipeline)}] PlayerSettings.applicationIdentifier = {PlayerSettings.GetApplicationIdentifier(buildTargetGroup)}");
            } catch (CommandLineArguments.CommandLineArgumentNotFoundException) { /*Ignore*/ }

            var outputBuildDirectory = buildConfiguration.GetComponentOrDefault <OutputBuildDirectory>();

            outputBuildDirectory.OutputDirectory = path;
            buildConfiguration.RemoveComponent <OutputBuildDirectory>();
            buildConfiguration.SetComponent(outputBuildDirectory);
            Debug.Log($"[{typeof(ScriptableBuildPipeline)}] {typeof(OutputBuildDirectory)} OutputBuildDirectory = {path}");

            try {
                Debug.Log($"[{nameof(ScriptableBuildPipeline)}] Building to {buildConfiguration.GetOutputBuildDirectory()}");
                buildConfiguration.Build();
                Debug.Log($"[{nameof(ScriptableBuildPipeline)}] Completed building to {buildConfiguration.GetOutputBuildDirectory()}");
                buildConfiguration.RestoreAsset();
            } finally {
                // Restore settings
                PlayerSettings.graphicsJobs = graphicsJobs;
                PlayerSettings.SetAdditionalIl2CppArgs(additionalil2CppArgs);
                PlayerSettings.SetApplicationIdentifier(buildTargetGroup, applicationIdentifier);
            }
        }
 public void create_from_text()
 {
     var config = new BuildConfiguration("		Debug|Mixed PlatformsKEY = Debug|Mixed Platforms");
     config.Key.ShouldEqual("Debug|Mixed PlatformsKEY");
     config.Value.ShouldEqual("Debug|Mixed Platforms");
 }
Exemplo n.º 47
0
        void Convert(Scene scene, Hash128 sceneGUID, GameObjectConversionUtility.ConversionFlags flags, BuildConfiguration config)
        {
            using (m_ConvertMarker.Auto())
            {
                // Try incremental conversion
                if (!_RequestCleanConversion)
                {
                    // Debug.Log("Incremental convert");
                    try
                    {
                        GameObjectConversionUtility.ConvertIncremental(_GameObjectWorld, _ChangedGameObjects, flags);
                        _ChangedGameObjects.Clear();
                    }
                    #pragma warning disable 168
                    catch (Exception e)
                    {
                        _RequestCleanConversion = true;

                        // Debug.Log("Incremental conversion failed. Performing full conversion instead\n" + e.ToString());
                    }
                    #pragma warning restore 168
                }

                // If anything failed, fall back to clean conversion
                if (_RequestCleanConversion)
                {
                    // Debug.Log("Clean convert");
                    _ConvertedWorld.EntityManager.DestroyEntity(_ConvertedWorld.EntityManager.UniversalQuery);
                    var conversionSettings = new GameObjectConversionSettings(_ConvertedWorld, flags);
                    conversionSettings.BuildConfiguration  = config;
                    conversionSettings.SceneGUID           = sceneGUID;
                    conversionSettings.DebugConversionName = _SceneName;
                    conversionSettings.BlobAssetStore      = m_BlobAssetStore;
                    conversionSettings.FilterFlags         = WorldSystemFilterFlags.HybridGameObjectConversion;

                    if (_GameObjectWorld != null && _GameObjectWorld.IsCreated)
                    {
                        _GameObjectWorld.Dispose();
                        _GameObjectWorld = null;
                    }
                    _GameObjectWorld = GameObjectConversionUtility.ConvertIncrementalInitialize(scene, conversionSettings);
                    m_AssetDependencies.Clear();
                    AddAssetDependencies(_GameObjectWorld.GetExistingSystem <GameObjectConversionMappingSystem>().Dependencies, ref m_AssetDependencies);
                }

                _ChangedGameObjects.Clear();
                _RequestCleanConversion = false;
            }
        }
 public override CppToolChain MakeCppToolChain(Unity.IL2CPP.Building.Architecture architecture, BuildConfiguration buildConfiguration, bool treatWarningsAsErrors)
 {
     return new GccToolChain(architecture, buildConfiguration);
 }
        private void GenerateGradleProject(NPath gradleProjectPath)
        {
            var gradleSrcPath = AsmDefConfigFile.AsmDefDescriptionFor("Unity.Build.Android.DotsRuntime").Path.Parent.Combine("AndroidProjectTemplate~/");

            var hasGradleDependencies = false;
            var gradleDependencies    = new StringBuilder();

            gradleDependencies.AppendLine("    dependencies {");
            var hasKotlin = false;

            foreach (var d in Deployables.Where(d => (d is DeployableFile)))
            {
                var f = d as DeployableFile;
                if (f.Path.Extension == "aar" || f.Path.Extension == "jar")
                {
                    gradleDependencies.AppendLine($"        compile(name:'{f.Path.FileNameWithoutExtension}', ext:'{f.Path.Extension}')");
                    hasGradleDependencies = true;
                }
                else if (f.Path.Extension == "kt")
                {
                    hasKotlin = true;
                }
            }
            if (hasGradleDependencies)
            {
                gradleDependencies.AppendLine("    }");
            }
            else
            {
                gradleDependencies.Clear();
            }

            var kotlinClassPath = hasKotlin ? "        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.11'" : "";
            var kotlinPlugin    = hasKotlin ? "apply plugin: 'kotlin-android'" : "";

            var  loadLibraries = new StringBuilder();
            bool useStaticLib  = Deployables.FirstOrDefault(l => l.ToString().Contains("lib_unity_tiny_android.so")) == default(IDeployable);

            if (useStaticLib)
            {
                loadLibraries.AppendLine($"        System.loadLibrary(\"{m_gameName}\");");
            }
            else
            {
                var rx = new Regex(@".*lib([\w\d_]+)\.so", RegexOptions.Compiled);
                foreach (var l in Deployables)
                {
                    var match = rx.Match(l.ToString());
                    if (match.Success)
                    {
                        loadLibraries.AppendLine($"        System.loadLibrary(\"{match.Groups[1].Value}\");");
                    }
                }
            }

            String abiFilters = "";

            if (AndroidApkToolchain.Config.Architectures.Architectures == AndroidArchitecture.ARM64)
            {
                abiFilters = "'arm64-v8a'";
            }
            else if (AndroidApkToolchain.Config.Architectures.Architectures == AndroidArchitecture.ARMv7)
            {
                abiFilters = "'armeabi-v7a'";
            }
            else if (AndroidApkToolchain.IsFatApk)
            {
                abiFilters = "'armeabi-v7a', 'arm64-v8a'";
            }
            else // shouldn't happen
            {
                Console.WriteLine($"Tiny android toolchain doesn't support {AndroidApkToolchain.Config.Architectures.Architectures.ToString()} architectures");
            }

            // Android docs say "density" value was added in API level 17, but it doesn't compile with target SDK level lower than 24.
            string configChanges         = ((int)AndroidApkToolchain.Config.APILevels.ResolvedTargetAPILevel > 23) ? AndroidConfigChanges + "|density" : AndroidConfigChanges;
            var    useKeystore           = BuildConfiguration.HasComponent <AndroidKeystore>();
            var    renderOutsideSafeArea = BuildConfiguration.HasComponent <AndroidRenderOutsideSafeArea>();

            var icons                         = AndroidApkToolchain.Config.Icons;
            var hasBackground                 = icons.Icons.Any(i => !String.IsNullOrEmpty(i.Background));
            var hasCustomIcons                = hasBackground || icons.Icons.Any(i => !String.IsNullOrEmpty(i.Foreground) || !String.IsNullOrEmpty(i.Legacy));
            var version                       = AndroidApkToolchain.Config.Settings.Version;
            var versionFieldCount             = version.Revision > 0 ? 4 : 3;
            var maxRatio                      = AndroidApkToolchain.Config.AspectRatio.GetMaxAspectRatio(AndroidApkToolchain.Config.APILevels.ResolvedTargetAPILevel);
            var additionalApplicationMetadata = "";
            var additionalPermissions         = "";
            var additionalFeatures            = "";

            if (!String.IsNullOrEmpty(maxRatio))
            {
                additionalApplicationMetadata += GetMetaDataString("android.max_aspect", maxRatio);
            }
            if (BuildConfiguration.HasComponent <ARCoreSettings>())
            {
                additionalPermissions += GetPermissionString("android.permission.CAMERA");
                if (AndroidApkToolchain.Config.ARCore.Requirement == Requirement.Optional)
                {
                    additionalApplicationMetadata += "\n" + GetMetaDataString("com.google.ar.core", "optional");
                }
                else
                {
                    additionalApplicationMetadata += "\n" + GetMetaDataString("com.google.ar.core", "required");
                    additionalFeatures            += GetFeatureString("android.hardware.camera.ar", true);
                }
                if (AndroidApkToolchain.Config.ARCore.DepthSupport == Requirement.Required)
                {
                    additionalFeatures += "\n" + GetFeatureString("com.google.ar.core.depth", true);
                }
            }
            var templateStrings = new Dictionary <string, string>
            {
                { "**LOADLIBRARIES**", loadLibraries.ToString() },
                { "**PACKAGENAME**", AndroidApkToolchain.Config.Identifier.PackageName },
                { "**PRODUCTNAME**", AndroidApkToolchain.Config.Settings.ProductName },
                { "**VERSIONNAME**", version.ToString(versionFieldCount) },
                { "**VERSIONCODE**", AndroidApkToolchain.Config.VersionCode.VersionCode.ToString() },
                { "**ORIENTATION**", GetOrientationAttr() },
                { "**INSTALLLOCATION**", AndroidApkToolchain.Config.InstallLocation?.PreferredInstallLocationAsString() },
                { "**CUTOUTMODE**", AndroidRenderOutsideSafeArea.CutoutMode(renderOutsideSafeArea) },
                { "**NOTCHCONFIG**", AndroidRenderOutsideSafeArea.NotchConfig(renderOutsideSafeArea) },
                { "**NOTCHSUPPORT**", AndroidRenderOutsideSafeArea.NotchSupport(renderOutsideSafeArea) },
                { "**GAMENAME**", m_gameName },
                { "**MINSDKVERSION**", ((int)AndroidApkToolchain.Config.APILevels.MinAPILevel).ToString() },
                { "**TARGETSDKVERSION**", ((int)AndroidApkToolchain.Config.APILevels.ResolvedTargetAPILevel).ToString() },
                { "**CONFIGCHANGES**", configChanges },
                { "**ACTIVITY_ASPECT**", String.IsNullOrEmpty(maxRatio) ? "" : $"android:maxAspectRatio=\"{maxRatio}\"" },
                { "**ADDITIONAL_APPLICATION_METADATA**", additionalApplicationMetadata },
                { "**ADDITIONAL_PERMISSIONS**", additionalPermissions },
                { "**ADDITIONAL_FEATURES**", additionalFeatures },
                { "**ABIFILTERS**", abiFilters },
                { "**SIGN**", AndroidApkToolchain.Config.Keystore.GetSigningConfigs(useKeystore) },
                { "**SIGNCONFIG**", AndroidApkToolchain.Config.Keystore.GetSigningConfig(useKeystore) },
                { "**DEPENDENCIES**", gradleDependencies.ToString() },
                { "**KOTLINCLASSPATH**", kotlinClassPath },
                { "**KOTLINPLUGIN**", kotlinPlugin },
                { "**ALLOWED_PORTRAIT**", AndroidApkToolchain.AllowedOrientationPortrait ? "true" : "false" },
                { "**ALLOWED_REVERSE_PORTRAIT**", AndroidApkToolchain.AllowedOrientationReversePortrait ? "true" : "false" },
                { "**ALLOWED_LANDSCAPE**", AndroidApkToolchain.AllowedOrientationLandscape ? "true" : "false" },
                { "**ALLOWED_REVERSE_LANDSCAPE**", AndroidApkToolchain.AllowedOrientationReverseLandscape ? "true" : "false" },
                { "**BACKGROUND_PATH**", hasBackground ? "mipmap" : "drawable" }
            };

            // copy icon files
            if (hasCustomIcons)
            {
                for (int i = 0; i < icons.Icons.Length; ++i)
                {
                    var dpi = ((ScreenDPI)i).ToString().ToLower();
                    if (AndroidApkToolchain.Config.APILevels.TargetSDKSupportsAdaptiveIcons)
                    {
                        CopyIcon(gradleProjectPath, dpi, "ic_launcher_foreground.png", icons.Icons[i].Foreground);
                        CopyIcon(gradleProjectPath, dpi, "ic_launcher_background.png", icons.Icons[i].Background);
                    }
                    CopyIcon(gradleProjectPath, dpi, "app_icon.png", icons.Icons[i].Legacy);
                }
            }

            // copy and patch project files
            var apiRx = new Regex(@".+res[\\|\/].+-v([0-9]+)$", RegexOptions.Compiled);

            foreach (var r in gradleSrcPath.Files(true))
            {
                if ((hasCustomIcons && r.HasDirectory("mipmap-mdpi")) ||
                    (hasBackground && r.HasDirectory("drawable"))) // skipping icons files if there are custom ones
                {
                    continue;
                }
                if (!AndroidApkToolchain.Config.APILevels.TargetSDKSupportsAdaptiveIcons && r.FileName.StartsWith("ic_launcher_"))
                {
                    continue;
                }
                var match = apiRx.Match(r.Parent.ToString());
                if (match.Success)
                {
                    var api = Int32.Parse(match.Groups[1].Value);
                    if (api > (int)AndroidApkToolchain.Config.APILevels.ResolvedTargetAPILevel)
                    {
                        continue;
                    }
                }

                var destPath = gradleProjectPath.Combine(r.RelativeTo(gradleSrcPath));
                if (r.Extension == "template")
                {
                    destPath = destPath.ChangeExtension("");
                    var code = r.ReadAllText();
                    foreach (var t in templateStrings)
                    {
                        if (code.IndexOf(t.Key) != -1)
                        {
                            code = code.Replace(t.Key, t.Value);
                        }
                    }
                    Backend.Current.AddWriteTextAction(destPath, code);
                }
                else
                {
                    destPath = CopyTool.Instance().Setup(destPath, r);
                }
                m_projectFiles.Add(destPath);
            }

            var localProperties = new StringBuilder();

            localProperties.AppendLine($"sdk.dir={new NPath(AndroidApkToolchain.Config.ExternalTools.SdkPath).ToString()}");
            localProperties.AppendLine($"ndk.dir={new NPath(AndroidApkToolchain.Config.ExternalTools.NdkPath).ToString()}");
            var localPropertiesPath = gradleProjectPath.Combine("local.properties");

            Backend.Current.AddWriteTextAction(localPropertiesPath, localProperties.ToString());
            m_projectFiles.Add(localPropertiesPath);
        }