public async Task ProcessRecord_ReturnProperty()
        {
            var project = Path.Combine(Environment.CurrentDirectory, "PowerBuild.Tests.targets");

            var itemSpec   = "ExpectedReturnPropertyValue";
            var parameters = new InvokeMSBuildParameters
            {
                Project    = project,
                Properties = new Dictionary <string, string>
                {
                    ["ReturnPropertyValue"] = itemSpec
                },
                Target       = new[] { "ReturnProperty" },
                ToolsVersion = "4.0"
            };

            var helper = new MSBuildHelper
            {
                Parameters = parameters,
            };

            helper.BeginProcessing();

            var buildResults = await helper.ProcessRecordAsync();

            helper.StopProcessing();

            var buildResult = buildResults.Single();

            Assert.Equal(1, buildResult["ReturnProperty"].Items.Length);
            Assert.Equal(itemSpec, buildResult["ReturnProperty"].Items[0].ItemSpec);
        }
Example #2
0
        public bool BuildTargetGaugeProject()
        {
            var projectFullPath = GetProjectFullPath();
            var projectConfig   = GetProjectConfiguration();
            var projectPlatform = GetProjectPlatform();
            var gaugeBinDir     = Utils.GetGaugeBinDir();

            try
            {
                var properties = new FSharpList <Tuple <string, string> >(Tuple.Create("Configuration", projectConfig),
                                                                          FSharpList <Tuple <string, string> > .Empty);
                properties = new FSharpList <Tuple <string, string> >(Tuple.Create("Platform", projectPlatform), properties);
                properties = new FSharpList <Tuple <string, string> >(Tuple.Create("OutputPath", gaugeBinDir), properties);
                MSBuildHelper.build(FuncConvert.ToFSharpFunc(delegate(MSBuildHelper.MSBuildParams input)
                {
                    input.Verbosity =
                        FSharpOption <MSBuildHelper.MSBuildVerbosity> .Some(MSBuildHelper.MSBuildVerbosity.Quiet);
                    input.Targets    = new FSharpList <string>("Build", FSharpList <string> .Empty);
                    input.Properties = properties;
                    return(input);
                }), projectFullPath);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "C# Project build failed {0}", ex.Message);
                return(false);
            }
            return(true);
        }
        public async Task ProcessRecord_Build()
        {
            var project = Path.Combine(Environment.CurrentDirectory, "PowerBuild.Tests.targets");

            var parameters = new InvokeMSBuildParameters
            {
                Project      = project,
                Target       = new[] { "Build" },
                ToolsVersion = "4.0"
            };

            var helper = new MSBuildHelper
            {
                Parameters = parameters,
            };

            helper.BeginProcessing();

            var buildResults = await helper.ProcessRecordAsync();

            helper.StopProcessing();

            var buildResult = buildResults.FirstOrDefault();

            Assert.NotNull(buildResult);
            Assert.True(buildResult.HasResultsForTarget("Build"));
            Assert.Equal(3, buildResult.Items.Count());
        }
        /// <summary>
        ///     The main program entry-point.
        /// </summary>
        /// <returns>
        ///     The process exit code.
        /// </returns>
        static int Main()
        {
            SynchronizationContext.SetSynchronizationContext(
                new SynchronizationContext()
                );

            try
            {
                AutoDetectExtensionDirectory();

                MSBuildHelper.DiscoverMSBuildEngine();

                return(AsyncMain().GetAwaiter().GetResult());
            }
            catch (AggregateException aggregateError)
            {
                foreach (Exception unexpectedError in aggregateError.Flatten().InnerExceptions)
                {
                    Console.Error.WriteLine(unexpectedError);
                }

                return(1);
            }
            catch (Exception unexpectedError)
            {
                Console.Error.WriteLine(unexpectedError);

                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Example #5
0
        public void TestFull()
        {
            var pathSolution = @"D:\prod\structures\MSBuild\RunFast.msbuild";
            var targetData   = MSBuildHelper.CreateTargetTree(pathSolution, "BuildTSAndDotAppsNORPC", @"D:\prod\structures\Packages", string.Empty, false, string.Empty, string.Empty, true, "16.0");

            Assert.That(targetData.Length, Is.EqualTo(1));
        }
        private static void ApplyBuildParametersForDotNetCore(this IConfiguration configuration, string projectOrSolutionFile, Action <string> setConfiguration, Func <DotNetCoreMSBuildSettings> getSettings, Action <DotNetCoreMSBuildSettings> setSettings)
        {
            if (!configuration.Has(ConfigurationConstants.BUILD_PARAMETERS_KEY))
            {
                return;
            }

            DotNetCoreMSBuildSettings settings = getSettings() ?? new DotNetCoreMSBuildSettings();

            var buildParameters = configuration.Get <DictionaryOfListConfigurationItem <string, string> >(ConfigurationConstants.BUILD_PARAMETERS_KEY);

            foreach (KeyValuePair <string, List <string> > buildParameter in buildParameters.Values)
            {
                if (buildParameter.Key.ToLowerInvariant() == "configuration")
                {
                    if (buildParameter.Value.Count > 1)
                    {
                        configuration.Context.CakeContext.LogAndThrow($"BuildParameter Configuration can only contains one value (currently: {string.Join(" ; ", buildParameter.Value)})");
                    }

                    setConfiguration(MSBuildHelper.PropertyValue(buildParameter.Value.Single()));
                }
                else if (buildParameter.Key.ToLowerInvariant() == "platform")
                {
                    if (buildParameter.Value.Count > 1)
                    {
                        configuration.Context.CakeContext.LogAndThrow($"BuildParameter Platform can only contains one value (currently: {string.Join(" ; ", buildParameter.Value)})");
                    }

                    string platform = buildParameter.Value.Single();
                    switch (platform.ToLowerInvariant())
                    {
                    case "any cpu":
                    case "anycpu":
                        if (projectOrSolutionFile.EndsWith("sln"))
                        {
                            settings.WithProperty("Platform", MSBuildHelper.PropertyValue("Any CPU"));
                        }
                        else
                        {
                            settings.WithProperty("Platform", MSBuildHelper.PropertyValue("AnyCPU"));
                        }
                        break;

                    default:
                        settings.WithProperty("Platform", MSBuildHelper.PropertyValue(platform));
                        break;
                    }
                }
                else
                {
                    settings.WithProperty(buildParameter.Key, MSBuildHelper.PropertyValue(buildParameter.Value));
                }
            }

            setSettings(settings);
        }
Example #7
0
        public void GetsIncludeGraphs()
        {
            var pathSolution = Path.Combine(executionFolder, "TestData", "ConsoleApp");
            var solution     = MSBuildHelper.PreProcessSolution("", "", Path.Combine(pathSolution, "ConsoleApp.sln"), true, false, "14.0");
            var guid         = new Guid("C864A049-0A9E-4139-8217-DA58D9A3B73D");
            var project      = solution.Projects[guid];
            var callGraph    = MSBuildHelper.GetIncludeGraphForFile(Path.Combine(pathSolution, "ConsoleApp", "ConsoleApp.cpp"), project);

            Assert.That(callGraph.Node.Length, Is.EqualTo(1));
        }
Example #8
0
        public void Execute(IConfiguration configuration, StepType currentStep)
        {
            DirectoryPath outputDirectory = configuration.GetArtifactsPath();

            string solutionFile = configuration.GetSolutionPath();
            string projectFile  = configuration.GetProjectPath();

            configuration.FileExistsOrThrow(solutionFile);

            //Create iPA package
            configuration.Context.CakeContext.MSBuild(solutionFile, settings =>
            {
                settings.SetConfiguration("Release");
                settings.WithProperty("BuildIpa", "true")
                .WithProperty("IpaIncludeArtwork", "false")
                .WithProperty("IpaPackageDir", MSBuildHelper.PropertyValue(outputDirectory.MakeAbsolute(configuration.Context.CakeContext.Environment).FullPath))
                .WithProperty("Platform", "iPhone");

                string codeSignKey = configuration.Has(iOSConstants.IOS_CODESIGN_KEY) ? configuration.GetSimple <string>(iOSConstants.IOS_CODESIGN_KEY) : null;
                if (string.IsNullOrEmpty(codeSignKey))
                {
                    configuration.Context.CakeContext.LogAndThrow("No codesignkey for iOS Release");
                }

                string codeSignProvision = configuration.Has(iOSConstants.IOS_CODESIGN_PROVISION) ? configuration.GetSimple <string>(iOSConstants.IOS_CODESIGN_PROVISION) : null;
                if (string.IsNullOrEmpty(codeSignProvision))
                {
                    configuration.Context.CakeContext.LogAndThrow("No codesignprovision for iOS Release");
                }

                settings.WithProperty("CodesignKey", MSBuildHelper.PropertyValue(codeSignKey))
                .WithProperty("CodesignProvision", MSBuildHelper.PropertyValue(codeSignProvision));

                configuration.ApplyBuildParameters(settings);
            });

            //Copy dSYM to output
            string searchPattern = new FilePath(projectFile).GetDirectory() + "/**/*.dSYM";
            string symDirectory  = configuration.Context.CakeContext.Globber
                                   .GetDirectories(searchPattern)
                                   .OrderBy(d => new DirectoryInfo(d.FullPath).LastWriteTimeUtc)
                                   .FirstOrDefault()?.FullPath;

            if (string.IsNullOrEmpty(symDirectory))
            {
                configuration.Context.CakeContext.LogAndThrow("Can not find dSYM file");
            }

            configuration.Context.CakeContext.Zip(symDirectory, $"{outputDirectory}/{System.IO.Path.GetFileName(symDirectory)}.zip");
        }
        /// <summary>
        ///     Load a test project.
        /// </summary>
        /// <param name="relativePathSegments">
        ///     The project file's relative path segments.
        /// </param>
        /// <returns>
        ///     The project.
        /// </returns>
        static Project LoadTestProject(params string[] relativePathSegments)
        {
            if (relativePathSegments == null)
            {
                throw new ArgumentNullException(nameof(relativePathSegments));
            }

            return(MSBuildHelper.CreateProjectCollection(TestDirectory.FullName).LoadProject(
                       Path.Combine(TestDirectory.FullName,
                                    "TestProjects",
                                    Path.Combine(relativePathSegments)
                                    )
                       ));
        }
Example #10
0
        /// <summary>
        /// Gets the project by unique identifier in solution.
        /// </summary>
        /// <param name="guid">The unique identifier.</param>
        /// <param name="solutionPath">The solution path.</param>
        /// <returns>returns guid for project</returns>
        public VsProjectItem GetProjectByGuidInSolution(string guid, string solutionPath)
        {
            var solutiondata = MSBuildHelper.CreateSolutionData(solutionPath);

            foreach (var project in solutiondata.Projects)
            {
                if (project.Value.Guid.ToString().ToLower().Equals(guid.ToLower()))
                {
                    return(CreateVsProjectItem(project.Value));
                }
            }

            return(null);
        }
Example #11
0
        /// <summary>
        /// Gets the project guid from path.
        /// </summary>
        /// <param name="projectPath">The project path.</param>
        /// <param name="solutionPath">The solution path.</param>
        /// <returns>
        /// project unique identifier
        /// </returns>
        public string GetGuidForProject(string projectPath, string solutionPath)
        {
            var solutiondata = MSBuildHelper.CreateSolutionData(solutionPath);

            foreach (var project in solutiondata.Projects)
            {
                var fullPathOne = Path.GetFullPath(project.Value.Path).ToLower();
                var fullPathTwo = Path.GetFullPath(projectPath).ToLower();
                if (fullPathOne.Equals(fullPathTwo))
                {
                    return(project.Value.Guid.ToString());
                }
            }

            return(null);
        }
Example #12
0
        public void LoadFile(FileInfo file, bool populate)
        {
            if (this.RootFile != null && this.RootFile.ProjectFile.FullPath == file.FullName)
            {
                return;
            }

            RaiseEvent(new RoutedEventArgs(TreeExplorer.StartExplore, this));
            MSBuildFileEqualityComparer eq = new MSBuildFileEqualityComparer();

            try
            {
                this.RootFile = MSBuildHelper.GetFile(file);
            }
            catch (Exception ex)
            {
                this.TreeExeption = ex;
                RaiseEvent(new RoutedEventArgs(TreeExplorer.FailedExplore, this));
                return;
            }

            if (this.files.Contains(this.RootFile, eq))
            {
                int i = 0;
                foreach (MSBuildFile f in this.files)
                {
                    if (f.Name == this.RootFile.Name)
                    {
                        this.files.RemoveAt(i);
                        break;
                    }

                    i++;
                }
            }

            this.files.Add(this.RootFile);
            this.files.BubbleSort();
            this.tvMain.ItemsSource = this.files;
            if (populate)
            {
                RaiseEvent(new RoutedEventArgs(TreeExplorer.PopulateEverything, this));
            }

            this.textBlockTitle.Text = this.tvMain.Items.Count == 0 ? "Explore" : "Explore - " + this.tvMain.Items.Count;
            RaiseEvent(new RoutedEventArgs(TreeExplorer.FinishedExplore, this));
        }
Example #13
0
 /// <summary>
 /// Evaluated the value for include file.
 /// </summary>
 /// <param name="msbuildProjectFile">The msbuild project file.</param>
 /// <param name="filePath">The file path.</param>
 /// <returns>
 /// returns evaluated include
 /// </returns>
 public string EvaluatedValueForIncludeFile(string msbuildProjectFile, string filePath)
 {
     return(MSBuildHelper.GetProjectFilePathForFile(msbuildProjectFile, filePath));
 }
        public static void ApplyBuildParameters(this IConfiguration configuration, MSBuildSettings settings)
        {
            if (!configuration.Has(ConfigurationConstants.BUILD_PARAMETERS_KEY))
            {
                return;
            }

            var buildParameters = configuration.Get <DictionaryOfListConfigurationItem <string, string> >(ConfigurationConstants.BUILD_PARAMETERS_KEY);

            foreach (KeyValuePair <string, List <string> > buildParameter in buildParameters.Values)
            {
                if (buildParameter.Key.ToLowerInvariant() == "configuration")
                {
                    if (buildParameter.Value.Count > 1)
                    {
                        configuration.Context.CakeContext.LogAndThrow($"BuildParameter Configuration can only contains one value (currently: {string.Join(" ; ", buildParameter.Value)})");
                    }

                    settings.SetConfiguration(MSBuildHelper.PropertyValue(buildParameter.Value.Single()));
                }
                else if (buildParameter.Key.ToLowerInvariant() == "platform")
                {
                    if (buildParameter.Value.Count > 1)
                    {
                        configuration.Context.CakeContext.LogAndThrow($"BuildParameter Platform can only contains one value (currently: {string.Join(" ; ", buildParameter.Value)})");
                    }

                    string platform = buildParameter.Value.Single();
                    switch (platform.ToLowerInvariant())
                    {
                    case "any cpu":
                    case "anycpu":
                        settings.SetPlatformTarget(PlatformTarget.MSIL);
                        break;

                    case "x86":
                        settings.SetPlatformTarget(PlatformTarget.x86);
                        break;

                    case "x64":
                        settings.SetPlatformTarget(PlatformTarget.x64);
                        break;

                    case "arm":
                        settings.SetPlatformTarget(PlatformTarget.ARM);
                        break;

                    case "win32":
                        settings.SetPlatformTarget(PlatformTarget.Win32);
                        break;

                    default:
                        settings.WithProperty("Platform", MSBuildHelper.PropertyValue(platform));
                        break;
                    }
                }
                else
                {
                    settings.WithProperty(buildParameter.Key, MSBuildHelper.PropertyValue(buildParameter.Value));
                }
            }
        }
        /// <summary>
        ///     Attempt to load the underlying MSBuild project.
        /// </summary>
        /// <returns>
        ///     <c>true</c>, if the project was successfully loaded; otherwise, <c>false</c>.
        /// </returns>
        protected override bool TryLoadMSBuildProject()
        {
            try
            {
                if (HasMSBuildProject && !IsDirty)
                {
                    return(true);
                }

                if (MSBuildProjectCollection == null)
                {
                    MSBuildProjectCollection = MSBuildHelper.CreateProjectCollection(ProjectFile.Directory.FullName,
                                                                                     globalPropertyOverrides: GetMSBuildGlobalPropertyOverrides()
                                                                                     );
                }

                if (HasMSBuildProject && IsDirty)
                {
                    using (StringReader reader = new StringReader(Xml.ToFullString()))
                        using (XmlTextReader xmlReader = new XmlTextReader(reader))
                        {
                            MSBuildProject.Xml.ReloadFrom(xmlReader,
                                                          throwIfUnsavedChanges: false,
                                                          preserveFormatting: true
                                                          );
                        }

                    MSBuildProject.ReevaluateIfNecessary();

                    Log.Verbose("Successfully updated MSBuild project '{ProjectFileName}' from in-memory changes.");
                }
                else
                {
                    MSBuildProject = MSBuildProjectCollection.LoadProject(ProjectFile.FullName);
                }

                return(true);
            }
            catch (InvalidProjectFileException invalidProjectFile)
            {
                if (Workspace.Configuration.Logging.IsDebugLoggingEnabled)
                {
                    Log.Error(invalidProjectFile, "Failed to load MSBuild proiect '{ProjectFileName}'.",
                              ProjectFile.FullName
                              );
                }

                AddErrorDiagnostic(invalidProjectFile.BaseMessage,
                                   range: invalidProjectFile.GetRange(XmlLocator),
                                   diagnosticCode: invalidProjectFile.ErrorCode
                                   );
            }
            catch (XmlException invalidProjectXml)
            {
                if (Workspace.Configuration.Logging.IsDebugLoggingEnabled)
                {
                    Log.Error(invalidProjectXml, "Failed to parse XML for project '{ProjectFileName}'.",
                              ProjectFile.FullName
                              );
                }

                // TODO: Match SourceUri (need overloads of AddXXXDiagnostic for reporting diagnostics for other files).
                AddErrorDiagnostic(invalidProjectXml.Message,
                                   range: invalidProjectXml.GetRange(XmlLocator),
                                   diagnosticCode: "MSBuild.InvalidXML"
                                   );
            }
            catch (Exception loadError)
            {
                Log.Error(loadError, "Error loading MSBuild project '{ProjectFileName}'.", ProjectFile.FullName);
            }

            return(false);
        }
        /// <summary>
        ///     Get completions for item attributes.
        /// </summary>
        /// <param name="location">
        ///     The <see cref="XmlLocation"/> where completions are requested.
        /// </param>
        /// <param name="projectDocument">
        ///     The <see cref="ProjectDocument"/> that contains the <paramref name="location"/>.
        /// </param>
        /// <param name="existingMetadata">
        ///     Metadata already declared on the item.
        /// </param>
        /// <returns>
        ///     A sequence of <see cref="CompletionItem"/>s.
        /// </returns>
        IEnumerable <CompletionItem> GetAttributeCompletions(XmlLocation location, ProjectDocument projectDocument, HashSet <string> existingMetadata)
        {
            Log.Verbose("Evaluate attribute completions for {XmlLocation:l}", location);

            XSElement   itemElement;
            XSAttribute replaceAttribute;
            PaddingType needsPadding;

            if (!location.CanCompleteAttribute(out itemElement, out replaceAttribute, out needsPadding))
            {
                Log.Verbose("Not offering any attribute completions for {XmlLocation:l} (not a location where we can offer attribute completion.", location);

                yield break;
            }

            // Must be an item element.
            if (!itemElement.HasParentPath(WellKnownElementPaths.ItemGroup))
            {
                Log.Verbose("Not offering any attribute completions for {XmlLocation:l} (element is not a direct child of a 'PropertyGroup' element).", location);

                yield break;
            }

            string itemType = itemElement.Name;

            if (String.IsNullOrWhiteSpace(itemType))
            {
                Log.Verbose("Not offering any attribute completions for {XmlLocation:l} (element represents a new, unnamed, item group).",
                            location,
                            itemType
                            );

                yield break;
            }

            if (MSBuildSchemaHelp.ForItemType(itemType) == null)
            {
                Log.Verbose("Not offering any attribute completions for {XmlLocation:l} ({ItemType} is not a well-known item type).",
                            location,
                            itemType
                            );

                yield break;
            }

            Log.Verbose("Will offer attribute completions for {XmlLocation:l} (padding: {NeedsPadding})", location, needsPadding);

            // Don't offer completions for existing metadata.
            existingMetadata.UnionWith(
                GetExistingMetadataNames(itemElement)
                );

            Range replaceRange = replaceAttribute?.Range ?? location.Position.ToEmptyRange();

            foreach (string metadataName in MSBuildSchemaHelp.WellKnownItemMetadataNames(itemType))
            {
                if (existingMetadata.Contains(metadataName))
                {
                    continue;
                }

                if (MSBuildHelper.IsWellKnownItemMetadata(metadataName))
                {
                    continue;
                }

                yield return(new CompletionItem
                {
                    Label = metadataName,
                    Kind = CompletionItemKind.Field,
                    Detail = "Item Metadata",
                    Documentation = MSBuildSchemaHelp.ForItemMetadata(itemType, metadataName),
                    SortText = GetItemSortText(metadataName),
                    TextEdit = new TextEdit
                    {
                        NewText = $"{metadataName}=\"$0\"".WithPadding(needsPadding),
                        Range = replaceRange.ToLsp()
                    },
                    InsertTextFormat = InsertTextFormat.Snippet
                });
            }
        }
        /// <summary>
        ///     Get completions for item elements.
        /// </summary>
        /// <param name="location">
        ///     The <see cref="XmlLocation"/> where completions are requested.
        /// </param>
        /// <param name="projectDocument">
        ///     The <see cref="ProjectDocument"/> that contains the <paramref name="location"/>.
        /// </param>
        /// <param name="existingMetadata">
        ///     Metadata already declared on the item.
        /// </param>
        /// <returns>
        ///     A sequence of <see cref="CompletionItem"/>s.
        /// </returns>
        IEnumerable <CompletionItem> GetElementCompletions(XmlLocation location, ProjectDocument projectDocument, HashSet <string> existingMetadata)
        {
            Log.Verbose("Evaluate element completions for {XmlLocation:l}", location);

            XSElement replaceElement;

            if (!location.CanCompleteElement(out replaceElement, parentPath: WellKnownElementPaths.Item))
            {
                Log.Verbose("Not offering any element completions for {XmlLocation:l} (not a location where an item metadata element can be created or replaced by completion).", location);

                yield break;
            }

            Range  replaceRange;
            string itemType;

            if (replaceElement != null)
            {
                replaceRange = replaceElement.Range;
                itemType     = replaceElement.ParentElement?.Name;
            }
            else
            {
                replaceRange = location.Position.ToEmptyRange();
                itemType     = location.Node.Path.Parent.Name;
            }

            // These items are handled by PackageReferenceCompletion.
            if (itemType == "PackageReference" || itemType == "DotNetCliToolReference")
            {
                Log.Verbose("Not offering any element completions for {XmlLocation:l} ({ItemType} items are handled by another provider).",
                            location,
                            itemType
                            );

                yield break;
            }

            if (MSBuildSchemaHelp.ForItemType(itemType) == null)
            {
                Log.Verbose("Not offering any element completions for {XmlLocation:l} ({ItemType} is not a well-known item type).",
                            location,
                            itemType
                            );

                yield break;
            }

            if (replaceElement != null)
            {
                // Don't offer completions for existing metadata.
                existingMetadata.UnionWith(
                    GetExistingMetadataNames(replaceElement)
                    );

                Log.Verbose("Will offer completions to replace item metadata element spanning {Range:l}", replaceRange);
            }
            else
            {
                Log.Verbose("Will offer completions to create item metadata element at {Position:l}", location.Position);
            }

            foreach (string metadataName in MSBuildSchemaHelp.WellKnownItemMetadataNames(itemType))
            {
                if (existingMetadata.Contains(metadataName))
                {
                    continue;
                }

                if (MSBuildHelper.IsWellKnownItemMetadata(metadataName))
                {
                    continue;
                }

                string completionLabel = $"<{metadataName}>";

                yield return(new CompletionItem
                {
                    Label = completionLabel,
                    Kind = CompletionItemKind.Field,
                    Detail = $"Item Metadata ({itemType})",
                    Documentation = MSBuildSchemaHelp.ForItemMetadata(itemType, metadataName),
                    SortText = GetItemSortText(completionLabel),
                    TextEdit = new TextEdit
                    {
                        NewText = $"<{metadataName}>$0</{metadataName}>",
                        Range = replaceRange.ToLsp()
                    },
                    InsertTextFormat = InsertTextFormat.Snippet
                });
            }
        }
 /// <summary>
 ///     Create a new <see cref="MSBuildEngineFixture"/>.
 /// </summary>
 public MSBuildEngineFixture()
 {
     MSBuildHelper.DiscoverMSBuildEngine();
 }