Exemplo n.º 1
0
        static void WriteSummaryResults(IProgressMonitor monitor, int succeeded, int warnings, int errors)
        {
            monitor.Log.WriteLine();

            int total = succeeded + warnings + errors;

            //this might not be correct for languages where pluralization affects the other arguments
            //but gettext doesn't really have an answer for sentences with multiple plurals
            monitor.Log.WriteLine(
                GettextCatalog.GetPluralString(
                    "{0} file processed total. {1} generated successfully, {2} with warnings, {3} with errors",
                    "{0} files processed total. {1} generated successfully, {2} with warnings, {3} with errors",
                    total,
                    total, succeeded, warnings, errors)
                );
            //ends the root task
            monitor.EndTask();

            if (errors > 0)
            {
                monitor.ReportError(GettextCatalog.GetString("Errors in file generation."), null);
            }
            else if (warnings > 0)
            {
                monitor.ReportSuccess(GettextCatalog.GetString("Warnings in file generation."));
            }
            else
            {
                monitor.ReportSuccess(GettextCatalog.GetString("Generated files successfully."));
            }

            monitor.Dispose();
        }
Exemplo n.º 2
0
 public void ReportSuccess(bool anyUpdates)
 {
     if (anyUpdates)
     {
         progressMonitor.ReportSuccess(GettextCatalog.GetString("Package updates are available."));
     }
     else if (eventMonitor.WarningReported)
     {
         progressMonitor.ReportWarning(progressMessage.Warning);
     }
     else
     {
         progressMonitor.ReportSuccess(progressMessage.Success);
     }
 }
Exemplo n.º 3
0
        protected override void DoClean(IProgressMonitor monitor, ConfigurationSelector configuration)
        {
            var cfg = GetConfiguration(configuration) as DProjectConfiguration;

            // delete obj/res files
            monitor.BeginTask("Delete intermediate files", Files.Count);
            foreach (var f in Files)
            {
                try {
                    if (File.Exists(f.LastGenOutput))
                    {
                        File.Delete(f.LastGenOutput);
                    }
                } catch (Exception ex) {
                    monitor.ReportError("Error while removing " + f, ex);
                } finally {
                    f.LastGenOutput = string.Empty;
                    monitor.Step(1);
                }
            }
            monitor.EndTask();

            // delete target file
            monitor.BeginTask("Delete output file", 1);

            if (File.Exists(cfg.CompiledOutputName))
            {
                File.Delete(cfg.CompiledOutputName);
            }

            monitor.EndTask();

            monitor.ReportSuccess("Cleanup successful!");
        }
 public void ReportSuccess(string message)
 {
     lock (monitor.SyncRoot)
     {
         monitor.ReportSuccess(message);
     }
 }
Exemplo n.º 5
0
        public void Convert(string guiFolderName, bool makeBackup)
        {
            GtkDesignInfo info = GtkDesignInfo.FromProject(project);

            Stetic.Project gproject = GuiBuilderService.SteticApp.CreateProject(info);
            //Stetic.Project does not implement IDisposable
            try {
                string newGuiFolderName = project.BaseDirectory.Combine(guiFolderName);
                gproject.ConvertProject(info.SteticFile, newGuiFolderName);
                info.ConvertGtkFolder(guiFolderName, makeBackup);
                info.UpdateGtkFolder();
                folderName = newGuiFolderName;
                IProgressMonitor monitor = IdeApp.Workbench.ProgressMonitors.GetBuildProgressMonitor();
                try {
                    ConfigurationSelector configuration = IdeApp.Workspace.ActiveConfiguration;
                    Generator             generator     = new Generator();
                    generator.Run(monitor, project, configuration);
                    monitor.ReportSuccess("Converting was succesfull");
                } finally {
                    monitor.Dispose();
                }
            } finally {
                gproject.Dispose();
            }
        }
 public void CreateSchemaCommand()
 {
     try {
         TaskService.Errors.Clear();
         string xml = Editor.Text;
         using (IProgressMonitor monitor = XmlEditorService.GetMonitor()) {
             XmlDocument doc = XmlEditorService.ValidateWellFormedness(monitor, xml, FileName);
             if (doc == null)
             {
                 return;
             }
             monitor.BeginTask(GettextCatalog.GetString("Creating schema..."), 0);
             try {
                 string schema   = XmlEditorService.CreateSchema(Document, xml);
                 string fileName = XmlEditorService.GenerateFileName(FileName, "{0}.xsd");
                 IdeApp.Workbench.NewDocument(fileName, "application/xml", schema);
                 monitor.ReportSuccess(GettextCatalog.GetString("Schema created."));
             } catch (Exception ex) {
                 string msg = GettextCatalog.GetString("Error creating XML schema.");
                 LoggingService.LogError(msg, ex);
                 monitor.ReportError(msg, ex);
             }
         }
     } catch (Exception ex) {
         MessageService.ShowError(ex.Message);
     }
 }
Exemplo n.º 7
0
        public Translation AddNewTranslation(string isoCode, IProgressMonitor monitor)
        {
            try
            {
                Translation tr = new Translation(this, isoCode);
                translations.Add(tr);
                string templateFile    = Path.Combine(this.BaseDirectory, "messages.po");
                string translationFile = GetFileName(isoCode);
                if (!File.Exists(templateFile))
                {
                    CreateDefaultCatalog(monitor);
                }
                File.Copy(templateFile, translationFile);

                monitor.ReportSuccess(String.Format(GettextCatalog.GetString("Language '{0}' successfully added."), isoCode));
                monitor.Step(1);
                this.Save(monitor);
                return(tr);
            }
            catch (Exception e)
            {
                monitor.ReportError(String.Format(GettextCatalog.GetString("Language '{0}' could not be added: "), isoCode), e);
                return(null);
            }
            finally
            {
                monitor.EndTask();
            }
        }
Exemplo n.º 8
0
        public void RunXslTransformCommand()
        {
            if (string.IsNullOrEmpty(stylesheetFileName))
            {
                stylesheetFileName = XmlEditorService.BrowseForStylesheetFile();
                if (string.IsNullOrEmpty(stylesheetFileName))
                {
                    return;
                }
            }

            using (IProgressMonitor monitor = XmlEditorService.GetMonitor())
            {
                try
                {
                    string xsltContent;
                    try
                    {
                        xsltContent = GetFileContent(stylesheetFileName);
                    }
                    catch (System.IO.IOException)
                    {
                        monitor.ReportError(
                            GettextCatalog.GetString("Error reading file '{0}'.", stylesheetFileName), null);
                        return;
                    }
                    System.Xml.Xsl.XslTransform xslt =
                        XmlEditorService.ValidateStylesheet(monitor, xsltContent, stylesheetFileName);
                    if (xslt == null)
                    {
                        return;
                    }

                    XmlDocument doc = XmlEditorService.ValidateXml(monitor, Editor.Text, FileName);
                    if (doc == null)
                    {
                        return;
                    }

                    string newFileName = XmlEditorService.GenerateFileName(FileName, "-transformed{0}.xml");

                    monitor.BeginTask(GettextCatalog.GetString("Executing transform..."), 1);
                    using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Document))
                    {
                        xslt.Transform(doc, null, output);
                        IdeApp.Workbench.NewDocument(
                            newFileName, "application/xml", output.ToString());
                    }
                    monitor.ReportSuccess(GettextCatalog.GetString("Transform completed."));
                    monitor.EndTask();
                }
                catch (Exception ex)
                {
                    string msg = GettextCatalog.GetString("Could not run transform.");
                    monitor.ReportError(msg, ex);
                    monitor.EndTask();
                }
            }
        }
Exemplo n.º 9
0
 void CheckForPackageUpdates(
     IProgressMonitor progressMonitor,
     ProgressMonitorStatusMessage progressMessage,
     PackageUpdatesEventMonitor eventMonitor)
 {
     updatedPackagesInSolution.CheckForUpdates();
     if (updatedPackagesInSolution.AnyUpdates())
     {
         progressMonitor.ReportSuccess(GettextCatalog.GetString("Package updates are available."));
     }
     else if (eventMonitor.WarningReported)
     {
         progressMonitor.ReportWarning(progressMessage.Warning);
     }
     else
     {
         progressMonitor.ReportSuccess(progressMessage.Success);
     }
 }
Exemplo n.º 10
0
 private void executeProgramCallback(object sender, DataReceivedEventArgs e)
 {
     lock (this)
     {
         if (!String.IsNullOrEmpty(e.Data))
         {
             progressMonitor.ReportSuccess(e.Data);
             executeProgramData = e.Data;
         }
     }
 }
 public void ReportResult(ProgressMonitorStatusMessage progressMessage)
 {
     if (HasWarnings)
     {
         progressMonitor.ReportWarning(progressMessage.Warning);
     }
     else
     {
         progressMonitor.ReportSuccess(progressMessage.Success);
     }
 }
Exemplo n.º 12
0
            protected override void Run()
            {
                IProgressMonitor monitor = Monitor;

                foreach (VersionControlItemList list in items.SplitByRepository())
                {
                    list[0].Repository.Add(list.Paths, true, monitor);
                }

                Gtk.Application.Invoke(delegate {
                    VersionControlService.NotifyFileStatusChanged(items);
                });
                monitor.ReportSuccess(GettextCatalog.GetString("Add operation completed."));
            }
        protected override void Clean(IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration)
        {
            Project proj = entry as Project;

            if (proj == null)
            {
                base.Clean(monitor, entry, configuration);
                return;
            }

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

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

            monitor.BeginTask(GettextCatalog.GetString("Cleaning project"), 1);
            try
            {
                string baseDir = proj.BaseDirectory;

                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             data.CleanTargetName,
                                                                             baseDir,
                                                                             monitor.Log,
                                                                             monitor.Log,
                                                                             null);
                process.WaitForOutput();

                if (process.ExitCode > 0)
                {
                    throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", "make " + data.CleanTargetName));
                }

                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("Project could not be cleaned: "), e);
                return;
            }
            finally
            {
                monitor.EndTask();
            }
            monitor.ReportSuccess(GettextCatalog.GetString("Project successfully cleaned"));
        }
 void ReportOutcome(
     IAsyncOperation operation,
     IProgressMonitor progressMonitor,
     ProgressMonitorStatusMessage progressMessage)
 {
     if (operation.Success)
     {
         progressMonitor.ReportSuccess(progressMessage.Success);
     }
     else
     {
         progressMonitor.ReportError(progressMessage.Error, null);
         progressMonitor.ShowPackageConsole();
     }
 }
Exemplo n.º 15
0
        void RestorePackages(IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage)
        {
            var action = new RestorePackagesAction(solution, packageManagementEvents);

            if (project != null)
            {
                action.Project = project;
            }
            action.Execute();

            RefreshProjectReferences();
            ForceCreationOfSharedRepositoriesConfigFile();

            progressMonitor.ReportSuccess(progressMessage.Success);
            packageManagementEvents.OnPackagesRestored();
        }
Exemplo n.º 16
0
        void LinkToTarget(BuildResult br, bool modificationsDone)
        {
            /// The target file to which all objects will be linked to
            var LinkTargetFile = Project.GetOutputFileName(BuildConfig.Selector);

            if (!modificationsDone &&
                File.Exists(LinkTargetFile))
            {
                monitor.ReportSuccess("Build successful! - No new linkage needed");
                monitor.Step(1);
                return;
            }

            // b.Build linker argument string
            // Build argument preparation
            var linkArgs = FillInMacros(Arguments.LinkerArguments + " " + BuildConfig.ExtraLinkerArguments,
                                        new DLinkerMacroProvider
            {
                ObjectsStringPattern = Commands.ObjectFileLinkPattern,
                Objects    = BuiltObjects.ToArray(),
                TargetFile = LinkTargetFile,
                RelativeTargetDirectory = BuildConfig.OutputDirectory.ToRelative(Project.BaseDirectory),
                Libraries = BuildConfig.ReferencedLibraries
            });

            var linkerOutput      = "";
            var linkerErrorOutput = "";

            var linkerExecutable = Commands.Linker;

            if (!Path.IsPathRooted(linkerExecutable))
            {
                linkerExecutable = Path.Combine(Compiler.BinPath, Commands.Linker);

                if (!File.Exists(linkerExecutable))
                {
                    linkerExecutable = Commands.Linker;
                }
            }

            int exitCode = ExecuteCommand(linkerExecutable, linkArgs, Project.BaseDirectory, monitor,
                                          out linkerErrorOutput,
                                          out linkerOutput);

            HandleOptLinkOutput(br, linkerOutput);
            HandleReturnCode(br, linkerExecutable, exitCode);
        }
Exemplo n.º 17
0
        public IAsyncOperation Update(IProgressMonitor monitor)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                string[] statuses;
                if (InitialUpdate)
                {
                    statuses = new string [] { "NEW", "ASSIGNED", "NEEDINFO" }
                }
                ;
                else
                {
                    statuses = new string [] { "NEW", "ASSIGNED", "NEEDINFO", "RESOLVED", "CLOSED", "VERIFIED" }
                };
                string[] severities = new string [] { "Critical", "Major", "Normal", "Minor", "Enhancement" };
                DateTime t          = DateTime.Now;
                monitor.BeginTask("Updating from bugzilla server", 3);
                try {
                    Connect();
                    int nb, mb;

                    // Bugs
                    int lastWork = -1;
                    Bug[] data   = server.GetBugsForProduct(Product, statuses, severities, lastUpdate, delegate(int total, int current) {
                        if (lastWork == -1)
                        {
                            monitor.BeginStepTask("Getting bug data", total, 2);
                            lastWork = 0;
                        }
                        monitor.Step(current - lastWork);
                        lastWork = current;
                    });
                    monitor.EndTask();
                    UpdateBugData(data, out nb, out mb);
                    lastUpdate = t;
                    monitor.Step(1);
                    Save();
                    monitor.Step(1);
                    monitor.ReportSuccess(string.Format("Bug list updated ({0} added, {1} modified)", nb, mb));
                } catch (Exception ex) {
                    monitor.ReportError("Update failed", ex);
                } finally {
                    monitor.Dispose();
                }
            });
        void CheckCompatibility()
        {
            PackageCompatibilityChecker checker = CreatePackageCompatibilityChecker(solution, registeredRepositories);

            checker.CheckProjectPackages(project);

            if (checker.AnyPackagesRequireReinstallation())
            {
                MarkPackagesForReinstallation(checker);
                ReportPackageReinstallationWarning(checker);
            }
            else
            {
                if (checker.PackagesMarkedForReinstallationInPackageReferenceFile())
                {
                    MarkPackagesForReinstallation(checker);
                }
                progressMonitor.ReportSuccess(progressMessage.Success);
            }
        }
Exemplo n.º 19
0
 public IAsyncOperation UpdateBugs(IProgressMonitor monitor, IEnumerable <BugInfo> bugs)
 {
     System.Threading.ThreadPool.QueueUserWorkItem(delegate {
         monitor.BeginTask("Updating from bugzilla server", 1);
         try {
             Connect();
             List <int> ids = new List <int>();
             foreach (var b in bugs)
             {
                 ids.Add(b.Id);
             }
             Bug[] data = server.GetBugs(ids.ToArray());
             int nb, mb;
             UpdateBugData(data, out nb, out mb);
             Save();
             monitor.ReportSuccess(string.Format("Bug list updated ({0} added, {1} modified)", nb, mb));
         } catch (Exception ex) {
             monitor.ReportError("Update failed", ex);
         } finally {
             monitor.Dispose();
         }
     });
     return(monitor.AsyncOperation);
 }
Exemplo n.º 20
0
		static void UpdateCompleted (IProgressMonitor monitor, AggregatedOperationMonitor aggOp,
		                             ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result)
		{
			monitor.EndTask ();
			aggOp.Dispose ();
			
			if (monitor.IsCancelRequested) {
				monitor.ReportError (GettextCatalog.GetString ("Cancelled"), null);
				monitor.Dispose ();
				return;
			}
			
			string genFileName;
			try {
				
				bool broken = false;
				
				if (result.UnhandledException != null) {
					broken = true;
					string msg = GettextCatalog.GetString ("The '{0}' code generator crashed", file.Generator);
					result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message));
					monitor.ReportError (msg, result.UnhandledException);
					LoggingService.LogError (msg, result.UnhandledException);
				}
				
				genFileName = result.GeneratedFilePath.IsNullOrEmpty?
					null : result.GeneratedFilePath.ToRelative (file.FilePath.ParentDirectory);
				
				bool validName = !string.IsNullOrEmpty (genFileName)
					&& genFileName.IndexOfAny (new char[] { '/', '\\' }) < 0
					&& FileService.IsValidFileName (genFileName);
				
				if (!broken && !validName) {
					broken = true;
					string msg = GettextCatalog.GetString ("The '{0}' code generator output invalid filename '{1}'",
					                                       file.Generator, result.GeneratedFilePath);
					result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg));
					monitor.ReportError (msg, null);
				}
				
				if (result.Errors.Count > 0) {
					foreach (CompilerError err in result.Errors)
						TaskService.Errors.Add (new Task (file.FilePath, err.ErrorText, err.Column, err.Line,
							                                  err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error,
							                                  TaskPriority.Normal, file.Project.ParentSolution, file));
				}
				
				if (broken)
					return;
				
				if (result.Success)
					monitor.ReportSuccess ("Generated file successfully.");
				else
					monitor.ReportError ("Failed to generate file. See error pad for details.", null);
				
			} finally {
				monitor.Dispose ();
			}
			
			if (!result.GeneratedFilePath.IsNullOrEmpty && File.Exists (result.GeneratedFilePath)) {
				Gtk.Application.Invoke (delegate {
					if (genFile == null) {
						genFile = file.Project.AddFile (result.GeneratedFilePath);
					} else if (result.GeneratedFilePath != genFile.FilePath) {
						genFile.Name = result.GeneratedFilePath;
					}
					file.LastGenOutput = genFileName;
					genFile.DependsOn = file.FilePath.FileName;
					
					IdeApp.ProjectOperations.Save (file.Project);
				});
			}
		}
Exemplo n.º 21
0
		public override void Save(IProgressMonitor monitor)
		{
			monitor.ReportSuccess("Skip saving dub project.");
		}
Exemplo n.º 22
0
		void ReportOutcome (
			IAsyncOperation operation,
			IProgressMonitor progressMonitor,
			ProgressMonitorStatusMessage progressMessage)
		{
			if (operation.Success) {
				progressMonitor.ReportSuccess (progressMessage.Success);
				packageManagementEvents.OnPackagesRestored ();
			} else {
				progressMonitor.ReportError (progressMessage.Error, null);
				progressMonitor.ShowPackageConsole ();
				RestoreFailed = true;
			}
		}
Exemplo n.º 23
0
		// Note: This method may throw TimeoutException or AppleScriptException
		public void UpdateProject (IProgressMonitor monitor, List<XcodeSyncedItem> allItems, XcodeProject emptyProject)
		{
			items = allItems;
			
			monitor.BeginTask (GettextCatalog.GetString ("Updating Xcode project for {0}...", name), items.Count);
			
			var ctx = new XcodeSyncContext (projectDir, syncTimeCache);
			
			var toRemove = new HashSet<string> (itemMap.Keys);
			var toClose = new HashSet<string> ();
			var syncList = new List<XcodeSyncedItem> ();
			bool updateProject = false;
			
			foreach (var item in items) {
				bool needsSync = item.NeedsSyncOut (monitor, ctx);
				if (needsSync)
					syncList.Add (item);
				
				var files = item.GetTargetRelativeFileNames ();
				foreach (var file in files) {
					toRemove.Remove (file);
					
					if (!itemMap.ContainsKey (file)) {
						monitor.Log.WriteLine ("'{0}' needs to be updated.", file);
						updateProject = true;
					} else if (needsSync) {
						monitor.Log.WriteLine ("'{0}' needs to be closed.", file);
						toClose.Add (file);
					}
					
					itemMap[file] = item;
				}
			}
			updateProject = updateProject || toRemove.Any ();
			
			bool removedOldProject = false;
			if (updateProject) {
				if (pendingProjectWrite == null && ProjectExists ()) {
					monitor.Log.WriteLine ("A project file needs to be updated, closing and removing old project.");
					CloseProject ();
					DeleteXcproj (monitor);
					removedOldProject = true;
				}
			} else {
				foreach (var f in toClose)
					CloseFile (monitor, projectDir.Combine (f));
			}
			
			foreach (var f in toRemove) {
				itemMap.Remove (f);
				syncTimeCache.Remove (f);
				var path = projectDir.Combine (f);
				if (File.Exists (path))
					File.Delete (path);
			}
			
			if (removedOldProject) {
				HackRelocateProject (monitor);
				ctx.ProjectDir = projectDir;
			}
			
			foreach (var item in items) {
				if (updateProject)
					item.AddToProject (emptyProject, projectDir);
			}
			
			foreach (var item in syncList) {
				item.SyncOut (monitor, ctx);
				monitor.Step (1);
			}
			
			if (updateProject) {
				monitor.Log.WriteLine ("Queued write of '{0}'.", xcproj);
				pendingProjectWrite = emptyProject;
			}

			monitor.EndTask ();
			monitor.ReportSuccess (GettextCatalog.GetString ("Xcode project updated."));
		}
Exemplo n.º 24
0
		public void Push (IProgressMonitor monitor, string remote, string remoteBranch)
		{
			RemoteConfig remoteConfig = new RemoteConfig (RootRepository.GetConfig (), remote);
			Transport tp = Transport.Open (RootRepository, remoteConfig);
			
			string remoteRef = "refs/heads/" + remoteBranch;
			
			RemoteRefUpdate rr = new RemoteRefUpdate (RootRepository, RootRepository.GetBranch (), remoteRef, false, null, null);
			List<RemoteRefUpdate> list = new List<RemoteRefUpdate> ();
			list.Add (rr);
			using (var gm = new GitMonitor (monitor))
				tp.Push (gm, list);
			switch (rr.GetStatus ()) {
			case RemoteRefUpdate.Status.UP_TO_DATE: monitor.ReportSuccess (GettextCatalog.GetString ("Remote branch is up to date.")); break;
			case RemoteRefUpdate.Status.REJECTED_NODELETE: monitor.ReportError (GettextCatalog.GetString ("The server is configured to deny deletion of the branch"), null); break;
			case RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD: monitor.ReportError (GettextCatalog.GetString ("The update is a non-fast-forward update. Merge the remote changes before pushing again."), null); break;
			case RemoteRefUpdate.Status.OK:
				monitor.ReportSuccess (GettextCatalog.GetString ("Push operation successfully completed."));
				// Update the remote branch
				ObjectId headId = rr.GetNewObjectId ();
				RefUpdate updateRef = RootRepository.UpdateRef (Constants.R_REMOTES + remote + "/" + remoteBranch);
				updateRef.SetNewObjectId(headId);
				updateRef.Update();
				break;
			default:
				string msg = rr.GetMessage ();
				msg = !string.IsNullOrEmpty (msg) ? msg : GettextCatalog.GetString ("Push operation failed");
				monitor.ReportError (msg, null);
				break;
			}
		}
 public override void ReportSuccess(string message)
 {
     base.ReportSuccess(message);
     statusMonitor.ReportSuccess(message);
 }
Exemplo n.º 26
0
		public void Push (IProgressMonitor monitor, string remote, string remoteBranch)
		{
			bool success = true;

			var branch = RootRepository.Head;
			if (branch.TrackedBranch == null) {
				RootRepository.Branches.Update (branch, b => b.TrackedBranch = "refs/remotes/" + remote + "/" + remoteBranch);
			}

			RetryUntilSuccess (monitor, () =>
				RootRepository.Network.Push (RootRepository.Network.Remotes [remote], "refs/heads/" + remoteBranch, new PushOptions {
					OnPushStatusError = pushStatusErrors => success = false,
					CredentialsProvider = GitCredentials.TryGet
				})
			);

			if (!success)
				return;

			monitor.ReportSuccess (GettextCatalog.GetString ("Push operation successfully completed."));
		}
Exemplo n.º 27
0
		protected override void OnRevertToRevision (FilePath localPath, Revision revision, IProgressMonitor monitor)
		{
			NGit.Repository repo = GetRepository (localPath);
			NGit.Api.Git git = new NGit.Api.Git (repo);
			GitRevision gitRev = (GitRevision)revision;

			// Rewrite file data from selected revision.
			foreach (var path in GetFilesInPaths (new FilePath[] { localPath })) {
				MonoDevelop.Projects.Text.TextFile.WriteFile (path, GetCommitTextContent (gitRev.Commit, path), null);
			}

			monitor.ReportSuccess (GettextCatalog.GetString ("Successfully reverted {0} to revision {1}", localPath, gitRev));
		}
Exemplo n.º 28
0
		static bool UpdateCompleted (IProgressMonitor monitor, AggregatedOperationMonitor aggOp,
		                             ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result,
		                             bool runMultipleFiles)
		{
			monitor.EndTask ();
			if (aggOp != null)
				aggOp.Dispose ();
			
			if (monitor.IsCancelRequested) {
				monitor.ReportError (GettextCatalog.GetString ("Cancelled"), null);
				monitor.Dispose ();
				return false;
			}
			
			string genFileName;
			try {
				
				bool broken = false;
				
				if (result.UnhandledException != null) {
					broken = true;
					string msg = GettextCatalog.GetString ("The '{0}' code generator crashed", file.Generator);
					result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message));
					monitor.ReportError (msg, result.UnhandledException);
					LoggingService.LogError (msg, result.UnhandledException);
				}

				genFileName = result.GeneratedFilePath.IsNullOrEmpty?
					null : result.GeneratedFilePath.ToRelative (file.FilePath.ParentDirectory);
				
				if (!string.IsNullOrEmpty (genFileName)) {
					bool validName = genFileName.IndexOfAny (new [] { '/', '\\' }) < 0
						&& FileService.IsValidFileName (genFileName);
					
					if (!broken && !validName) {
						broken = true;
						string msg = GettextCatalog.GetString ("The '{0}' code generator output invalid filename '{1}'",
						                                       file.Generator, result.GeneratedFilePath);
						result.Errors.Add (new CompilerError (file.Name, 0, 0, "", msg));
						monitor.ReportError (msg, null);
					}
				}
				
				if (result.Errors.Count > 0) {
					DispatchService.GuiDispatch (delegate {
						foreach (CompilerError err in result.Errors)
							TaskService.Errors.Add (new Task (file.FilePath, err.ErrorText, err.Column, err.Line,
								err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error,
								TaskPriority.Normal, file.Project.ParentSolution, file));
					});
				}
				
				if (broken)
					return true;

				if (!runMultipleFiles) {
					if (result.Success)
						monitor.ReportSuccess ("Generated file successfully.");
					else if (result.SuccessWithWarnings)
						monitor.ReportSuccess ("Warnings in file generation.");
					else
						monitor.ReportError ("Errors in file generation.", null);
				}
			} finally {
				if (!runMultipleFiles)
					monitor.Dispose ();
			}

			if (result.GeneratedFilePath.IsNullOrEmpty || !File.Exists (result.GeneratedFilePath))
				return true;

			// broadcast a change event so text editors etc reload the file
			FileService.NotifyFileChanged (result.GeneratedFilePath);

			// add file to project, update file properties, etc
			Gtk.Application.Invoke (delegate {
				bool projectChanged = false;
				if (genFile == null) {
					genFile = file.Project.AddFile (result.GeneratedFilePath, result.OverrideBuildAction);
					projectChanged = true;
				} else if (result.GeneratedFilePath != genFile.FilePath) {
					genFile.Name = result.GeneratedFilePath;
					projectChanged = true;
				}

				if (file.LastGenOutput != genFileName) {
					file.LastGenOutput = genFileName;
					projectChanged = true;
				}

				if (genFile.DependsOn != file.FilePath.FileName) {
					genFile.DependsOn = file.FilePath.FileName;
					projectChanged = true;
				}

				if (projectChanged)
					IdeApp.ProjectOperations.Save (file.Project);
			});

			return true;
		}
Exemplo n.º 29
0
        BuildResult DoOneStepBuild()
        {
            var br = new BuildResult();

            bool filesModified = false;

            // Enum files & build resource files
            foreach (var pf in Project.Files)
            {
                if (pf.BuildAction != BuildAction.Compile || pf.Subtype == Subtype.Directory)
                {
                    continue;
                }

                DateTime dt;
                if (Project.LastModificationTimes.TryGetValue(pf, out dt))
                {
                    filesModified |= File.GetLastWriteTime(pf.FilePath) != dt;
                }
                else
                {
                    filesModified = true;
                }
                Project.LastModificationTimes[pf] = File.GetLastWriteTime(pf.FilePath);

                if (pf.FilePath.Extension.EndsWith(".rc", StringComparison.OrdinalIgnoreCase))
                {
                    if (!CompileResourceScript(br, pf))
                    {
                        return(br);
                    }
                }
                else
                {
                    BuiltObjects.Add(MakeRelativeToPrjBase(pf.FilePath));
                }
            }

            // Build argument string
            var target = Project.GetOutputFileName(BuildConfig.Selector);

            if (!filesModified && Project.EnableIncrementalLinking &&
                File.Exists(target))
            {
                monitor.ReportSuccess("Build successful! - No new linkage needed");
                monitor.Step(1);
                return(br);
            }

            var rawArgumentString = new StringBuilder();

            if (!string.IsNullOrEmpty(AdditionalCompilerAttributes))
            {
                rawArgumentString.Append(AdditionalCompilerAttributes.Trim()).Append(' ');
            }
            rawArgumentString.Append(BuildArguments.OneStepBuildArguments.Trim());
            if (!string.IsNullOrEmpty(BuildConfig.ExtraCompilerArguments))
            {
                rawArgumentString.Append(' ').Append(BuildConfig.ExtraCompilerArguments.Trim());
            }
            if (!string.IsNullOrEmpty(BuildConfig.ExtraLinkerArguments))
            {
                rawArgumentString.Append(' ').Append(PrefixedExtraLinkerFlags);
            }

            var argumentString = FillInMacros(rawArgumentString.ToString(),
                                              new OneStepBuildArgumentMacroProvider
            {
                ObjectsStringPattern  = Compiler.ArgumentPatterns.ObjectFileLinkPattern,
                IncludesStringPattern = Compiler.ArgumentPatterns.IncludePathPattern,

                SourceFiles = BuiltObjects,
                Includes    = FillCommonMacros(Project.IncludePaths),
                Libraries   = GetLibraries(BuildConfig, Compiler),

                RelativeTargetDirectory = BuildConfig.OutputDirectory,
                ObjectsDirectory        = ObjectDirectory,
                TargetFile = target,
            }, commonMacros);


            // Execute the compiler
            var stdOut   = "";
            var stdError = "";

            var linkerExecutable = Compiler.SourceCompilerCommand;

            if (!Path.IsPathRooted(linkerExecutable) && !string.IsNullOrEmpty(Compiler.BinPath))
            {
                linkerExecutable = Path.Combine(Compiler.BinPath, LinkTargetCfg.Linker);

                if (!File.Exists(linkerExecutable))
                {
                    linkerExecutable = LinkTargetCfg.Linker;
                }
            }

            monitor.Log.WriteLine("Current dictionary: " + Project.BaseDirectory);

            string cmdLineFile;

            HandleOverLongArgumentStrings(Compiler, true, ref argumentString, out cmdLineFile);

            int exitCode = ExecuteCommand(linkerExecutable, argumentString, Project.BaseDirectory, monitor,
                                          out stdError,
                                          out stdOut);

            ErrorExtracting.HandleCompilerOutput(Project, br, stdError);
            ErrorExtracting.HandleCompilerOutput(Project, br, stdOut);
            ErrorExtracting.HandleOptLinkOutput(Project, br, stdOut);
            ErrorExtracting.HandleReturnCode(monitor, br, exitCode);

            if (cmdLineFile != null)
            {
                File.Delete(cmdLineFile);
            }

            return(br);
        }
        static void UpdateCompleted(IProgressMonitor monitor, AggregatedOperationMonitor aggOp,
                                    ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result)
        {
            monitor.EndTask();
            aggOp.Dispose();

            if (monitor.IsCancelRequested)
            {
                monitor.ReportError(GettextCatalog.GetString("Cancelled"), null);
                monitor.Dispose();
                return;
            }

            string genFileName;

            try
            {
                bool broken = false;

                if (result.UnhandledException != null)
                {
                    broken = true;
                    string msg = GettextCatalog.GetString("The '{0}' code generator crashed", file.Generator);
                    result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message));
                    monitor.ReportError(msg, result.UnhandledException);
                    LoggingService.LogError(msg, result.UnhandledException);
                }

                genFileName = result.GeneratedFilePath.IsNullOrEmpty?
                              null : result.GeneratedFilePath.ToRelative(file.FilePath.ParentDirectory);

                bool validName = !string.IsNullOrEmpty(genFileName) &&
                                 genFileName.IndexOfAny(new char[] { '/', '\\' }) < 0 &&
                                 FileService.IsValidFileName(genFileName);

                if (!broken && !validName)
                {
                    broken = true;
                    string msg = GettextCatalog.GetString("The '{0}' code generator output invalid filename '{1}'",
                                                          file.Generator, result.GeneratedFilePath);
                    result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg));
                    monitor.ReportError(msg, null);
                }

                if (result.Errors.Count > 0)
                {
                    foreach (CompilerError err in result.Errors)
                    {
                        TaskService.Errors.Add(new Task(file.FilePath, err.ErrorText, err.Column, err.Line,
                                                        err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error,
                                                        TaskPriority.Normal, file.Project.ParentSolution, file));
                    }
                }

                if (broken)
                {
                    return;
                }

                if (result.Success)
                {
                    monitor.ReportSuccess("Generated file successfully.");
                }
                else
                {
                    monitor.ReportError("Failed to generate file. See error pad for details.", null);
                }
            }
            finally
            {
                monitor.Dispose();
            }

            if (!result.GeneratedFilePath.IsNullOrEmpty && File.Exists(result.GeneratedFilePath))
            {
                Gtk.Application.Invoke(delegate
                {
                    if (genFile == null)
                    {
                        genFile = file.Project.AddFile(result.GeneratedFilePath);
                    }
                    else if (result.GeneratedFilePath != genFile.FilePath)
                    {
                        genFile.Name = result.GeneratedFilePath;
                    }
                    file.LastGenOutput = genFileName;
                    genFile.DependsOn  = file.FilePath.FileName;

                    IdeApp.ProjectOperations.Save(file.Project);
                });
            }
        }
Exemplo n.º 31
0
		void RestorePackages (IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage)
		{
			var msbuildTargetsMonitor = new MSBuildTargetsRestoredMonitor (packageManagementEvents);
			using (msbuildTargetsMonitor) {
				var action = new RestorePackagesAction (solution, packageManagementEvents);
				if (project != null) {
					action.Project = project;
				}
				action.Execute ();
			}

			RefreshProjectReferences (msbuildTargetsMonitor.AnyMSBuildTargetsRestored);
			ForceCreationOfSharedRepositoriesConfigFile ();

			progressMonitor.ReportSuccess (progressMessage.Success);
			packageManagementEvents.OnPackagesRestored ();
		}
        // Note: This method may throw TimeoutException or AppleScriptException
        public void UpdateProject(IProgressMonitor monitor, List <XcodeSyncedItem> allItems, XcodeProject emptyProject)
        {
            items = allItems;

            monitor.BeginTask(GettextCatalog.GetString("Updating Xcode project for {0}...", name), items.Count);

            var ctx = new XcodeSyncContext(projectDir, syncTimeCache);

            var  toRemove      = new HashSet <string> (itemMap.Keys);
            var  toClose       = new HashSet <string> ();
            var  syncList      = new List <XcodeSyncedItem> ();
            bool updateProject = false;

            monitor.Log.WriteLine("Calculating sync list...");
            foreach (var item in items)
            {
                bool needsSync = item.NeedsSyncOut(monitor, ctx);
                if (needsSync)
                {
                    syncList.Add(item);
                }

                var files = item.GetTargetRelativeFileNames();
                foreach (var file in files)
                {
                    toRemove.Remove(file);

                    if (!itemMap.ContainsKey(file))
                    {
                        monitor.Log.WriteLine("   '{0}' needs to be added.", file);
                        updateProject = true;
                    }
                    else if (needsSync)
                    {
                        monitor.Log.WriteLine("   '{0}' needs to be closed & updated.", file);
                        toClose.Add(file);
                    }

                    itemMap[file] = item;
                }
            }
            updateProject = updateProject || toRemove.Any();

            bool removedOldProject = false;

            if (updateProject)
            {
                if (pendingProjectWrite == null && ProjectExists())
                {
                    monitor.Log.WriteLine("The project.pbxproj file needs to be updated, closing and removing old project.");
                    CloseProject();
                    DeleteXcproj(monitor);
                    removedOldProject = true;

                    // All items need to be re-synced...
                    syncList.Clear();
                    foreach (var item in items)
                    {
                        syncList.Add(item);

                        var files = item.GetTargetRelativeFileNames();
                        foreach (var file in files)
                        {
                            itemMap[file] = item;
                        }
                    }
                }
            }
            else
            {
                foreach (var f in toClose)
                {
                    CloseFile(monitor, projectDir.Combine(f));
                }
            }

            if (removedOldProject)
            {
                HackRelocateProject(monitor);
                ctx.ProjectDir = projectDir;
                syncTimeCache.Clear();
            }
            else
            {
                foreach (var f in toRemove)
                {
                    itemMap.Remove(f);
                    syncTimeCache.Remove(f);
                    var path = projectDir.Combine(f);
                    try
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                    catch
                    {
                    }
                }
            }

            foreach (var item in items)
            {
                if (updateProject)
                {
                    item.AddToProject(emptyProject, projectDir);
                }
            }

            foreach (var item in syncList)
            {
                item.SyncOut(monitor, ctx);
                monitor.Step(1);
            }

            if (updateProject)
            {
                monitor.Log.WriteLine("Queued write of '{0}'.", xcproj);
                pendingProjectWrite = emptyProject;
            }

            monitor.EndTask();
            monitor.ReportSuccess(GettextCatalog.GetString("Xcode project updated."));
        }
Exemplo n.º 33
0
        public void UpdateProject(IProgressMonitor monitor, List <XcodeSyncedItem> allItems, XcodeProject emptyProject)
        {
            items = allItems;

            monitor.BeginTask(GettextCatalog.GetString("Updating Xcode project..."), items.Count);
            monitor.Log.WriteLine("Updating synced project with {0} items", items.Count);
            XC4Debug.Log("Updating synced project with {0} items", items.Count);

            var ctx = new XcodeSyncContext(projectDir, syncTimeCache);

            var  toRemove      = new HashSet <string> (itemMap.Keys);
            var  toClose       = new HashSet <string> ();
            var  syncList      = new List <XcodeSyncedItem> ();
            bool updateProject = false;

            foreach (var item in items)
            {
                bool needsSync = item.NeedsSyncOut(ctx);
                if (needsSync)
                {
                    syncList.Add(item);
                }

                var files = item.GetTargetRelativeFileNames();
                foreach (var f in files)
                {
                    toRemove.Remove(f);
                    if (!itemMap.ContainsKey(f))
                    {
                        updateProject = true;
                    }
                    else if (needsSync)
                    {
                        toClose.Add(f);
                    }
                    itemMap [f] = item;
                }
            }
            updateProject = updateProject || toRemove.Any();

            bool removedOldProject = false;

            if (updateProject)
            {
                if (pendingProjectWrite == null && ProjectExists())
                {
                    monitor.Log.WriteLine("Project file needs to be updated, closing and removing old project");
                    CloseProject();
                    DeleteXcproj();
                    removedOldProject = true;
                }
            }
            else
            {
                foreach (var f in toClose)
                {
                    CloseFile(projectDir.Combine(f));
                }
            }

            foreach (var f in toRemove)
            {
                itemMap.Remove(f);
                syncTimeCache.Remove(f);
                var path = projectDir.Combine(f);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }

            if (removedOldProject)
            {
                HackRelocateProject();
            }

            foreach (var item in items)
            {
                if (updateProject)
                {
                    item.AddToProject(emptyProject, projectDir);
                }
            }

            foreach (var item in syncList)
            {
                monitor.Log.WriteLine("Syncing item {0}", item.GetTargetRelativeFileNames()[0]);
                item.SyncOut(ctx);
                monitor.Step(1);
            }

            if (updateProject)
            {
                monitor.Log.WriteLine("Queuing Xcode project {0} to write when opened", projectDir);
                pendingProjectWrite = emptyProject;
            }

            monitor.EndTask();
            monitor.ReportSuccess(GettextCatalog.GetString("Xcode project updated."));
        }
Exemplo n.º 34
0
        /// <summary>
        /// Compiles a D project.
        /// </summary>
        public static BuildResult Compile(
            DProject Project,
            ProjectFileCollection FilesToCompile,
            DProjectConfiguration BuildConfig,
            IProgressMonitor monitor)
        {
            var relObjDir = "objs";
            var objDir    = Path.Combine(Project.BaseDirectory, relObjDir);

            if (!Directory.Exists(objDir))
            {
                Directory.CreateDirectory(objDir);
            }

            // List of created object files
            var  BuiltObjects      = new List <string>();
            var  compilerResults   = new CompilerResults(new TempFileCollection());
            var  buildResult       = new BuildResult(compilerResults, "");
            bool succesfullyBuilt  = true;
            bool modificationsDone = false;

            var Compiler  = Project.Compiler;
            var Commands  = Compiler.GetTargetConfiguration(Project.CompileTarget);
            var Arguments = Commands.GetArguments(BuildConfig.DebugMode);

            /// The target file to which all objects will be linked to
            var LinkTarget = BuildConfig.OutputDirectory.Combine(BuildConfig.CompiledOutputName);

            monitor.BeginTask("Build Project", FilesToCompile.Count + 1);

            var SourceIncludePaths = new List <string>(Compiler.GlobalParseCache.DirectoryPaths);

            SourceIncludePaths.AddRange(Project.LocalIncludeCache.DirectoryPaths);

            #region Compile sources to objects
            foreach (var f in FilesToCompile)
            {
                if (monitor.IsCancelRequested)
                {
                    return(buildResult);
                }

                // If not compilable, skip it
                if (f.BuildAction != BuildAction.Compile || !File.Exists(f.FilePath))
                {
                    continue;
                }

                // a.Check if source file was modified and if object file still exists
                if (Project.LastModificationTimes.ContainsKey(f) &&
                    Project.LastModificationTimes[f] == File.GetLastWriteTime(f.FilePath) &&
                    File.Exists(f.LastGenOutput))
                {
                    // File wasn't edited since last build
                    // but add the built object to the objs array
                    BuiltObjects.Add(f.LastGenOutput);
                    monitor.Step(1);
                    continue;
                }
                else
                {
                    modificationsDone = true;
                }

                #region Resource file
                if (f.Name.EndsWith(".rc", StringComparison.OrdinalIgnoreCase))
                {
                    var res = Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath)) + ".res";

                    if (File.Exists(res))
                    {
                        File.Delete(res);
                    }

                    // Build argument string
                    var resCmpArgs = FillInMacros(Win32ResourceCompiler.Instance.Arguments,
                                                  new Win32ResourceCompiler.ArgProvider {
                        RcFile  = f.FilePath.ToString(),
                        ResFile = res
                    });

                    // Execute compiler
                    string output;
                    int    _exitCode = ExecuteCommand(Win32ResourceCompiler.Instance.Executable,
                                                      resCmpArgs,
                                                      Project.BaseDirectory,
                                                      monitor,
                                                      out output);

                    // Error analysis
                    if (!string.IsNullOrEmpty(output))
                    {
                        compilerResults.Errors.Add(new CompilerError {
                            FileName = f.FilePath, ErrorText = output
                        });
                    }
                    CheckReturnCode(_exitCode, compilerResults);

                    monitor.Step(1);

                    if (_exitCode != 0)
                    {
                        buildResult.FailedBuildCount++;
                        succesfullyBuilt = false;
                        break;
                    }
                    else
                    {
                        f.LastGenOutput = res;
                        buildResult.BuildCount++;
                        Project.LastModificationTimes[f] = File.GetLastWriteTime(f.FilePath);

                        // Especially when compiling large projects, do only add the relative part of the r file due to command shortness
                        if (res.StartsWith(Project.BaseDirectory))
                        {
                            BuiltObjects.Add(res.Substring(Project.BaseDirectory.ToString().Length).TrimStart(Path.DirectorySeparatorChar));
                        }
                        else
                        {
                            BuiltObjects.Add(res);
                        }
                    }

                    continue;
                }
                #endregion

                // Create object file path
                var obj = Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath)) + ObjectExtension;

                if (File.Exists(obj))
                {
                    File.Delete(obj);
                }

                // Prevent duplicates e.g. when having the samely-named source files in different sub-packages
                int i = 2;
                while (File.Exists(obj))
                {
                    // Simply add a number between the obj name and its extension
                    obj = Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath)) + i + ObjectExtension;
                    i++;
                }

                // Create argument string for source file compilation.
                var dmdArgs = FillInMacros(Arguments.CompilerArguments + " " + BuildConfig.ExtraCompilerArguments, new DCompilerMacroProvider
                {
                    IncludePathConcatPattern = Commands.IncludePathPattern,
                    SourceFile = f.FilePath,
                    ObjectFile = obj,
                    Includes   = SourceIncludePaths,
                });

                // b.Execute compiler
                string dmdOutput;
                int    exitCode = ExecuteCommand(Commands.Compiler, dmdArgs, Project.BaseDirectory, monitor, out dmdOutput);

                ParseCompilerOutput(dmdOutput, compilerResults);
                CheckReturnCode(exitCode, compilerResults);

                monitor.Step(1);

                if (exitCode != 0)
                {
                    buildResult.FailedBuildCount++;
                    succesfullyBuilt = false;
                    break;
                }
                else
                {
                    f.LastGenOutput = obj;
                    buildResult.BuildCount++;
                    Project.LastModificationTimes[f] = File.GetLastWriteTime(f.FilePath);

                    // Especially when compiling large projects, do only add the relative part of the obj file due to command shortness
                    if (obj.StartsWith(Project.BaseDirectory))
                    {
                        BuiltObjects.Add(obj.Substring(Project.BaseDirectory.ToString().Length).TrimStart(Path.DirectorySeparatorChar));
                    }
                    else
                    {
                        BuiltObjects.Add(obj);
                    }
                }
            }
            #endregion

            #region Link files
            if (succesfullyBuilt)
            {
                // a.
                if ((!modificationsDone) && lastLinkerActionSuccessfull)
                {
                    // Only return if build target is still existing
                    if (File.Exists(LinkTarget))
                    {
                        monitor.Step(1);
                        return(new BuildResult(compilerResults, ""));
                    }
                }

                // b.Build linker argument string

                // Build argument preparation

                /*
                 * var libPaths=new List<string>(Compiler.DefaultLibPaths);
                 * libPaths.AddRange(Project.LibraryPaths);
                 */
                var libs = new List <string>(Compiler.DefaultLibraries);
                libs.AddRange(Project.ExtraLibraries);

                var linkArgs = FillInMacros(Arguments.LinkerArguments + " " + BuildConfig.ExtraLinkerArguments,
                                            new DLinkerMacroProvider {
                    ObjectsStringPattern = Commands.ObjectFileLinkPattern,
                    Objects    = BuiltObjects.ToArray(),
                    TargetFile = LinkTarget,
                    RelativeTargetDirectory = BuildConfig.OutputDirectory.ToRelative(Project.BaseDirectory),

                    //LibraryPaths=libPaths,
                    Libraries = libs
                });
                var linkerOutput = "";
                int exitCode     = ExecuteCommand(Commands.Linker, linkArgs, Project.BaseDirectory, monitor, out linkerOutput);

                compilerResults.NativeCompilerReturnValue = exitCode;

                CheckReturnCode(exitCode, compilerResults);

                lastLinkerActionSuccessfull = (exitCode == 0);
                if (lastLinkerActionSuccessfull)
                {
                    monitor.ReportSuccess("Build successful!");
                    monitor.Step(1);
                }
            }
            #endregion

            return(new BuildResult(compilerResults, ""));
        }
Exemplo n.º 35
0
		static void WriteSummaryResults (IProgressMonitor monitor, int succeeded, int warnings, int errors)
		{
			monitor.Log.WriteLine ();

			int total = succeeded + warnings + errors;

			//this might not be correct for languages where pluralization affects the other arguments
			//but gettext doesn't really have an answer for sentences with multiple plurals
			monitor.Log.WriteLine (
				GettextCatalog.GetPluralString (
					"{0} file processed total. {1} generated successfully, {2} with warnings, {3} with errors",
					"{0} files processed total. {1} generated successfully, {2} with warnings, {3} with errors",
					total,
					total, succeeded, warnings, errors)
			);
			//ends the root task
			monitor.EndTask ();

			if (errors > 0)
				monitor.ReportError (GettextCatalog.GetString ("Errors in file generation."), null);
			else if (warnings > 0)
				monitor.ReportSuccess (GettextCatalog.GetString ("Warnings in file generation."));
			else
				monitor.ReportSuccess (GettextCatalog.GetString ("Generated files successfully."));

			monitor.Dispose ();
		}
		public bool Deploy ( DeployContext ctx, Solution solution, string defaultConf, string targetDir, bool generateFiles, IProgressMonitor monitor  )
		{
			if (generateFiles) {
				if ( !GenerateFiles ( ctx, solution, defaultConf, monitor ) ) 
					return false;
			}
			
			monitor.BeginTask ( GettextCatalog.GetString( "Deploying Solution to Tarball" ) , 3 );
			try
			{
				string baseDir = Path.GetDirectoryName ( solution.FileName);
	
				ProcessWrapper ag_process = Runtime.ProcessService.StartProcess ( "sh", 
						generateAutotools ? "autogen.sh" : "configure",
						baseDir, 
						monitor.Log, 
						monitor.Log, 
						null );
				ag_process.WaitForOutput ();
				
				if ( ag_process.ExitCode > 0 )
					throw new Exception ( GettextCatalog.GetString ("An unspecified error occurred while running '{0}'", generateAutotools ? "autogen.sh" : "configure") );
				
				monitor.Step ( 1 );

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

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

				if ( process.ExitCode > 0 )
					throw new Exception ( GettextCatalog.GetString ("An unspecified error occurred while running '{0}'", "make dist") );

				monitor.Step ( 1 );

				// FIXME: hackish way to get the created tarball's filename
				string output = sw.ToString();
				int targz = output.LastIndexOf  ( "tar.gz" );
				int begin = output.LastIndexOf ( '>', targz );

				string filename = output.Substring ( begin + 1, (targz - begin) + 5 ).Trim ();
				
				FileService.CopyFile (Path.Combine (baseDir, filename), Path.Combine (targetDir, filename));
				monitor.Step ( 1 );
			}
			catch ( Exception e )
			{
				monitor.ReportError ( GettextCatalog.GetString ("Solution could not be deployed: "), e );
				return false;
			}
			finally 
			{
				monitor.EndTask ();
			}
			monitor.ReportSuccess (GettextCatalog.GetString ("Solution was successfully deployed."));
			return true;
		}
Exemplo n.º 37
0
        protected override void DoClean(IProgressMonitor monitor, ConfigurationSelector configuration)
        {
            var cfg = GetConfiguration (configuration) as DProjectConfiguration;

            // delete obj/res files
            monitor.BeginTask ("Delete intermediate files", Files.Count);
            foreach (var f in Files) {
                try {
                    if (File.Exists (f.LastGenOutput))
                        File.Delete (f.LastGenOutput);
                } catch (Exception ex) {
                    monitor.ReportError ("Error while removing " + f, ex);
                } finally {
                    f.LastGenOutput = string.Empty;
                    monitor.Step (1);
                }
            }
            monitor.EndTask ();

            // delete target file
            monitor.BeginTask ("Delete output file", 1);

            if (File.Exists (cfg.CompiledOutputName))
                File.Delete (cfg.CompiledOutputName);

            monitor.EndTask ();

            monitor.ReportSuccess ("Cleanup successful!");
        }
		public bool GenerateFiles (DeployContext ctx, Solution solution, string defaultConf, IProgressMonitor monitor )
		{
			string filesString = generateAutotools ? "Autotools files" : "Makefiles";
			monitor.BeginTask ( GettextCatalog.GetString ("Generating {0} for Solution {1}", filesString, solution.Name), 1 );

			try
			{
				solution_dir = Path.GetDirectoryName(solution.FileName);

				string[] configs = new string [ solution.Configurations.Count ];
				for (int ii=0; ii < configs.Length; ii++ )
					configs [ii] = solution.Configurations[ii].Id;
					
				MakefileType mt = generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile;
				
				context = new AutotoolsContext ( ctx, solution_dir, configs, mt );
				context.TargetSolution = solution;
				context.Switches = switchs;
				
				IMakefileHandler handler = AutotoolsContext.GetMakefileHandler (solution.RootFolder, mt);
				if (handler == null)
					throw new Exception (string.Format (
						"{0} does not currently support generating {1} for one (or more) child projects.",
						filesString, BrandingService.ApplicationName
					));

				solution_name = solution.Name;
				solution_version = AutotoolsContext.EscapeStringForAutoconf (solution.Version, true);
				if (string.IsNullOrEmpty (solution_version))
					solution_version = "0.1";

				Makefile makefile = handler.Deploy ( context, solution.RootFolder, monitor );
				string path = Path.Combine (solution_dir, "Makefile");
				if (generateAutotools) {
					context.AddAutoconfFile (path);
					CreateAutoGenDotSH (context, monitor);
					CreateConfigureDotAC (solution, defaultConf, monitor, context);
					CreateMacros ();
				} else {
					CreateConfigureScript (solution, defaultConf, context, monitor);

					monitor.Log.WriteLine ( GettextCatalog.GetString ("Creating rules.make"));
					string rules_make_path = Path.Combine (solution_dir, "rules.make");
					File.Copy (Path.Combine (context.TemplateDir, "rules.make"), rules_make_path, true);
					context.AddGeneratedFile (rules_make_path);
				}

				CreateMakefileInclude ( context, monitor );
				AddTopLevelMakefileVars ( makefile, monitor );

				if (generateAutotools)
					path = path + ".am";
				StreamWriter writer = new StreamWriter (path);
				makefile.Write ( writer );
				writer.Close ();

				context.AddGeneratedFile (path);

				monitor.ReportSuccess ( GettextCatalog.GetString ("{0} were successfully generated.", filesString ) );
				monitor.Step (1);
			}
			catch ( Exception e )
			{
				monitor.ReportError ( GettextCatalog.GetString ("{0} could not be generated: ", filesString ), e );
				LoggingService.LogError (GettextCatalog.GetString ("{0} could not be generated: ", filesString ), e);
				DeleteGeneratedFiles ( context );
				return false;
			}
			finally
			{
				monitor.EndTask ();
			}
			return true;
		}
Exemplo n.º 39
0
		public void Push (IProgressMonitor monitor, string remote, string remoteBranch)
		{
			string remoteRef = "refs/heads/" + remoteBranch;
			IEnumerable<PushResult> res;

			var push = new NGit.Api.Git (RootRepository).Push ();

			// We only have one pushed branch.
			push.SetRemote (remote).SetRefSpecs (new RefSpec (remoteRef));
			using (var gm = new GitMonitor (monitor)) {
				push.SetProgressMonitor (gm);
				res = push.Call ();
			}

			foreach (var pr in res) {
				var remoteUpdate = pr.GetRemoteUpdate (remoteRef);

				switch (remoteUpdate.GetStatus ()) {
					case RemoteRefUpdate.Status.UP_TO_DATE: monitor.ReportSuccess (GettextCatalog.GetString ("Remote branch is up to date.")); break;
					case RemoteRefUpdate.Status.REJECTED_NODELETE: monitor.ReportError (GettextCatalog.GetString ("The server is configured to deny deletion of the branch"), null); break;
					case RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD: monitor.ReportError (GettextCatalog.GetString ("The update is a non-fast-forward update. Merge the remote changes before pushing again."), null); break;
					case RemoteRefUpdate.Status.OK:
						monitor.ReportSuccess (GettextCatalog.GetString ("Push operation successfully completed."));
						// Update the remote branch
						ObjectId headId = remoteUpdate.GetNewObjectId ();
						RefUpdate updateRef = RootRepository.UpdateRef (Constants.R_REMOTES + remote + "/" + remoteBranch);
						updateRef.SetNewObjectId(headId);
						updateRef.Update();
						break;
					default:
						string msg = remoteUpdate.GetMessage ();
						msg = !string.IsNullOrEmpty (msg) ? msg : GettextCatalog.GetString ("Push operation failed");
						monitor.ReportError (msg, null);
						break;
				}
			}
		}
Exemplo n.º 40
0
		void CheckForPackageUpdates (
			IProgressMonitor progressMonitor,
			ProgressMonitorStatusMessage progressMessage,
			PackageUpdatesEventMonitor eventMonitor)
		{
			updatedPackagesInSolution.CheckForUpdates ();
			if (updatedPackagesInSolution.AnyUpdates ()) {
				progressMonitor.ReportSuccess (GettextCatalog.GetString ("Package updates are available."));
			} else if (eventMonitor.WarningReported) {
				progressMonitor.ReportWarning (progressMessage.Warning);
			} else {
				progressMonitor.ReportSuccess (progressMessage.Success);
			}
		}
Exemplo n.º 41
0
        /// <summary>
        /// Compiles a D project.
        /// </summary>
        public static BuildResult Compile(
            DProject Project,
            ProjectFileCollection FilesToCompile,
            DProjectConfiguration BuildConfig,
            IProgressMonitor monitor)
        {
            var relObjDir = "objs";
            var objDir = Path.Combine(Project.BaseDirectory, relObjDir);

            if(!Directory.Exists(objDir))
                Directory.CreateDirectory(objDir);

            // List of created object files
            var BuiltObjects = new List<string>();
            var compilerResults = new CompilerResults(new TempFileCollection());
            var buildResult = new BuildResult(compilerResults, "");
            bool succesfullyBuilt = true;
            bool modificationsDone = false;

            var Compiler = Project.Compiler;
            var Commands = Compiler.GetTargetConfiguration(Project.CompileTarget);
            var Arguments= Commands.GetArguments(BuildConfig.DebugMode);

            /// The target file to which all objects will be linked to
            var LinkTarget = BuildConfig.OutputDirectory.Combine(BuildConfig.CompiledOutputName);

            monitor.BeginTask("Build Project", FilesToCompile.Count + 1);

            var SourceIncludePaths=new List<string>(Compiler.GlobalParseCache.DirectoryPaths);
                SourceIncludePaths.AddRange(Project.LocalIncludeCache.DirectoryPaths);

            #region Compile sources to objects
            foreach (var f in FilesToCompile)
            {
                if (monitor.IsCancelRequested)
                    return buildResult;

                // If not compilable, skip it
                if (f.BuildAction != BuildAction.Compile || !File.Exists(f.FilePath))
                    continue;

                // a.Check if source file was modified and if object file still exists
                if (Project.LastModificationTimes.ContainsKey(f) &&
                    Project.LastModificationTimes[f] == File.GetLastWriteTime(f.FilePath) &&
                    File.Exists(f.LastGenOutput))
                {
                    // File wasn't edited since last build
                    // but add the built object to the objs array
                    BuiltObjects.Add(f.LastGenOutput);
                    monitor.Step(1);
                    continue;
                }
                else
                    modificationsDone=true;

                #region Resource file
                if(f.Name.EndsWith(".rc",StringComparison.OrdinalIgnoreCase))
                {
                    var res = Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath))+ ".res";

                    if(File.Exists(res))
                        File.Delete(res);

                    // Build argument string
                    var resCmpArgs = FillInMacros(Win32ResourceCompiler.Instance.Arguments,
                        new Win32ResourceCompiler.ArgProvider{
                            RcFile=f.FilePath.ToString(),
                            ResFile=res
                        });

                    // Execute compiler
                    string output;
                    int _exitCode = ExecuteCommand(Win32ResourceCompiler.Instance.Executable,
                        resCmpArgs,
                        Project.BaseDirectory,
                        monitor,
                        out output);

                    // Error analysis
                    if(!string.IsNullOrEmpty(output))
                        compilerResults.Errors.Add(new CompilerError{ FileName=f.FilePath, ErrorText=output});
                    CheckReturnCode(_exitCode, compilerResults);

                    monitor.Step(1);

                    if (_exitCode != 0)
                    {
                        buildResult.FailedBuildCount++;
                        succesfullyBuilt = false;
                        break;
                    }
                    else
                    {
                        f.LastGenOutput = res;
                        buildResult.BuildCount++;
                        Project.LastModificationTimes[f] = File.GetLastWriteTime(f.FilePath);

                        // Especially when compiling large projects, do only add the relative part of the r file due to command shortness
                        if (res.StartsWith(Project.BaseDirectory))
                            BuiltObjects.Add(res.Substring(Project.BaseDirectory.ToString().Length).TrimStart(Path.DirectorySeparatorChar));
                        else
                            BuiltObjects.Add(res);
                    }

                    continue;
                }
                #endregion

                // Create object file path
                var obj = Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath)) + ObjectExtension;

                if (File.Exists(obj))
                    File.Delete(obj);

                // Prevent duplicates e.g. when having the samely-named source files in different sub-packages
                int i=2;
                while(File.Exists(obj))
                {
                    // Simply add a number between the obj name and its extension
                    obj= Path.Combine(objDir, Path.GetFileNameWithoutExtension(f.FilePath))+i + ObjectExtension;
                    i++;
                }

                // Create argument string for source file compilation.
                var dmdArgs = FillInMacros(Arguments.CompilerArguments + " " + BuildConfig.ExtraCompilerArguments,  new DCompilerMacroProvider
                {
                    IncludePathConcatPattern=Commands.IncludePathPattern,
                    SourceFile = f.FilePath,
                    ObjectFile = obj,
                    Includes=SourceIncludePaths,
                });

                // b.Execute compiler
                string dmdOutput;
                int exitCode = ExecuteCommand(Commands.Compiler, dmdArgs, Project.BaseDirectory, monitor, out dmdOutput);

                ParseCompilerOutput(dmdOutput, compilerResults);
                CheckReturnCode(exitCode, compilerResults);

                monitor.Step(1);

                if (exitCode != 0)
                {
                    buildResult.FailedBuildCount++;
                    succesfullyBuilt = false;
                    break;
                }
                else
                {
                    f.LastGenOutput = obj;
                    buildResult.BuildCount++;
                    Project.LastModificationTimes[f] = File.GetLastWriteTime(f.FilePath);

                    // Especially when compiling large projects, do only add the relative part of the obj file due to command shortness
                    if (obj.StartsWith(Project.BaseDirectory))
                        BuiltObjects.Add(obj.Substring(Project.BaseDirectory.ToString().Length).TrimStart(Path.DirectorySeparatorChar));
                    else
                        BuiltObjects.Add(obj);
                }
            }
            #endregion

            #region Link files
            if (succesfullyBuilt)
            {
                // a.
                if ((!modificationsDone) && lastLinkerActionSuccessfull)
                {
                    // Only return if build target is still existing
                    if (File.Exists(LinkTarget))
                    {
                        monitor.Step(1);
                        return new BuildResult(compilerResults, "");
                    }
                }

                // b.Build linker argument string

                // Build argument preparation
                /*
                var libPaths=new List<string>(Compiler.DefaultLibPaths);
                libPaths.AddRange(Project.LibraryPaths);
                */
                var libs=new List<string>(Compiler.DefaultLibraries);
                libs.AddRange(Project.ExtraLibraries);

                var linkArgs = FillInMacros(Arguments.LinkerArguments + " "+BuildConfig.ExtraLinkerArguments,
                    new DLinkerMacroProvider {
                        ObjectsStringPattern=Commands.ObjectFileLinkPattern,
                        Objects=BuiltObjects.ToArray(),
                        TargetFile=LinkTarget,
                        RelativeTargetDirectory=BuildConfig.OutputDirectory.ToRelative(Project.BaseDirectory),

                        //LibraryPaths=libPaths,
                        Libraries=libs
                });
                var linkerOutput = "";
                int exitCode = ExecuteCommand(Commands.Linker,linkArgs,Project.BaseDirectory,monitor,out linkerOutput);

                compilerResults.NativeCompilerReturnValue = exitCode;

                CheckReturnCode(exitCode, compilerResults);

                lastLinkerActionSuccessfull = (exitCode == 0);
                if (lastLinkerActionSuccessfull)
                {
                    monitor.ReportSuccess("Build successful!");
                    monitor.Step(1);
                }
            }
            #endregion

            return new BuildResult(compilerResults,"");
        }
Exemplo n.º 42
0
		void BuildDone (IProgressMonitor monitor, BuildResult result, IBuildTarget entry, ITimeTracker tt)
		{
			Task[] tasks = null;
			tt.Trace ("Begin reporting build result");
			try {
				if (result != null) {
					lastResult = result;
					monitor.Log.WriteLine ();
					monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));
					
					tt.Trace ("Updating task service");
					tasks = new Task [result.Errors.Count];
					for (int n=0; n<tasks.Length; n++) {
						tasks [n] = new Task (result.Errors [n]);
						tasks [n].Owner = this;
					}

					TaskService.Errors.AddRange (tasks);
					TaskService.Errors.ResetLocationList ();
					IdeApp.Workbench.ActiveLocationList = TaskService.Errors;
					
					tt.Trace ("Reporting result");
					
					string errorString = GettextCatalog.GetPluralString("{0} error", "{0} errors", result.ErrorCount, result.ErrorCount);
					string warningString = GettextCatalog.GetPluralString("{0} warning", "{0} warnings", result.WarningCount, result.WarningCount);

					if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) {
						monitor.ReportSuccess (GettextCatalog.GetString ("Build successful."));
					} else if (result.ErrorCount == 0 && result.WarningCount > 0) {
						monitor.ReportWarning(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString);
					} else if (result.ErrorCount > 0) {
						monitor.ReportError(GettextCatalog.GetString("Build: ") + errorString + ", " + warningString, null);
					} else {
						monitor.ReportError(GettextCatalog.GetString("Build failed."), null);
					}
					tt.Trace ("End build event");
					OnEndBuild (monitor, lastResult.FailedBuildCount == 0, lastResult, entry as SolutionItem);
				} else {
					tt.Trace ("End build event");
					OnEndBuild (monitor, false);
				}
				
				tt.Trace ("Showing results pad");
				
				try {
					Pad errorsPad = IdeApp.Workbench.GetPad<MonoDevelop.Ide.Gui.Pads.ErrorListPad> ();
					switch (IdeApp.Preferences.ShowErrorPadAfterBuild) {
					case BuildResultStates.Always:
						if (!errorsPad.Visible)
							errorsPad.IsOpenedAutomatically = true;
						errorsPad.Visible = true;
						errorsPad.BringToFront ();
						break;
					case BuildResultStates.Never:
						break;
					case BuildResultStates.OnErrors:
						if (TaskService.Errors.Any (task => task.Severity == TaskSeverity.Error))
							goto case BuildResultStates.Always;
						goto case BuildResultStates.Never;
					case BuildResultStates.OnErrorsOrWarnings:
						if (TaskService.Errors.Any (task => task.Severity == TaskSeverity.Error || task.Severity == TaskSeverity.Warning))
							goto case BuildResultStates.Always;
						goto case BuildResultStates.Never;
					}
				} catch {}
				
				if (tasks != null) {
					Task jumpTask = null;
					switch (IdeApp.Preferences.JumpToFirstErrorOrWarning) {
					case JumpToFirst.Error:
						jumpTask = tasks.FirstOrDefault (t => t.Severity == TaskSeverity.Error && TaskStore.IsProjectTaskFile (t));
						break;
					case JumpToFirst.ErrorOrWarning:
						jumpTask = tasks.FirstOrDefault (t => (t.Severity == TaskSeverity.Error || t.Severity == TaskSeverity.Warning) && TaskStore.IsProjectTaskFile (t));
						break;
					}
					if (jumpTask != null) {
						tt.Trace ("Jumping to first result position");
						jumpTask.JumpToPosition ();
					}
				}
				
			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
Exemplo n.º 43
0
		public Translation AddNewTranslation (string isoCode, IProgressMonitor monitor)
		{
			try {
				Translation tr = new Translation (this, isoCode);
				translations.Add (tr);
				string templateFile    = Path.Combine (this.BaseDirectory, "messages.po");
				string translationFile = GetFileName (isoCode);
				if (!File.Exists (templateFile)) 
					CreateDefaultCatalog (monitor);
				File.Copy (templateFile, translationFile);
				
				monitor.ReportSuccess (String.Format (GettextCatalog.GetString ("Language '{0}' successfully added."), isoCode));
				monitor.Step (1);
				this.Save (monitor);
				return tr;
			} catch (Exception e) {
				monitor.ReportError (String.Format ( GettextCatalog.GetString ("Language '{0}' could not be added: "), isoCode), e);
				return null;
			} finally {
				monitor.EndTask ();
			}
		}
		void ReportOutcome (
			IAsyncOperation operation,
			IProgressMonitor progressMonitor,
			ProgressMonitorStatusMessage progressMessage)
		{
			if (operation.Success) {
				progressMonitor.ReportSuccess (progressMessage.Success);
			} else {
				progressMonitor.ReportError (progressMessage.Error, null);
				progressMonitor.ShowPackageConsole ();
			}
		}
Exemplo n.º 45
0
		public override void RevertRevision (FilePath localPath, Revision revision, IProgressMonitor monitor)
		{
			var git = new NGit.Api.Git (GetRepository (localPath));
			var gitRev = (GitRevision)revision;
			var revert = git.Revert ().Include (gitRev.Commit.ToObjectId ());
			var newRevision = revert.Call ();

			var revertResult = revert.GetFailingResult ();
			if (revertResult == null) {
				monitor.ReportSuccess (GettextCatalog.GetString ("Revision {0} successfully reverted", gitRev));
			} else {
				var errorMessage = GettextCatalog.GetString ("Could not revert commit {0}", gitRev);
				var description = GettextCatalog.GetString ("The following files had merge conflicts");
				description += Environment.NewLine + string.Join (Environment.NewLine, revertResult.GetFailingPaths ().Keys);
				monitor.ReportError (errorMessage, new UserException (errorMessage, description));
			} 
		}
Exemplo n.º 46
0
        public bool GenerateFiles(DeployContext ctx, Solution solution, string defaultConf, IProgressMonitor monitor)
        {
            string filesString = generateAutotools ? "Autotools files" : "Makefiles";

            monitor.BeginTask(GettextCatalog.GetString("Generating {0} for Solution {1}", filesString, solution.Name), 1);

            try
            {
                solution_dir = Path.GetDirectoryName(solution.FileName);

                string[] configs = new string [solution.Configurations.Count];
                for (int ii = 0; ii < configs.Length; ii++)
                {
                    configs [ii] = solution.Configurations[ii].Id;
                }

                MakefileType mt = generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile;

                context = new AutotoolsContext(ctx, solution_dir, configs, mt);
                context.TargetSolution = solution;
                context.Switches       = switchs;

                IMakefileHandler handler = AutotoolsContext.GetMakefileHandler(solution.RootFolder, mt);
                if (handler == null)
                {
                    throw new Exception(GettextCatalog.GetString("MonoDevelop does not currently support generating {0} for one (or more) child projects.", filesString));
                }

                solution_name    = solution.Name;
                solution_version = AutotoolsContext.EscapeStringForAutoconf(solution.Version, true);
                if (string.IsNullOrEmpty(solution_version))
                {
                    solution_version = "0.1";
                }

                Makefile makefile = handler.Deploy(context, solution.RootFolder, monitor);
                string   path     = Path.Combine(solution_dir, "Makefile");
                if (generateAutotools)
                {
                    context.AddAutoconfFile(path);
                    CreateAutoGenDotSH(context, monitor);
                    CreateConfigureDotAC(solution, defaultConf, monitor, context);
                    CreateMacros();
                }
                else
                {
                    CreateConfigureScript(solution, defaultConf, context, monitor);

                    monitor.Log.WriteLine(GettextCatalog.GetString("Creating rules.make"));
                    string rules_make_path = Path.Combine(solution_dir, "rules.make");
                    File.Copy(Path.Combine(context.TemplateDir, "rules.make"), rules_make_path, true);
                    context.AddGeneratedFile(rules_make_path);
                }

                CreateMakefileInclude(context, monitor);
                AddTopLevelMakefileVars(makefile, monitor);

                if (generateAutotools)
                {
                    path = path + ".am";
                }
                StreamWriter writer = new StreamWriter(path);
                makefile.Write(writer);
                writer.Close();

                context.AddGeneratedFile(path);

                monitor.ReportSuccess(GettextCatalog.GetString("{0} were successfully generated.", filesString));
                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("{0} could not be generated: ", filesString), e);
                LoggingService.LogError(GettextCatalog.GetString("{0} could not be generated: ", filesString), e);
                DeleteGeneratedFiles(context);
                return(false);
            }
            finally
            {
                monitor.EndTask();
            }
            return(true);
        }
Exemplo n.º 47
0
 public override void Save(IProgressMonitor monitor)
 {
     monitor.ReportSuccess("Skip saving dub project.");
 }
Exemplo n.º 48
0
        BuildResult DoOneStepBuild()
        {
            var br = new BuildResult();

            bool filesModified = false;

            // Enum files & build resource files
            foreach (var pf in Project.Files)
            {
                if (pf.BuildAction != BuildAction.Compile || pf.Subtype == Subtype.Directory)
                {
                    continue;
                }

                DateTime dt;
                if (Project.LastModificationTimes.TryGetValue(pf, out dt))
                {
                    filesModified |= File.GetLastWriteTime(pf.FilePath) != dt;
                }
                else
                {
                    filesModified = true;
                }
                Project.LastModificationTimes[pf] = File.GetLastWriteTime(pf.FilePath);

                if (pf.FilePath.Extension.EndsWith(".rc", StringComparison.OrdinalIgnoreCase))
                {
                    if (!CompileResourceScript(br, pf))
                    {
                        return(br);
                    }
                }
                else
                {
                    BuiltObjects.Add(MakeRelativeToPrjBase(Project, pf.FilePath));
                }
            }

            // Build argument string
            var target = Project.GetOutputFileName(BuildConfig.Selector);

            if (!Project.NeedsFullRebuild && !filesModified && Project.EnableIncrementalLinking &&
                File.Exists(target))
            {
                monitor.ReportSuccess("Build successful! - No new linkage needed");
                monitor.Step(1);
                return(br);
            }

            var argumentString = BuildOneStepBuildString(Project, BuiltObjects, BuildConfig.Selector);


            // Execute the compiler
            var stdOut   = "";
            var stdError = "";
            var linkCfg  = LinkTargetCfg(BuildConfig);

            var linkerExecutable = Compiler.SourceCompilerCommand;

            if (!Path.IsPathRooted(linkerExecutable) && !string.IsNullOrEmpty(Compiler.BinPath))
            {
                linkerExecutable = Path.Combine(Compiler.BinPath, linkCfg.Linker);

                if (!File.Exists(linkerExecutable))
                {
                    linkerExecutable = linkCfg.Linker;
                }
            }

            monitor.Log.WriteLine("Current dictionary: " + Project.BaseDirectory);

            string cmdLineFile;

            HandleOverLongArgumentStrings(monitor, Compiler, true, ref argumentString, out cmdLineFile);

            int exitCode = ExecuteCommand(linkerExecutable, argumentString, Project.BaseDirectory, monitor,
                                          out stdError,
                                          out stdOut);

            ErrorExtracting.HandleCompilerOutput(Project, br, stdError);
            ErrorExtracting.HandleCompilerOutput(Project, br, stdOut);
            ErrorExtracting.HandleOptLinkOutput(Project, br, stdOut);
            ErrorExtracting.HandleLdOutput(Project, br, stdOut);
            ErrorExtracting.HandleReturnCode(monitor, br, exitCode);

            if (cmdLineFile != null)
            {
                File.Delete(cmdLineFile);
            }

            if (!br.Failed)
            {
                Project.CopySupportFiles(monitor, this.BuildConfig.Selector);
                Project.NeedsFullRebuild = false;
            }

            return(br);
        }
		protected override void Clean (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration)
		{
			Project proj = entry as Project;
			if (proj == null) {
				base.Clean (monitor, entry, configuration);
				return;
			}

			MakefileData data = proj.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.CleanTargetName)) {
				base.Clean (monitor, entry, configuration); 
				return;
			}

			monitor.BeginTask (GettextCatalog.GetString ("Cleaning project"), 1);
			try {
				string baseDir = proj.BaseDirectory;
	
				ProcessWrapper process = Runtime.ProcessService.StartProcess (data.AbsoluteMakeCommand, 
						data.CleanTargetName, 
						baseDir, 
						monitor.Log, 
						monitor.Log, 
						null);
				process.WaitForOutput ();

				if (process.ExitCode > 0)
					throw new Exception ( GettextCatalog.GetString ("An unspecified error occurred while running '{0} {1}'", data.AbsoluteMakeCommand, data.CleanTargetName) );

				monitor.Step (1);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Project could not be cleaned: "), e);
				return;
			} finally {
				monitor.EndTask ();
			}
			monitor.ReportSuccess (GettextCatalog.GetString ("Project successfully cleaned"));
		}
        void BuildDone(IProgressMonitor monitor, ICompilerResult result)
        {
            lastResult = result;
            monitor.Log.WriteLine ();
            monitor.Log.WriteLine (String.Format (GettextCatalog.GetString ("---------------------- Done ----------------------")));

            foreach (CompilerError err in result.CompilerResults.Errors) {
                Runtime.TaskService.AddTask (new Task(null, err));
            }

            if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) {
                monitor.ReportSuccess (GettextCatalog.GetString ("Build successful."));
            } else if (result.ErrorCount == 0 && result.WarningCount > 0) {
                monitor.ReportWarning (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount));
            } else if (result.ErrorCount > 0) {
                monitor.ReportError (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount), null);
            } else {
                monitor.ReportError (String.Format (GettextCatalog.GetString ("Build failed.")), null);
            }

            OnEndBuild (lastResult.FailedBuildCount == 0);
        }
Exemplo n.º 51
0
        static bool UpdateCompleted(IProgressMonitor monitor, AggregatedOperationMonitor aggOp,
                                    ProjectFile file, ProjectFile genFile, SingleFileCustomToolResult result,
                                    bool runMultipleFiles)
        {
            monitor.EndTask();
            if (aggOp != null)
            {
                aggOp.Dispose();
            }

            if (monitor.IsCancelRequested)
            {
                monitor.ReportError(GettextCatalog.GetString("Cancelled"), null);
                monitor.Dispose();
                return(false);
            }

            string genFileName;

            try {
                bool broken = false;

                if (result.UnhandledException != null)
                {
                    broken = true;
                    string msg = GettextCatalog.GetString("The '{0}' code generator crashed", file.Generator);
                    result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg + ": " + result.UnhandledException.Message));
                    monitor.ReportError(msg, result.UnhandledException);
                    LoggingService.LogError(msg, result.UnhandledException);
                }

                genFileName = result.GeneratedFilePath.IsNullOrEmpty?
                              null : result.GeneratedFilePath.ToRelative(file.FilePath.ParentDirectory);

                if (!string.IsNullOrEmpty(genFileName))
                {
                    bool validName = genFileName.IndexOfAny(new [] { '/', '\\' }) < 0 &&
                                     FileService.IsValidFileName(genFileName);

                    if (!broken && !validName)
                    {
                        broken = true;
                        string msg = GettextCatalog.GetString("The '{0}' code generator output invalid filename '{1}'",
                                                              file.Generator, result.GeneratedFilePath);
                        result.Errors.Add(new CompilerError(file.Name, 0, 0, "", msg));
                        monitor.ReportError(msg, null);
                    }
                }

                if (result.Errors.Count > 0)
                {
                    DispatchService.GuiDispatch(delegate {
                        foreach (CompilerError err in result.Errors)
                        {
                            TaskService.Errors.Add(new Task(file.FilePath, err.ErrorText, err.Column, err.Line,
                                                            err.IsWarning? TaskSeverity.Warning : TaskSeverity.Error,
                                                            TaskPriority.Normal, file.Project.ParentSolution, file));
                        }
                    });
                }

                if (broken)
                {
                    return(true);
                }

                if (!runMultipleFiles)
                {
                    if (result.Success)
                    {
                        monitor.ReportSuccess("Generated file successfully.");
                    }
                    else if (result.SuccessWithWarnings)
                    {
                        monitor.ReportSuccess("Warnings in file generation.");
                    }
                    else
                    {
                        monitor.ReportError("Errors in file generation.", null);
                    }
                }
            } finally {
                if (!runMultipleFiles)
                {
                    monitor.Dispose();
                }
            }

            if (result.GeneratedFilePath.IsNullOrEmpty || !File.Exists(result.GeneratedFilePath))
            {
                return(true);
            }

            // broadcast a change event so text editors etc reload the file
            FileService.NotifyFileChanged(result.GeneratedFilePath);

            // add file to project, update file properties, etc
            Gtk.Application.Invoke(delegate {
                bool projectChanged = false;
                if (genFile == null)
                {
                    genFile        = file.Project.AddFile(result.GeneratedFilePath, result.OverrideBuildAction);
                    projectChanged = true;
                }
                else if (result.GeneratedFilePath != genFile.FilePath)
                {
                    genFile.Name   = result.GeneratedFilePath;
                    projectChanged = true;
                }

                if (file.LastGenOutput != genFileName)
                {
                    file.LastGenOutput = genFileName;
                    projectChanged     = true;
                }

                if (genFile.DependsOn != file.FilePath.FileName)
                {
                    genFile.DependsOn = file.FilePath.FileName;
                    projectChanged    = true;
                }

                if (projectChanged)
                {
                    IdeApp.ProjectOperations.Save(file.Project);
                }
            });

            return(true);
        }
Exemplo n.º 52
0
		public void Push (IProgressMonitor monitor, string remote, string remoteBranch)
		{
			RunCommand ("push " + remote + " HEAD:" + remoteBranch, true, monitor);
			monitor.ReportSuccess ("Repository successfully pushed");
		}
Exemplo n.º 53
0
		void CleanDone (IProgressMonitor monitor, IBuildTarget entry, ITimeTracker tt)
		{
			tt.Trace ("Begin reporting clean result");
			try {
				monitor.Log.WriteLine ();
				monitor.Log.WriteLine (GettextCatalog.GetString ("---------------------- Done ----------------------"));
				tt.Trace ("Reporting result");			
				monitor.ReportSuccess (GettextCatalog.GetString ("Clean successful."));
				OnEndClean (monitor, tt);
			} finally {
				monitor.Dispose ();
				tt.End ();
			}
		}
Exemplo n.º 54
0
        public bool Deploy(DeployContext ctx, Solution solution, string defaultConf, string targetDir, bool generateFiles, IProgressMonitor monitor)
        {
            if (generateFiles)
            {
                if (!GenerateFiles(ctx, solution, defaultConf, monitor))
                {
                    return(false);
                }
            }

            monitor.BeginTask(GettextCatalog.GetString("Deploying Solution to Tarball"), 3);
            try
            {
                string baseDir = Path.GetDirectoryName(solution.FileName);

                ProcessWrapper ag_process = Runtime.ProcessService.StartProcess("sh",
                                                                                generateAutotools ? "autogen.sh" : "configure",
                                                                                baseDir,
                                                                                monitor.Log,
                                                                                monitor.Log,
                                                                                null);
                ag_process.WaitForOutput();

                if (ag_process.ExitCode > 0)
                {
                    throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", generateAutotools ? "autogen.sh" : "configure"));
                }

                monitor.Step(1);

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

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

                if (process.ExitCode > 0)
                {
                    throw new Exception(GettextCatalog.GetString("An unspecified error occurred while running '{0}'", "make dist"));
                }

                monitor.Step(1);

                // FIXME: hackish way to get the created tarball's filename
                string output = sw.ToString();
                int    targz  = output.LastIndexOf("tar.gz");
                int    begin  = output.LastIndexOf('>', targz);

                string filename = output.Substring(begin + 1, (targz - begin) + 5).Trim();

                FileService.CopyFile(Path.Combine(baseDir, filename), Path.Combine(targetDir, filename));
                monitor.Step(1);
            }
            catch (Exception e)
            {
                monitor.ReportError(GettextCatalog.GetString("Solution could not be deployed: "), e);
                return(false);
            }
            finally
            {
                monitor.EndTask();
            }
            monitor.ReportSuccess(GettextCatalog.GetString("Solution was successfully deployed."));
            return(true);
        }