public override void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context)
		{
			DirectoryInfo tempDir = null;
			try {
				tempDir = CreateTempDir ();
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not create temporary directory."), e);
				return;
			}
			
			try {
				MountTempDirectory (copyConfig, tempDir.FullName);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not mount FUSE filesystem."), e);
				RemoveTempDirIfEmpty (tempDir);
				return;
			}
			
			try {
				base.InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, tempDir.FullName);
			} finally {
				try {
					//unmount the fuse directory
					RunFuseCommand ("fusermount", string.Format ("-u \"{0}\"", tempDir.FullName));
				} catch (Exception e) {
					monitor.ReportError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
				}
				RemoveTempDirIfEmpty (tempDir);
			}
		}
		protected override bool OnBuild (IProgressMonitor monitor, DeployContext ctx)
		{
			string tmpFolder = null;
			
			try {
				SolutionConfigurationSelector conf = (SolutionConfigurationSelector) configuration;
				if (RootSolutionItem.NeedsBuilding (conf)) {
					BuildResult res = RootSolutionItem.Build (monitor, conf);
					if (res.ErrorCount > 0) {
						foreach (BuildError e in res.Errors)
							monitor.ReportError (e.ToString (), null);
						monitor.ReportError (GettextCatalog.GetString ("The source project failed to build."), null);
						return false;
					}
				}
				
				tmpFolder = FileService.CreateTempDirectory ();
				
				string tf = Path.GetFileNameWithoutExtension (targetFile);
				if (tf.EndsWith (".tar")) tf = Path.GetFileNameWithoutExtension (tf);
				string folder = FileService.GetFullPath (Path.Combine (tmpFolder, tf));
				
				// Export the binary files
				DeployFileCollection deployFiles = GetDeployFiles (ctx, conf);
				foreach (DeployFile file in deployFiles) {
					string tfile = Path.Combine (folder, file.ResolvedTargetFile);
					string tdir = FileService.GetFullPath (Path.GetDirectoryName (tfile));
					if (!Directory.Exists (tdir))
						Directory.CreateDirectory (tdir);
					File.Copy (file.SourcePath, tfile, true);
				}
				
				// Create the archive
				string td = Path.GetDirectoryName (targetFile);
				if (!Directory.Exists (td))
					Directory.CreateDirectory (td);
				DeployService.CreateArchive (monitor, tmpFolder, targetFile);
			}
			catch (Exception ex) {
				monitor.ReportError ("Package creation failed", ex);
				LoggingService.LogError ("Package creation failed", ex);
				return false;
			}
			finally {
				if (tmpFolder != null)
					Directory.Delete (tmpFolder, true);
			}
			if (monitor.AsyncOperation.Success)
				monitor.Log.WriteLine (GettextCatalog.GetString ("Created file: {0}", targetFile));
			return true;
		}
        protected override void DoExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            IodineConfiguration config = (IodineConfiguration)GetConfiguration (configuration);
            IConsole console = config.ExternalConsole ?
                context.ExternalConsoleFactory.CreateConsole (!config.PauseConsoleOutput) :
                context.ConsoleFactory.CreateConsole (!config.PauseConsoleOutput);

            AggregatedOperationMonitor aggregatedMonitor = new AggregatedOperationMonitor (monitor);
            try {
                string param = string.Format ("\"{0}\" {1}", config.MainFile, config.CommandLineParameters);

                IProcessAsyncOperation op = Runtime.ProcessService.StartConsoleProcess ("iodine",
                        param, BaseDirectory,
                        config.EnvironmentVariables, console, null);

                monitor.CancelRequested += delegate {
                    op.Cancel ();
                };

                aggregatedMonitor.AddOperation (op);
                op.WaitForCompleted ();
                monitor.Log.WriteLine ("Iodine exited with code: " + op.ExitCode);

            } catch (Exception e) {
                monitor.ReportError (GettextCatalog.GetString ("Cannot execute \"{0}\"", config.MainFile), e);
            } finally {
                console.Dispose ();
                aggregatedMonitor.Dispose ();
            }
        }
示例#4
0
        public static object ReadFile_(string file, Type expectedType, IProgressMonitor monitor)
        {
            bool clearLoadedPrjList = AlreadyLoadedPackages == null;
            if (clearLoadedPrjList)
                AlreadyLoadedPackages = new List<string> ();

            if (AlreadyLoadedPackages.Contains (file))
                return null;
            AlreadyLoadedPackages.Add (file);

            DubProject defaultPackage;
            try{
                using (var s = File.OpenText (file))
                using (var r = new JsonTextReader (s))
                    defaultPackage = ReadPackageInformation(file, r, monitor);
            }catch(Exception ex){
                if (clearLoadedPrjList)
                    AlreadyLoadedPackages = null;
                monitor.ReportError ("Couldn't load dub package \"" + file + "\"", ex);
                return null;
            }

            if (expectedType.IsInstanceOfType (defaultPackage)) {
                LoadDubProjectReferences (defaultPackage, monitor);

                if (clearLoadedPrjList)
                    AlreadyLoadedPackages = null;

                return defaultPackage;
            }

            var sln = new DubSolution();

            if (!expectedType.IsInstanceOfType (sln)) {
                if (clearLoadedPrjList)
                    AlreadyLoadedPackages = null;
                return null;
            }

            sln.RootFolder.AddItem(defaultPackage, false);
            sln.StartupItem = defaultPackage;

            // Introduce solution configurations
            foreach (var cfg in defaultPackage.Configurations)
                sln.AddConfiguration(cfg.Name, false).Platform = cfg.Platform;

            LoadDubProjectReferences (defaultPackage, monitor, sln);

            sln.LoadUserProperties();

            if (clearLoadedPrjList) {
                AlreadyLoadedPackages = null;

                // Clear 'dub list' outputs
                DubReferencesCollection.DubListOutputs.Clear ();
            }

            return sln;
        }
        bool SyncXcodeChanges(IProgressMonitor monitor)
        {
            try {
                monitor.BeginTask(GettextCatalog.GetString("Detecting changed files in Xcode"), 0);
                var changeCtx = xcode.GetChanges(monitor, infoService, dnp);
                monitor.EndTask();

                updatingProjectFiles = true;
                bool filesAdded = false;
                bool typesAdded = false;

                // First, copy any changed/added resource files to MonoDevelop's project directory.
                CopyFilesToMD(monitor, changeCtx);

                // Then update CLI types.
                if (UpdateCliTypes(monitor, changeCtx, out typesAdded))
                {
                    filesAdded = true;
                }

                // Next, parse UI definition files for custom classes
                if (AddCustomClassesFromUIDefinitionFiles(monitor, changeCtx))
                {
                    typesAdded = true;
                }

                // Finally, add any newly created resource files to the DotNetProject.
                if (AddFilesToMD(monitor, changeCtx))
                {
                    filesAdded = true;
                }

                // Save the DotNetProject.
                if (filesAdded || typesAdded)
                {
                    Ide.IdeApp.ProjectOperations.Save(dnp);
                }

                // Notify MonoDevelop of file changes.
                Gtk.Application.Invoke(delegate {
                    // FIXME: this should probably filter out any IsFreshlyAdded file jobs
                    FileService.NotifyFilesChanged(changeCtx.FileSyncJobs.Select(f => f.Original));
                });

                if (typesAdded)
                {
                    UpdateXcodeProject(monitor);
                }

                return(true);
            } catch (Exception ex) {
                monitor.ReportError(GettextCatalog.GetString("Error synchronizing changes from Xcode"), ex);
                return(false);
            } finally {
                updatingProjectFiles = false;
            }
        }
        protected override BuildResult OnBuild(IProgressMonitor monitor, ConfigurationSelector configuration)
        {
            ReadOnlyCollection <SolutionItem> allProjects;

            try
            {
                allProjects = GetAllBuildableEntries(configuration, true, true);
            }
            catch (CyclicDependencyException)
            {
                monitor.ReportError(GettextCatalog.GetString("Cyclic dependencies are not supported."), null);
                return(new BuildResult("", 1, 1));
            }

            try
            {
                List <SolutionItem> toBuild = new List <SolutionItem> (allProjects.Where(p => p.NeedsBuilding(configuration)));

                monitor.BeginTask(GettextCatalog.GetString("Building Solution: {0} ({1})", Name, configuration.ToString()), toBuild.Count);

                BuildResult cres = new BuildResult();
                cres.BuildCount = 0;
                HashSet <SolutionItem> failedItems = new HashSet <SolutionItem> ();

                foreach (SolutionItem item in toBuild)
                {
                    if (monitor.IsCancelRequested)
                    {
                        break;
                    }

                    if (!item.ContainsReferences(failedItems, configuration))
                    {
                        BuildResult res = item.Build(monitor, configuration, false);
                        if (res != null)
                        {
                            cres.Append(res);
                            if (res.ErrorCount > 0)
                            {
                                failedItems.Add(item);
                            }
                        }
                    }
                    else
                    {
                        failedItems.Add(item);
                    }
                    monitor.Step(1);
                }
                return(cres);
            }
            finally
            {
                monitor.EndTask();
            }
        }
示例#7
0
        /// <summary>
        /// Executes a file and reports events related to the execution to the 'monitor' passed in the parameters.
        /// </summary>
        public static int ExecuteCommand(
            string command,
            string args,
            string baseDirectory,

            IProgressMonitor monitor,
            out string errorOutput,
            out string programOutput)
        {
            errorOutput = string.Empty;
            int exitCode = -1;

            var swError  = new StringWriter();
            var swOutput = new StringWriter();

            var chainedError = new LogTextWriter();

            chainedError.ChainWriter(monitor.Log);
            chainedError.ChainWriter(swError);

            var chainedOutput = new LogTextWriter();

            chainedOutput.ChainWriter(monitor.Log);
            chainedOutput.ChainWriter(swOutput);

            monitor.Log.WriteLine("{0} {1}", command, args);

            var operationMonitor = new AggregatedOperationMonitor(monitor);
            var p = Runtime.ProcessService.StartProcess(command, args, baseDirectory, chainedOutput, chainedError, null);

            operationMonitor.AddOperation(p);              //handles cancellation


            p.WaitForOutput();
            errorOutput   = swError.ToString();
            programOutput = swOutput.ToString();
            exitCode      = p.ExitCode;
            p.Dispose();

            if (monitor.IsCancelRequested)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Build cancelled"));
                monitor.ReportError(GettextCatalog.GetString("Build cancelled"), null);
                if (exitCode == 0)
                {
                    exitCode = -1;
                }
            }
            {
                chainedError.Close();
                swError.Close();
                operationMonitor.Dispose();
            }

            return(exitCode);
        }
示例#8
0
        private void RealOpenFile(IProgressMonitor monitor, FileOpenInfo openFileInfo)
        {
            FilePath fileName = openFileInfo.FileName;

            if (fileName == (FilePath)((string)null))
            {
                monitor.ReportError("Invalid file name", (Exception)null);
            }
            else if (fileName.IsDirectory)
            {
                monitor.ReportError(string.Format("{0} is a directory", (object)fileName), (Exception)null);
            }
            else if (!File.Exists((string)fileName))
            {
                monitor.ReportError(string.Format("File not found: {0}", (object)fileName), (Exception)null);
            }
            else
            {
                Project             project = openFileInfo.Project;
                IViewDisplayBuilder binding;
                IDisplayBuilder     displayBuilder;
                if (openFileInfo.DisplayBuilder != null)
                {
                    displayBuilder = (IDisplayBuilder)(binding = openFileInfo.DisplayBuilder);
                }
                else
                {
                    displayBuilder = DisplayBuilderService.GetDisplayBuilders(fileName, (string)null, project).FirstOrDefault <IDisplayBuilder>((Func <IDisplayBuilder, bool>)(d => d.CanUseAsDefault));
                    binding        = displayBuilder as IViewDisplayBuilder;
                }
                try
                {
                    if (displayBuilder != null && binding != null)
                    {
                        new LoadFileWrapper(monitor, this.mainWindow, binding, project, openFileInfo).Invoke((string)fileName);
                    }
                }
                catch (Exception ex)
                {
                    monitor.ReportError("Create ViewContent failed.", ex);
                }
            }
        }
示例#9
0
        void SignPackageAsync(IProgressMonitor monitor, ConfigurationSelector configSel)
        {
            monitor.BeginTask("Signing package", 0);

            BuildResult result = null;

            try {
                result = this.OnRunTarget(monitor, "SignAndroidPackage", configSel);
                if (result.ErrorCount > 0)
                {
                    monitor.ReportError("Signing failed", null);
                }
            } catch (Exception ex) {
                monitor.ReportError(GettextCatalog.GetString("Signing failed."), ex);
            }
            DispatchService.GuiDispatch(delegate {
                SignPackageDone(monitor, result);                  // disposes the monitor
            });
        }
 bool UpdateXcodeProject(IProgressMonitor monitor)
 {
     try {
         xcode.UpdateProject(monitor, CreateSyncList(), CreateProject(dnp.Name));
         return(true);
     } catch (Exception ex) {
         monitor.ReportError(GettextCatalog.GetString("Error updating Xcode project"), ex);
         return(false);
     }
 }
示例#11
0
        bool CopyFiles(IProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable <FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles)
        {
            FilePath baseDir = obj.BaseDirectory.FullPath;

            foreach (FilePath file in files)
            {
                if (!File.Exists(file))
                {
                    monitor.ReportWarning(GettextCatalog.GetString("File '{0}' not found.", file));
                    continue;
                }
                FilePath fname = file.FullPath;

                // Can't export files from outside the root solution directory
                if (!fname.IsChildPathOf(baseDir))
                {
                    if (ignoreExternalFiles)
                    {
                        continue;
                    }
                    if (obj is Solution)
                    {
                        monitor.ReportError("The solution '" + obj.Name + "' is referencing the file '" + Path.GetFileName(file) + "' which is located outside the root solution directory.", null);
                    }
                    else
                    {
                        monitor.ReportError("The project '" + obj.Name + "' is referencing the file '" + Path.GetFileName(file) + "' which is located outside the project directory.", null);
                    }
                    return(false);
                }

                FilePath rpath = fname.ToRelative(baseDir);
                rpath = rpath.ToAbsolute(targetBasePath);

                if (!Directory.Exists(rpath.ParentDirectory))
                {
                    Directory.CreateDirectory(rpath.ParentDirectory);
                }

                File.Copy(file, rpath, true);
            }
            return(true);
        }
示例#12
0
        protected internal override void OnExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            if (SingleStartup)
            {
                if (StartupItem == null)
                {
                    monitor.ReportError(GettextCatalog.GetString("Startup item not set"), null);
                    return;
                }
                StartupItem.Execute(monitor, context, configuration);
            }
            else
            {
                List <IAsyncOperation> list = new List <IAsyncOperation> ();
                monitor.BeginTask("Executing projects", 1);

                SynchronizedProgressMonitor syncMonitor = new SynchronizedProgressMonitor(monitor);

                foreach (SolutionEntityItem it in MultiStartupItems)
                {
                    if (!it.CanExecute(context, configuration))
                    {
                        continue;
                    }
                    AggregatedProgressMonitor mon = new AggregatedProgressMonitor();
                    mon.AddSlaveMonitor(syncMonitor, MonitorAction.ReportError | MonitorAction.ReportWarning | MonitorAction.SlaveCancel);
                    list.Add(mon.AsyncOperation);
                    SolutionEntityItem cit = it;

                    Thread t = new Thread(delegate()
                    {
                        try
                        {
                            using (mon)
                            {
                                cit.Execute(mon, context, configuration);
                            }
                        }
                        catch (Exception ex)
                        {
                            LoggingService.LogError("Project execution failed", ex);
                        }
                    });
                    t.Name         = "Project execution";
                    t.IsBackground = true;
                    t.Start();
                }
                foreach (IAsyncOperation op in list)
                {
                    op.WaitForCompleted();
                }

                monitor.EndTask();
            }
        }
示例#13
0
        /// <summary>
        /// Loads catalog from .po file.
        /// </summary>
        public bool Load(IProgressMonitor monitor, string poFile)
        {
            Clear();
            isOk     = false;
            fileName = poFile;

            // Load the .po file:
            try
            {
                CharsetInfoFinder charsetFinder = new CharsetInfoFinder(parentProj, poFile);
                charsetFinder.Parse();
                Charset         = charsetFinder.Charset;
                originalNewLine = charsetFinder.NewLine;
            }
            catch (Exception e)
            {
                string msg = "Error during getting charset of file '" + poFile + "'.";
                LoggingService.LogFatalError(msg, e);
                if (monitor != null)
                {
                    monitor.ReportError(msg, e);
                }
                return(false);
            }

            LoadParser parser = new LoadParser(this, poFile, Catalog.GetEncoding(this.Charset));

            if (!parser.Parse())
            {
                string msg = string.Format("Error during parsing '{0}' file, file is probably corrupted.", poFile);
                LoggingService.LogError(msg);
                if (monitor != null)
                {
                    monitor.ReportError(msg, null);
                }
                return(false);
            }

            isOk    = true;
            IsDirty = false;
            return(true);
        }
        public static void Run(NMEProject project, NMEProjectConfiguration configuration, IProgressMonitor monitor, ExecutionContext context)
        {
            ExecutionCommand cmd = CreateExecutionCommand(project, configuration);

            IConsole console;

            if (configuration.ExternalConsole)
            {
                console = context.ExternalConsoleFactory.CreateConsole(false);
            }
            else
            {
                console = context.ConsoleFactory.CreateConsole(false);
            }

            AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor(monitor);

            try
            {
                if (!context.ExecutionHandler.CanExecute(cmd))
                {
                    monitor.ReportError(String.Format("Cannot execute '{0}'.", cmd.CommandString), null);
                    return;
                }

                IProcessAsyncOperation operation = context.ExecutionHandler.Execute(cmd, console);

                operationMonitor.AddOperation(operation);
                operation.WaitForCompleted();

                monitor.Log.WriteLine("Player exited with code {0}.", operation.ExitCode);
            }
            catch (Exception)
            {
                monitor.ReportError(String.Format("Error while executing '{0}'.", cmd.CommandString), null);
            }
            finally
            {
                operationMonitor.Dispose();
                console.Dispose();
            }
        }
示例#15
0
 public void Initialize(IProgressMonitor monitor)
 {
     try
     {
         this.OnInitialize(monitor);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Project item initialize failed.", ex);
     }
 }
示例#16
0
 void BackgroundWorker(object state)
 {
     try
     {
         Run();
     }
     catch (DllNotFoundException e)
     {
         tracker.ReportError("The operation could not be completed because a shared library is missing: " + e.Message, null);
     }
     catch (Exception e)
     {
         string msg = GettextCatalog.GetString("Version control operation failed: ");
         tracker.ReportError(msg, e);
     }
     finally
     {
         threadnotify.WakeupMain();
     }
 }
示例#17
0
        protected internal override void OnExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            ProjectConfiguration config = GetConfiguration(configuration) as ProjectConfiguration;

            if (config == null)
            {
                monitor.ReportError(GettextCatalog.GetString("Configuration '{0}' not found in project '{1}'", configuration, Name), null);
                return;
            }
            DoExecute(monitor, context, configuration);
        }
示例#18
0
        protected override void DoExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector config)
        {
            //check XSP is available

            var configuration = (AspNetAppProjectConfiguration)GetConfiguration(config);
            var cmd           = CreateExecutionCommand(config, configuration);

            IConsole console          = null;
            var      operationMonitor = new AggregatedOperationMonitor(monitor);

            try {
                if (configuration.ExternalConsole)
                {
                    console = context.ExternalConsoleFactory.CreateConsole(!configuration.PauseConsoleOutput);
                }
                else
                {
                    console = context.ConsoleFactory.CreateConsole(!configuration.PauseConsoleOutput);
                }

                string url = String.Format("http://{0}:{1}", this.XspParameters.Address, this.XspParameters.Port);

                bool isXsp = true;                 //FIXME: fix this when it might not be true

                if (isXsp)
                {
                    console = new XspBrowserLauncherConsole(console, delegate {
                        BrowserLauncher.LaunchDefaultBrowser(url);
                    });
                }

                monitor.Log.WriteLine("Running web server...");

                var op = context.ExecutionHandler.Execute(cmd, console);
                operationMonitor.AddOperation(op);                  //handles cancellation

                if (!isXsp)
                {
                    BrowserLauncher.LaunchDefaultBrowser(url);
                }

                op.WaitForCompleted();

                monitor.Log.WriteLine("The web server exited with code: {0}", op.ExitCode);
            } catch (Exception ex) {
                monitor.ReportError("Could not launch web server.", ex);
            } finally {
                operationMonitor.Dispose();
                if (console != null)
                {
                    console.Dispose();
                }
            }
        }
 public void Save(IProgressMonitor monitor)
 {
     try
     {
         this.OnSave(monitor);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Save failed.", ex);
     }
 }
示例#20
0
 public void WriteFile(FilePath file, object obj, IProgressMonitor monitor)
 {
     try
     {
         this.OnWriteFile(file, obj, monitor);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Write file failed.", ex);
     }
 }
        internal protected override void OnExecute(IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            ProjectConfiguration conf = (ProjectConfiguration)GetConfiguration(configuration);

            monitor.Log.WriteLine(GettextCatalog.GetString("Running {0} ...", FileName));

            IConsole console = conf.ExternalConsole
                           ? context.ExternalConsoleFactory.CreateConsole(!conf.PauseConsoleOutput)
                           : context.ConsoleFactory.CreateConsole(!conf.PauseConsoleOutput);

            AggregatedOperationMonitor aggregatedOperationMonitor = new AggregatedOperationMonitor(monitor);

            try
            {
                try
                {
                    ExecutionCommand executionCommand = CreateExecutionCommand(configuration, conf);

                    if (!context.ExecutionHandler.CanExecute(executionCommand))
                    {
                        monitor.ReportError(GettextCatalog.GetString("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", FileName), null);
                        return;
                    }

                    IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute(executionCommand, console);
                    aggregatedOperationMonitor.AddOperation(asyncOp);
                    asyncOp.WaitForCompleted();

                    monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", asyncOp.ExitCode));
                }
                finally
                {
                    console.Dispose();
                    aggregatedOperationMonitor.Dispose();
                }
            }
            catch (Exception ex)
            {
                monitor.ReportError(GettextCatalog.GetString("Cannot execute \"{0}\"", FileName), ex);
            }
        }
		public override void CopyFiles (IProgressMonitor monitor, IFileReplacePolicy replacePolicy, FileCopyConfiguration copyConfig, DeployFileCollection deployFiles, DeployContext context)
		{
			DirectoryInfo tempDir = null;
			try {
				tempDir = CreateTempDir ();
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not create temporary directory."), e);
				return;
			}
			
			try {
				MountTempDirectory (monitor, copyConfig, tempDir.FullName);
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString ("Could not mount FUSE filesystem."), e);
				RemoveTempDirIfEmpty (tempDir);
				return;
			}
			
			try {
				base.InternalCopyFiles (monitor, replacePolicy, copyConfig, deployFiles, context, tempDir.FullName);
			} finally {
				//unmount the filesystem
				try {
					string escapedDir = tempDir.FullName.Replace ("\"", "\\\"");
					string cmd, args;
					
					if (PropertyService.IsMac) {
						cmd = "umount";
						args = string.Format ("\"{0}\"", escapedDir);
					} else {
						cmd = "fusermount";
						args = string.Format ("-u \"{0}\"", escapedDir);
					}
					RunFuseCommand (monitor, cmd, args);
				} catch (Exception e) {
					LoggingService.LogError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
					monitor.ReportError (GettextCatalog.GetString ("Could not unmount FUSE filesystem."), e);
				}
				RemoveTempDirIfEmpty (tempDir);
			}
		}
示例#23
0
 public void Load(IProgressMonitor monitor)
 {
     try
     {
         this.IsLoaded = true;
         this.OnLoad(monitor);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Load failed,", ex);
     }
 }
示例#24
0
 public void Refactor(IProgressMonitor monitor, RefactorerContext rctx, IRefactorer r, string fileName)
 {
     try {
         IEnumerable <MemberReference> refs = r.FindClassReferences(rctx, fileName, cls, includeXmlComment);
         if (refs != null)
         {
             references.AddRange(refs);
         }
     } catch (Exception ex) {
         monitor.ReportError(GettextCatalog.GetString("Could not look for references in file '{0}': {1}", fileName, ex.Message), ex);
     }
 }
示例#25
0
        static int DoCompilation(string outstr, string workingDir, Dictionary <string, string> envVars, List <string> gacRoots, ref string output, ref string error, IProgressMonitor monitor)
        {
            output = Path.GetTempFileName();
            error  = Path.GetTempFileName();

            var outwr = new StreamWriter(output);
            var errwr = new StreamWriter(error);

            // the default should be valid,
            string luac = PropertyService.Get <string>("Lua.DefaultInterpreterPath");

            if (string.IsNullOrEmpty(luac))
            {
                monitor.ReportError("Can't find Lua compiler (please set the default interpreter path)", new Exception());
                return(1);
            }

            luac += "c";

            var pinfo = new ProcessStartInfo(luac, outstr);

            pinfo.WorkingDirectory = workingDir;

            if (gacRoots.Count > 0)
            {
                // Create the gac prefix string
                string gacPrefix = string.Join("" + Path.PathSeparator, gacRoots.ToArray());
                string oldGacVar = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
                if (!string.IsNullOrEmpty(oldGacVar))
                {
                    gacPrefix += Path.PathSeparator + oldGacVar;
                }
                pinfo.EnvironmentVariables["MONO_GAC_PREFIX"] = gacPrefix;
            }

            foreach (KeyValuePair <string, string> kv in envVars)
            {
                pinfo.EnvironmentVariables.Add(kv.Key, kv.Value);
            }

            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            pinfo.RedirectStandardError  = true;

            MonoDevelop.Core.Execution.ProcessWrapper pw = Runtime.ProcessService.StartProcess(pinfo, outwr, errwr, null);
            pw.WaitForOutput();
            int exitCode = pw.ExitCode;

            outwr.Close();
            errwr.Close();
            pw.Dispose();
            return(exitCode);
        }
        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));
        }
示例#27
0
 public void WriteFile(FilePath file, object obj, IProgressMonitor monitor)
 {
     try
     {
         using (var x = new XmlTextWriter(file, Encoding.UTF8))
             Write(obj as VisualDProject, x);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Couldn't write project file", ex);
     }
 }
示例#28
0
 public void Publish(IProgressMonitor monitor, PublishInfo info)
 {
     try
     {
         this.OnPublish(monitor, info);
     }
     catch (Exception ex)
     {
         string message = string.Format("Project {0} publish failed, the error is {1}", (object)this.FullPath, (object)ex.Message);
         monitor.ReportError(message, ex);
     }
 }
示例#29
0
 public object ReadFile(FilePath file, Type expectedType, IProgressMonitor monitor)
 {
     try
     {
         return(this.OnReadFile(file, expectedType, monitor));
     }
     catch (Exception ex)
     {
         monitor.ReportError("Read file failed.", ex);
         return((object)null);
     }
 }
		public static BuildResult CreateMergedPlist (IProgressMonitor monitor, 
			ProjectFile template, string outPath,
			Func<PlistDocument,BuildResult> merge)
		{
			var result = new BuildResult ();
			
			var doc = new PlistDocument ();
			if (template != null) {
				try {
					doc.LoadFromXmlFile (template.FilePath);
				} catch (Exception ex) {
					if (ex is XmlException)
						result.AddError (template.FilePath, ((XmlException)ex).LineNumber,
						                 ((XmlException)ex).LinePosition, null, ex.Message);
					else
						result.AddError (template.FilePath, 0, 0, null, ex.Message);
					monitor.ReportError (GettextCatalog.GetString ("Could not load file '{0}': {1}",
					                                               template.FilePath, ex.Message), null);
					return result;
				}
			}
			
			try {
				if (result.Append (merge (doc)).ErrorCount > 0)
					return result;
			} catch (Exception ex) {
				result.AddError ("Error merging Info.plist: " + ex.Message);
				LoggingService.LogError ("Error merging Info.plist", ex);
				return result;
			}
			
			try {
				EnsureDirectoryForFile (outPath);
				doc.WriteToFile (outPath);
			} catch (Exception ex) {
				result.AddError (outPath, 0, 0, null, ex.Message);
				monitor.ReportError (GettextCatalog.GetString ("Could not write file '{0}'", outPath), ex);
			}
			return result;
		}
        void RunExternalTool(ExternalTools.ExternalTool tool, string argumentsTool)
        {
            string commandTool          = StringParserService.Parse(tool.Command, IdeApp.Workbench.GetStringTagModel());
            string initialDirectoryTool = StringParserService.Parse(tool.InitialDirectory, IdeApp.Workbench.GetStringTagModel());

            //Execute tool
            IProgressMonitor progressMonitor = IdeApp.Workbench.ProgressMonitors.GetRunProgressMonitor();

            try
            {
                progressMonitor.Log.WriteLine(GettextCatalog.GetString("Running: {0} {1}", (commandTool), (argumentsTool)));
                progressMonitor.Log.WriteLine();

                ProcessWrapper processWrapper;
                if (tool.UseOutputPad)
                {
                    processWrapper = Runtime.ProcessService.StartProcess(commandTool, argumentsTool, initialDirectoryTool, progressMonitor.Log, progressMonitor.Log, null);
                }
                else
                {
                    processWrapper = Runtime.ProcessService.StartProcess(commandTool, argumentsTool, initialDirectoryTool, null);
                }

                string processName = System.IO.Path.GetFileName(commandTool);
                try
                {
                    processName = processWrapper.ProcessName;
                }
                catch (SystemException)
                {
                }

                processWrapper.WaitForOutput();

                if (processWrapper.ExitCode == 0)
                {
                    progressMonitor.Log.WriteLine(GettextCatalog.GetString("Process '{0}' has completed succesfully", processName));
                }
                else
                {
                    progressMonitor.Log.WriteLine(GettextCatalog.GetString("Process '{0}' has exited with error code {1}", processName, processWrapper.ExitCode));
                }
            }
            catch (Exception ex)
            {
                progressMonitor.ReportError(GettextCatalog.GetString("External program execution failed.\nError while starting:\n '{0} {1}'", commandTool, argumentsTool), ex);
            }
            finally
            {
                progressMonitor.Dispose();
            }
        }
        public override void Publish(IProgressMonitor monitor, PublishInfo info)
        {
            string text = string.Empty;

            if (Services.ProjectOperations.CurrentSelectedSolution != null)
            {
                text = Services.ProjectsService.SerializeGameProject(info, base.ProjectFile);
            }
            if (!string.IsNullOrEmpty(text))
            {
                monitor.ReportError(text, null);
            }
        }
        public void Save(IProjectFile projectFile)
        {
            IProgressMonitor monitor = Services.ProgressMonitors.Default;

            try
            {
                projectFile.Save(monitor);
            }
            catch (Exception ex)
            {
                monitor.ReportError("Save failed.", ex);
            }
        }
示例#34
0
 public void Save(IProgressMonitor monitor)
 {
     try
     {
         ProjectsService.Instance.Save(monitor, this);
         this.SaveUserProperties();
         this.OnSaved(monitor);
     }
     catch (Exception ex)
     {
         monitor.ReportError("Save failed.", ex);
     }
 }
 void ReportPackageReinstallationWarning(PackageCompatibilityChecker checker)
 {
     checker.GenerateReport(progressMonitor.Log);
     if (checker.AnyIncompatiblePackages())
     {
         progressMonitor.ReportError(GettextCatalog.GetString("Incompatible packages found."), null);
     }
     else
     {
         progressMonitor.ReportWarning(progressMessage.Warning);
     }
     ShowPackageConsole(progressMonitor);
 }
        public static void Generate(IProgressMonitor monitor, BuildResult result, MonobjcProject project, ConfigurationSelector configuration, String outputDirectory, bool native)
        {
            // Infer application name from configuration
            String applicationName = project.GetApplicationName(configuration);

            LoggingService.LogInfo("Generate => applicationName='" + applicationName + "'");
            LoggingService.LogInfo("Generate => outputDirectory='" + outputDirectory + "'");

            // Create the bundle maker
            BundleMaker maker = new BundleMaker(applicationName, outputDirectory);

            // Compile the XIB files
            BuildHelper.CompileXIBFiles(monitor, project, maker, result);
            if (result.ErrorCount > 0)
            {
                monitor.ReportError(GettextCatalog.GetString("Failed to compile XIB files"), null);
                return;
            }

            // Copy the output and dependencies
            BuildHelper.CopyOutputFiles(monitor, project, configuration, maker);

            // Copy the content files
            BuildHelper.CopyContentFiles(monitor, project, configuration, maker);

            // Create the Info.plist
            BuildHelper.CreateInfoPList(monitor, project, configuration, maker);

            if (native)
            {
                GenerateNative(monitor, result, project, configuration, maker);
            }
            else
            {
                // Copy the Monobjc assemblies
                BuildHelper.CopyMonobjcAssemblies(monitor, project, configuration, maker);

                // Write the native runtime
                monitor.BeginTask(GettextCatalog.GetString("Copying native launcher..."), 0);
                maker.WriteRuntime(project.TargetOSVersion);
                monitor.EndTask();
            }

            BuildHelper.CombineArtwork(monitor, project, maker);
            BuildHelper.EncryptContentFiles(monitor, project, configuration, maker);

            // Perform the signing
            BuildHelper.SignBundle(monitor, project, maker);
            BuildHelper.SignNativeBinaries(monitor, project, maker);
        }
		public override WorkspaceItem LoadWorkspaceItem (IProgressMonitor monitor, string fileName)
		{
			WorkspaceItem item = base.LoadWorkspaceItem (monitor, fileName);
			
			Solution sol = item as Solution;
			if (sol != null) {
				//Resolve project references
				try {
					MakefileData.ResolveProjectReferences (sol.RootFolder, monitor);
				} catch (Exception e) {
					LoggingService.LogError (GettextCatalog.GetString (
						"Error resolving Makefile based project references for solution {0}", sol.Name), e);
					monitor.ReportError (GettextCatalog.GetString (
						"Error resolving Makefile based project references for solution {0}", sol.Name), e);
				}
			}
			
			return item;
		}
示例#38
0
        internal static void ExecuteProject(DubProject prj,IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            var conf = prj.GetConfiguration(configuration) as DubProjectConfiguration;
            IConsole console;
            if (conf.ExternalConsole)
                console = context.ExternalConsoleFactory.CreateConsole(!conf.PauseConsoleOutput);
            else
                console = context.ConsoleFactory.CreateConsole(true);

            var operationMonitor = new AggregatedOperationMonitor(monitor);

            var sr = new StringBuilder("run");
            Instance.BuildCommonArgAppendix(sr, prj, configuration);

            try
            {
                var cmd = new NativeExecutionCommand(Instance.DubExecutable, sr.ToString(), prj.BaseDirectory.ToString());
                if (!context.ExecutionHandler.CanExecute(cmd))
                {
                    monitor.ReportError("Cannot execute \""  + "\". The selected execution mode is not supported for Dub projects.", null);
                    return;
                }

                var op = context.ExecutionHandler.Execute(cmd, console);

                operationMonitor.AddOperation(op);
                op.WaitForCompleted();

                monitor.Log.WriteLine(Instance.DubExecutable+" exited with code: {0}", op.ExitCode);

            }
            catch (Exception ex)
            {
                monitor.ReportError("Cannot execute \"" + sr.ToString() + "\"", ex);
            }
            finally
            {
                operationMonitor.Dispose();
                console.Dispose();
            }
        }
		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;
		}
示例#40
0
		//use events.. 
		public void UpdateProject (IProgressMonitor monitor, bool promptForRemoval)
		{
			if (!IntegrationEnabled)
				return;

			if (ownerProject == null)
				throw new InvalidOperationException ("Internal Error: ownerProject not set");

			this.monitor = monitor;

			try {
				Makefile.GetVariables ();
			} catch (Exception e) {
				monitor.ReportError (GettextCatalog.GetString (
					"Invalid Makefile '{0}'. Disabling Makefile integration.", AbsoluteMakefileName), e);
				IntegrationEnabled = false;

				return;
			}

			//FIXME: Improve the message
			if (promptForRemoval) {
				AlertButton projectButton = new AlertButton ("_Project");
				AlertButton makefileButton = new AlertButton ("_Makefile");
				AlertButton choice = MessageService.AskQuestion (GettextCatalog.GetString ("Enabling Makefile integration. You can choose to have either the Project or the Makefile be used as the master copy. This is done only when enabling this feature. After this, the Makefile will be taken as the master copy."),
				                                                 projectButton, makefileButton);
				if (choice == projectButton) {
					//Sync Project --> Makefile
					dirty = true;
					return;
				}
			}

			dirty = true;
			encodeValues = null;

			try {
				if (IsAutotoolsProject) {
					string path = Path.Combine (AbsoluteConfigureInPath, "configure.in");
					if (!File.Exists (path))
						path = Path.Combine (AbsoluteConfigureInPath, "configure.ac");
					
					configuredPackages = null;
					WeakReference weakref;
					if (PkgManagerTable.TryGetValue (path, out weakref)) {
						if (weakref.IsAlive) {
							configuredPackages = (ConfiguredPackagesManager) weakref.Target;
							FileInfo finfo = new FileInfo (path);
							if (finfo.LastWriteTime > configuredPackages.LastWriteTime)
								// file has changed since last time we parsed it!
								configuredPackages = null;
						}
					}

					// no entry in table or it got collected or file has changed
					if (configuredPackages == null) {
						configuredPackages = new ConfiguredPackagesManager (path);
						PkgManagerTable [path] = new WeakReference (configuredPackages);
						ownerProject.ExtendedProperties ["MonoDevelop.Autotools.ConfiguredPackagesManager"] = configuredPackages;
					}
				}
			} catch (Exception e) {
				LoggingService.LogWarning (
					"Error trying to read configure.in ('{0}') for project '{1}':\n{2}",
					AbsoluteConfigureInPath, OwnerProject.Name, e.ToString ());

				monitor.ReportWarning (GettextCatalog.GetString (
					"Error trying to read configure.in ('{0}') for project '{1}':\n{2}",
					AbsoluteConfigureInPath, OwnerProject.Name, e.Message));
			}

			ReadFiles (BuildFilesVar, BuildAction.Compile, "Build", promptForRemoval);
			ReadFiles (DeployFilesVar, BuildAction.Content, "Deploy", promptForRemoval);
			ReadFiles (OthersVar, BuildAction.None, "Others", promptForRemoval);
			ReadFiles (ResourcesVar, BuildAction.EmbeddedResource, "Resources", promptForRemoval);

			if (!SyncReferences)
				return;

			try {
				SaveReferences = true;

				//Do these for DotNetProject only
				DotNetProject dotnetProject = ownerProject as DotNetProject;
				if (dotnetProject != null) {
					GacRefVar.Extra.Clear ();
					AsmRefVar.Extra.Clear ();
					ProjectRefVar.Extra.Clear ();

					existingGacRefs = new Dictionary<string, ProjectReference> ();
					requiredPackageVersions = new Dictionary<string,string> ();
					newGacRefs = new Dictionary<string, ProjectReference> ();

					List<ProjectReference> toRemove = new List<ProjectReference> ();
					foreach (ProjectReference pref in dotnetProject.References) {
						if (pref.ReferenceType == ReferenceType.Gac) {
							string [] files = pref.GetReferencedFileNames (ConfigurationSelector.Default);
							if (files == null)
								continue;

							if (pref.ReferenceType == ReferenceType.Gac) {
								// Store the package version required by this reference. We'll use
								// the same version when trying to match references coming from the makefile
								SystemAssembly asm = assemblyContext.GetAssemblyFromFullName (pref.StoredReference, pref.Package != null ? pref.Package.Name : null, dotnetProject.TargetFramework);
								if (asm != null && asm.Package != null)
									requiredPackageVersions [asm.Package.Name] = asm.Package.Version;
							}
							// this should help normalize paths like /foo//bar/../
							string fullpath = Path.GetFullPath (files [0]);
							if (existingGacRefs.ContainsKey (fullpath))
								toRemove.Add (pref);
							else
								existingGacRefs [fullpath] = pref;
						}
					}

					// Remove the repeats
					foreach (ProjectReference pref in toRemove)
						dotnetProject.References.Remove (pref);

					ReadReferences (GacRefVar, ReferenceType.Gac, "Gac References", dotnetProject);

					// !SaveReferences indicates that previous ref reading failed
					if (SaveReferences && String.Compare (AsmRefVar.Name, GacRefVar.Name) != 0)
						ReadReferences (AsmRefVar, ReferenceType.Assembly, "Asm References", dotnetProject);
					if (SaveReferences && (String.Compare (ProjectRefVar.Name, GacRefVar.Name) != 0) && 
						(String.Compare (ProjectRefVar.Name, AsmRefVar.Name) != 0))
						ReadReferences (ProjectRefVar, ReferenceType.Project, "Project References", dotnetProject);
					
					//Resolve References
					//Required when UpdateProject gets called by ui
					if (ownerProject.ParentSolution != null)
						ResolveProjectReferences (ownerProject.ParentSolution.RootFolder, monitor);

					foreach (ProjectReference pr in existingGacRefs.Values)
						dotnetProject.References.Remove (pr);

					existingGacRefs.Clear ();
					newGacRefs.Clear ();
				}
			} catch (Exception e) {
				string msg = GettextCatalog.GetString (
					"Error in loading references: {0}. Skipping syncing of references", e.Message);
				LoggingService.LogWarning (msg);
				monitor.ReportWarning (msg);

				SaveReferences = false;
			}

			this.monitor = null;
		}
示例#41
0
		void CleanAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt, bool isRebuilding)
		{
			try {
				tt.Trace ("Cleaning item");
				SolutionItem it = entry as SolutionItem;
				if (it != null) {
					it.Clean (monitor, IdeApp.Workspace.ActiveConfiguration);
				}
				else {
					entry.RunTarget (monitor, ProjectService.CleanTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Clean failed."), ex);
			} finally {
				tt.Trace ("Done cleaning");
			}
			
			if (isRebuilding) {
				if (EndClean != null) {
					DispatchService.GuiSyncDispatch (() => OnEndClean (monitor, tt));
				}
			} else {
				DispatchService.GuiDispatch (() => CleanDone (monitor, entry, tt));
			}
		}
示例#42
0
		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 ();
		}
示例#43
0
		void BuildSolutionItemAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt)
		{
			BuildResult result = null;
			try {
				tt.Trace ("Pre-build operations");
				result = DoBeforeCompileAction ();

				if (result.ErrorCount == 0) {
					tt.Trace ("Building item");
					SolutionItem it = entry as SolutionItem;
					if (it != null)
						result = it.Build (monitor, IdeApp.Workspace.ActiveConfiguration, true);
					else
						result = entry.RunTarget (monitor, ProjectService.BuildTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Build failed."), ex);
			} finally {
				tt.Trace ("Done building");
			}
			DispatchService.GuiDispatch (
				delegate {
					BuildDone (monitor, result, entry, tt);	// BuildDone disposes the monitor
			});
		}
示例#44
0
		string Export (IProgressMonitor monitor, IWorkspaceFileObject obj, string[] includedChildIds, string targetPath, FileFormat format)
		{
			string rootSourceFile = obj.FileName;
			string sourcePath = Path.GetFullPath (Path.GetDirectoryName (rootSourceFile));
			targetPath = Path.GetFullPath (targetPath);
			
			if (sourcePath != targetPath) {
				if (!CopyFiles (monitor, obj, obj.GetItemFiles (true), targetPath, true))
					return null;
				
				string newFile = Path.Combine (targetPath, Path.GetFileName (rootSourceFile));
				if (IsWorkspaceItemFile (rootSourceFile))
					obj = ReadWorkspaceItem (monitor, newFile);
				else
					obj = (SolutionEntityItem) ReadSolutionItem (monitor, newFile);
				
				using (obj) {
					List<FilePath> oldFiles = obj.GetItemFiles (true);
					ExcludeEntries (obj, includedChildIds);
					if (format != null)
						obj.ConvertToFormat (format, true);
					obj.Save (monitor);
					List<FilePath> newFiles = obj.GetItemFiles (true);
					
					foreach (FilePath f in newFiles) {
						if (!f.IsChildPathOf (targetPath)) {
							if (obj is Solution)
								monitor.ReportError ("The solution '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the root solution directory.", null);
							else
								monitor.ReportError ("The project '" + obj.Name + "' is referencing the file '" + f.FileName + "' which is located outside the project directory.", null);
						}
						oldFiles.Remove (f);
					}
	
					// Remove old files
					foreach (FilePath file in oldFiles) {
						if (File.Exists (file)) {
							File.Delete (file);
						
							// Exclude empty directories
							FilePath dir = file.ParentDirectory;
							if (Directory.GetFiles (dir).Length == 0 && Directory.GetDirectories (dir).Length == 0) {
								try {
									Directory.Delete (dir);
								} catch (Exception ex) {
									monitor.ReportError (null, ex);
								}
							}
						}
					}
					return obj.FileName;
				}
			}
			else {
				using (obj) {
					ExcludeEntries (obj, includedChildIds);
					if (format != null)
						obj.ConvertToFormat (format, true);
					obj.Save (monitor);
					return obj.FileName;
				}
			}
		}
示例#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));
			} 
		}
示例#46
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 static void Run(HaxeProject project, HaxeProjectConfiguration configuration, IProgressMonitor monitor, ExecutionContext context)
        {
            ExecutionCommand cmd = CreateExecutionCommand (project, configuration);

            if (cmd is NativeExecutionCommand)
            {
                IConsole console;
                if (configuration.ExternalConsole)
                    console = context.ExternalConsoleFactory.CreateConsole (false);
                else
                    console = context.ConsoleFactory.CreateConsole (false);

                AggregatedOperationMonitor operationMonitor = new AggregatedOperationMonitor (monitor);

                try
                {
                    if (!context.ExecutionHandler.CanExecute (cmd))
                    {
                        monitor.ReportError (String.Format ("Cannot execute '{0}'.", cmd.CommandString), null);
                        return;
                    }

                    IProcessAsyncOperation operation = context.ExecutionHandler.Execute (cmd, console);

                    operationMonitor.AddOperation (operation);
                    operation.WaitForCompleted ();

                    monitor.Log.WriteLine ("Player exited with code {0}.", operation.ExitCode);
                }
                catch (Exception)
                {
                    monitor.ReportError (String.Format ("Error while executing '{0}'.", cmd.CommandString), null);
                }
                finally
                {
                    operationMonitor.Dispose ();
                    console.Dispose ();
                }
            }
            else
            {
                Process.Start (cmd.CommandString);
            }
        }
示例#48
0
		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 {
					var pb = new ProcessArgumentBuilder ();
					pb.Add ("-U");
					pb.AddQuoted (poFileName);
					pb.Add ("-v");
					pb.AddQuoted (this.BaseDirectory.Combine ("messages.po"));
					
					var process = Runtime.ProcessService.StartProcess (Translation.GetTool ("msgmerge"),
						pb.ToString (), this.BaseDirectory, monitor.Log, monitor.Log, null);
					process.WaitForOutput ();
				}
				catch (System.ComponentModel.Win32Exception) {
					var msg = GettextCatalog.GetString ("Did not find msgmerge. Please ensure that gettext tools are installed.");
					monitor.ReportError (msg, null);
				}
				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;
				}
			}
		}
示例#49
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 ();
			}
		}
		public override void Save (IProgressMonitor monitor, SolutionEntityItem entry)
		{
			base.Save (monitor, entry);
			
			Project project = entry as Project;
			if (project == null)
				return;
				
			MakefileData data = project.ExtendedProperties ["MonoDevelop.Autotools.MakefileInfo"] as MakefileData;
			if (data == null || !data.SupportsIntegration)
				return;

			try {
				data.UpdateMakefile (monitor);
			} catch (Exception e) {
				LoggingService.LogError (GettextCatalog.GetString ("Error saving to Makefile ({0}) for project {1}",
					data.AbsoluteMakefileName, project.Name, e));
				monitor.ReportError (GettextCatalog.GetString (
					"Error saving to Makefile ({0}) for project {1}", data.AbsoluteMakefileName, project.Name), e);
			}
		}
示例#51
0
		protected override void DoExecute (IProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
		{
			DotNetProjectConfiguration dotNetProjectConfig = GetConfiguration (configuration) as DotNetProjectConfiguration;
			monitor.Log.WriteLine (GettextCatalog.GetString ("Running {0} ...", dotNetProjectConfig.CompiledOutputName));

			IConsole console = dotNetProjectConfig.ExternalConsole
				? context.ExternalConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput)
				: context.ConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput);
			
			AggregatedOperationMonitor aggregatedOperationMonitor = new AggregatedOperationMonitor (monitor);

			try {
				try {
					ExecutionCommand executionCommand = CreateExecutionCommand (configuration, dotNetProjectConfig);
					if (context.ExecutionTarget != null)
						executionCommand.Target = context.ExecutionTarget;

					if (!context.ExecutionHandler.CanExecute (executionCommand)) {
						monitor.ReportError (GettextCatalog.GetString ("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", dotNetProjectConfig.CompiledOutputName), null);
						return;
					}

					IProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console);
					aggregatedOperationMonitor.AddOperation (asyncOp);
					asyncOp.WaitForCompleted ();

					monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", asyncOp.ExitCode));
				} finally {
					console.Dispose ();
					aggregatedOperationMonitor.Dispose ();
				}
			} catch (Exception ex) {
				LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", dotNetProjectConfig.CompiledOutputName), ex);
				monitor.ReportError (GettextCatalog.GetString ("Cannot execute \"{0}\"", dotNetProjectConfig.CompiledOutputName), ex);
			}
		}
 protected override void OnDeleteDirectories(FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal)
 {
     foreach (var ws in GroupFilesPerWorkspace(localPaths))
     {
         List<Failure> failures;
         ws.Key.PendDelete(ws.ToList(), RecursionType.Full, keepLocal, out failures);
         if (failures.Any(f => f.SeverityType == SeverityType.Error))
         {
             foreach (var failure in failures.Where(f => f.SeverityType == SeverityType.Error))
             {
                 monitor.ReportError(failure.Code, new Exception(failure.Message));
             }
         }
     }
     cache.RefreshItems(localPaths);
     FileService.NotifyFilesChanged(localPaths);
 }
示例#53
0
		bool CopyFiles (IProgressMonitor monitor, IWorkspaceFileObject obj, IEnumerable<FilePath> files, FilePath targetBasePath, bool ignoreExternalFiles)
		{
			FilePath baseDir = obj.BaseDirectory.FullPath;
			foreach (FilePath file in files) {

				if (!File.Exists (file)) {
					monitor.ReportWarning (GettextCatalog.GetString ("File '{0}' not found.", file));
					continue;
				}
				FilePath fname = file.FullPath;
				
				// Can't export files from outside the root solution directory
				if (!fname.IsChildPathOf (baseDir)) {
					if (ignoreExternalFiles)
						continue;
					if (obj is Solution)
						monitor.ReportError ("The solution '" + obj.Name + "' is referencing the file '" + Path.GetFileName (file) + "' which is located outside the root solution directory.", null);
					else
						monitor.ReportError ("The project '" + obj.Name + "' is referencing the file '" + Path.GetFileName (file) + "' which is located outside the project directory.", null);
					return false;
				}

				FilePath rpath = fname.ToRelative (baseDir);
				rpath = rpath.ToAbsolute (targetBasePath);
				
				if (!Directory.Exists (rpath.ParentDirectory))
					Directory.CreateDirectory (rpath.ParentDirectory);

				File.Copy (file, rpath, true);
			}
			return true;
		}
		//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;
		}
示例#55
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 ();
			}
		}
		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"));
		}
示例#57
0
		void ExecuteSolutionItemAsync (IProgressMonitor monitor, IBuildTarget entry, ExecutionContext context)
		{
			try {
				OnBeforeStartProject ();
				entry.Execute (monitor, context, IdeApp.Workspace.ActiveConfiguration);
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Execution failed."), ex);
				LoggingService.LogError ("Execution failed", ex);
			} finally {
				monitor.Dispose ();
			}
		}
		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 ();
			}
		}
示例#59
0
		void BuildSolutionItemAsync (IBuildTarget entry, IProgressMonitor monitor, ITimeTracker tt, bool skipPrebuildCheck = false, ProjectOperationContext context = null)
		{
			BuildResult result = null;
			try {
				if (!skipPrebuildCheck) {
					tt.Trace ("Pre-build operations");
					result = DoBeforeCompileAction ();
				}

				//wait for any custom tools that were triggered by the save, since the build may depend on them
				MonoDevelop.Ide.CustomTools.CustomToolService.WaitForRunningTools (monitor);

				if (skipPrebuildCheck || result.ErrorCount == 0) {
					tt.Trace ("Building item");
					SolutionItem it = entry as SolutionItem;
					if (it != null)
						result = it.Build (monitor, IdeApp.Workspace.ActiveConfiguration, true, context);
					else if (entry is WorkspaceItem)
						result = ((WorkspaceItem)entry).Build (monitor, IdeApp.Workspace.ActiveConfiguration, context);
					else
						result = entry.RunTarget (monitor, ProjectService.BuildTarget, IdeApp.Workspace.ActiveConfiguration);
				}
			} catch (Exception ex) {
				monitor.ReportError (GettextCatalog.GetString ("Build failed."), ex);
				if (result == null)
					result = new BuildResult ();
				result.AddError ("Build failed. See the build log for details.");
				if (result.SourceTarget == null)
					result.SourceTarget = entry;
			} finally {
				tt.Trace ("Done building");
			}
			DispatchService.GuiDispatch (
				delegate {
					BuildDone (monitor, result, entry, tt);	// BuildDone disposes the monitor
			});
		}
示例#60
0
		/// <summary>
		/// Resolves the type by mapping the known Objective-C type information to .NET types.
		/// </summary>
		/// <returns>
		/// The number of unresolved types still remaining.
		/// </returns>
		/// <param name='type'>
		/// The NSObjectTypeInfo that contains the known Objective-C type information.
		/// Typically this will be the result of NSObjectInfoService.ParseHeader().
		/// </param>
		/// <param name='provider'>
		/// A CodeDom provider which is used to make sure type names don't conflict with language keywords.
		/// </param>
		/// <param name='defaultNamespace'>
		/// The default namespace used when forcing type resolution.
		/// </param>
		public void ResolveObjcToCli (IProgressMonitor monitor, NSObjectTypeInfo type, CodeDomProvider provider, string defaultNamespace)
		{
			NSObjectTypeInfo resolved;
			
			// Resolve our base type
			if (type.BaseCliType == null) {
				if (TryResolveObjcToCli (type.BaseObjCType, out resolved)) {
					type.BaseCliType = resolved.CliName;
				} else {
					var reference = new GetClassTypeReference (defaultNamespace, provider.CreateValidIdentifier (type.BaseObjCType));
					type.BaseCliType = reference.Resolve (dom.Compilation).ReflectionName;

					var message = string.Format ("Failed to resolve Objective-C type '{0}' to a type in the current solution.", type.BaseObjCType);
					message += string.Format (" Adding a [Register (\"{0}\")] attribute to the class which corresponds to this will allow it to be synced to Objective-C.", type.BaseObjCType);
					monitor.ReportError (null, new UserException ("Error while syncing", message));
				}
			}
			
			// Resolve [Outlet] types
			foreach (var outlet in type.Outlets) {
				if (outlet.CliType != null)
					continue;
				
				if (TryResolveObjcToCli (outlet.ObjCType, out resolved)) {
					outlet.CliType = resolved.CliName;
				} else {
					outlet.CliType = defaultNamespace + "." + provider.CreateValidIdentifier (outlet.ObjCType);

					var message = string.Format ("Failed to resolve Objective-C outlet '{0}' of type '{1}' to a type in the current solution.", outlet.ObjCName, outlet.ObjCType);
					message += string.Format (" Adding a [Register (\"{0}\")] attribute to the class which corresponds to this will allow it to be synced to Objective-C.", outlet.ObjCType);
					monitor.ReportError (null, new UserException ("Error while syncing", message));
				}
			}
			
			// Resolve [Action] param types
			foreach (var action in type.Actions) {
				foreach (var param in action.Parameters) {
					if (param.CliType != null)
						continue;
					
					if (TryResolveObjcToCli (param.ObjCType, out resolved)) {
						param.CliType = resolved.CliName;
					} else {
						param.CliType = defaultNamespace + "." + provider.CreateValidIdentifier (param.ObjCType);
	
						var message = string.Format ("Failed to resolve paramater '{0}' of type '{2}' on Objective-C action '{1}' to a type in the current solution.", param.Name, action.ObjCName, param.ObjCType);
						message += string.Format (" Adding a [Register (\"{0}\")] attribute to the class which corresponds to this will allow it to be synced to Objective-C.", param.ObjCType);
						monitor.ReportError (null, new UserException ("Error while syncing", message));
					}
				}
			}
		}