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 UpdateTranslations(IProgressMonitor monitor, params Translation[] translations) { monitor.BeginTask(null, Translations.Count + 1); try { List <Project> projects = new List <Project> (); foreach (Project p in ParentSolution.GetAllProjects()) { if (IsIncluded(p)) { projects.Add(p); } } monitor.BeginTask(GettextCatalog.GetString("Updating message catalog"), projects.Count); CreateDefaultCatalog(monitor); monitor.Log.WriteLine(GettextCatalog.GetString("Done")); } finally { monitor.EndTask(); monitor.Step(1); } if (monitor.IsCancelRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled.")); return; } Dictionary <string, bool> isIncluded = new Dictionary <string, bool> (); foreach (Translation translation in translations) { isIncluded[translation.IsoCode] = true; } foreach (Translation translation in this.Translations) { if (!isIncluded.ContainsKey(translation.IsoCode)) { continue; } string poFileName = translation.PoFile; monitor.BeginTask(GettextCatalog.GetString("Updating {0}", translation.PoFile), 1); try { Runtime.ProcessService.StartProcess("msgmerge", " -U \"" + poFileName + "\" -v \"" + Path.Combine(this.BaseDirectory, "messages.po") + "\"", this.BaseDirectory, monitor.Log, monitor.Log, null).WaitForOutput(); } catch (Exception ex) { monitor.ReportError(GettextCatalog.GetString("Could not update file {0}", translation.PoFile), ex); } finally { monitor.EndTask(); monitor.Step(1); } if (monitor.IsCancelRequested) { monitor.Log.WriteLine(GettextCatalog.GetString("Operation cancelled.")); return; } } }
/// <summary> /// Builds the specified solution item. /// </summary> /// <param name = "monitor">The monitor.</param> /// <param name = "item">The item.</param> /// <param name = "configuration">The configuration.</param> /// <returns>The build result.</returns> protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration) { BuildResult result = new BuildResult (); // Pre-build monitor.BeginTask (GettextCatalog.GetString ("Pre-Building..."), 1); this.PreBuild (result, monitor, item, configuration); monitor.EndTask(); if (result.ErrorCount > 0) { return result; } // Build monitor.BeginTask (GettextCatalog.GetString ("Building"), 1); result.Append (base.Build (monitor, item, configuration)); monitor.EndTask(); if (result.ErrorCount > 0) { return result; } // Post-build monitor.BeginTask (GettextCatalog.GetString ("Post-Building..."), 1); this.PostBuild (result, monitor, item, configuration); monitor.EndTask(); return result; }
public XcodeSyncBackContext GetChanges(IProgressMonitor monitor, NSObjectInfoService infoService, DotNetProject project) { var ctx = new XcodeSyncBackContext(projectDir, syncTimeCache, infoService, project); var needsSync = new List <XcodeSyncedItem> (items.Where(i => i.NeedsSyncBack(monitor, ctx))); var knownFiles = GetKnownFiles(); if (Directory.Exists(projectDir)) { monitor.BeginTask("Scanning for newly-added files in the Xcode project...", 0); ScanForAddedFiles(monitor, ctx, knownFiles, projectDir, null); monitor.EndTask(); } if (needsSync.Count > 0) { monitor.BeginStepTask(GettextCatalog.GetString("Synchronizing changes made to known files in Xcode back to MonoDevelop..."), needsSync.Count, 1); for (int i = 0; i < needsSync.Count; i++) { var item = needsSync [i]; item.SyncBack(monitor, ctx); monitor.Step(1); } monitor.EndTask(); } return(ctx); }
internal string DownloadFile(IProgressMonitor monitor, string url) { if (url.StartsWith("file://")) { string tmpfile = Path.GetTempFileName(); string path = url.Substring(7); File.Delete(tmpfile); File.Copy(path, tmpfile); return(tmpfile); } monitor.BeginTask("Requesting " + url, 2); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Headers ["Pragma"] = "no-cache"; HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); monitor.Step(1); monitor.BeginTask("Downloading " + url, (int)resp.ContentLength); string file = Path.GetTempFileName(); FileStream fs = null; Stream s = null; try { fs = new FileStream(file, FileMode.Create, FileAccess.Write); s = req.GetResponse().GetResponseStream(); byte[] buffer = new byte [4096]; int n; while ((n = s.Read(buffer, 0, buffer.Length)) != 0) { monitor.Step(n); fs.Write(buffer, 0, n); if (monitor.IsCancelRequested) { throw new InstallException("Installation cancelled."); } } fs.Close(); s.Close(); return(file); } catch { if (fs != null) { fs.Close(); } if (s != null) { s.Close(); } File.Delete(file); throw; } finally { monitor.EndTask(); monitor.EndTask(); } }
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(); } } }
public IEnumerable <SearchResult> FindAll(Scope scope, IProgressMonitor monitor, string pattern, string replacePattern, FilterOptions filter) { if (filter.RegexSearch) { RegexOptions regexOptions = RegexOptions.Compiled; if (!filter.CaseSensitive) { regexOptions |= RegexOptions.IgnoreCase; } regex = new Regex(pattern, regexOptions); } IsRunning = true; FoundMatchesCount = SearchedFilesCount = 0; monitor.BeginTask(scope.GetDescription(filter, pattern, replacePattern), 50); try { int totalWork = scope.GetTotalWork(filter); int step = Math.Max(1, totalWork / 50); string content; foreach (FileProvider provider in scope.GetFiles(monitor, filter)) { if (monitor.IsCancelRequested) { yield break; } SearchedFilesCount++; try { content = provider.ReadString(); if (replacePattern != null) { provider.BeginReplace(content); } } catch (System.IO.FileNotFoundException) { MessageService.ShowError(string.Format(GettextCatalog.GetString("File {0} not found.")), provider.FileName); continue; } foreach (SearchResult result in FindAll(monitor, provider, content, pattern, replacePattern, filter)) { if (monitor.IsCancelRequested) { yield break; } FoundMatchesCount++; yield return(result); } if (replacePattern != null) { provider.EndReplace(); } if (SearchedFilesCount % step == 0) { monitor.Step(1); } } } finally { monitor.EndTask(); IsRunning = false; } }
private void MakeStaticLibrary(Project project, ProjectFileCollection projectFiles, CProjectConfiguration configuration, ProjectPackageCollection packages, CompilerResults cr, IProgressMonitor monitor, string outputName) { if (!NeedsUpdate(projectFiles, configuration, outputName)) { return; } string objectFiles = string.Join(" ", ObjectFiles(projectFiles, configuration, true)); string args = string.Format("rcs \"{0}\" {1}", outputName, objectFiles); monitor.BeginTask(GettextCatalog.GetString("Generating static library {0} from object files", Path.GetFileName(outputName)), 1); string errorOutput; int exitCode = ExecuteCommand("ar", args, Path.GetDirectoryName(outputName), monitor, out errorOutput); if (exitCode == 0) { monitor.Step(1); } monitor.EndTask(); ParseCompilerOutput(errorOutput, cr); ParseLinkerOutput(errorOutput, cr); CheckReturnCode(exitCode, cr); }
public void EndTask() { lock (monitor.SyncRoot) { monitor.EndTask(); } }
protected override BuildResult Build(IProgressMonitor monitor, SolutionEntityItem project, ConfigurationSelector configuration) { var aspProject = project as AspNetAppProject; //get the config object and validate AspNetAppProjectConfiguration config = (AspNetAppProjectConfiguration)aspProject.GetConfiguration(configuration); if (config == null || config.DisableCodeBehindGeneration) { return(base.Build(monitor, project, configuration)); } var writer = CodeBehindWriter.CreateForProject(monitor, aspProject); if (!writer.SupportsPartialTypes) { return(base.Build(monitor, project, configuration)); } var result = new BuildResult(); monitor.BeginTask("Updating CodeBehind designer files", 0); foreach (var file in aspProject.Files) { ProjectFile designerFile = CodeBehind.GetDesignerFile(file); if (designerFile == null) { continue; } if (File.GetLastWriteTimeUtc(designerFile.FilePath) > File.GetLastWriteTimeUtc(file.FilePath)) { continue; } monitor.Log.WriteLine("Updating CodeBehind for file '{0}'", file); result.Append(CodeBehind.UpdateDesignerFile(writer, aspProject, file, designerFile)); } writer.WriteOpenFiles(); monitor.EndTask(); if (writer.WrittenCount > 0) { monitor.Log.WriteLine("{0} CodeBehind designer classes updated.", writer.WrittenCount); } else { monitor.Log.WriteLine("No changes made to CodeBehind classes."); } if (result.Failed) { return(result); } return(result.Append(base.Build(monitor, project, configuration))); }
protected override void OnClean(IProgressMonitor monitor, ConfigurationSelector configuration) { SetDirty(); ProjectConfiguration config = GetConfiguration(configuration) as ProjectConfiguration; if (config == null) { monitor.ReportError(GettextCatalog.GetString("Configuration '{0}' not found in project '{1}'", config.Id, Name), null); return; } monitor.BeginTask(GettextCatalog.GetString("Performing clean..."), 0); // Delete generated files foreach (FilePath file in GetOutputFiles(configuration)) { if (File.Exists(file)) { FileService.DeleteFile(file); if (file.ParentDirectory.CanonicalPath != config.OutputDirectory.CanonicalPath && Directory.GetFiles(file.ParentDirectory).Length == 0) { FileService.DeleteDirectory(file.ParentDirectory); } } } DeleteSupportFiles(monitor, configuration); DoClean(monitor, config.Selector); monitor.Log.WriteLine(); monitor.Log.WriteLine(GettextCatalog.GetString("Clean complete")); monitor.EndTask(); }
protected override DataNode ReadChild(XmlReader reader, DataItem parent) { if (reader.LocalName == "Entries") { if (reader.IsEmptyElement) { reader.Skip(); return(null); } string basePath = Path.GetDirectoryName(baseFile); reader.ReadStartElement(); ArrayList files = new ArrayList(); while (MoveToNextElement(reader)) { string nodefile = reader.GetAttribute("filename"); nodefile = FileService.RelativeToAbsolutePath(basePath, nodefile); files.Add(nodefile); reader.Skip(); } monitor.BeginTask(GettextCatalog.GetString("Loading solution: {0}", baseFile), files.Count); try { foreach (string nodefile in files) { try { if (Path.GetExtension(nodefile).ToLower() == ".mds") { entries.Add(ReadSolutionFolder(nodefile, monitor)); } else { SolutionEntityItem entry = (SolutionEntityItem)Services.ProjectService.ReadSolutionItem(monitor, nodefile); entries.Add(entry); } } catch (Exception ex) { UnknownSolutionItem entry = new UnknownSolutionItem(); entry.FileName = nodefile; entry.LoadError = ex.Message; entries.Add(entry); monitor.ReportError(GettextCatalog.GetString("Could not load item: {0}", nodefile), ex); } monitor.Step(1); } } finally { monitor.EndTask(); } reader.ReadEndElement(); return(null); } return(base.ReadChild(reader, parent)); }
public static BuildResult UpdateCodeBehind (IProgressMonitor monitor, XibCodeBehind generator, IEnumerable<ProjectFile> items) { var result = new BuildResult (); var writer = MonoDevelop.DesignerSupport.CodeBehindWriter.CreateForProject (monitor, generator.Project); if (!writer.SupportsPartialTypes) { monitor.ReportWarning ("Cannot generate designer code, because CodeDom " + "provider does not support partial classes."); return result; } var files = generator.GetDesignerFilesNeedBuilding (items, false).ToList (); if (files.Count == 0) return result; monitor.BeginTask (GettextCatalog.GetString ("Updating CodeBehind files"), 0); foreach (var f in files) { try { generator.GenerateDesignerCode (writer, f.Key, f.Value); var relPath = f.Value.FilePath.ToRelative (generator.Project.BaseDirectory); monitor.Log.WriteLine (GettextCatalog.GetString ("Updated {0}", relPath)); } catch (Exception ex) { result = result ?? new BuildResult (); result.AddError (f.Key.FilePath, 0, 0, null, ex.Message); LoggingService.LogError (String.Format ("Error generating code for xib file '{0}'", f.Key.FilePath), ex); } } writer.WriteOpenFiles (); monitor.EndTask (); return result; }
public static BuildResult CompileXibFiles (IProgressMonitor monitor, IEnumerable<ProjectFile> files, FilePath outputRoot) { var result = new BuildResult (); var ibfiles = GetIBFilePairs (files, outputRoot).Where (NeedsBuilding).ToList (); if (ibfiles.Count > 0) { monitor.BeginTask (GettextCatalog.GetString ("Compiling interface definitions"), 0); foreach (var file in ibfiles) { file.EnsureOutputDirectory (); var psi = new ProcessStartInfo ("ibtool", String.Format ("\"{0}\" --compile \"{1}\"", file.Input, file.Output) ); monitor.Log.WriteLine (psi.FileName + " " + psi.Arguments); psi.WorkingDirectory = outputRoot; string errorOutput; int code; try { code = ExecuteCommand (monitor, psi, out errorOutput); } catch (System.ComponentModel.Win32Exception ex) { LoggingService.LogError ("Error running ibtool", ex); result.AddError (null, 0, 0, null, "ibtool not found. Please ensure the Apple SDK is installed."); return result; } if (code != 0) { //FIXME: parse the plist that ibtool returns result.AddError (null, 0, 0, null, "ibtool returned error code " + code); } } monitor.EndTask (); } return result; }
/// <summary> /// Cleans the files produced by this solution item /// </summary> /// <param name='monitor'> /// A progress monitor /// </param> /// <param name='configuration'> /// Configuration to use to clean the project /// </param> public void Clean(IProgressMonitor monitor, ConfigurationSelector configuration) { ITimeTracker tt = Counters.CleanProjectTimer.BeginTiming("Cleaning " + Name, GetProjectEventMetadata(configuration)); try { //SolutionFolder handles the begin/end task itself, don't duplicate if (this is SolutionFolder) { RunTarget(monitor, ProjectService.CleanTarget, configuration); return; } try { SolutionEntityItem it = this as SolutionEntityItem; SolutionItemConfiguration iconf = it != null?it.GetConfiguration(configuration) : null; string confName = iconf != null ? iconf.Id : configuration.ToString(); monitor.BeginTask(GettextCatalog.GetString("Cleaning: {0} ({1})", Name, confName), 1); RunTarget(monitor, ProjectService.CleanTarget, configuration); } finally { monitor.EndTask(); } } finally { tt.End(); } }
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(); } }
/// <summary> /// Updates the add-in index of the provided repository /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status and log /// </param> /// <param name="url"> /// URL of the repository /// </param> public void UpdateRepository(IProgressStatus statusMonitor, string url) { repoList = null; IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor(statusMonitor); monitor.BeginTask("Updating repositories", service.Configuration.Repositories.Count); try { int num = service.Configuration.Repositories.Count; for (int n = 0; n < num; n++) { RepositoryRecord rr = (RepositoryRecord)service.Configuration.Repositories [n]; if (((url == null && rr.Enabled) || rr.Url == url) && !rr.IsReference) { UpdateRepository(monitor, new Uri(rr.Url), rr); } monitor.Step(1); } } catch (Exception ex) { statusMonitor.ReportError("Could not get information from repository", ex); return; } finally { monitor.EndTask(); } PurgeUnusedRepositories(); service.SaveConfiguration(); }
internal protected override BuildResult OnRunTarget(IProgressMonitor monitor, string target, ConfigurationSelector configuration) { BuildResult result = null; monitor.BeginTask(null, Items.Count); try { foreach (WorkspaceItem it in Items) { BuildResult res = it.RunTarget(monitor, target, configuration); if (res != null) { if (result == null) { result = new BuildResult(); result.BuildCount = 0; } result.Append(res); } monitor.Step(1); } } finally { monitor.EndTask(); } return(result); }
public static void Run(string filePath, DProject project, DProjectConfiguration conf) { if (manager == null) { manager = new ProgressMonitorManager(); monitor = manager.GetOutputProgressMonitor("Run Unittest", Stock.RunProgramIcon, true, true); } Pad pad = manager.GetPadForMonitor(monitor); if (pad != null) { pad.BringToFront(); } monitor.BeginTask("start unittest...", 1); new System.Threading.Thread(delegate(){ string[] cmdParts = GetCmdParts(project); string args = GetCommandArgs(cmdParts.Length >= 2 ?cmdParts[1] : "", filePath, project, conf); string errorOutput; string stdOutput; string execDir = GetExecDir(project, conf); ProjectBuilder.ExecuteCommand(cmdParts[0], args, execDir, monitor, out stdOutput, out errorOutput); monitor.Log.WriteLine("unittest done."); monitor.EndTask(); }).Start(); }
/// <summary> /// Adds any newly created resource files to MonoDevelop's DotNetProject. /// </summary> /// <param name='monitor'> /// A progress monitor. /// </param> /// <param name='context'> /// The sync context. /// </param> /// <returns> /// Returns whether or not new files were added to the project. /// </returns> bool AddFilesToMD(IProgressMonitor monitor, XcodeSyncBackContext context) { bool needsEndTask = false; if (context.FileSyncJobs.Count == 0) { return(false); } foreach (var file in context.FileSyncJobs) { if (!file.IsFreshlyAdded) { continue; } monitor.Log.WriteLine("Adding new file to project: {0}", file.SyncedRelative); FilePath path = new FilePath(file.Original); string buildAction = HasInterfaceDefinitionExtension(path) ? BuildAction.InterfaceDefinition : BuildAction.Content; context.Project.AddFile(path, buildAction); needsEndTask = true; } if (needsEndTask) { monitor.EndTask(); return(true); } return(false); }
static IAsyncOperation BuildPackages(ICollection packages) { IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor(true); // Run the deploy command in a background thread to avoid // deadlocks with the gui thread System.Threading.Thread t = new System.Threading.Thread( delegate() { using (mon) { mon.BeginTask("Creating packages", packages.Count); foreach (Package p in packages) { DeployService.BuildPackage(mon, p); mon.Step(1); } mon.EndTask(); } }); t.IsBackground = true; t.Start(); return(mon.AsyncOperation); }
object ReadWorkspaceItemFile(FilePath fileName, IProgressMonitor monitor) { XmlTextReader reader = new XmlTextReader(new StreamReader(fileName)); try { monitor.BeginTask(string.Format(GettextCatalog.GetString("Loading workspace item: {0}"), fileName), 1); reader.MoveToContent(); XmlDataSerializer ser = new XmlDataSerializer(MD1ProjectService.DataContext); ser.SerializationContext.BaseFile = fileName; ser.SerializationContext.ProgressMonitor = monitor; WorkspaceItem entry = (WorkspaceItem)ser.Deserialize(reader, typeof(WorkspaceItem)); entry.ConvertToFormat(MD1ProjectService.FileFormat, false); entry.FileName = fileName; return(entry); } catch (Exception ex) { monitor.ReportError(string.Format(GettextCatalog.GetString("Could not load solution item: {0}"), fileName), ex); throw; } finally { monitor.EndTask(); reader.Close(); } }
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(); }
/// <summary> /// Checks that the xml in this view is well-formed. /// </summary> public static XmlDocument ValidateWellFormedness(IProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask(GettextCatalog.GetString("Validating XML..."), 1); bool error = false; XmlDocument doc = null; try { doc = new XmlDocument(); doc.LoadXml(xml); } catch (XmlException ex) { monitor.ReportError(ex.Message, ex); AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error); error = true; } if (error) { monitor.Log.WriteLine(GettextCatalog.GetString("Validation failed.")); TaskService.ShowErrors(); } else { monitor.Log.WriteLine(GettextCatalog.GetString("XML is valid.")); } monitor.EndTask(); return(error? null: doc); }
internal void Initialize(IProgressMonitor monitor) { monitor.BeginTask(GettextCatalog.GetString("Initializing Main Window"), 4); try { Counters.Initialization.Trace("Creating DefaultWorkbench"); workbench = new DefaultWorkbench(); monitor.Step(1); Counters.Initialization.Trace("Initializing Workspace"); workbench.InitializeWorkspace(); monitor.Step(1); Counters.Initialization.Trace("Initializing Layout"); workbench.InitializeLayout(); monitor.Step(1); ((Gtk.Window)workbench).Visible = false; workbench.ActiveWorkbenchWindowChanged += OnDocumentChanged; IdeApp.Workspace.StoringUserPreferences += OnStoringWorkspaceUserPreferences; IdeApp.Workspace.LoadingUserPreferences += OnLoadingWorkspaceUserPreferences; IdeApp.CommandService.ApplicationFocusOut += delegate(object o, EventArgs args) { SaveFileStatus(); }; IdeApp.CommandService.ApplicationFocusIn += delegate(object o, EventArgs args) { CheckFileStatus(); }; pads = null; // Make sure we get an up to date pad list. monitor.Step(1); } finally { monitor.EndTask(); } }
void InstallEntry(IProgressMonitor monitor, DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) { foreach (DeployFile df in DeployService.GetDeployFiles(ctx, new SolutionItem[] { entry }, configuration)) { string targetPath = df.ResolvedTargetFile; if (targetPath == null) { monitor.ReportWarning("Could not copy file '" + df.RelativeTargetPath + "': Unknown target directory."); continue; } CopyFile(monitor, df.SourcePath, df.ResolvedTargetFile, df.FileAttributes); } SolutionFolder c = entry as SolutionFolder; if (c != null) { monitor.BeginTask("Installing solution '" + c.Name + "'", c.Items.Count); foreach (SolutionItem ce in c.Items) { InstallEntry(monitor, ctx, ce, configuration); monitor.Step(1); } monitor.EndTask(); } }
public object ReadFile(FilePath fileName, Type expectedType, IProgressMonitor monitor) { object readObject = null; ProjectExtensionUtil.BeginLoadOperation(); try { string ext = Path.GetExtension(fileName).ToLower(); if (ext == ".mdp") { object project = ReadProjectFile(fileName, monitor); if (project is DotNetProject) { ((DotNetProject)project).SetItemHandler(new MD1DotNetProjectHandler((DotNetProject)project)); } readObject = project; } else if (ext == ".mds") { readObject = ReadCombineFile(fileName, monitor); } else if (ext == ".mdw") { readObject = ReadWorkspaceItemFile(fileName, monitor); } else { XmlTextReader reader = new XmlTextReader(new StreamReader(fileName)); try { monitor.BeginTask(string.Format(GettextCatalog.GetString("Loading solution item: {0}"), fileName), 1); reader.MoveToContent(); XmlDataSerializer ser = new XmlDataSerializer(MD1ProjectService.DataContext); ser.SerializationContext.BaseFile = fileName; ser.SerializationContext.ProgressMonitor = monitor; SolutionEntityItem entry = (SolutionEntityItem)ser.Deserialize(reader, typeof(SolutionEntityItem)); entry.FileName = fileName; MD1ProjectService.InitializeHandler(entry); readObject = entry; } catch (Exception ex) { monitor.ReportError(string.Format(GettextCatalog.GetString("Could not load solution item: {0}"), fileName), ex); throw; } finally { monitor.EndTask(); reader.Close(); } } } finally { ProjectExtensionUtil.EndLoadOperation(); } IWorkspaceFileObject fo = readObject as IWorkspaceFileObject; if (fo != null) { fo.ConvertToFormat(MD1ProjectService.FileFormat, false); } return(readObject); }
void UpdateRepository(IProgressMonitor monitor, Uri baseUri, RepositoryRecord rr) { Uri absUri = new Uri(baseUri, rr.Url); monitor.BeginTask("Updating from " + absUri.ToString(), 2); Repository newRep; try { newRep = (Repository)service.Store.DownloadObject(monitor, absUri.ToString(), typeof(Repository)); } catch (Exception ex) { monitor.ReportError("Could not get information from repository" + ": " + absUri.ToString(), ex); return; } monitor.Step(1); foreach (ReferenceRepositoryEntry re in newRep.Repositories) { Uri refRepUri = new Uri(absUri, re.Url); string refRepUrl = refRepUri.ToString(); RepositoryRecord refRep = FindRepositoryRecord(refRepUrl); if (refRep == null) { refRep = RegisterRepository(refRepUrl, true); } if (refRep.LastModified < re.LastModified) { UpdateRepository(monitor, refRepUri, refRep); } } monitor.EndTask(); rr.UpdateCachedRepository(newRep); }
internal bool Build(IProgressMonitor monitor) { monitor.BeginTask("Package: " + Description, 1); DeployContext ctx = null; try { ctx = CreateDeployContext(); if (ctx != null) { ctx.FileFilter = this; } if (!OnBuild(monitor, ctx)) { monitor.AsyncOperation.Cancel(); return(false); } } catch (Exception ex) { monitor.ReportError("Package creation failed", ex); LoggingService.LogError("Package creation failed", ex); monitor.AsyncOperation.Cancel(); return(false); } finally { monitor.EndTask(); if (ctx != null) { ctx.Dispose(); } } return(true); }
public object ReadFile(FilePath file, Type expectedType, IProgressMonitor monitor) { XmlTextReader reader = new XmlTextReader(new StreamReader(file)); try { monitor.BeginTask(string.Format(GettextCatalog.GetString("Loading project: {0}"), file), 1); reader.MoveToContent(); XmlDataSerializer ser = new XmlDataSerializer(MD1ProjectService.DataContext); ser.SerializationContext.BaseFile = file; SolutionEntityItem entry = (SolutionEntityItem)ser.Deserialize(reader, typeof(NUnitAssemblyGroupProject)); entry.FileName = file; return(entry); } catch (Exception ex) { monitor.ReportError(string.Format(GettextCatalog.GetString("Could not load project: {0}"), file), ex); throw; } finally { monitor.EndTask(); reader.Close(); } }
protected override SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName) { SolutionEntityItem entry = base.LoadSolutionItem (monitor, fileName); if (entry == null) return null; Project project = entry as Project; if (project == null) return entry; //Project MakefileData data = entry.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; if (data == null) return entry; monitor.BeginTask (GettextCatalog.GetString ("Updating project from Makefile"), 1); try { data.OwnerProject = project; if (data.SupportsIntegration) data.UpdateProject (monitor, false); monitor.Step (1); } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ( "Error loading Makefile for project {0}", project.Name), e); } finally { monitor.EndTask (); } return entry; }
public List<WorkItem> LoadByWorkItem(IProgressMonitor progress) { var ids = this.clientService.GetWorkItemIds(this.query, CachedMetaData.Instance.Fields); var list = new List<WorkItem>(); progress.BeginTask("Loading WorkItems", ids.Count); foreach (var id in ids) { list.Add(clientService.GetWorkItem(id)); progress.Step(1); } progress.EndTask(); return list; }
public static void Archive(IProgressMonitor monitor, BuildResult result, MonobjcProject project, ConfigurationSelector configuration, String outputDirectory) { monitor.BeginTask(GettextCatalog.GetString("Archiving..."), 0); // Infer application name from configuration String applicationName = project.GetApplicationName(configuration); // Create the bundle maker BundleMaker maker = new BundleMaker(applicationName, outputDirectory); // Archive the application BuildHelper.ArchiveBundle(monitor, project, maker); monitor.EndTask(); }
public List<WorkItem> LoadByPage(IProgressMonitor progress) { var ids = this.clientService.GetWorkItemIds(this.query, CachedMetaData.Instance.Fields); int pages = (int)Math.Ceiling((double)ids.Count / (double)50); var result = new List<WorkItem>(); progress.BeginTask("Loading WorkItems", pages); for (int i = 0; i < pages; i++) { var idList = new List<int>(ids.Skip(i * 50).Take(50)); var items = this.clientService.PageWorkitemsByIds(this.query, idList); result.AddRange(items); progress.Step(1); } progress.EndTask(); return result; }
/// <summary> /// Archive the application bundle. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'maker'>The bundle maker.</param> public static void ArchiveBundle(IProgressMonitor monitor, MonobjcProject project, BundleMaker maker) { if (project.Archive && project.ArchiveIdentity != null) { FilePath definitionFile = project.BaseDirectory.Combine ("Definition.plist"); String definitionFilename = File.Exists (definitionFile) ? definitionFile.ToString () : null; monitor.BeginTask (GettextCatalog.GetString ("Signing archive..."), 0); using (StringWriter outputWriter = new StringWriter()) { using (StringWriter errorWriter = new StringWriter()) { ProductBuild.ArchiveApplication (maker.ApplicationDirectory, project.ArchiveIdentity, definitionFilename, outputWriter, errorWriter); LoggingService.LogInfo ("ProductBuild returns: " + outputWriter.ToString ()); } } monitor.EndTask (); } }
protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem project, ConfigurationSelector configuration) { var aspProject = project as AspNetAppProject; //get the config object and validate AspNetAppProjectConfiguration config = (AspNetAppProjectConfiguration)aspProject.GetConfiguration (configuration); if (config == null || config.DisableCodeBehindGeneration) { return base.Build (monitor, project, configuration); } var writer = CodeBehindWriter.CreateForProject (monitor, aspProject); if (!writer.SupportsPartialTypes) { return base.Build (monitor, project, configuration); } var result = new BuildResult (); monitor.BeginTask ("Updating CodeBehind designer files", 0); foreach (var file in aspProject.Files) { ProjectFile designerFile = CodeBehind.GetDesignerFile (file); if (designerFile == null) continue; if (File.GetLastWriteTimeUtc (designerFile.FilePath) > File.GetLastWriteTimeUtc (file.FilePath)) continue; monitor.Log.WriteLine ("Updating CodeBehind for file '{0}'", file); result.Append (CodeBehind.UpdateDesignerFile (writer, aspProject, file, designerFile)); } writer.WriteOpenFiles (); monitor.EndTask (); if (writer.WrittenCount > 0) monitor.Log.WriteLine ("{0} CodeBehind designer classes updated.", writer.WrittenCount); else monitor.Log.WriteLine ("No changes made to CodeBehind classes."); if (result.Failed) return result; return result.Append (base.Build (monitor, project, configuration)); }
public IEnumerable<Tuple<ProjectDom, FilePath>> GetFileNames(Solution solution, ProjectDom dom, ICompilationUnit unit, IProgressMonitor monitor) { int counter = 0; ReadOnlyCollection<Project> allProjects = solution.GetAllProjects(); if (monitor != null) monitor.BeginTask(GettextCatalog.GetString("Finding references in solution..."), allProjects.Sum<Project>(p => p.Files.Count)); foreach (Project project in allProjects) { if (monitor != null && monitor.IsCancelRequested) yield break; ProjectDom currentDom = ProjectDomService.GetProjectDom(project); foreach (ProjectFile projectFile in (Collection<ProjectFile>) project.Files) { if (monitor != null && monitor.IsCancelRequested) yield break; yield return Tuple.Create<ProjectDom, FilePath>(currentDom, projectFile.FilePath); if (monitor != null) { if (counter % 10 == 0) monitor.Step(10); ++counter; } } } if (monitor != null) monitor.EndTask(); }
void InstallEntry (IProgressMonitor monitor, DeployContext ctx, SolutionItem entry, ConfigurationSelector configuration) { foreach (DeployFile df in DeployService.GetDeployFiles (ctx, new SolutionItem[] { entry }, configuration)) { string targetPath = df.ResolvedTargetFile; if (targetPath == null) { monitor.ReportWarning ("Could not copy file '" + df.RelativeTargetPath + "': Unknown target directory."); continue; } CopyFile (monitor, df.SourcePath, df.ResolvedTargetFile, df.FileAttributes); } SolutionFolder c = entry as SolutionFolder; if (c != null) { monitor.BeginTask ("Installing solution '" + c.Name + "'", c.Items.Count); foreach (SolutionItem ce in c.Items) { InstallEntry (monitor, ctx, ce, configuration); monitor.Step (1); } monitor.EndTask (); } }
/// <summary> /// Sign the native libraries inside the bundle. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'maker'>The bundle maker.</param> public static void SignNativeBinaries(IProgressMonitor monitor, MonobjcProject project, BundleMaker maker) { if (project.Signing && !String.IsNullOrEmpty(project.SigningIdentity)) { String[] files = Directory.GetFiles (maker.MacOSDirectory, "*.dylib"); if (files == null || files.Count() == 0) { return; } monitor.BeginTask (GettextCatalog.GetString ("Signing native libraries..."), files.Length); foreach (String file in files) { using (StringWriter outputWriter = new StringWriter()) { using (StringWriter errorWriter = new StringWriter()) { CodeSign.PerformSigning (file, project.SigningIdentity, outputWriter, errorWriter); LoggingService.LogInfo ("CodeSign returns: " + outputWriter.ToString ()); } } monitor.Step (1); } monitor.EndTask (); } }
/// <summary> /// Sign the application bundle. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'maker'>The bundle maker.</param> public static void SignBundle(IProgressMonitor monitor, MonobjcProject project, BundleMaker maker) { if (project.Signing && !String.IsNullOrEmpty(project.SigningIdentity)) { monitor.BeginTask (GettextCatalog.GetString ("Signing bundle..."), 0); using (StringWriter outputWriter = new StringWriter()) { using (StringWriter errorWriter = new StringWriter()) { FilePath file = project.BaseDirectory.Combine(Constants.APP_ENTITLEMENTS); if (project.UseEntitlements && File.Exists(file)) { monitor.Log.WriteLine (GettextCatalog.GetString ("Signing with identity '{0}' and entitlements '{1}'", project.SigningIdentity, file.FileName)); CodeSign.PerformSigning (maker.ApplicationDirectory, project.SigningIdentity, file, outputWriter, errorWriter); } else { monitor.Log.WriteLine (GettextCatalog.GetString ("Signing with identity='{0}'", project.SigningIdentity)); CodeSign.PerformSigning (maker.ApplicationDirectory, project.SigningIdentity, outputWriter, errorWriter); } LoggingService.LogInfo ("CodeSign returns: " + outputWriter.ToString ()); } } monitor.EndTask (); } }
/// <summary> /// Combines the artwork. /// </summary> public static void EncryptContentFiles(IProgressMonitor monitor, MonobjcProject project, ConfigurationSelector configuration, BundleMaker maker) { IEnumerable<FilePair> files = project.GetEncryptedContentFiles (configuration, maker.ResourcesFolder); if (files == null || files.Count() == 0) { return; } Aes provider = FileEncrypter.GetProvider (project.EncryptionSeed); monitor.BeginTask (GettextCatalog.GetString ("Encrypting content files..."), files.Count ()); foreach (FilePair pair in files) { monitor.Log.WriteLine (GettextCatalog.GetString ("Encrypting {0}", pair.Source.ToRelative (project.BaseDirectory))); pair.Encrypt(provider); monitor.Step (1); } monitor.EndTask (); }
/// <summary> /// Embeds the XIB files. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'maker'>The bundle maker.</param> /// <param name = 'result'>The build result.</param> public static void EmbedXIBFiles(IProgressMonitor monitor, MonobjcProject project, BuildResult result) { XibCompiler xibCompiler = new XibCompiler (); IEnumerable<FilePair> files = project.GetIBFiles (Constants.EmbeddedInterfaceDefinition, null); if (files == null || files.Count() == 0) { return; } monitor.BeginTask (GettextCatalog.GetString ("Embed XIB files..."), files.Count ()); foreach (FilePair pair in files) { // If the destination file is a place-holder, change its dates FileInfo sourceInfo = new FileInfo (pair.Source); FileInfo destInfo = new FileInfo (pair.Destination); if (destInfo.Length == 0) { DateTime dateTime = sourceInfo.CreationTime.Subtract (new TimeSpan (0, 0, 1)); File.SetCreationTime (pair.Destination, dateTime); File.SetLastAccessTime (pair.Destination, dateTime); File.SetLastWriteTime (pair.Destination, dateTime); } FilePath relativeFile = pair.Source.ToRelative (project.BaseDirectory); monitor.Log.WriteLine (GettextCatalog.GetString ("Compiling {0}", relativeFile)); xibCompiler.Logger = new BuildLogger (pair.Source, monitor, result); xibCompiler.Compile (pair.Source, pair.DestinationDir); monitor.Step (1); } monitor.EndTask (); }
/// <summary> /// Creates the Info.plist file. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'configuration'>The configuration.</param> /// <param name = 'maker'>The bundle maker.</param> public static void CreateInfoPList(IProgressMonitor monitor, MonobjcProject project, ConfigurationSelector configuration, BundleMaker maker) { monitor.BeginTask (GettextCatalog.GetString ("Generating the Info.plist..."), 0); InfoPListGenerator pListGenerator = new InfoPListGenerator (); // If an Info.plist exists in the project then use it FilePath infoPListFile = project.BaseDirectory.Combine (Constants.INFO_PLIST); if (File.Exists (infoPListFile)) { pListGenerator.Content = File.ReadAllText (infoPListFile); } String mainAssembly = project.GetOutputFileName (configuration); Assembly assembly = Assembly.ReflectionOnlyLoadFrom (mainAssembly); AssemblyName assemblyName = assembly.GetName (); // TODO: Review to use new parameters pListGenerator.DevelopmentRegion = project.DevelopmentRegion; pListGenerator.ApplicationName = assemblyName.Name; pListGenerator.Identifier = project.BundleId; pListGenerator.Version = project.BundleVersion; pListGenerator.Icon = project.BundleIcon.IsNullOrEmpty ? null : project.BundleIcon.FileNameWithoutExtension; pListGenerator.MainNibFile = project.MainNibFile.IsNullOrEmpty ? null : project.MainNibFile.FileNameWithoutExtension; pListGenerator.TargetOSVersion = project.TargetOSVersion; pListGenerator.PrincipalClass = "NSApplication"; pListGenerator.WriteTo (Path.Combine (maker.ContentsDirectory, Constants.INFO_PLIST)); monitor.EndTask (); }
//FIXME: Check whether autogen.sh is required or not protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem entry, ConfigurationSelector configuration) { Project project = entry as Project; if (project == null) return base.Build (monitor, entry, configuration); MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.BuildTargetName)) return base.Build (monitor, entry, configuration); //FIXME: Gen autofoo ? autoreconf? string output = String.Empty; int exitCode = 0; monitor.BeginTask (GettextCatalog.GetString ("Building {0}", project.Name), 1); try { string baseDir = project.BaseDirectory; StringBuilder args = new StringBuilder (); if (data.RelativeMakeCommand.EndsWith ("make", StringComparison.OrdinalIgnoreCase)) args.AppendFormat (" -j {0}", data.ParallelProcesses, data.BuildTargetName); args.AppendFormat (" {0}", data.BuildTargetName); StringWriter swOutput = new StringWriter (); LogTextWriter chainedOutput = new LogTextWriter (); chainedOutput.ChainWriter (monitor.Log); chainedOutput.ChainWriter (swOutput); ProcessWrapper process = Runtime.ProcessService.StartProcess (data.AbsoluteMakeCommand, args.ToString (), baseDir, chainedOutput, chainedOutput, null); process.WaitForOutput (); exitCode = process.ExitCode; output = swOutput.ToString (); chainedOutput.Close (); swOutput.Close (); monitor.Step (1); } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ("Project could not be built: "), e); return null; } finally { monitor.EndTask (); } TempFileCollection tf = new TempFileCollection (); Regex regexError = data.GetErrorRegex (false); Regex regexWarning = data.GetWarningRegex (false); BuildResult cr = ParseOutput (tf, output, project.BaseDirectory, regexError, regexWarning); if (exitCode != 0 && cr.FailedBuildCount == 0) cr.AddError (GettextCatalog.GetString ("Build failed. See Build Output panel.")); else entry.SetNeedsBuilding (false, configuration); return cr; }
/// <summary> /// Copies the Monobjc assemblies. /// </summary> /// <param name="monitor">The monitor.</param> /// <param name="project">The project.</param> /// <param name="configuration">The configuration.</param> /// <param name="maker">The maker.</param> public static void CopyMonobjcAssemblies(IProgressMonitor monitor, MonobjcProject project, ConfigurationSelector configuration, BundleMaker maker) { IEnumerable<String> assemblies = project.ProjectMonobjcAssemblies.Select (a => a.GetReferencedFileNames (configuration) [0]); monitor.BeginTask (GettextCatalog.GetString ("Copying Monobjc assemblies..."), assemblies.Count ()); foreach (String assembly in assemblies) { String filename = Path.GetFileName (assembly); monitor.Log.WriteLine (GettextCatalog.GetString ("Copying {0}", filename)); File.Copy (assembly, Path.Combine (maker.ResourcesFolder, filename), true); monitor.Step (1); } monitor.EndTask (); }
public static void Initialize (IProgressMonitor monitor) { Counters.Initialization.Trace ("Creating Workbench"); workbench = new Workbench (); Counters.Initialization.Trace ("Creating Root Workspace"); workspace = new RootWorkspace (); Counters.Initialization.Trace ("Creating Services"); projectOperations = new ProjectOperations (); helpOperations = new HelpOperations (); commandService = new CommandManager (); ideServices = new IdeServices (); CustomToolService.Init (); AutoTestService.Start (commandService, Preferences.EnableAutomatedTesting); commandService.CommandTargetScanStarted += CommandServiceCommandTargetScanStarted; commandService.CommandTargetScanFinished += CommandServiceCommandTargetScanFinished; KeyBindingService.LoadBindingsFromExtensionPath ("/MonoDevelop/Ide/KeyBindingSchemes"); KeyBindingService.LoadCurrentBindings ("MD2"); commandService.CommandError += delegate (object sender, CommandErrorArgs args) { MessageService.ShowException (args.Exception, args.ErrorMessage); }; FileService.ErrorHandler = FileServiceErrorHandler; monitor.BeginTask (GettextCatalog.GetString("Loading Workbench"), 5); Counters.Initialization.Trace ("Loading Commands"); commandService.LoadCommands ("/MonoDevelop/Ide/Commands"); monitor.Step (1); Counters.Initialization.Trace ("Initializing Workbench"); workbench.Initialize (monitor); monitor.Step (1); InternalLog.EnableErrorNotification (); monitor.Step (1); Counters.Initialization.Trace ("Restoring Workbench State"); workbench.Show ("SharpDevelop.Workbench.WorkbenchMemento"); monitor.Step (1); Counters.Initialization.Trace ("Flushing GUI events"); DispatchService.RunPendingEvents (); Counters.Initialization.Trace ("Flushed GUI events"); MessageService.RootWindow = workbench.RootWindow; commandService.EnableIdleUpdate = true; // Default file format MonoDevelop.Projects.Services.ProjectServiceLoaded += delegate(object sender, EventArgs e) { ((ProjectService)sender).DefaultFileFormatId = IdeApp.Preferences.DefaultProjectFileFormat; }; IdeApp.Preferences.DefaultProjectFileFormatChanged += delegate { IdeApp.Services.ProjectService.DefaultFileFormatId = IdeApp.Preferences.DefaultProjectFileFormat; }; // Perser service initialization MonoDevelop.Projects.Dom.Parser.ProjectDomService.TrackFileChanges = true; MonoDevelop.Projects.Dom.Parser.ProjectDomService.ParseProgressMonitorFactory = new ParseProgressMonitorFactory (); // Startup commands Counters.Initialization.Trace ("Running Startup Commands"); AddinManager.AddExtensionNodeHandler ("/MonoDevelop/Ide/StartupHandlers", OnExtensionChanged); monitor.EndTask (); // Set initial run flags Counters.Initialization.Trace ("Upgrading Settings"); if (PropertyService.Get("MonoDevelop.Core.FirstRun", false)) { isInitialRun = true; PropertyService.Set ("MonoDevelop.Core.FirstRun", false); PropertyService.Set ("MonoDevelop.Core.LastRunVersion", BuildVariables.PackageVersion); PropertyService.Set ("MonoDevelop.Core.LastRunVersion", CurrentRevision); PropertyService.SaveProperties (); } string lastVersion = PropertyService.Get ("MonoDevelop.Core.LastRunVersion", "1.9.1"); int lastRevision = PropertyService.Get ("MonoDevelop.Core.LastRunRevision", 0); if (lastRevision != CurrentRevision && !isInitialRun) { isInitialRunAfterUpgrade = true; if (lastRevision == 0) { switch (lastVersion) { case "1.0": lastRevision = 1; break; case "2.0": lastRevision = 2; break; case "2.2": lastRevision = 3; break; case "2.2.1": lastRevision = 4; break; } } upgradedFromRevision = lastRevision; PropertyService.Set ("MonoDevelop.Core.LastRunVersion", BuildVariables.PackageVersion); PropertyService.Set ("MonoDevelop.Core.LastRunRevision", CurrentRevision); PropertyService.SaveProperties (); } // The ide is now initialized isInitialized = true; if (isInitialRun) { try { OnInitialRun (); } catch (Exception e) { LoggingService.LogError ("Error found while initializing the IDE", e); } } if (isInitialRunAfterUpgrade) { try { OnUpgraded (upgradedFromRevision); } catch (Exception e) { LoggingService.LogError ("Error found while initializing the IDE", e); } } if (initializedEvent != null) initializedEvent (null, EventArgs.Empty); // load previous combine if ((bool)PropertyService.Get("SharpDevelop.LoadPrevProjectOnStartup", false)) { RecentOpen recentOpen = Workbench.RecentOpen; if (recentOpen.RecentProjectsCount > 0) { IdeApp.Workspace.OpenWorkspaceItem(recentOpen.RecentProjects.First ().ToString()).WaitForCompleted (); } } commandService.CommandSelected += OnCommandSelected; commandService.CommandDeselected += OnCommandDeselected; //FIXME: we should really make this on-demand. consumers can display a "loading help cache" message like VS MonoDevelop.Projects.HelpService.AsyncInitialize (); UpdateInstrumentationIcon (); IdeApp.Preferences.EnableInstrumentationChanged += delegate { UpdateInstrumentationIcon (); }; AutoTestService.NotifyEvent ("MonoDevelop.Ide.IdeStart"); }
// 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.")); }
public XcodeSyncBackContext GetChanges (IProgressMonitor monitor, NSObjectInfoService infoService, DotNetProject project) { var ctx = new XcodeSyncBackContext (projectDir, syncTimeCache, infoService, project); var needsSync = new List<XcodeSyncedItem> (items.Where (i => i.NeedsSyncBack (monitor, ctx))); var knownFiles = GetKnownFiles (); if (Directory.Exists (projectDir)) { monitor.BeginTask ("Scanning for newly-added files in the Xcode project...", 0); ScanForAddedFiles (monitor, ctx, knownFiles, projectDir, null); monitor.EndTask (); } if (needsSync.Count > 0) { monitor.BeginStepTask (GettextCatalog.GetString ("Synchronizing changes made to known files in Xcode back to MonoDevelop..."), needsSync.Count, 1); for (int i = 0; i < needsSync.Count; i++) { var item = needsSync [i]; item.SyncBack (monitor, ctx); monitor.Step (1); } monitor.EndTask (); } return ctx; }
public override void Revert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) { foreach (var group in localPaths.GroupBy (f => GetRepository (f))) { var repository = group.Key; var files = group.ToArray (); var c = GetHeadCommit (repository); RevTree tree = c != null ? c.Tree : null; List<FilePath> changedFiles = new List<FilePath> (); List<FilePath> removedFiles = new List<FilePath> (); monitor.BeginTask (GettextCatalog.GetString ("Reverting files"), 3); monitor.BeginStepTask (GettextCatalog.GetString ("Reverting files"), files.Length, 2); DirCache dc = repository.LockDirCache (); DirCacheBuilder builder = dc.Builder (); try { HashSet<string> entriesToRemove = new HashSet<string> (); HashSet<string> foldersToRemove = new HashSet<string> (); // Add the new entries foreach (FilePath fp in files) { string p = repository.ToGitPath (fp); // Register entries to be removed from the index if (Directory.Exists (fp)) foldersToRemove.Add (p); else entriesToRemove.Add (p); TreeWalk tw = tree != null ? TreeWalk.ForPath (repository, p, tree) : null; if (tw == null) { // Removed from the index } else { // Add new entries TreeWalk r; if (tw.IsSubtree) { // It's a directory. Make sure we remove existing index entries of this directory foldersToRemove.Add (p); // We have to iterate through all folder files. We need a new iterator since the // existing rw is not recursive r = new NGit.Treewalk.TreeWalk(repository); r.Reset (tree); r.Filter = PathFilterGroup.CreateFromStrings(new string[]{p}); r.Recursive = true; r.Next (); } else { r = tw; } do { // There can be more than one entry if reverting a whole directory string rpath = repository.FromGitPath (r.PathString); DirCacheEntry e = new DirCacheEntry (r.PathString); e.SetObjectId (r.GetObjectId (0)); e.FileMode = r.GetFileMode (0); if (!Directory.Exists (Path.GetDirectoryName (rpath))) Directory.CreateDirectory (rpath); DirCacheCheckout.CheckoutEntry (repository, rpath, e); builder.Add (e); changedFiles.Add (rpath); } while (r.Next ()); } monitor.Step (1); } // Add entries we want to keep int count = dc.GetEntryCount (); for (int n=0; n<count; n++) { DirCacheEntry e = dc.GetEntry (n); string path = e.PathString; if (!entriesToRemove.Contains (path) && !foldersToRemove.Any (f => IsSubpath (f,path))) builder.Add (e); } builder.Commit (); } catch { dc.Unlock (); throw; } monitor.EndTask (); monitor.BeginTask (null, files.Length); foreach (FilePath p in changedFiles) { FileService.NotifyFileChanged (p); monitor.Step (1); } foreach (FilePath p in removedFiles) { FileService.NotifyFileRemoved (p); monitor.Step (1); } monitor.EndTask (); } }
public void Merge (string branch, bool saveLocalChanges, IProgressMonitor monitor) { IEnumerable<DiffEntry> statusList = null; Stash stash = null; StashCollection stashes = GetStashes (RootRepository); monitor.BeginTask (null, 4); try { // Get a list of files that are different in the target branch statusList = GitUtil.GetChangedFiles (RootRepository, branch); monitor.Step (1); if (saveLocalChanges) { monitor.BeginTask (GettextCatalog.GetString ("Merging"), 3); monitor.Log.WriteLine (GettextCatalog.GetString ("Saving local changes")); using (var gm = new GitMonitor (monitor)) stash = stashes.Create (gm, GetStashName ("_tmp_")); monitor.Step (1); } // Apply changes ObjectId branchId = RootRepository.Resolve (branch); NGit.Api.Git git = new NGit.Api.Git (RootRepository); MergeCommandResult mergeResult = git.Merge ().SetStrategy (MergeStrategy.RESOLVE).Include (branchId).Call (); if (mergeResult.GetMergeStatus () == MergeStatus.CONFLICTING || mergeResult.GetMergeStatus () == MergeStatus.FAILED) { var conflicts = mergeResult.GetConflicts (); bool commit = true; if (conflicts != null) { foreach (string conflictFile in conflicts.Keys) { ConflictResult res = ResolveConflict (RootRepository.FromGitPath (conflictFile)); if (res == ConflictResult.Abort) { GitUtil.HardReset (RootRepository, GetHeadCommit (RootRepository)); commit = false; break; } else if (res == ConflictResult.Skip) { Revert (RootRepository.FromGitPath (conflictFile), false, monitor); break; } } } if (commit) git.Commit ().Call (); } } finally { if (saveLocalChanges) monitor.Step (1); // Restore local changes if (stash != null) { monitor.Log.WriteLine (GettextCatalog.GetString ("Restoring local changes")); using (var gm = new GitMonitor (monitor)) stash.Apply (gm); stashes.Remove (stash); monitor.EndTask (); } } monitor.Step (1); // Notify changes if (statusList != null) NotifyFileChanges (monitor, statusList); monitor.EndTask (); }
/// <summary> /// Combines the artwork. /// </summary> public static void CombineArtwork(IProgressMonitor monitor, MonobjcProject project, BundleMaker maker) { if (!project.CombineArtwork) { return; } monitor.BeginTask (GettextCatalog.GetString ("Combining artwork..."), 0); using (StringWriter outputWriter = new StringWriter()) { using (StringWriter errorWriter = new StringWriter()) { ArtworkCombiner combiner = new ArtworkCombiner(); combiner.Combine(maker.ResourcesFolder, outputWriter, errorWriter); LoggingService.LogInfo ("Combiner returns: " + outputWriter.ToString ()); } } monitor.EndTask (); }
/// <summary> /// Copies the content files. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'configuration'>The configuration.</param> /// <param name = 'maker'>The bundle maker.</param> public static void CopyOutputFiles(IProgressMonitor monitor, MonobjcProject project, ConfigurationSelector configuration, BundleMaker maker) { IEnumerable<FilePair> files = project.GetOutputFiles (configuration, maker.ResourcesFolder); if (files == null || files.Count() == 0) { return; } monitor.BeginTask (GettextCatalog.GetString ("Copying output files..."), files.Count ()); foreach (FilePair pair in files) { monitor.Log.WriteLine (GettextCatalog.GetString ("Copying {0}", pair.Source.ToRelative (project.BaseDirectory))); pair.Copy (false); monitor.Step (1); } monitor.EndTask (); }
/// <summary> /// Compiles the XIB files. /// </summary> /// <param name = 'monitor'>The progress monitor.</param> /// <param name = 'project'>The project.</param> /// <param name = 'maker'>The bundle maker.</param> /// <param name = 'result'>The build result.</param> public static void CompileXIBFiles(IProgressMonitor monitor, MonobjcProject project, BundleMaker maker, BuildResult result) { XibCompiler xibCompiler = new XibCompiler (); IEnumerable<FilePair> files = project.GetIBFiles (Constants.InterfaceDefinition, maker.ResourcesFolder); if (files == null || files.Count() == 0) { return; } List<FilePair> pairs = new List<FilePair> (files); monitor.BeginTask (GettextCatalog.GetString ("Compiling XIB files..."), files.Count ()); foreach (FilePair pair in pairs) { monitor.Log.WriteLine (GettextCatalog.GetString ("Compiling {0}", pair.Source.ToRelative (project.BaseDirectory))); xibCompiler.Logger = new BuildLogger (pair.Source, monitor, result); xibCompiler.Compile (pair.Source, pair.DestinationDir); monitor.Step (1); } monitor.EndTask (); }
protected override void Execute (IProgressMonitor monitor, SolutionEntityItem entry, ExecutionContext context, ConfigurationSelector configuration) { Project project = entry as Project; if (project == null) { base.Execute (monitor, entry, context, configuration); return; } MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty (data.ExecuteTargetName)) { base.Execute (monitor, entry, context, configuration); return; } IConsole console = context.ConsoleFactory.CreateConsole (true); monitor.BeginTask (GettextCatalog.GetString ("Executing {0}", project.Name), 1); try { ProcessWrapper process = Runtime.ProcessService.StartProcess (data.AbsoluteMakeCommand, data.ExecuteTargetName, project.BaseDirectory, console.Out, console.Error, null); process.WaitForOutput (); monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", process.ExitCode)); monitor.Step (1); } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ("Project could not be executed: "), e); return; } finally { monitor.EndTask (); console.Dispose (); } }
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")); }
public override void MoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor) { VersionInfo[] versionedFiles = GetDirectoryVersionInfo (localSrcPath, false, true); base.MoveDirectory (localSrcPath, localDestPath, force, monitor); monitor.BeginTask ("Moving files", versionedFiles.Length); foreach (VersionInfo vif in versionedFiles) { if (vif.IsDirectory) continue; FilePath newDestPath = vif.LocalPath.ToRelative (localSrcPath).ToAbsolute (localDestPath); Add (newDestPath, false, monitor); monitor.Step (1); } monitor.EndTask (); }
protected override SolutionEntityItem LoadSolutionItem (IProgressMonitor monitor, string fileName) { SolutionEntityItem entry = base.LoadSolutionItem (monitor, fileName); if (entry == null) return null; Project project = entry as Project; if (project == null) return entry; //Project MakefileData data = entry.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData; if (data == null) return entry; monitor.BeginTask (GettextCatalog.GetString ("Updating project from Makefile"), 1); try { data.OwnerProject = project; if (data.SupportsIntegration) data.UpdateProject (monitor, false); monitor.Step (1); } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ( "Error loading Makefile for project {0}", project.Name), e); } finally { monitor.EndTask (); } entry.SetNeedsBuilding (false); return entry; }
public override void Update (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) { IEnumerable<DiffEntry> statusList = null; monitor.BeginTask (GettextCatalog.GetString ("Updating"), 5); // Fetch remote commits string remote = GetCurrentRemote (); if (remote == null) throw new InvalidOperationException ("No remotes defined"); monitor.Log.WriteLine (GettextCatalog.GetString ("Fetching from '{0}'", remote)); RemoteConfig remoteConfig = new RemoteConfig (RootRepository.GetConfig (), remote); Transport tn = Transport.Open (RootRepository, remoteConfig); using (var gm = new GitMonitor (monitor)) tn.Fetch (gm, null); monitor.Step (1); string upstreamRef = GitUtil.GetUpstreamSource (RootRepository, GetCurrentBranch ()); if (upstreamRef == null) upstreamRef = GetCurrentRemote () + "/" + GetCurrentBranch (); if (GitService.UseRebaseOptionWhenPulling) Rebase (upstreamRef, GitService.StashUnstashWhenUpdating, monitor); else Merge (upstreamRef, GitService.StashUnstashWhenUpdating, monitor); monitor.Step (1); // Notify changes if (statusList != null) NotifyFileChanges (monitor, statusList); monitor.EndTask (); }
public void TransferFiles (IProgressMonitor monitor, Project sourceProject, FilePath sourcePath, Project targetProject, FilePath targetPath, bool removeFromSource, bool copyOnlyProjectFiles) { // When transfering directories, targetPath is the directory where the source // directory will be transfered, including the destination directory or file name. // For example, if sourcePath is /a1/a2/a3 and targetPath is /b1/b2, the // new folder or file will be /b1/b2 if (targetProject == null) throw new ArgumentNullException ("targetProject"); if (!targetPath.IsChildPathOf (targetProject.BaseDirectory)) throw new ArgumentException ("Invalid project folder: " + targetPath); if (sourceProject != null && !sourcePath.IsChildPathOf (sourceProject.BaseDirectory)) throw new ArgumentException ("Invalid project folder: " + sourcePath); if (copyOnlyProjectFiles && sourceProject == null) throw new ArgumentException ("A source project must be specified if copyOnlyProjectFiles is True"); bool sourceIsFolder = Directory.Exists (sourcePath); bool movingFolder = (removeFromSource && sourceIsFolder && ( !copyOnlyProjectFiles || IsDirectoryHierarchyEmpty (sourcePath))); // We need to remove all files + directories from the source project // but when dealing with the VCS addins we need to process only the // files so we do not create a 'file' in the VCS which corresponds // to a directory in the project and blow things up. List<ProjectFile> filesToRemove = null; List<ProjectFile> filesToMove = null; try { //get the real ProjectFiles if (sourceProject != null) { if (sourceIsFolder) { var virtualPath = sourcePath.ToRelative (sourceProject.BaseDirectory); // Grab all the child nodes of the folder we just dragged/dropped filesToRemove = sourceProject.Files.GetFilesInVirtualPath (virtualPath).ToList (); // Add the folder itself so we can remove it from the soruce project if its a Move operation var folder = sourceProject.Files.Where (f => f.ProjectVirtualPath == virtualPath).FirstOrDefault (); if (folder != null) filesToRemove.Add (folder); } else { filesToRemove = new List<ProjectFile> (); var pf = sourceProject.Files.GetFileWithVirtualPath (sourceProject.GetRelativeChildPath (sourcePath)); if (pf != null) filesToRemove.Add (pf); } } //get all the non-project files and create fake ProjectFiles if (!copyOnlyProjectFiles || sourceProject == null) { var col = new List<ProjectFile> (); GetAllFilesRecursive (sourcePath, col); if (sourceProject != null) { var names = new HashSet<string> (filesToRemove.Select (f => sourceProject.BaseDirectory.Combine (f.ProjectVirtualPath).ToString ())); foreach (var f in col) if (names.Add (f.Name)) filesToRemove.Add (f); } else { filesToRemove = col; } } } catch (Exception ex) { monitor.ReportError (GettextCatalog.GetString ("Could not get any file from '{0}'.", sourcePath), ex); return; } // Strip out all the directories to leave us with just the files. filesToMove = filesToRemove.Where (f => f.Subtype != Subtype.Directory).ToList (); // If copying a single file, bring any grouped children along ProjectFile sourceParent = null; if (filesToMove.Count == 1 && sourceProject != null) { var pf = filesToMove[0]; if (pf != null && pf.HasChildren) foreach (ProjectFile child in pf.DependentChildren) filesToMove.Add (child); sourceParent = pf; } // Ensure that the destination folder is created, even if no files // are copied try { if (sourceIsFolder && !Directory.Exists (targetPath) && !movingFolder) FileService.CreateDirectory (targetPath); } catch (Exception ex) { monitor.ReportError (GettextCatalog.GetString ("Could not create directory '{0}'.", targetPath), ex); return; } // Transfer files // If moving a folder, do it all at once if (movingFolder) { try { FileService.MoveDirectory (sourcePath, targetPath); } catch (Exception ex) { monitor.ReportError (GettextCatalog.GetString ("Directory '{0}' could not be moved.", sourcePath), ex); return; } } monitor.BeginTask (GettextCatalog.GetString ("Copying files..."), filesToMove.Count); ProjectFile targetParent = null; foreach (ProjectFile file in filesToMove) { bool fileIsLink = file.Project != null && file.IsLink; var sourceFile = fileIsLink ? file.Project.BaseDirectory.Combine (file.ProjectVirtualPath) : file.FilePath; FilePath newFile; if (sourceIsFolder) newFile = targetPath.Combine (sourceFile.ToRelative (sourcePath)); else if (sourceFile == sourcePath) newFile = targetPath; else if (sourceFile.ParentDirectory != targetPath.ParentDirectory) newFile = targetPath.ParentDirectory.Combine (sourceFile.ToRelative (sourcePath.ParentDirectory)); else newFile = GetTargetCopyName (sourceFile, false); if (!movingFolder && !fileIsLink) { try { FilePath fileDir = newFile.ParentDirectory; if (!Directory.Exists (fileDir) && !file.IsLink) FileService.CreateDirectory (fileDir); if (removeFromSource) FileService.MoveFile (sourceFile, newFile); else FileService.CopyFile (sourceFile, newFile); } catch (Exception ex) { monitor.ReportError (GettextCatalog.GetString ("File '{0}' could not be created.", newFile), ex); monitor.Step (1); continue; } } if (sourceProject != null) { if (fileIsLink) { var linkFile = (ProjectFile) file.Clone (); if (movingFolder) { var abs = linkFile.Link.ToAbsolute (sourceProject.BaseDirectory); var relSrc = abs.ToRelative (sourcePath); var absTarg = relSrc.ToAbsolute (targetPath); linkFile.Link = absTarg.ToRelative (targetProject.BaseDirectory); } else { linkFile.Link = newFile.ToRelative (targetProject.BaseDirectory); } targetProject.Files.Add (linkFile); } else if (targetProject.Files.GetFile (newFile) == null) { ProjectFile projectFile = (ProjectFile) file.Clone (); projectFile.Name = newFile; if (targetParent == null) { if (file == sourceParent) targetParent = projectFile; } else if (sourceParent != null) { if (projectFile.DependsOn == sourceParent.Name) projectFile.DependsOn = targetParent.Name; } targetProject.Files.Add (projectFile); } } monitor.Step (1); } if (removeFromSource) { // Remove all files and directories under 'sourcePath' foreach (var v in filesToRemove) sourceProject.Files.Remove (v); } var pfolder = sourcePath.ParentDirectory; // If this was the last item in the folder, make sure we keep // a reference to the folder, so it is not deleted from the tree. if (removeFromSource && sourceProject != null && pfolder.CanonicalPath != sourceProject.BaseDirectory.CanonicalPath && pfolder.IsChildPathOf (sourceProject.BaseDirectory)) { pfolder = pfolder.ToRelative (sourceProject.BaseDirectory); if (!sourceProject.Files.GetFilesInVirtualPath (pfolder).Any ()) { var folderFile = new ProjectFile (sourceProject.BaseDirectory.Combine (pfolder)); folderFile.Subtype = Subtype.Directory; sourceProject.Files.Add (folderFile); } } monitor.EndTask (); }
public void Rebase (string upstreamRef, bool saveLocalChanges, IProgressMonitor monitor) { StashCollection stashes = GitUtil.GetStashes (RootRepository); Stash stash = null; try { if (saveLocalChanges) { monitor.BeginTask (GettextCatalog.GetString ("Rebasing"), 3); monitor.Log.WriteLine (GettextCatalog.GetString ("Saving local changes")); using (var gm = new GitMonitor (monitor)) stash = stashes.Create (gm, GetStashName ("_tmp_")); monitor.Step (1); } NGit.Api.Git git = new NGit.Api.Git (RootRepository); RebaseCommand rebase = git.Rebase (); rebase.SetOperation (RebaseCommand.Operation.BEGIN); rebase.SetUpstream (upstreamRef); var gmonitor = new GitMonitor (monitor); rebase.SetProgressMonitor (gmonitor); bool aborted = false; try { var result = rebase.Call (); while (!aborted && result.GetStatus () == RebaseResult.Status.STOPPED) { rebase = git.Rebase (); rebase.SetProgressMonitor (gmonitor); rebase.SetOperation (RebaseCommand.Operation.CONTINUE); bool commitChanges = true; var conflicts = GitUtil.GetConflictedFiles (RootRepository); foreach (string conflictFile in conflicts) { ConflictResult res = ResolveConflict (RootRepository.FromGitPath (conflictFile)); if (res == ConflictResult.Abort) { aborted = true; commitChanges = false; rebase.SetOperation (RebaseCommand.Operation.ABORT); break; } else if (res == ConflictResult.Skip) { rebase.SetOperation (RebaseCommand.Operation.SKIP); commitChanges = false; break; } } if (commitChanges) { NGit.Api.AddCommand cmd = git.Add (); foreach (string conflictFile in conflicts) cmd.AddFilepattern (conflictFile); cmd.Call (); } result = rebase.Call (); } } catch { if (!aborted) { rebase = git.Rebase (); rebase.SetOperation (RebaseCommand.Operation.ABORT); rebase.SetProgressMonitor (gmonitor); rebase.Call (); } throw; } finally { gmonitor.Dispose (); } } finally { if (saveLocalChanges) monitor.Step (1); // Restore local changes if (stash != null) { monitor.Log.WriteLine (GettextCatalog.GetString ("Restoring local changes")); using (var gm = new GitMonitor (monitor)) stash.Apply (gm); stashes.Remove (stash); monitor.EndTask (); } } }