public Microsoft.TeamFoundation.Build.Server.BuildStatus ConvertBuildStatus(BuildStatus? status, BuildResult? result)
 {
     if (!status.HasValue)
     {
         return Microsoft.TeamFoundation.Build.Server.BuildStatus.NotStarted;
     }
     BuildStatus value = status.Value;
     switch (value)
     {
         case BuildStatus.None:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.None;
         case BuildStatus.InProgress:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.InProgress;
         case BuildStatus.Completed:
             return this.ConvertBuildResult(result);
         case (BuildStatus)3:
         case (BuildStatus)5:
         case (BuildStatus)6:
         case (BuildStatus)7:
             break;
         case BuildStatus.Cancelling:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.Stopped;
         case BuildStatus.Postponed:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.NotStarted;
         default:
             if (value == BuildStatus.NotStarted)
             {
                 return Microsoft.TeamFoundation.Build.Server.BuildStatus.NotStarted;
             }
             break;
     }
     return Microsoft.TeamFoundation.Build.Server.BuildStatus.NotStarted;
 }
 public Microsoft.TeamFoundation.Build.Server.BuildStatus ConvertBuildResult(BuildResult? result)
 {
     if (!result.HasValue)
     {
         return Microsoft.TeamFoundation.Build.Server.BuildStatus.None;
     }
     BuildResult value = result.Value;
     switch (value)
     {
         case BuildResult.None:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.None;
         case (BuildResult)1:
         case (BuildResult)3:
             break;
         case BuildResult.Succeeded:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.Succeeded;
         case BuildResult.PartiallySucceeded:
             return Microsoft.TeamFoundation.Build.Server.BuildStatus.PartiallySucceeded;
         default:
             if (value == BuildResult.Failed)
             {
                 return Microsoft.TeamFoundation.Build.Server.BuildStatus.Failed;
             }
             if (value == BuildResult.Canceled)
             {
                 return Microsoft.TeamFoundation.Build.Server.BuildStatus.Stopped;
             }
             break;
     }
     return Microsoft.TeamFoundation.Build.Server.BuildStatus.None;
 }
Example #3
0
        public Color ConvertBuildResultToColor(BuildResult buildResult)
        {
            switch (buildResult)
            {
                case BuildResult.Running:
                    {
                        return Color.Yellow;
                    }

                case BuildResult.Success:
                    {
                        return Color.Green;
                    }

                case BuildResult.Queued:
                    {
                        return Color.Blue;
                    }

                case BuildResult.Failed:
                    {
                        return Color.Red;
                    }

                case BuildResult.Cancelled:
                case BuildResult.Unknown:
                default:
                    {
                        return Color.White;
                    }
            }
        }
 protected override void DoBuild(Query query, BuildResult result)
 {
     if (query.Variables != null && query.Variables.Count > 0)
     {
         result.QuerystringParts.Add("with=" + TextBuilder.Join(query.Variables, ";", v => v.ToString()));
     }
 }
 protected override void DoBuild(Query query, BuildResult result)
 {
     if (query.OrderBy.Count > 0)
     {
         result.QuerystringParts.Add("sort=" + query.OrderBy.Token);
     }
 }
        protected override void DoBuild(Query query, BuildResult result) {
            var filtertoken = query.Filter.Token;

            if (filtertoken != null) {
                result.QuerystringParts.Add("where=" + filtertoken);
            }
        }
Example #7
0
        public static BuildResult BuildProject(string workingDirectory, string projectFilePath, string topModule)
        {
            string fusePath = XilinxHelper.GetXilinxToolPath("fuse.exe");
            if (string.IsNullOrEmpty(fusePath))
            {
                fusePath = XilinxHelper.GetXilinxToolPath("fuse");
                if (string.IsNullOrEmpty(fusePath))
                {
                    throw new Exception("Unable to find the fuse Executable");
                }
            }

            // Create prj file on disk
            string projectExecutablePath = PathHelper.Combine(workingDirectory, "x.exe");

            List<string> arguments = new List<string>();
            arguments.Add(string.Format("--prj \"{0}\"", projectFilePath));
            //arguments.Add(string.Format("-o \"{0}\"", projectExecutablePath));
            arguments.Add(topModule);

            ProcessHelper.ProcessExecutionResult result = XilinxProcess.ExecuteProcess(workingDirectory, fusePath, arguments);

            BuildResult buildResult = new BuildResult();
            buildResult.BuildLog = result.StandardOutput + "\n\n\n" + result.StandardError;
            buildResult.WorkingDirectory = workingDirectory;
            buildResult.ExecutableFile = projectExecutablePath;
            buildResult.Built = true;

            return buildResult;
        }
 protected override void DoBuild(Query query, BuildResult result)
 {
     if (query.Paging.Start != 0 || query.Paging.PageSize != int.MaxValue)
     {
         result.QuerystringParts.Add("page=" + query.Paging.Token);
     }
 }
        public string Convert(BuildResult value)
        {
            var result = (BuildResult)value;

            string resourceKey = String.Format("BuildResult_{0:G}", result);

            return resources.GetString(resourceKey);
        }
 private string ConvertToCruiseBuildStatus(BuildResult result)
 {
     switch (result)
     {
         case BuildResult.Success: return "Success";
         case BuildResult.Failed: return "Failure";
         default: return "Unknown";
     }
 }
 public void BuildWithInvalidParametersTest()
 {
     var assetType = _context.MetaModel.GetAssetType("Member");
     _target.Build(null, null);
     _target.Build(new Query(assetType), new BuildResult());
     var result = new BuildResult();
     _target.Build(new Query(assetType), result);
     Assert.AreEqual(0, result.QuerystringParts.Count);
 }
Example #12
0
        public BuildResult Execute(string virtualPath)
        {
            BuildResult response = null;
            var basePath = TemplateVirtualPathProvider.BasePath;
            var types = BuildManager.GetCompiledType(virtualPath);
            var webPage = Activator.CreateInstance(types) as WebPageBase;
            response = new BuildResult(ExecutCore(basePath, virtualPath, webPage));

            return response;
        }
 public void BuildWithValidParametersTest()
 {
     var assetType = _context.MetaModel.GetAssetType("Member");
     var query = new Query(assetType);
     var nameAttribute = assetType.GetAttributeDefinition("Username");
     query.Selection.Add(nameAttribute);
     query.Find = new QueryFind("admin", new AttributeSelection("Username", assetType));
     var result = new BuildResult();
     _target.Build(query, result);
     Assert.AreEqual(2, result.QuerystringParts.Count); //one part for find, one part for findin
     Assert.AreEqual("?find=admin&findin=Member.Username", result.ToUrl());
 }
 public void QueryStringEscapeTest()
 {
     var assetType = _context.MetaModel.GetAssetType("Member");
     var query = new Query(assetType);
     var nameAttribute = assetType.GetAttributeDefinition("Username");
     query.Selection.Add(nameAttribute);
     query.Find = new QueryFind("*****@*****.**", new AttributeSelection("Username", assetType));  //make sure ampersand get url encoded
     var result = new BuildResult();
     _target.Build(query, result);
     Assert.AreEqual(2, result.QuerystringParts.Count); //one part for find, one part for findin
     Assert.AreEqual("?find=admin%40mydomain.com&findin=Member.Username", result.ToUrl());
 }
        protected override void DoBuild(Query query, BuildResult result) {
            result.PathParts.Add(query.IsHistorical ? "Hist" : "Data");

            result.PathParts.Add(query.AssetType.Token);

            if(!query.Oid.IsNull) {
                result.PathParts.Add(query.Oid.Key.ToString());
            }

            if(query.Oid.HasMoment) {
                result.PathParts.Add(query.Oid.Moment.ToString());
            }
        }
        protected override void DoBuild(Query query, BuildResult result) {
            if(query.ParentRelation != null) {
                query.Selection.Add(query.ParentRelation);
            }

            if(query.Selection.Count == 1 && !query.Oid.IsNull) {
                result.PathParts.Add(query.Selection[0].Name);
            } else if(query.Selection.Count > 0) {
                result.QuerystringParts.Add("sel=" + query.Selection.Token);
            } else {
                result.QuerystringParts.Add("sel=");
            }
        }
Example #17
0
        public static BuildResultChange GetBuildResultChange(BuildResult oldValue, BuildResult newValue)
        {
            if (oldValue == newValue)
            {
                return BuildResultChange.None;
            }

            switch (newValue)
            {
                case BuildResult.Success: return BuildResultChange.Fixed;
                case BuildResult.Failed: return BuildResultChange.Failed;
                default: return BuildResultChange.Unavailable;
            }
        }
Example #18
0
        public static BuildResult BuildProject(string workingDirectory, PrjFile projectFile, IModule topModule)
        {
            // Create prj file on disk
            string toplevelComponentName = string.Format("{0}.{1}", topModule.Parent.Name, topModule.Name);
            string projectFilePath = PathHelper.Combine(workingDirectory, "projectfile.prj");
            File.WriteAllText(projectFilePath, projectFile.ToString(ExecutionType.SynthesisOnly));
            string projectXstFilePath = PathHelper.Combine(workingDirectory, "projectfile.xst");
            string projectSyrFilePath = PathHelper.Combine(workingDirectory, "projectfile.syr");
            string projectXstPath = PathHelper.Combine(workingDirectory, "xst");
            string projectTmpPath = PathHelper.Combine(projectXstPath, ".tmp");
            File.WriteAllText(projectXstFilePath, GenerateScript(workingDirectory, projectFilePath, topModule.Name));

            Directory.CreateDirectory(projectXstPath);
            Directory.CreateDirectory(projectTmpPath);

            Logger.Instance.WriteDebug("Top Level component name: {0}", toplevelComponentName);
            Logger.Instance.WriteDebug("Xst path: {0}", projectXstFilePath);

            List<string> arguments = new List<string>();
            arguments.Add(string.Format("-ifn \"{0}\"", projectXstFilePath));
            arguments.Add(string.Format("-ofn \"{0}\"", projectSyrFilePath));

            XilinxProcess process = new XilinxProcess("xst", arguments);
            DefaultMessageParser parser = new DefaultMessageParser();
            StringProcessListener stringParser = new StringProcessListener();
            parser.MessageOccured += ((obj) => obj.WriteToLogger());

            process.Listeners.Add(parser);
            process.Listeners.Add(stringParser);
            process.WorkingDirectory = workingDirectory;

            process.Start();
            process.WaitForExit();

            BuildResult buildResult = new BuildResult();
            buildResult.BuildLog = stringParser.Output + "\n\n\n" + stringParser.ErrorOutput;
            buildResult.WorkingDirectory = workingDirectory;

            File.Delete(projectFilePath);
            File.Delete(projectXstFilePath);
            Directory.Delete(PathHelper.Combine(workingDirectory, "xst"), true);

            return buildResult;
        }
        /// <summary>
        /// Creates an assembly refernce node from a project element.
        /// </summary>
        internal virtual AssemblyReferenceNode CreateAssemblyReferenceNode(ProjectElement element, BuildResult buildResult)
        {
            AssemblyReferenceNode node = null;
            try
            {
                node = AssemblyReferenceNode.CreateFromProjectFile(this.ProjectMgr, element, buildResult);
            }
            catch (ArgumentNullException e)
            {
                Trace.WriteLine("Exception : " + e.Message);
            }
            catch (FileNotFoundException e)
            {
                Trace.WriteLine("Exception : " + e.Message);
            }
            catch (BadImageFormatException e)
            {
                Trace.WriteLine("Exception : " + e.Message);
            }
            catch (FileLoadException e)
            {
                Trace.WriteLine("Exception : " + e.Message);
            }
            catch (System.Security.SecurityException e)
            {
                Trace.WriteLine("Exception : " + e.Message);
            }

            return node;
        }
Example #20
0
        private void buildNaCl(BuildResult result, MonoNaClProjectConfiguration config, ConfigurationSelector configSel)
        {
            string NACL_SDK_ROOT  = MonoNaClSettingsService.Instance.NACL_SDK_ROOT;
            string NACL_MONO_ROOT = MonoNaClSettingsService.Instance.NACL_MONO_ROOT;

            // Set compiler flags
            string WARNINGS = "-Wno-long-long -Wall";            //"-w";
            string CFLAGS   = string.Format(@"-O0 -g {0} -I {1}/include/mono-2.0", WARNINGS, NACL_MONO_ROOT);
            string flags    = "";

            if (RequiresGLES)
            {
                flags = "-lppapi_gles2 ";
            }
            string LDFLAGS   = string.Format(@"{0}-lppapi -lmono-2.0 -L {1}/lib32 -Wl,--export-dynamic -ldl", flags, NACL_MONO_ROOT);
            string LDFLAGS64 = string.Format(@"{0}-lppapi -lmono-2.0 -L {1}/lib -Wl,--export-dynamic -ldl", flags, NACL_MONO_ROOT);

            // Get output name
            string PROJECT = "main";            //config.AppName;

            // Get C and CS sources
            string CC_SOURCES = "";

            foreach (var file in Files)
            {
                string fullPath = '"' + file.FilePath.FullPath + '"' + ' ';
                switch (file.FilePath.Extension.ToLower())
                {
                case (".c"): CC_SOURCES += fullPath; break;
                }
            }
            if (CC_SOURCES == "")
            {
                return;
            }

            // Get .dll sources
            string CS_DLL_SOURCES = "";

            foreach (var reference in References)
            {
                var names = reference.GetReferencedFileNames(configSel);
                foreach (var name in names)
                {
                    CS_DLL_SOURCES += "-r:" + '"' + name + '"';
                }
            }

            // Get OS name
            string OSNAME = executeProgram("python", string.Format(@"{0}/tools/getos.py", NACL_SDK_ROOT));

            // If libmono was compiled in a posix environment (NaCl) use forward slashes so Windows can cope with the paths.
            if (OSNAME == "win")
            {
                NACL_SDK_ROOT  = NACL_SDK_ROOT.Replace(@"\", @"/");
                NACL_MONO_ROOT = NACL_MONO_ROOT.Replace(@"\", @"/");
            }

            // Get System architecture type
            //string ARCH = executeProgram("python", string.Format(@"{0}/tools/getos.py --arch", NACL_SDK_ROOT));

            // Get NaCl Tool Chain path
            string TC_PATH = string.Format(@"{0}/toolchain/{1}_x86_glibc", NACL_SDK_ROOT, OSNAME);

            // Get NaCl gcc compiler
            string CC = string.Format(@"{0}/bin/i686-nacl-gcc", TC_PATH);

            // Compile .nexe's
            executeProgram(CC, string.Format(@"-o {0} {1} -m32 -O0 -g {2} {3}", PROJECT + "_x86_32.nexe", CC_SOURCES, CFLAGS, LDFLAGS));
            executeProgram(CC, string.Format(@"-o {0} {1} -m64 -O0 -g {2} {3}", PROJECT + "_x86_64.nexe", CC_SOURCES, CFLAGS, LDFLAGS64));

            // Generate manifiest(.nmf) file
            string NMF       = string.Format(@"{0}/tools/create_nmf.py", NACL_SDK_ROOT);
            string NMF_ARGS  = string.Format(@"-D {0}/x86_64-nacl/bin/objdump", TC_PATH);
            string NMF_PATHS = string.Format(@"-L {0}/x86_64-nacl/lib32 -L {0}/x86_64-nacl/lib -L {1}/lib32 -L {1}/lib", TC_PATH, NACL_MONO_ROOT);

            executeProgram("python", string.Format(@"{0} {1} -s . -o {2}.nmf {2}_x86_64.nexe {2}_x86_32.nexe {3}", NMF, NMF_ARGS, PROJECT, NMF_PATHS));

            // Copy and create other nacl files
            if (config.CompileTarget == MonoDevelop.Projects.CompileTarget.Exe)
            {
                // Create manifest.json
                if (GenerateManifest)
                {
                    var manifest = new Manifest();
                    manifest.manifest_version = 2;
                    manifest.version          = AppVersion;
                    manifest.name             = AppName;
                    manifest.description      = AppDescription;

                    manifest.app                   = new Manifest.App();
                    manifest.app.launch            = new Manifest.App.Launch();
                    manifest.app.launch.local_path = "main.html";

                    if (RequiresGLES)
                    {
                        manifest.requirements              = new Manifest.Requirements();
                        manifest.requirements._3d          = new Manifest.Requirements._3D();
                        manifest.requirements._3d.features = new string[2]
                        {
                            "css3d",
                            "webgl"
                        };
                    }

                    manifest.permissions = new string[2]
                    {
                        "unlimitedStorage",
                        "notifications"
                    };

                    var json         = new DataContractJsonSerializer(typeof(Manifest));
                    var memoryStream = new MemoryStream();
                    json.WriteObject(memoryStream, manifest);

                    memoryStream.Position = 0;
                    var reader = new StreamReader(memoryStream);
                    var value  = reader.ReadToEnd();
                    value = Regex.Replace(value, @"\," + '"' + @"\w*" + '"' + @"\:null", "", RegexOptions.Singleline);
                    value = Regex.Replace(value, '"' + @"\w*" + '"' + @"\:null", "", RegexOptions.Singleline);

                    using (var stream = new FileStream(config.OutputDirectory + "/manifest.json", FileMode.Create, FileAccess.Write))
                        using (var writer = new StreamWriter(stream))
                        {
                            writer.Write(value);
                        }
                }

                // Copy Json and Html files
                if (CopyAllJsonObjects || CopyAllHtmlObjects || CopyAllJSObjects)
                {
                    foreach (var file in Files)
                    {
                        var    srcFileInfo = new FileInfo(file.FilePath.FullPath);
                        string dstDir      = config.OutputDirectory + "/" + srcFileInfo.Name;
                        var    dstFileInfo = new FileInfo(dstDir);
                        if (dstFileInfo.LastWriteTimeUtc != srcFileInfo.LastWriteTimeUtc)
                        {
                            string ext = file.FilePath.Extension.ToLower();
                            if (CopyAllJsonObjects && ext == ".json")
                            {
                                srcFileInfo.CopyTo(dstDir, true);
                            }

                            if (CopyAllJsonObjects && ext == ".html")
                            {
                                srcFileInfo.CopyTo(dstDir, true);
                            }

                            if (CopyAllJSObjects && ext == ".js")
                            {
                                srcFileInfo.CopyTo(dstDir, true);
                            }
                        }
                    }
                }
            }
        }
		private void BuildCoda(BuildResult result, IVsOutputWindowPane output, bool shouldRepaintReferences)
		{
			try
			{
				// Now repaint references if that is needed. 
				// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
				// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable, 
				// but msbuild can actually resolve it.
				// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
				if (shouldRepaintReferences && result.IsSuccessful)
				{
					this.RefreshReferences();
				}
			}
			finally
			{
				try
				{
					ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
				}
				finally
				{
					NotifyBuildEnd(result.IsSuccessful);
				}
			}
		}
Example #22
0
 public BuildResult ToBuildResult(GenerateResult generateResult)
 => IsSuccess || File.Exists(generateResult.ArtifactsPaths.ExecutablePath)     // dotnet cli could have successfully built the program, but returned 1 as exit code because it had some warnings
         ? BuildResult.Success(generateResult)
         : BuildResult.Failure(generateResult, new Exception(ProblemDescription));
Example #23
0
 /// <summary>
 /// Callback for event raised when a build request is completed
 /// </summary>
 /// <param name="request">The request which completed</param>
 /// <param name="result">The result for the request</param>
 private void Engine_RequestComplete(BuildRequest request, BuildResult result)
 {
     _requestComplete_Request = request;
     _requestComplete_Result  = result;
     _requestCompleteEvent.Set();
 }
        private void BindFromBuildResult(Build.Evaluation.ProjectItem element, BuildResult buildResult)
        {
            var include = MSBuildItem.GetEvaluatedInclude(element);
            fsprojIncludeHasFilename = (include.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
                                             include.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));

            ResolveFromBuiltProject(include, buildResult);
            if (!fsprojIncludeHasFilename)
            {
                InitializeAssemblyName(include);
            }
            InitializeFileChangeEvents();
        }
Example #25
0
            private void BuilderThreadProc()
            {
                _entry.RequestConfiguration.Project = CreateStandinProject();

                if (ThrowExceptionOnRequest)
                {
                    BuildResult errorResult = new BuildResult(_entry.Request, new InvalidOperationException("ContinueRequest not received in time."));
                    _entry.Complete(errorResult);
                    RaiseRequestComplete(_entry);
                    return;
                }

                bool completeSuccess = CompleteRequestSuccessfully;

                if (_cancelEvent.WaitOne(1000))
                {
                    BuildResult res = new BuildResult(_entry.Request, new BuildAbortedException());
                    _entry.Complete(res);
                    RaiseRequestComplete(_entry);
                    return;
                }

                for (int i = 0; i < NewRequests.Count; ++i)
                {
                    OnNewBuildRequests(_entry, NewRequests[i]);
                    WaitHandle[] handles = new WaitHandle[2] {
                        _cancelEvent, _continueEvent
                    };
                    int evt = WaitHandle.WaitAny(handles, 5000);
                    if (evt == 0)
                    {
                        BuildResult res = new BuildResult(_entry.Request, new BuildAbortedException());
                        _entry.Complete(res);
                        RaiseRequestComplete(_entry);
                        return;
                    }
                    else if (evt == 1)
                    {
                        IDictionary <int, BuildResult> results = _entry.Continue();
                        foreach (BuildResult configResult in results.Values)
                        {
                            if (configResult.OverallResult == BuildResultCode.Failure)
                            {
                                completeSuccess = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        BuildResult errorResult = new BuildResult(_entry.Request, new InvalidOperationException("ContinueRequest not received in time."));
                        _entry.Complete(errorResult);
                        RaiseRequestComplete(_entry);
                        return;
                    }
                    if (!completeSuccess)
                    {
                        break;
                    }
                    Delay();
                }

                BuildResult result = new BuildResult(_entry.Request);

                foreach (string target in _entry.Request.Targets)
                {
                    result.AddResultsForTarget(target, new TargetResult(new TaskItem[1] {
                        new TaskItem("include", _entry.RequestConfiguration.ProjectFullPath)
                    }, completeSuccess ? TestUtilities.GetSuccessResult() : TestUtilities.GetStopWithErrorResult()));
                }
                _entry.Complete(result);
            }
Example #26
0
        //FIXME: Check whether autogen.sh is required or not
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration)
        {
            Project project = entry as Project;

            if (project == null)
            {
                return(base.Build(monitor, entry, configuration));
            }

            MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;

            if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.BuildTargetName))
            {
                return(base.Build(monitor, entry, configuration));
            }

            //FIXME: Gen autofoo ? autoreconf?

            string output   = String.Empty;
            int    exitCode = 0;

            monitor.BeginTask(GettextCatalog.GetString("Building {0}", project.Name), 1);
            try
            {
                string baseDir = project.BaseDirectory;
                string args    = string.Format("-j {0} {1}", data.ParallelProcesses, data.BuildTargetName);

                StringWriter  swOutput      = new StringWriter();
                LogTextWriter chainedOutput = new LogTextWriter();
                chainedOutput.ChainWriter(monitor.Log);
                chainedOutput.ChainWriter(swOutput);

                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             args,
                                                                             baseDir,
                                                                             chainedOutput,
                                                                             chainedOutput,
                                                                             null);
                process.WaitForOutput();

                exitCode = process.ExitCode;
                output   = swOutput.ToString();
                chainedOutput.Close();
                swOutput.Close();
                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("Project could not be built: "), e);
                return(null);
            }
            finally
            {
                monitor.EndTask();
            }

            TempFileCollection tf = new TempFileCollection();
            Regex regexError      = data.GetErrorRegex(false);
            Regex regexWarning    = data.GetWarningRegex(false);

            BuildResult cr = ParseOutput(tf, output, project.BaseDirectory, regexError, regexWarning);

            if (exitCode != 0 && cr.FailedBuildCount == 0)
            {
                cr.AddError(GettextCatalog.GetString("Build failed. See Build Output panel."));
            }
            else
            {
                entry.SetNeedsBuilding(false, configuration);
            }

            return(cr);
        }
Example #27
0
 internal void SetResultsToReturn(BuildResult result)
 {
     _cache.AddResult(result);
 }
        private static List <ExecuteResult> Execute(ILogger logger, Benchmark benchmark, IToolchain toolchain, BuildResult buildResult, IConfig config, IResolver resolver, out GcStats gcStats)
        {
            var executeResults = new List <ExecuteResult>();

            gcStats = default(GcStats);

            logger.WriteLineInfo("// *** Execute ***");
            bool analyzeRunToRunVariance = benchmark.Job.ResolveValue(AccuracyMode.AnalyzeLaunchVarianceCharacteristic, resolver);
            bool autoLaunchCount         = !benchmark.Job.HasValue(RunMode.LaunchCountCharacteristic);
            int  defaultValue            = analyzeRunToRunVariance ? 2 : 1;
            int  launchCount             = Math.Max(
                1,
                autoLaunchCount ? defaultValue: benchmark.Job.Run.LaunchCount);

            for (int launchIndex = 0; launchIndex < launchCount; launchIndex++)
            {
                string printedLaunchCount = (analyzeRunToRunVariance &&
                                             autoLaunchCount &&
                                             launchIndex < 2)
                    ? ""
                    : " / " + launchCount;
                logger.WriteLineInfo($"// Launch: {launchIndex + 1}{printedLaunchCount}");

                var executeResult = toolchain.Executor.Execute(
                    new ExecuteParameters(buildResult, benchmark, logger, resolver, config));

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError($"Executable {buildResult.ArtifactsPaths.ExecutablePath} not found");
                }
                if (executeResult.ExitCode != 0)
                {
                    logger.WriteLineError("ExitCode != 0");
                }
                executeResults.Add(executeResult);

                var measurements = executeResults
                                   .SelectMany(r => r.Data)
                                   .Select(line => Measurement.Parse(logger, line, 0))
                                   .Where(r => r.IterationMode != IterationMode.Unknown).
                                   ToArray();

                if (!measurements.Any())
                {
                    // Something went wrong during the benchmark, don't bother doing more runs
                    logger.WriteLineError("No more Benchmark runs will be launched as NO measurements were obtained from the previous run!");
                    break;
                }

                if (autoLaunchCount && launchIndex == 1 && analyzeRunToRunVariance)
                {
                    // TODO: improve this logic
                    var idleApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.IdleTarget).Select(m => m.Nanoseconds)).Median;
                    var mainApprox = new Statistics(measurements.Where(m => m.IterationMode == IterationMode.MainTarget).Select(m => m.Nanoseconds)).Median;
                    var percent    = idleApprox / mainApprox * 100;
                    launchCount = (int)Math.Round(Math.Max(2, 2 + (percent - 1) / 3)); // an empirical formula
                }
            }
            logger.WriteLine();

            // Do a "Diagnostic" run, but DISCARD the results, so that the overhead of Diagnostics doesn't skew the overall results
            if (config.GetDiagnosers().Any())
            {
                logger.WriteLineInfo("// Run, Diagnostic");
                var compositeDiagnoser = config.GetCompositeDiagnoser();

                var executeResult = toolchain.Executor.Execute(
                    new ExecuteParameters(buildResult, benchmark, logger, resolver, config, compositeDiagnoser));

                var allRuns = executeResult.Data.Select(line => Measurement.Parse(logger, line, 0)).Where(r => r.IterationMode != IterationMode.Unknown).ToList();
                gcStats = GcStats.Parse(executeResult.Data.Last());
                var report = new BenchmarkReport(benchmark, null, null, new[] { executeResult }, allRuns, gcStats);
                compositeDiagnoser.ProcessResults(benchmark, report);

                if (!executeResult.FoundExecutable)
                {
                    logger.WriteLineError("Executable not found");
                }
                logger.WriteLine();
            }
            else if (config.GetHardwareCounters().Any())
            {
                logger.WriteLineError("Hardware Counters are not supported for your current platform yet");
            }

            return(executeResults);
        }
Example #29
0
 public void TestNullParameterInConstructor()
 {
     BuildResult shouldFail = new BuildResult(null, false /* shallow copy */);
 }
 private static void AssertExpectedStyleCopSetting(string expectedValue, BuildResult actualResult)
 {
     BuildAssertions.AssertExpectedAnalysisSetting(actualResult, TargetConstants.StyleCopProjectPathItemName, expectedValue);
 }
Example #31
0
        private async Task <int> GetPipelineIdAsync(
            AgentTaskPluginExecutionContext context,
            string pipelineDefinition,
            string pipelineVersionToDownload,
            string project,
            string[] tagFilters,
            BuildResult resultFilter            = BuildResult.Succeeded,
            string branchName                   = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrWhiteSpace(pipelineDefinition))
            {
                throw new InvalidOperationException(StringUtil.Loc("CannotBeNullOrEmpty", "Pipeline Definition"));
            }

            VssConnection   connection      = context.VssConnection;
            BuildHttpClient buildHttpClient = connection.GetClient <BuildHttpClient>();

            var isDefinitionNum = Int32.TryParse(pipelineDefinition, out int definition);

            if (!isDefinitionNum)
            {
                var definitionReferencesWithName = await AsyncHttpRetryHelper.InvokeAsync(
                    async() => await buildHttpClient.GetDefinitionsAsync(new Guid(project), pipelineDefinition, cancellationToken: cancellationToken),
                    maxRetries : MaxRetries,
                    tracer : tracer,
                    context : "GetBuildDefinitionReferencesByName",
                    cancellationToken : cancellationToken,
                    continueOnCapturedContext : false);

                var definitionRef = definitionReferencesWithName.FirstOrDefault();

                if (definitionRef == null)
                {
                    throw new ArgumentException(StringUtil.Loc("PipelineDoesNotExist", pipelineDefinition));
                }
                else
                {
                    definition = definitionRef.Id;
                }
            }
            var definitions = new List <int>()
            {
                definition
            };

            List <Build> list;

            if (pipelineVersionToDownload == pipelineVersionToDownloadLatest)
            {
                list = await AsyncHttpRetryHelper.InvokeAsync(
                    async() => await buildHttpClient.GetBuildsAsync(
                        project,
                        definitions,
                        tagFilters: tagFilters,
                        queryOrder: BuildQueryOrder.FinishTimeDescending,
                        resultFilter: resultFilter,
                        cancellationToken: cancellationToken),
                    maxRetries : MaxRetries,
                    tracer : tracer,
                    context : "GetLatestBuild",
                    cancellationToken : cancellationToken,
                    continueOnCapturedContext : false);
            }
            else if (pipelineVersionToDownload == pipelineVersionToDownloadLatestFromBranch)
            {
                list = await AsyncHttpRetryHelper.InvokeAsync(
                    async() => await buildHttpClient.GetBuildsAsync(
                        project,
                        definitions,
                        branchName: branchName,
                        tagFilters: tagFilters,
                        queryOrder: BuildQueryOrder.FinishTimeDescending,
                        resultFilter: resultFilter,
                        cancellationToken: cancellationToken),
                    maxRetries : MaxRetries,
                    tracer : tracer,
                    context : "GetLatestBuildFromBranch",
                    cancellationToken : cancellationToken,
                    continueOnCapturedContext : false);
            }
            else
            {
                throw new InvalidOperationException("Unreachable code!");
            }

            if (list.Count > 0)
            {
                return(list.First().Id);
            }
            else
            {
                throw new ArgumentException(StringUtil.Loc("BuildsDoesNotExist"));
            }
        }
Example #32
0
 public static void AddWarning(this BuildResult buildResult, ITaskRunnerNode task, ITaskRunnerCommandResult result)
 {
     buildResult.AddWarning(GetBuildWarning(task, result));
 }
        /// <summary>
        /// Resolves references.
        /// </summary>
        internal virtual void ResolveReference(BuildResult buildResult)
        {

        }
Example #34
0
        public static bool BuildPackage(IProgressMonitor monitor, MonoMacProject project,
                                        ConfigurationSelector conf, MonoMacPackagingSettings settings, FilePath target)
        {
            string bundleKey  = settings.BundleSigningKey;
            string packageKey = settings.PackageSigningKey;

            if (settings.SignBundle || (settings.CreatePackage && settings.SignPackage))
            {
                var identities = Keychain.GetAllSigningIdentities();

                if (string.IsNullOrEmpty(bundleKey))
                {
                    bundleKey = identities.FirstOrDefault(k => k.StartsWith(MonoMacPackagingSettingsWidget.APPLICATION_PREFIX));
                    if (string.IsNullOrEmpty(bundleKey))
                    {
                        monitor.ReportError("Did not find default app signing key", null);
                        return(false);
                    }
                    else if (!identities.Any(k => k == bundleKey))
                    {
                        monitor.ReportError("Did not find app signing key in keychain", null);
                        return(false);
                    }
                }

                if (string.IsNullOrEmpty(packageKey))
                {
                    packageKey = identities.FirstOrDefault(k => k.StartsWith(MonoMacPackagingSettingsWidget.INSTALLER_PREFIX));
                    if (string.IsNullOrEmpty(packageKey))
                    {
                        monitor.ReportError("Did not find default package signing key", null);
                        return(false);
                    }
                    else if (!identities.Any(k => k == packageKey))
                    {
                        monitor.ReportError("Did not find package signing key in keychain", null);
                        return(false);
                    }
                }
            }

            if (project.NeedsBuilding(conf))
            {
                BuildResult res = project.Build(monitor, conf);
                if (res.ErrorCount > 0)
                {
                    foreach (BuildError e in res.Errors)
                    {
                        monitor.ReportError(e.ToString(), null);
                    }
                    monitor.ReportError(GettextCatalog.GetString("The project failed to build."), null);
                    return(false);
                }
            }

            var cfg = (MonoMacProjectConfiguration)project.GetConfiguration(conf);

            FilePath tempDir    = "/tmp/monomac-build-" + DateTime.Now.Ticks;
            FilePath workingApp = tempDir.Combine(cfg.AppDirectory.FileName);

            try {
                //user will have agreed to overwrite when they picked the target
                if (Directory.Exists(target))
                {
                    Directory.Delete(target);
                }
                else if (File.Exists(target))
                {
                    File.Delete(target);
                }

                monitor.BeginTask(GettextCatalog.GetString("Creating app bundle"), 0);
                var files = Directory.GetFiles(cfg.AppDirectory, "*", SearchOption.AllDirectories);
                HashSet <string> createdDirs = new HashSet <string> ();
                foreach (FilePath f in files)
                {
                    var rel       = f.ToRelative(cfg.AppDirectory);
                    var parentDir = rel.ParentDirectory;
                    if (settings.IncludeMono)
                    {
                        if (parentDir.IsNullOrEmpty || parentDir == "." || parentDir == "Contents/MacOS")
                        {
                            continue;
                        }
                        var ext = rel.Extension;
                        if (ext == ".mdb" || ext == ".exe" || ext == ".dll")
                        {
                            continue;
                        }
                    }
                    if (monitor.IsCancelRequested)
                    {
                        return(false);
                    }
                    if (createdDirs.Add(parentDir))
                    {
                        Directory.CreateDirectory(workingApp.Combine(parentDir));
                    }
                    monitor.Log.WriteLine(rel);
                    File.Copy(f, workingApp.Combine(rel));
                }
                monitor.EndTask();

                if (settings.IncludeMono)
                {
                    monitor.BeginTask(GettextCatalog.GetString("Merging Mono into app bundle"), 0);

                    var args = new ProcessArgumentBuilder();
                    switch (settings.LinkerMode)
                    {
                    case MonoMacLinkerMode.LinkNone:
                        args.Add("--nolink");
                        break;

                    case MonoMacLinkerMode.LinkFramework:
                        args.Add("--linksdkonly");
                        break;

                    case MonoMacLinkerMode.LinkAll:
                        // nothing
                        break;
                    }

                    args.Add("-o");
                    args.AddQuoted(tempDir);
                    args.Add("-n");
                    args.AddQuoted(cfg.AppName);

                    var assemblies = project.GetReferencedAssemblies(conf, true);
                    foreach (var a in assemblies)
                    {
                        args.Add("-a");
                        args.AddQuoted(a);
                    }
                    args.AddQuoted(cfg.CompiledOutputName);

                    string mmpPath = Mono.Addins.AddinManager.CurrentAddin.GetFilePath("mmp");

                    //FIXME: workaround for Mono.Addins losing the executable bit during packaging
                    var mmpInfo = new Mono.Unix.UnixFileInfo(mmpPath);
                    if ((mmpInfo.FileAccessPermissions & Mono.Unix.FileAccessPermissions.UserExecute) == 0)
                    {
                        mmpInfo.FileAccessPermissions |= Mono.Unix.FileAccessPermissions.UserExecute;
                    }

                    var psi = new ProcessStartInfo(mmpPath, args.ToString());
                    monitor.Log.WriteLine("mmp " + psi.Arguments);

                    string err;
                    if (MacBuildUtilities.ExecuteCommand(monitor, psi, out err) != 0)
                    {
                        monitor.Log.WriteLine(err);
                        monitor.ReportError("Merging Mono failed", null);
                        return(false);
                    }

                    var plistFile = workingApp.Combine("Contents", "Info.plist");
                    var plistDoc  = new PlistDocument();
                    plistDoc.LoadFromXmlFile(plistFile);
                    ((PlistDictionary)plistDoc.Root)["MonoBundleExecutable"] = cfg.CompiledOutputName.FileName;
                    plistDoc.WriteToFile(plistFile);

                    monitor.EndTask();
                }

                //TODO: verify bundle details if for app store?

                if (settings.SignBundle)
                {
                    monitor.BeginTask(GettextCatalog.GetString("Signing app bundle"), 0);

                    var args = new ProcessArgumentBuilder();
                    args.Add("-v", "-f", "-s");
                    args.AddQuoted(bundleKey, workingApp);

                    var psi = new ProcessStartInfo("codesign", args.ToString());
                    monitor.Log.WriteLine("codesign " + psi.Arguments);

                    string err;
                    if (MacBuildUtilities.ExecuteCommand(monitor, psi, out err) != 0)
                    {
                        monitor.Log.WriteLine(err);
                        monitor.ReportError("Signing failed", null);
                        return(false);
                    }

                    monitor.EndTask();
                }

                if (settings.CreatePackage)
                {
                    monitor.BeginTask(GettextCatalog.GetString("Creating installer"), 0);

                    var args = new ProcessArgumentBuilder();
                    args.Add("--component");
                    args.AddQuoted(workingApp);
                    args.Add("/Applications");
                    if (settings.SignPackage)
                    {
                        args.Add("--sign");
                        args.AddQuoted(packageKey);
                    }
                    if (!settings.ProductDefinition.IsNullOrEmpty)
                    {
                        args.Add("--product");
                        args.AddQuoted(settings.ProductDefinition);
                    }
                    args.AddQuoted(target);

                    var psi = new ProcessStartInfo("productbuild", args.ToString());
                    monitor.Log.WriteLine("productbuild " + psi.Arguments);

                    string err;
                    int    pbRet;
                    try {
                        pbRet = MacBuildUtilities.ExecuteCommand(monitor, psi, out err);
                    } catch (System.ComponentModel.Win32Exception) {
                        monitor.ReportError("productbuild not found", null);
                        return(false);
                    }
                    if (pbRet != 0)
                    {
                        monitor.Log.WriteLine(err);
                        monitor.ReportError("Package creation failed", null);
                        return(false);
                    }
                    monitor.EndTask();
                }
                else
                {
                    Directory.Move(workingApp, target);
                }
            } finally {
                try {
                    if (Directory.Exists(tempDir))
                    {
                        Directory.Delete(tempDir, true);
                    }
                } catch (Exception ex) {
                    LoggingService.LogError("Error removing temp directory", ex);
                }
            }

            return(true);
        }
 /// <summary>
 /// Creating AssemblyReferenceNode from fsproj element
 /// </summary>
 private AssemblyReferenceNode(ProjectNode root, ProjectElement element, BuildResult buildResult)
     : base(root, element)
 {
     BindFromBuildResult(element.Item, buildResult);
 }
Example #36
0
 /// <summary>
 /// Required for interface - this should never be called.
 /// </summary>
 Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingGlobalBuildRequestId, string blockingTarget, BuildResult partialBuildResult)
 {
     ErrorUtilities.ThrowInternalError("This method should never be called by anyone except the TargetBuilder.");
     return(Task.FromResult(false));
 }
        private void ResolveFromBuiltProject(string assemblyInclude, BuildResult buildResult)
        {
            Action<string> Trace = (s) => FSharpTrace.PrintLine("ProjectSystemReferenceResolution", () => "ResolveAssemblyReferenceCore: " + s);
            Trace("starting: \"" + assemblyInclude + "\"");
            if (!buildResult.IsSuccessful)
            {
                Trace("ResolveAssemblyReferences build failed.");
                return;
            }
            System.Collections.Generic.IEnumerable<ProjectItemInstance> group = buildResult.ProjectInstance.GetItems(ProjectFileConstants.ReferencePath);
            if (group != null)
            {
                foreach (var item in group)
                {
                    // TODO, the logic here is too brittle - if a user adds a 'logical duplicate' assembly with a different name, it may not find resolution
                    // and then wind up with wrong diagnostic later because it failed to resolve (when in fact it would resolve if not for duplicate)
                    if (0 == string.Compare(assemblyInclude, MSBuildItem.GetMetadataValue(item, "OriginalItemSpec"), StringComparison.Ordinal))
                    {
                        var fusionName = MSBuildItem.GetMetadataValue(item, "FusionName");
                        if (!string.IsNullOrEmpty(fusionName))
                        {
                            this.resolvedInfo.ResolvedAssemblyName = new System.Reflection.AssemblyName(fusionName);
                            this.resolvedInfo.AssemblyName = this.resolvedInfo.ResolvedAssemblyName;
                        }
                        this.resolvedInfo.IsPlatformAssembly = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.ResolvedFrom), "{TargetFrameworkDirectory}", StringComparison.OrdinalIgnoreCase);
                        this.resolvedInfo.IsNoPIA = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.EmbedInteropTypes), "true", StringComparison.OrdinalIgnoreCase);
                        this.resolvedInfo.CopyLocalDefault = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.CopyLocal), "true", StringComparison.OrdinalIgnoreCase);
                        this.resolvedInfo.WasSuccessfullyResolved = true;
                        this.myAssemblyPath = MSBuildItem.GetEvaluatedInclude(item);

                        if (!Path.IsPathRooted(this.myAssemblyPath))
                        {
                            this.myAssemblyPath = Path.Combine(this.ProjectMgr.ProjectFolder, this.myAssemblyPath);
                        }
                        Trace("finished and found original item: \"" + assemblyInclude + "\"");
                        return;
                    }
                }
            }
            Trace("finished without finding original item: \"" + assemblyInclude + "\"");
        }
Example #38
0
 public bool Equals(BuildResult other)
 {
     return this.buildResult == other.buildResult && this.projectInstance == other.ProjectInstance;
 }
Example #39
0
        /// <summary>
        /// Logs the project started/finished pair for projects which are skipped entirely because all
        /// of their results are available in the cache.
        /// </summary>
        internal void LogRequestHandledFromCache(BuildRequest request, BuildRequestConfiguration configuration, BuildResult result)
        {
            ProjectLoggingContext projectLoggingContext = LogProjectStarted(request, configuration);

            // When pulling a request from the cache, we want to make sure we log a target skipped event for any targets which
            // were used to build the request including default and initial targets.
            foreach (string target in configuration.GetTargetsUsedToBuildRequest(request))
            {
                var  targetResult = result[target];
                bool isFailure    = targetResult.ResultCode == TargetResultCode.Failure;

                var skippedTargetEventArgs = new TargetSkippedEventArgs(message: null)
                {
                    BuildEventContext         = projectLoggingContext.BuildEventContext,
                    TargetName                = target,
                    BuildReason               = TargetBuiltReason.None,
                    SkipReason                = isFailure ? TargetSkipReason.PreviouslyBuiltUnsuccessfully : TargetSkipReason.PreviouslyBuiltSuccessfully,
                    OriginallySucceeded       = !isFailure,
                    OriginalBuildEventContext = (targetResult as TargetResult)?.OriginalBuildEventContext
                };

                projectLoggingContext.LogBuildEvent(skippedTargetEventArgs);

                if (targetResult.ResultCode == TargetResultCode.Failure)
                {
                    break;
                }
            }

            projectLoggingContext.LogProjectFinished(result.OverallResult == BuildResultCode.Success);
        }
Example #40
0
        private void ReportDefaultParentRequestIsFinished()
        {
            var buildResult = new BuildResult(_defaultParentRequest);

            _scheduler.ReportResult(_defaultParentRequest.NodeRequestId, buildResult);
        }
Example #41
0
        /// <summary>
        /// Builds the specified targets.
        /// </summary>
        /// <param name="loggingContext">The logging context for the project.</param>
        /// <param name="entry">The BuildRequestEntry for which we are building targets.</param>
        /// <param name="callback">The callback to be used to handle new project build requests.</param>
        /// <param name="targetNames">The names of the targets to build.</param>
        /// <param name="baseLookup">The Lookup containing all current items and properties for this target.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use when building the targets.</param>
        /// <returns>The target's outputs and result codes</returns>
        public async Task <BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targetNames, Lookup baseLookup, CancellationToken cancellationToken)
        {
            ErrorUtilities.VerifyThrowArgumentNull(loggingContext, "projectLoggingContext");
            ErrorUtilities.VerifyThrowArgumentNull(entry, nameof(entry));
            ErrorUtilities.VerifyThrowArgumentNull(callback, "requestBuilderCallback");
            ErrorUtilities.VerifyThrowArgumentNull(targetNames, nameof(targetNames));
            ErrorUtilities.VerifyThrowArgumentNull(baseLookup, nameof(baseLookup));
            ErrorUtilities.VerifyThrow(targetNames.Length > 0, "List of targets must be non-empty");
            ErrorUtilities.VerifyThrow(_componentHost != null, "InitializeComponent must be called before building targets.");

            _requestEntry           = entry;
            _requestBuilderCallback = callback;
            _projectLoggingContext  = loggingContext;
            _cancellationToken      = cancellationToken;

            // Clone the base lookup so that if we are re-entered by another request while this one in blocked, we don't have visibility to
            // their state, and they have no visibility into ours.
            _baseLookup = baseLookup.Clone();

            _targetsToBuild = new ConcurrentStack <TargetEntry>();

            // Get the actual target objects from the names
            BuildRequestConfiguration configuration = _requestEntry.RequestConfiguration;

            bool previousCacheableStatus = configuration.IsCacheable;

            configuration.IsCacheable = false;
            configuration.RetrieveFromCache();
            _projectInstance = configuration.Project;

            // Now get the current results cache entry.
            IResultsCache resultsCache        = (IResultsCache)_componentHost.GetComponent(BuildComponentType.ResultsCache);
            BuildResult   existingBuildResult = resultsCache.GetResultsForConfiguration(_requestEntry.Request.ConfigurationId);

            _buildResult = new BuildResult(entry.Request, existingBuildResult, null);

            if (existingBuildResult == null)
            {
                // Add this result so that if our project gets re-entered we won't rebuild any targets we have already built.
                resultsCache.AddResult(_buildResult);
            }

            List <TargetSpecification> targets = new List <TargetSpecification>(targetNames.Length);

            foreach (string targetName in targetNames)
            {
                var targetExists = _projectInstance.Targets.TryGetValue(targetName, out ProjectTargetInstance targetInstance);
                if (!targetExists && entry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.SkipNonexistentTargets))
                {
                    _projectLoggingContext.LogComment(Framework.MessageImportance.Low,
                                                      "TargetSkippedWhenSkipNonexistentTargets", targetName);
                }
                else
                {
                    targets.Add(new TargetSpecification(targetName, targetExists ? targetInstance.Location : _projectInstance.ProjectFileLocation));
                }
            }

            // Push targets onto the stack.  This method will reverse their push order so that they
            // get built in the same order specified in the array.
            await PushTargets(targets, null, baseLookup, false, false, TargetBuiltReason.None);

            // Now process the targets
            ITaskBuilder taskBuilder = _componentHost.GetComponent(BuildComponentType.TaskBuilder) as ITaskBuilder;

            try
            {
                await ProcessTargetStack(taskBuilder);
            }
            finally
            {
                // If there are still targets left on the stack, they need to be removed from the 'active targets' list
                foreach (TargetEntry target in _targetsToBuild)
                {
                    configuration.ActivelyBuildingTargets.Remove(target.Name);
                }

                ((IBuildComponent)taskBuilder).ShutdownComponent();
            }

            if (_cancellationToken.IsCancellationRequested)
            {
                throw new BuildAbortedException();
            }

            // Gather up outputs for the requested targets and return those.  All of our information should be in the base lookup now.
            ComputeAfterTargetFailures(targetNames);
            BuildResult resultsToReport = new BuildResult(_buildResult, targetNames);

            // Return after-build project state if requested.
            if (_requestEntry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.ProvideProjectStateAfterBuild))
            {
                resultsToReport.ProjectStateAfterBuild = _projectInstance;
            }

            if (_requestEntry.Request.RequestedProjectState != null)
            {
                resultsToReport.ProjectStateAfterBuild =
                    _projectInstance.FilteredCopy(_requestEntry.Request.RequestedProjectState);
            }

            configuration.IsCacheable = previousCacheableStatus;

            return(resultsToReport);
        }
Example #42
0
        public void TestBuildWithNewConfiguration()
        {
            BuildRequestData          data   = new BuildRequestData(Path.GetFullPath("TestFile"), new Dictionary <string, string>(), "TestToolsVersion", new string[0], null);
            BuildRequestConfiguration config = new BuildRequestConfiguration(1, data, "2.0");

            _cache.AddConfiguration(config);

            // Configure the builder to spawn build requests
            MockRequestBuilder        builder          = (MockRequestBuilder)_host.GetComponent(BuildComponentType.RequestBuilder);
            BuildRequestData          data2            = new BuildRequestData(Path.GetFullPath("OtherFile"), new Dictionary <string, string>(), "TestToolsVersion", new string[0], null);
            BuildRequestConfiguration unresolvedConfig = new BuildRequestConfiguration(data2, "2.0");

            builder.NewRequests.Add(new FullyQualifiedBuildRequest[1] {
                new FullyQualifiedBuildRequest(unresolvedConfig, new string[1] {
                    "requiredTarget1"
                }, true)
            });

            // Create the initial build request
            string[] targets = new string[3] {
                "target1", "target2", "target3"
            };
            BuildRequest request = CreateNewBuildRequest(1, targets);

            // Kick it off
            VerifyEngineStatus(BuildRequestEngineStatus.Uninitialized);
            _engine.InitializeForBuild(new NodeLoggingContext(_host.LoggingService, 0, false));
            _engine.SubmitBuildRequest(request);
            Thread.Sleep(250);
            VerifyEngineStatus(BuildRequestEngineStatus.Active);

            // Wait for the request to generate the child request with the unresolved configuration
            WaitForEvent(_newConfigurationEvent, "NewConfigurationEvent");
            Assert.Equal(Path.GetFullPath("OtherFile"), _newConfiguration_Config.ProjectFullPath);
            Assert.Equal("TestToolsVersion", _newConfiguration_Config.ToolsVersion);
            Assert.True(_newConfiguration_Config.WasGeneratedByNode);
            Thread.Sleep(250);
            VerifyEngineStatus(BuildRequestEngineStatus.Waiting);

            // Resolve the configuration
            BuildRequestConfigurationResponse response = new BuildRequestConfigurationResponse(_newConfiguration_Config.ConfigurationId, 2, 0);

            _engine.ReportConfigurationResponse(response);

            // Now wait for the actual requests to be issued.
            WaitForEvent(_newRequestEvent, "NewRequestEvent");
            Assert.Equal(2, _newRequest_Request.BuildRequests[0].ConfigurationId);
            Assert.Equal(2, _newRequest_Request.BuildRequests[0].ConfigurationId);
            Assert.Equal(1, _newRequest_Request.BuildRequests[0].Targets.Count);
            Assert.Equal("requiredTarget1", _newRequest_Request.BuildRequests[0].Targets[0]);

            // Report a result to satisfy the build request
            BuildResult result = new BuildResult(_newRequest_Request.BuildRequests[0]);

            result.AddResultsForTarget("requiredTarget1", TestUtilities.GetEmptySucceedingTargetResult());
            _engine.UnblockBuildRequest(new BuildRequestUnblocker(result));

            // Continue the request
            _engine.UnblockBuildRequest(new BuildRequestUnblocker(request.GlobalRequestId));

            // Wait for the original request to complete
            WaitForEvent(_requestCompleteEvent, "RequestComplete");
            Assert.Equal(request, _requestComplete_Request);
            Assert.Equal(BuildResultCode.Success, _requestComplete_Result.OverallResult);
            Thread.Sleep(250);
            VerifyEngineStatus(BuildRequestEngineStatus.Idle);
        }
 /// <summary>
 /// Constructor over a result.
 /// </summary>
 public BlockingRequestKey(BuildResult result)
 {
     _globalRequestId = result.GlobalRequestId;
     _nodeRequestId   = result.NodeRequestId;
 }
 private static void AssertExpectedErrorLog(BuildResult result, string expectedErrorLog)
 {
     BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, TargetProperties.ErrorLog, expectedErrorLog);
 }
Example #45
0
        private void buildCS(BuildResult result, MonoNaClProjectConfiguration config, ConfigurationSelector configSel)
        {
            string NACL_MONO_ROOT = MonoNaClSettingsService.Instance.NACL_MONO_ROOT;
            var    projProperties = ((CSharpCompilerParameters)config.CompilationParameters);

            // Get output name
            string OUTPUT_TARGET = config.CompileTarget == MonoDevelop.Projects.CompileTarget.Exe ? "exe" : "library";
            string CS_OUTPUT     = config.AppFullName;
            string PROJECT       = "main";      //config.AppName;

            // Get C and CS sources
            string CS_SOURCES = "";

            foreach (var file in Files)
            {
                string fullPath = '"' + file.FilePath.FullPath + '"' + ' ';
                switch (file.FilePath.Extension.ToLower())
                {
                case (".cs"): CS_SOURCES += fullPath; break;
                }

                // Copy dependency files
                if (file.CopyToOutputDirectory == FileCopyMode.Always || file.CopyToOutputDirectory == FileCopyMode.PreserveNewest)
                {
                    string virtualFileName = buildingConfig.OutputDirectory + file.ProjectVirtualPath.FullPath;
                    var    dstFileInfo     = new FileInfo(virtualFileName);

                    if (!dstFileInfo.Directory.Exists)
                    {
                        dstFileInfo.Directory.Create();
                    }
                    if (!dstFileInfo.Exists)
                    {
                        var srcFileInfo = new FileInfo(file.FilePath.FullPath);
                        srcFileInfo.CopyTo(virtualFileName);
                    }
                    else
                    {
                        if (file.CopyToOutputDirectory == FileCopyMode.Always)
                        {
                            var srcFileInfo = new FileInfo(file.FilePath.FullPath);
                            srcFileInfo.CopyTo(virtualFileName, true);
                        }
                        else
                        {
                            var srcFileInfo = new FileInfo(file.FilePath.FullPath);
                            if (srcFileInfo.LastWriteTimeUtc != dstFileInfo.LastWriteTimeUtc)
                            {
                                srcFileInfo.CopyTo(virtualFileName, true);
                            }
                        }
                    }
                }
            }
            if (CS_SOURCES == "")
            {
                return;
            }

            // Get .dll sources
            string CS_DLL_SOURCES = "";
            var    dlls           = new List <string>();

            foreach (var reference in References)
            {
                var names = reference.GetReferencedFileNames(configSel);
                foreach (var name in names)
                {
                    var    srcLibFileInfo = new FileInfo(name);
                    string filePath       = name;
                    if (reference.ReferenceType == ReferenceType.Package && reference.Package.Name == "mono")
                    {
                        string dstDirectory = string.Format("{0}/lib/mono/4.0/", NACL_MONO_ROOT);
                        filePath = dstDirectory + srcLibFileInfo.Name;
                    }

                    CS_DLL_SOURCES += "-r:" + '"' + filePath + '"' + " ";
                    dlls.Add(filePath);

                    if (config.CompileTarget == MonoDevelop.Projects.CompileTarget.Exe)
                    {
                        string dstName        = buildingConfig.OutputDirectory + "/" + srcLibFileInfo.Name;
                        var    dstLibFileInfo = new FileInfo(dstName);
                        if (!dstLibFileInfo.Exists || srcLibFileInfo.LastWriteTimeUtc != dstLibFileInfo.LastWriteTimeUtc)
                        {
                            srcLibFileInfo.CopyTo(dstName, true);
                        }
                    }
                }
            }

            if (dlls.Count != 0 && config.CompileTarget == MonoDevelop.Projects.CompileTarget.Exe)
            {
                using (var stream = new FileStream(string.Format("{0}/{1}.dep", buildingConfig.OutputDirectory, PROJECT), FileMode.Create, FileAccess.Write))
                    using (var writer = new StreamWriter(stream))
                    {
                        int i = 0;
                        foreach (var dll in dlls)
                        {
                            var fileInfo = new FileInfo(dll);
                            if (i == dlls.Count - 1)
                            {
                                writer.Write(fileInfo.Name);
                            }
                            else
                            {
                                writer.WriteLine(fileInfo.Name);
                            }
                            ++i;
                        }
                    }
            }

            // Get flags
            string flags = " -sdk:2";

            if (projProperties.UnsafeCode)
            {
                flags += " -unsafe";
            }
            if (projProperties.Optimize)
            {
                flags += " -optimize";
            }

            // Get compiler directives
            var symbols    = projProperties.DefineSymbols;
            var symbolList = symbols.Split(';', ' ');

            symbols = "";
            foreach (var symbol in symbolList)
            {
                if (!string.IsNullOrEmpty(symbol))
                {
                    symbols += "-define:" + symbol + " ";
                }
            }

            // Compile dll's and .exe
            string GMCS = string.Format(@"{0}/lib/mono/4.0/mcs.exe", NACL_MONO_ROOT);

            executeProgram(GMCS, string.Format(@"{0}{1} -out:{2} {3}-target:{4}{5}", symbols, CS_SOURCES, CS_OUTPUT, CS_DLL_SOURCES, OUTPUT_TARGET, flags));            //-pkg:gtk-sharp

            // Copy over mscorlib.dll
            if (config.CompileTarget == MonoDevelop.Projects.CompileTarget.Exe)
            {
                string mscorlibPath    = buildingConfig.OutputDirectory + "/mscorlib.dll";
                var    dstCoreFileInfo = new FileInfo(mscorlibPath);
                if (!dstCoreFileInfo.Exists)
                {
                    var srcCoreFileInfo = new FileInfo(string.Format("{0}/lib/mono/4.0/mscorlib.dll", NACL_MONO_ROOT));
                    srcCoreFileInfo.CopyTo(mscorlibPath);
                }
            }
        }
Example #46
0
        /// <summary>
        /// Resolves the location of the reference files.
        /// </summary>
        /// <param name="baseProject">The base project.</param>
        /// <param name="referenceReplacements">A different set of references to use instead of those in the project.
        /// Used by the GacReferencePanel.</param>
        public static IList <ReferenceProjectItem> ResolveAssemblyReferences(
            MSBuildBasedProject baseProject,
            ReferenceProjectItem[] additionalReferences = null, bool resolveOnlyAdditionalReferences = false,
            bool logErrorsToOutputPad = true)
        {
            ProjectInstance project = baseProject.CreateProjectInstance();

            project.SetProperty("BuildingProject", "false");

            List <ProjectItemInstance> references = (
                from item in project.Items
                where ItemType.ReferenceItemTypes.Contains(new ItemType(item.ItemType))
                select item
                ).ToList();

            List <ReferenceProjectItem> referenceProjectItems;

            if (resolveOnlyAdditionalReferences)
            {
                // Remove existing references from project
                foreach (ProjectItemInstance reference in references)
                {
                    project.RemoveItem(reference);
                }
                references.Clear();
                referenceProjectItems = new List <ReferenceProjectItem>();
            }
            else
            {
                // Remove the "Private" meta data.
                // This is necessary to detect the default value for "Private"
                foreach (ProjectItemInstance reference in references)
                {
                    reference.RemoveMetadata("Private");
                }
                referenceProjectItems = baseProject.Items.OfType <ReferenceProjectItem>().ToList();
            }

            if (additionalReferences != null)
            {
                referenceProjectItems.AddRange(additionalReferences);
                foreach (ReferenceProjectItem item in additionalReferences)
                {
                    references.Add(project.AddItem("Reference", item.Include));
                }
            }

            string[]         targets     = { "ResolveAssemblyReferences" };
            BuildRequestData requestData = new BuildRequestData(project, targets, new HostServices());
            List <ILogger>   loggers     = new List <ILogger>();

            if (logErrorsToOutputPad)
            {
                loggers.Add(new SimpleErrorLogger());
            }
            lock (SolutionProjectCollectionLock)
            {
                BuildParameters parameters = new BuildParameters(baseProject.MSBuildProjectCollection);
                parameters.Loggers = loggers;

                LoggingService.Debug("Started build for ResolveAssemblyReferences");
                BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, requestData);
                if (result == null)
                {
                    throw new InvalidOperationException("BuildResult is null");
                }
                LoggingService.Debug("Build for ResolveAssemblyReferences finished: " + result.OverallResult);
            }

            IEnumerable <ProjectItemInstance> resolvedAssemblyProjectItems = project.GetItems("_ResolveAssemblyReferenceResolvedFiles");

            var query =
                from msbuildItem in resolvedAssemblyProjectItems
                let originalInclude = msbuildItem.GetMetadataValue("OriginalItemSpec")
                                      join item in referenceProjectItems.Where(p => p.ItemType != ItemType.ProjectReference) on originalInclude equals item.Include into referenceItems
                                      select new
            {
                OriginalInclude = originalInclude,
                AssemblyName    = new DomAssemblyName(msbuildItem.GetMetadataValue("FusionName")),
                FullPath        = FileUtility.GetAbsolutePath(baseProject.Directory, msbuildItem.GetMetadataValue("Identity")),
                Redist          = msbuildItem.GetMetadataValue("Redist"),
                CopyLocal       = bool.Parse(msbuildItem.GetMetadataValue("CopyLocal")),
                ReferenceItems  = referenceItems
            };
            List <ReferenceProjectItem> resolvedAssemblies    = new List <ReferenceProjectItem>();
            List <ReferenceProjectItem> handledReferenceItems = new List <ReferenceProjectItem>();

            foreach (var assembly in query)
            {
                LoggingService.Debug("Got information about " + assembly.OriginalInclude + "; fullpath=" + assembly.FullPath);
                foreach (var referenceItem in assembly.ReferenceItems)
                {
                    referenceItem.AssemblyName          = assembly.AssemblyName;
                    referenceItem.FileName              = assembly.FullPath;
                    referenceItem.Redist                = assembly.Redist;
                    referenceItem.DefaultCopyLocalValue = assembly.CopyLocal;
                    handledReferenceItems.Add(referenceItem);
                }
                ReferenceProjectItem firstItem = assembly.ReferenceItems.FirstOrDefault();
                if (firstItem != null)
                {
                    resolvedAssemblies.Add(firstItem);
                }
                else
                {
                    resolvedAssemblies.Add(new ReferenceProjectItem(baseProject, assembly.OriginalInclude)
                    {
                        FileName = assembly.FullPath
                    });
                }
            }
            // Add any assemblies that weren't resolved yet. This is important - for example, this adds back project references.
            foreach (var referenceItem in referenceProjectItems.Except(handledReferenceItems))
            {
                resolvedAssemblies.Add(referenceItem);
            }
            return(resolvedAssemblies);
        }
Example #47
0
 public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark, IResolver resolver)
 {
     logger.WriteLine("Building");
     Done = true;
     return(BuildResult.Success(generateResult));
 }
        static BuildResult ParseOutput(string stdout, string stderr)
        {
            BuildResult result = new BuildResult();

            StringBuilder compilerOutput    = new StringBuilder();
            bool          typeLoadException = false;

            foreach (string s in new string[] { stdout, stderr })
            {
                StreamReader sr = File.OpenText(s);
                while (true)
                {
                    if (typeLoadException)
                    {
                        compilerOutput.Append(sr.ReadToEnd());
                        break;
                    }
                    string curLine = sr.ReadLine();
                    compilerOutput.AppendLine(curLine);

                    if (curLine == null)
                    {
                        break;
                    }

                    curLine = curLine.Trim();
                    if (curLine.Length == 0)
                    {
                        continue;
                    }

                    if (curLine.StartsWith("Unhandled Exception: System.TypeLoadException") ||
                        curLine.StartsWith("Unhandled Exception: System.IO.FileNotFoundException"))
                    {
                        result.ClearErrors();
                        typeLoadException = true;
                    }

                    BuildError error = CreateErrorFromString(curLine);

                    if (error != null)
                    {
                        result.Append(error);
                    }
                }
                sr.Close();
            }
            if (typeLoadException)
            {
                Regex reg = new Regex(@".*WARNING.*used in (mscorlib|System),.*", RegexOptions.Multiline);
                if (reg.Match(compilerOutput.ToString()).Success)
                {
                    result.AddError("", 0, 0, "", "Error: A referenced assembly may be built with an incompatible CLR version. See the compilation output for more details.");
                }
                else
                {
                    result.AddError("", 0, 0, "", "Error: A dependency of a referenced assembly may be missing, or you may be referencing an assembly created with a newer CLR version. See the compilation output for more details.");
                }
            }
            result.CompilerOutput = compilerOutput.ToString();
            return(result);
        }
        internal virtual ReferenceNode CreateReferenceNode(string referenceType, ProjectElement element, BuildResult buildResult)
        {
            ReferenceNode node = null;
            if (referenceType == ProjectFileConstants.COMReference)
            {
                node = this.CreateComReferenceNode(element);
            }
            else if (referenceType == ProjectFileConstants.Reference)
            {
                node = this.CreateAssemblyReferenceNode(element, buildResult);
            }
            else if (referenceType == ProjectFileConstants.ProjectReference)
            {
                node = this.CreateProjectReferenceNode(element);
                EnableCachingForProjectReferencesInBatchUpdate(node);
            }

            return node;
        }
        public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor)
        {
            var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters();
            var projectParameters  = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters();

            FilePath outputName       = configuration.CompiledOutputName;
            string   responseFileName = Path.GetTempFileName();

            //make sure that the output file is writable
            if (File.Exists(outputName))
            {
                bool isWriteable = false;
                int  count       = 0;
                do
                {
                    try {
                        outputName.MakeWritable();
                        using (var stream = File.OpenWrite(outputName)) {
                            isWriteable = true;
                        }
                    } catch (Exception) {
                        Thread.Sleep(20);
                    }
                } while (count++ < 5 && !isWriteable);
                if (!isWriteable)
                {
                    MessageService.ShowError(string.Format(GettextCatalog.GetString("Can't lock file: {0}."), outputName));
                    return(null);
                }
            }

            //get the runtime
            TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime;
            DotNetProject project = configuration.ParentItem as DotNetProject;

            if (project != null)
            {
                runtime = project.TargetRuntime;
            }

            //get the compiler name
            string compilerName;

            try {
                compilerName = GetCompilerName(runtime, configuration.TargetFramework);
            } catch (Exception e) {
                string message = "Could not obtain a PlayScript compiler";
                monitor.ReportError(message, e);
                return(null);
            }

            var sb = new StringBuilder();

            HashSet <string> alreadyAddedReference = new HashSet <string> ();

            var monoRuntime = runtime as MonoTargetRuntime;

            if (!compilerParameters.NoStdLib && (monoRuntime == null || monoRuntime.HasMultitargetingMcs))
            {
                string corlib = project.AssemblyContext.GetAssemblyFullName("mscorlib", project.TargetFramework);
                if (corlib != null)
                {
                    corlib = project.AssemblyContext.GetAssemblyLocation(corlib, project.TargetFramework);
                }
                if (corlib == null)
                {
                    var br = new BuildResult();
                    br.AddError(string.Format("Could not find mscorlib for framework {0}", project.TargetFramework.Id));
                    return(br);
                }
                AppendQuoted(sb, "/r:", corlib);
                sb.AppendLine("-nostdlib");
            }

            List <string> gacRoots = new List <string> ();

            sb.AppendFormat("\"/out:{0}\"", outputName);
            sb.AppendLine();

            foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ())
            {
                if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName(lib.Reference) is DotNetProject))
                {
                    continue;
                }
                string refPrefix = string.IsNullOrEmpty(lib.Aliases) ? "" : lib.Aliases + "=";
                foreach (string fileName in lib.GetReferencedFileNames(configSelector))
                {
                    switch (lib.ReferenceType)
                    {
                    case ReferenceType.Package:
                        SystemPackage pkg = lib.Package;
                        if (pkg == null)
                        {
                            string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference);
                            monitor.ReportWarning(msg);
                            continue;
                        }

                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }

                        if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot))
                        {
                            gacRoots.Add(pkg.GacRoot);
                        }
                        if (!string.IsNullOrEmpty(pkg.Requires))
                        {
                            foreach (string requiredPackage in pkg.Requires.Split(' '))
                            {
                                SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage);
                                if (rpkg == null)
                                {
                                    continue;
                                }
                                foreach (SystemAssembly assembly in rpkg.Assemblies)
                                {
                                    if (alreadyAddedReference.Add(assembly.Location))
                                    {
                                        AppendQuoted(sb, "/r:", assembly.Location);
                                    }
                                }
                            }
                        }
                        break;

                    default:
                        if (alreadyAddedReference.Add(fileName))
                        {
                            AppendQuoted(sb, "/r:", refPrefix + fileName);
                        }
                        break;
                    }
                }
            }

            string sysCore = project.AssemblyContext.GetAssemblyFullName("System.Core", project.TargetFramework);

            if (sysCore != null)
            {
                sysCore = project.AssemblyContext.GetAssemblyLocation(sysCore, project.TargetFramework);
                if (sysCore != null && !alreadyAddedReference.Contains(sysCore))
                {
                    AppendQuoted(sb, "/r:", sysCore);
                }
            }

            sb.AppendLine("/nologo");
            sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString());
            sb.AppendLine();

            if (configuration.SignAssembly)
            {
                if (File.Exists(configuration.AssemblyKeyFile))
                {
                    AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile);
                }
            }

            if (configuration.DebugMode)
            {
//				sb.AppendLine ("/debug:+");
                sb.AppendLine("/debug:full");
            }

            if (compilerParameters.LangVersion != LangVersion.Default)
            {
                var langVersionString = CSharpCompilerParameters.TryLangVersionToString(compilerParameters.LangVersion);
                if (langVersionString == null)
                {
                    string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'";
                    monitor.ReportError(message, null);
                    LoggingService.LogError(message);
                    return(null);
                }
                sb.AppendLine("/langversion:" + langVersionString);
            }

            // mcs default is + but others might not be
            if (compilerParameters.Optimize)
            {
                sb.AppendLine("/optimize+");
            }
            else
            {
                sb.AppendLine("/optimize-");
            }

            bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource);

            if (hasWin32Res)
            {
                AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource);
            }

            if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon))
            {
                if (hasWin32Res)
                {
                    monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon.");
                }
                else
                {
                    AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon);
                }
            }

            if (projectParameters.CodePage != 0)
            {
                sb.AppendLine("/codepage:" + projectParameters.CodePage);
            }
            else if (runtime is MonoTargetRuntime)
            {
                sb.AppendLine("/codepage:utf8");
            }

            if (compilerParameters.UnsafeCode)
            {
                sb.AppendLine("-unsafe");
            }
            if (compilerParameters.NoStdLib)
            {
                sb.AppendLine("-nostdlib");
            }

            if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu")
            {
                //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it
                if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null)
                {
                    LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName +
                                              "' appears to be too old to support the 'platform' PlayScript compiler flag.");
                }
                else
                {
                    sb.AppendLine("/platform:" + compilerParameters.PlatformTarget);
                }
            }

            if (compilerParameters.TreatWarningsAsErrors)
            {
                sb.AppendLine("-warnaserror");
                if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors))
                {
                    sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors);
                }
            }

            if (compilerParameters.DefineSymbols.Length > 0)
            {
                string define_str = string.Join(";", compilerParameters.DefineSymbols.Split(new char [] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries));
                if (define_str.Length > 0)
                {
                    AppendQuoted(sb, "/define:", define_str);
                    sb.AppendLine();
                }
            }

            CompileTarget ctarget = configuration.CompileTarget;

            if (!string.IsNullOrEmpty(projectParameters.MainClass))
            {
                sb.AppendLine("/main:" + projectParameters.MainClass);
                // mcs does not allow providing a Main class when compiling a dll
                // As a workaround, we compile as WinExe (although the output will still
                // have a .dll extension).
                if (ctarget == CompileTarget.Library)
                {
                    ctarget = CompileTarget.WinExe;
                }
            }

            switch (ctarget)
            {
            case CompileTarget.Exe:
                sb.AppendLine("/t:exe");
                break;

            case CompileTarget.WinExe:
                sb.AppendLine("/t:winexe");
                break;

            case CompileTarget.Library:
                sb.AppendLine("/t:library");
                break;
            }

            foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ())
            {
                if (finfo.Subtype == Subtype.Directory)
                {
                    continue;
                }

                switch (finfo.BuildAction)
                {
                case "Compile":
                    AppendQuoted(sb, "", finfo.Name);
                    break;

                case "EmbeddedResource":
                    string fname = finfo.Name;
                    if (string.Compare(Path.GetExtension(fname), ".resx", true) == 0)
                    {
                        fname = Path.ChangeExtension(fname, ".resources");
                    }
                    sb.Append('"'); sb.Append("/res:");
                    sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId);
                    sb.Append('"'); sb.AppendLine();
                    break;

                default:
                    continue;
                }
            }
            if (compilerParameters.GenerateXmlDocumentation)
            {
                AppendQuoted(sb, "/doc:", Path.ChangeExtension(outputName, ".xml"));
            }

            if (!string.IsNullOrEmpty(compilerParameters.AdditionalArguments))
            {
                sb.AppendLine(compilerParameters.AdditionalArguments);
            }

            if (!string.IsNullOrEmpty(compilerParameters.NoWarnings))
            {
                AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings);
            }

            if (runtime.RuntimeId == "MS.NET")
            {
                sb.AppendLine("/fullpaths");
                sb.AppendLine("/utf8output");
            }

            string output = "";
            string error  = "";

            File.WriteAllText(responseFileName, sb.ToString());



            monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' '));

            string workingDir = ".";

            if (configuration.ParentItem != null)
            {
                workingDir = configuration.ParentItem.BaseDirectory;
                if (workingDir == null)
                {
                    // Dummy projects created for single files have no filename
                    // and so no BaseDirectory.
                    // This is a workaround for a bug in
                    // ProcessStartInfo.WorkingDirectory - not able to handle null
                    workingDir = ".";
                }
            }

            LoggingService.LogInfo(compilerName + " " + sb.ToString());

            ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework);
            string cargs = "/noconfig @\"" + responseFileName + "\"";

            int exitCode = DoCompilation(monitor, compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error);

            BuildResult result = ParseOutput(output, error);

            if (result.CompilerOutput.Trim().Length != 0)
            {
                monitor.Log.WriteLine(result.CompilerOutput);
            }

            //if compiler crashes, output entire error string
            if (result.ErrorCount == 0 && exitCode != 0)
            {
                try {
                    monitor.Log.Write(File.ReadAllText(error));
                } catch (IOException) {
                }
                result.AddError("The compiler appears to have crashed. Check the build output pad for details.");
                LoggingService.LogError("PlayScript compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'",
                                        responseFileName, output, error);
            }
            else
            {
                FileService.DeleteFile(responseFileName);
                FileService.DeleteFile(output);
                FileService.DeleteFile(error);
            }
            return(result);
        }
 /// <summary>
 /// Refreshes a reference by re-resolving it and redrawing the icon.
 /// </summary>
 internal virtual void RefreshReference(BuildResult buildResult)
 {
     this.ResolveReference(buildResult);
     this.ReDraw(UIHierarchyElement.Icon);
 }
 private static void AssertCodeAnalysisIsDisabled(BuildResult result)
 {
     // Check the ruleset and error log are not set
     AssertExpectedErrorLog(result, string.Empty);
     AssertExpectedResolvedRuleset(result, string.Empty);
 }
 internal static AssemblyReferenceNode CreateFromProjectFile(ProjectNode root, ProjectElement element, BuildResult buildResult)
 { return new AssemblyReferenceNode(root, element, buildResult); }
Example #54
0
 public void TestConstructorGood()
 {
     BuildRequest request = CreateNewBuildRequest(1, new string[0]);
     BuildResult  result2 = new BuildResult(request);
 }
        internal void RebindFSharpCoreAfterUpdatingVersion(BuildResult buildResult)
        {
            Debug.Assert(IsFSharpCoreReference(this));
            if (!ContainsUsagesOfTargetFSharpCoreVersionProperty(this))
                return;

            UnregisterFromFileChangeService();
            ItemNode.RefreshProperties();

            fsprojIncludeHasFilename = false;
            resolvedInfo = default(AssemblyResolvedInfo);
            myAssemblyPath = string.Empty;
            msbuildProjectionInfo = default(AssemblyMSBuildProjectionInfo);

            BindFromBuildResult(ItemNode.Item, buildResult);

            this.ReDraw(UIHierarchyElement.Icon);
            this.ReDraw(UIHierarchyElement.Caption);
        }
Example #56
0
        public override BuildResult Compile(
            Project project,
            ProjectFileCollection projectFiles,
            ProjectPackageCollection packages,
            CProjectConfiguration configuration,
            IProgressMonitor monitor)
        {
            if (!appsChecked)
            {
                appsChecked   = true;
                compilerFound = CheckApp(compilerCommand);
                linkerFound   = CheckApp(linkerCommand);
            }

            if (!compilerFound)
            {
                BuildResult cres = new BuildResult();
                cres.AddError("Compiler not found: " + compilerCommand);
                return(cres);
            }

            if (!linkerFound)
            {
                BuildResult cres = new BuildResult();
                cres.AddError("Linker not found: " + linkerCommand);
                return(cres);
            }

            CompilerResults cr           = new CompilerResults(new TempFileCollection());
            bool            success      = true;
            string          compilerArgs = GetCompilerFlags(project, configuration) + " " + GeneratePkgCompilerArgs(packages);

            string outputName = Path.Combine(configuration.OutputDirectory,
                                             configuration.CompiledOutputName);

            // Precompile header files and place them in .prec/<config_name>/
            if (configuration.PrecompileHeaders)
            {
                string precDir       = Path.Combine(configuration.SourceDirectory, ".prec");
                string precConfigDir = Path.Combine(precDir, configuration.Id);
                if (!Directory.Exists(precDir))
                {
                    Directory.CreateDirectory(precDir);
                }
                if (!Directory.Exists(precConfigDir))
                {
                    Directory.CreateDirectory(precConfigDir);
                }

                if (!PrecompileHeaders(projectFiles, configuration, compilerArgs, monitor, cr))
                {
                    success = false;
                }
            }
            else
            {
                //old headers could interfere with the build
                CleanPrecompiledHeaders(configuration);
            }

            //compile source to object files
            monitor.BeginTask(GettextCatalog.GetString("Compiling source to object files"), 1);
            foreach (ProjectFile f in projectFiles)
            {
                if (!success)
                {
                    break;
                }
                if (f.Subtype == Subtype.Directory || f.BuildAction != BuildAction.Compile || CProject.IsHeaderFile(f.FilePath))
                {
                    continue;
                }

                if (configuration.UseCcache || NeedsCompiling(f, configuration))
                {
                    success = DoCompilation(f, configuration, compilerArgs, monitor, cr, configuration.UseCcache);
                }
            }
            if (success)
            {
                monitor.Step(1);
            }
            monitor.EndTask();

            if (success)
            {
                switch (configuration.CompileTarget)
                {
                case CBinding.CompileTarget.Bin:
                    MakeBin(project, projectFiles, configuration, packages, cr, monitor, outputName);
                    break;

                case CBinding.CompileTarget.StaticLibrary:
                    MakeStaticLibrary(project, projectFiles, configuration, packages, cr, monitor, outputName);
                    break;

                case CBinding.CompileTarget.SharedLibrary:
                    MakeSharedLibrary(project, projectFiles, configuration, packages, cr, monitor, outputName);
                    break;
                }
            }

            return(new BuildResult(cr, ""));
        }
 internal override void ResolveReference(BuildResult buildResult)
 {
     Debug.Assert(this.ItemNode != null && this.ItemNode.Item != null, "called ResolveReference before initializing ItemNode");
     this.ResolveFromBuiltProject(MSBuildItem.GetEvaluatedInclude(this.ItemNode.Item), buildResult);
 }
Example #58
0
        public static BuildResult GenerateCodeBehind(
            AspNetAppProject project,
            string filename,
            WebFormsParsedDocument document,
            out CodeCompileUnit ccu)
        {
            ccu = null;
            var    result    = new BuildResult();
            string className = document.Info.InheritedClass;

            AddErrorsToResult(result, filename, document.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            if (string.IsNullOrEmpty(className))
            {
                return(result);
            }

            var refman = new WebFormsTypeContext {
                Project = project, Doc = document
            };
            var memberList = new WebFormsMemberListBuilder(refman, document.XDocument);

            memberList.Build();

            AddErrorsToResult(result, filename, memberList.Errors);
            if (result.ErrorCount > 0)
            {
                return(result);
            }

            //initialise the generated type
            ccu = new CodeCompileUnit();
            var namespac = new CodeNamespace();

            ccu.Namespaces.Add(namespac);
            var typeDecl = new CodeTypeDeclaration {
                IsClass   = true,
                IsPartial = true,
            };

            namespac.Types.Add(typeDecl);

            //name the class and namespace
            int namespaceSplit = className.LastIndexOf('.');

            if (namespaceSplit > -1)
            {
                namespac.Name = project.StripImplicitNamespace(className.Substring(0, namespaceSplit));
                typeDecl.Name = className.Substring(namespaceSplit + 1);
            }
            else
            {
                typeDecl.Name = className;
            }

            string masterTypeName = null;

            if (!String.IsNullOrEmpty(document.Info.MasterPageTypeName))
            {
                masterTypeName = document.Info.MasterPageTypeName;
            }
            else if (!String.IsNullOrEmpty(document.Info.MasterPageTypeVPath))
            {
                try {
                    ProjectFile            resolvedMaster       = project.ResolveVirtualPath(document.Info.MasterPageTypeVPath, document.FileName);
                    WebFormsParsedDocument masterParsedDocument = null;
                    if (resolvedMaster != null)
                    {
                        masterParsedDocument = TypeSystemService.ParseFile(project, resolvedMaster.FilePath) as WebFormsParsedDocument;
                    }
                    if (masterParsedDocument != null && !String.IsNullOrEmpty(masterParsedDocument.Info.InheritedClass))
                    {
                        masterTypeName = masterParsedDocument.Info.InheritedClass;
                    }
                } catch (Exception ex) {
                    LoggingService.LogWarning("Error resolving master page type", ex);
                }
                if (string.IsNullOrEmpty(masterTypeName))
                {
                    var msg = string.Format("Could not find type for master '{0}'", document.Info.MasterPageTypeVPath);
                    result.AddError(filename, msg);
                    return(result);
                }
            }

            if (masterTypeName != null)
            {
                var masterProp = new CodeMemberProperty {
                    Name       = "Master",
                    Type       = new CodeTypeReference(masterTypeName),
                    HasGet     = true,
                    HasSet     = false,
                    Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final,
                };
                masterProp.GetStatements.Add(new CodeMethodReturnStatement(
                                                 new CodeCastExpression(masterTypeName,
                                                                        new CodePropertyReferenceExpression(
                                                                            new CodeBaseReferenceExpression(), "Master"))));
                typeDecl.Members.Add(masterProp);
            }

            //shortcut building the existing members type map
            if (memberList.Members.Count == 0)
            {
                return(result);
            }

            var dom     = refman.Compilation;
            var cls     = ReflectionHelper.ParseReflectionName(className).Resolve(dom);
            var members = GetDesignerMembers(memberList.Members.Values, cls, filename);

            //add fields for each control in the page

            foreach (var member in members)
            {
                var type = new CodeTypeReference(member.Type.FullName);
                typeDecl.Members.Add(new CodeMemberField(type, member.Name)
                {
                    Attributes = MemberAttributes.Family
                });
            }
            return(result);
        }
        protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem project, ConfigurationSelector configuration)
        {
            AspNetAppProject aspProject = project as AspNetAppProject;

            //get the config object and validate
            AspNetAppProjectConfiguration config = (AspNetAppProjectConfiguration)aspProject.GetConfiguration(configuration);

            if (config == null)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Project configuration is invalid. Skipping CodeBehind member generation."));
                return(base.Build(monitor, project, configuration));
            }

            if (config.DisableCodeBehindGeneration)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("Skipping updating of CodeBehind partial classes, because this feature is disabled."));
                return(base.Build(monitor, project, configuration));
            }

            CodeBehindWriter writer = CodeBehindWriter.CreateForProject(monitor, aspProject);

            if (!writer.SupportsPartialTypes)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString
                                          ("The code generator for {0} does not support partial classes. Skipping CodeBehind member generation.",
                                          aspProject.LanguageBinding.Language));;
                return(base.Build(monitor, project, configuration));
            }

            //get the extension used for codebehind files
            string langExt = aspProject.LanguageBinding.GetFileName("a");

            langExt = langExt.Substring(1, langExt.Length - 1);

            List <CodeBehindWarning> errors = new List <CodeBehindWarning> ();

            monitor.Log.WriteLine(GettextCatalog.GetString("Generating CodeBehind members..."));

            bool updatedParseDb = false;

            //go over all the files generating members where necessary
            foreach (ProjectFile file in aspProject.Files)
            {
                WebSubtype type = AspNetAppProject.DetermineWebSubtype(file.FilePath);
                if (type != WebSubtype.WebForm && type != WebSubtype.WebControl && type != WebSubtype.MasterPage)
                {
                    continue;
                }

                //find the designer file
                ProjectFile designerFile = aspProject.Files.GetFile(file.Name + ".designer" + langExt);
                if (designerFile == null)
                {
                    aspProject.Files.GetFile(file.Name + ".Designer" + langExt);
                }
                if (designerFile == null)
                {
                    continue;
                }

                //only regenerate the designer class if it's older than the aspx (etc) file
                if (System.IO.File.GetLastWriteTimeUtc(designerFile.FilePath)
                    > System.IO.File.GetLastWriteTimeUtc(file.FilePath))
                {
                    continue;
                }

                //need parse DB to be up to date
                if (!updatedParseDb)
                {
                    updatedParseDb = true;
                    monitor.Log.Write(GettextCatalog.GetString("Waiting for project type database to finish updating..."));
                    ProjectDom dom = ProjectDomService.GetProjectDom(aspProject);
                    dom.ForceUpdate(true);
                    monitor.Log.WriteLine(GettextCatalog.GetString(" complete."));
                }

                //parse the ASP.NET file
                var parsedDocument = ProjectDomService.Parse(aspProject, file.FilePath) as AspNetParsedDocument;
                if (parsedDocument == null)
                {
                    continue;
                }

                var ccu = CodeBehind.GenerateCodeBehind(aspProject, designerFile.FilePath, parsedDocument, errors);
                if (ccu == null)
                {
                    continue;
                }

                writer.WriteFile(designerFile.FilePath, ccu);
            }

            writer.WriteOpenFiles();

            //write out a friendly message aout what we did
            if (writer.WrittenCount > 0)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("{0} CodeBehind designer classes updated.", writer.WrittenCount));
            }
            else
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("No changes made to CodeBehind classes."));
            }

            //and construct and return a build result
            BuildResult baseResult = base.Build(monitor, project, configuration);

            foreach (CodeBehindWarning cbw in errors)
            {
                if (cbw.FileName != null)
                {
                    baseResult.AddWarning(cbw.FileName, cbw.Line, cbw.Column, null, cbw.WarningText);
                }
                else
                {
                    baseResult.AddWarning(cbw.WarningText);
                }
            }
            return(baseResult);
        }
 private static void AssertExpectedResolvedRuleset(BuildResult result, string expectedResolvedRuleset)
 {
     BuildAssertions.AssertExpectedPropertyValue(result.ProjectStateAfterBuild, TargetProperties.ResolvedCodeAnalysisRuleset, expectedResolvedRuleset);
 }