void ReportWarning(string message) { progressMonitor.ReportWarning(message); LogMessage(message); HasWarnings = true; }
protected SolutionItemConfiguration CreateConfigurationBlock(MonoDevelop.Projects.DotNetProject project, Config ConfigBlock, string AssemblyName, string OuputType, IProgressMonitor monitor) { DotNetProjectConfiguration confObj = project.CreateConfiguration(ConfigBlock.Name) as DotNetProjectConfiguration; confObj.RunWithWarnings = false; confObj.DebugMode = ConfigBlock.DebugSymbols; project.CompileTarget = (CompileTarget)Enum.Parse(typeof(CompileTarget), OuputType, true); string dir = MapPath(project.BaseDirectory, ConfigBlock.OutputPath); if (dir == null) { dir = Path.Combine("bin", ConfigBlock.Name); monitor.ReportWarning(string.Format(GettextCatalog.GetString("Output directory '{0}' can't be mapped to a local directory. The directory '{1}' will be used instead"), ConfigBlock.OutputPath, dir)); } confObj.OutputDirectory = dir; confObj.OutputAssembly = AssemblyName; CSharpCompilerParameters compilerParams = new CSharpCompilerParameters(); compilerParams.WarningLevel = ConfigBlock.WarningLevel; compilerParams.NoWarnings = ""; compilerParams.Optimize = ConfigBlock.Optimize; compilerParams.DefineSymbols = ConfigBlock.DefineConstants; compilerParams.UnsafeCode = ConfigBlock.AllowUnsafeBlocks; compilerParams.GenerateOverflowChecks = ConfigBlock.CheckForOverflowUnderflow; return(confObj); }
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(string file, IProgressMonitor monitor) { XmlTextReader reader = new XmlTextReader (new StreamReader (file)); reader.MoveToContent (); string version = reader.GetAttribute ("version"); if (version == null) version = reader.GetAttribute ("fileversion"); DataSerializer serializer = new DataSerializer (Runtime.ProjectService.DataContext, file); ICombineReader combineReader = null; if (version == "1.0" || version == "1") { combineReader = new CombineReaderV1 (serializer, monitor); monitor.ReportWarning (string.Format (GettextCatalog.GetString ("The file '{0}' is using an old combine file format. It will be automatically converted to the current format."), file)); } else if (version == "2.0") combineReader = new CombineReaderV2 (serializer, monitor); try { if (combineReader != null) return combineReader.ReadCombine (reader); else throw new UnknownProjectVersionException (file, version); } finally { reader.Close (); } }
string FindItemConfiguration(List <IExtendedDataItem> chain, string configId) { for (int n = 0; n < chain.Count - 1; n++) { CombineConfigurationSet configs = (CombineConfigurationSet)chain[n].ExtendedProperties ["Configurations"]; if (configs == null) { return(null); } SolutionItem item = (SolutionItem)chain [n + 1]; CombineConfiguration combineConfig = configs.GetConfig(configId); if (combineConfig == null) { monitor.ReportWarning("Configuration '" + configId + "' not found in solution item '" + item.Name + "'."); return(null); } string mappedConfigId = combineConfig.GetMappedConfig(item.Name); if (mappedConfigId == null) { return(null); } if (mappedConfigId != string.Empty) { configId = mappedConfigId; } } return(configId); }
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; }
internal override void CommitUninstall(IProgressMonitor monitor, AddinStore service) { if (tempFolder == null) { return; } monitor.Log.WriteLine("Uninstalling " + info.Name + " v" + info.Version); AddinDescription conf = iaddin.Description; string basePath = Path.GetDirectoryName(conf.AddinFile); foreach (string relPath in conf.AllFiles) { string path = Path.Combine(basePath, relPath); if (!File.Exists(path)) { continue; } File.Delete(path); } File.Delete(iaddin.AddinFile); if (Directory.GetFiles(basePath).Length == 0) { try { Directory.Delete(basePath); } catch { monitor.ReportWarning("Directory " + basePath + " could not be deleted."); } } monitor.Log.WriteLine("Done"); }
public void ReportWarning(string message) { lock (monitor.SyncRoot) { monitor.ReportWarning(message); } }
/// <summary> /// Validates the schema. /// </summary> public static XmlSchema ValidateSchema(IProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask(GettextCatalog.GetString("Validating schema..."), 1); bool error = false; XmlSchema schema = null; try { StringReader stringReader = new StringReader(xml); XmlTextReader xmlReader = new XmlTextReader(stringReader); xmlReader.XmlResolver = null; ValidationEventHandler callback = delegate(object source, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { monitor.ReportWarning(args.Message); } else { monitor.ReportError(args.Message, args.Exception); error = true; } AddTask(fileName, args.Message, args.Exception.LinePosition, args.Exception.LineNumber, (args.Severity == XmlSeverityType.Warning)? TaskSeverity.Warning : TaskSeverity.Error); }; schema = XmlSchema.Read(xmlReader, callback); XmlSchemaSet sset = new XmlSchemaSet(); sset.Add(schema); sset.ValidationEventHandler += callback; sset.Compile(); } catch (XmlSchemaException ex) { monitor.ReportError(ex.Message, ex); AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error); error = true; } 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("Schema is valid.")); } monitor.EndTask(); return(error? null: schema); }
protected override BuildResult DoBuild(IProgressMonitor monitor, ConfigurationSelector configuration) { LuaConfiguration config = this.DefaultConfiguration as LuaConfiguration; if (config != null && config.LangVersion == LangVersion.GarrysMod) { monitor.ReportWarning("Can't build a with Garry's Mod Lua syntax!"); return(new BuildResult("Can't build a with Garry's Mod Lua syntax!", 0, 0)); } return(LuaCompilerManager.Compile(this.Items, config, configuration, monitor)); }
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); }
protected override BuildResult DoBuild(IProgressMonitor monitor, ConfigurationSelector configuration) { var config = DefaultConfiguration as LuaConfiguration; if (config != null && !string.IsNullOrEmpty(config.Launcher) && config.LangVersion == LangVersion.Moai) { monitor.ReportWarning("Can't build project with Moai syntax!"); return(new BuildResult("Can't build project with Moai syntax!", 0, 0)); } if (config != null && !string.IsNullOrEmpty(config.Launcher) && config.LangVersion == LangVersion.Love) { monitor.ReportWarning("Can't build project with Love syntax!"); return(new BuildResult("Can't build project with Love syntax!", 0, 0)); } if (config != null && config.LangVersion == LangVersion.GarrysMod) { monitor.ReportWarning("Can't build project with Garry's Mod Lua syntax!"); return(new BuildResult("Can't build project with Garry's Mod Lua syntax!", 0, 0)); } return(LuaCompilerManager.Compile(Items, config, configuration, monitor)); }
public void ReportSuccess(bool anyUpdates) { if (anyUpdates) { progressMonitor.ReportSuccess(GettextCatalog.GetString("Package updates are available.")); } else if (eventMonitor.WarningReported) { progressMonitor.ReportWarning(progressMessage.Warning); } else { progressMonitor.ReportSuccess(progressMessage.Success); } }
internal override void PrepareUninstall(IProgressMonitor monitor, AddinStore service) { iaddin = service.Registry.GetAddin(info.Id, true); if (iaddin == null) { throw new InstallException(string.Format("The add-in '{0}' is not installed.", info.Name)); } AddinDescription conf = iaddin.Description; if (!File.Exists(iaddin.AddinFile)) { monitor.ReportWarning(string.Format("The add-in '{0}' is scheduled for uninstalling, but the add-in file could not be found.", info.Name)); return; } // The add-in is a core application add-in. It can't be uninstalled, so it will be disabled. if (!service.IsUserAddin(iaddin.AddinFile)) { disablingOnUninstall = true; return; } // If the add-in assemblies are loaded, or if there is any file with a write lock, delay the uninstallation HashSet <string> files = new HashSet <string> (GetInstalledFiles(conf)); if (AddinManager.CheckAssembliesLoaded(files) || files.Any(f => HasWriteLock(f))) { uninstallingLoaded = true; return; } if (!service.HasWriteAccess(iaddin.AddinFile)) { throw new InstallException(AddinStore.GetUninstallErrorNoRoot(info)); } foreach (string path in GetInstalledFiles(conf)) { if (!service.HasWriteAccess(path)) { throw new InstallException(AddinStore.GetUninstallErrorNoRoot(info)); } } tempFolder = CreateTempFolder(); CopyAddinFiles(monitor, conf, iaddin.AddinFile, tempFolder); }
void RecDeleteDir(IProgressMonitor monitor, string path) { if (Directory.GetFiles(path).Length != 0) { return; } foreach (string dir in Directory.GetDirectories(path)) { RecDeleteDir(monitor, dir); } try { Directory.Delete(path); } catch { monitor.ReportWarning("Directory " + path + " could not be deleted."); } }
void EmitCustomCommandTargets(CustomCommandCollection commands, Project project, StringBuilder builder, string configName, CustomCommandType[] types, IProgressMonitor monitor) { bool warned = false; configName = configName.ToUpper(); foreach (CustomCommandType type in types) { bool targetEmitted = false; for (int i = 0; i < commands.Count; i++) { CustomCommand cmd = commands [i]; if (cmd.Type != type) { if (!warned && Array.IndexOf(types, cmd.Type) < 0) { //Warn (only once) if unsupported custom command is found, StringBuilder types_list = new StringBuilder(); foreach (CustomCommandType t in types) { types_list.AppendFormat("{0}, ", t); } monitor.ReportWarning(GettextCatalog.GetString( "Custom commands of only the following types are supported: {0}.", types_list.ToString())); warned = true; } continue; } if (!targetEmitted) { builder.AppendFormat("{0}_{1}:\n", configName, type.ToString()); targetEmitted = true; } string dir, exe, args; ResolveCustomCommand(project, cmd, out dir, out exe, out args); builder.AppendFormat("\t(cd {0} && {1} {2})\n", dir, exe, args); } if (targetEmitted) { builder.Append("\n"); } } }
void CheckForPackageUpdates( IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage, PackageUpdatesEventMonitor eventMonitor) { updatedPackagesInSolution.CheckForUpdates(); if (updatedPackagesInSolution.AnyUpdates()) { progressMonitor.ReportSuccess(GettextCatalog.GetString("Package updates are available.")); } else if (eventMonitor.WarningReported) { progressMonitor.ReportWarning(progressMessage.Warning); } else { progressMonitor.ReportSuccess(progressMessage.Success); } }
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); }
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> /// Copies resource files from the Xcode project (back) to the MonoDevelop project directory. /// </summary> /// <param name='monitor'> /// A progress monitor. /// </param> /// <param name='context'> /// The sync context. /// </param> void CopyFilesToMD(IProgressMonitor monitor, XcodeSyncBackContext context) { if (context.FileSyncJobs.Count == 0) { return; } monitor.BeginStepTask("Copying files from Xcode back to MonoDevelop...", context.FileSyncJobs.Count, 1); foreach (var file in context.FileSyncJobs) { monitor.Log.WriteLine("Copying {0} file from Xcode: {1}", file.IsFreshlyAdded ? "new" : "changed", file.SyncedRelative); if (!Directory.Exists(file.Original.ParentDirectory)) { Directory.CreateDirectory(file.Original.ParentDirectory); } var tempFile = file.Original.ParentDirectory.Combine(".#" + file.Original.ParentDirectory.FileName); FilePath path = context.ProjectDir.Combine(file.SyncedRelative); if (File.Exists(path)) { File.Copy(path, tempFile); FileService.SystemRename(tempFile, file.Original); DateTime mtime = File.GetLastWriteTime(file.Original); context.SetSyncTime(file.SyncedRelative, mtime); } else { monitor.ReportWarning(string.Format("'{0}' does not exist.", file.SyncedRelative)); } monitor.Step(1); } monitor.EndTask(); }
internal override void PrepareUninstall(IProgressMonitor monitor, AddinStore service) { iaddin = service.Registry.GetAddin(info.Id, true); if (iaddin == null) { throw new InstallException(string.Format("The add-in '{0}' is not installed.", info.Name)); } AddinDescription conf = iaddin.Description; string basePath = Path.GetDirectoryName(conf.AddinFile); if (!File.Exists(iaddin.AddinFile)) { monitor.ReportWarning(string.Format("The add-in '{0}' is scheduled for uninstalling, but the add-in file could not be found.", info.Name)); return; } if (!service.HasWriteAccess(iaddin.AddinFile)) { throw new InstallException(AddinStore.GetUninstallErrorNoRoot(info)); } foreach (string relPath in conf.AllFiles) { string path = Path.Combine(basePath, relPath); if (!File.Exists(path)) { continue; } if (!service.HasWriteAccess(path)) { throw new InstallException(AddinStore.GetUninstallErrorNoRoot(info)); } } tempFolder = CreateTempFolder(); CopyAddinFiles(monitor, conf, iaddin.AddinFile, tempFolder); }
//ExtendedProperties // Per config // Platform : Eg. Any CPU // SolutionConfigurationPlatforms // SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor) { string headerComment; string version = GetSlnFileVersion (fileName, out headerComment); ListDictionary globals = null; SolutionFolder folder = null; SlnData data = null; List<Section> projectSections = null; List<string> lines = null; FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format); monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1); //Parse the .sln file using (StreamReader reader = new StreamReader(fileName)) { sol.FileName = fileName; sol.ConvertToFormat (projectFormat, false); folder = sol.RootFolder; sol.Version = "0.1"; //FIXME: data = new SlnData (); folder.ExtendedProperties [typeof (SlnFileFormat)] = data; data.VersionString = version; data.HeaderComment = headerComment; string s = null; projectSections = new List<Section> (); lines = new List<string> (); globals = new ListDictionary (); //Parse while (reader.Peek () >= 0) { s = GetNextLine (reader, lines).Trim (); if (String.Compare (s, "Global", StringComparison.OrdinalIgnoreCase) == 0) { ParseGlobal (reader, lines, globals); continue; } if (s.StartsWith ("Project", StringComparison.Ordinal)) { Section sec = new Section (); projectSections.Add (sec); sec.Start = lines.Count - 1; int e = ReadUntil ("EndProject", reader, lines); sec.Count = (e < 0) ? 1 : (e - sec.Start + 1); continue; } if (s.StartsWith ("VisualStudioVersion = ", StringComparison.Ordinal)) { Version v; if (Version.TryParse (s.Substring ("VisualStudioVersion = ".Length), out v)) data.VisualStudioVersion = v; else monitor.Log.WriteLine ("Ignoring unparseable VisualStudioVersion value in sln file"); } if (s.StartsWith ("MinimumVisualStudioVersion = ", StringComparison.Ordinal)) { Version v; if (Version.TryParse (s.Substring ("MinimumVisualStudioVersion = ".Length), out v)) data.MinimumVisualStudioVersion = v; else monitor.Log.WriteLine ("Ignoring unparseable MinimumVisualStudioVersion value in sln file"); } } } monitor.BeginTask("Loading projects ..", projectSections.Count + 1); Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> (); List<SolutionItem> sortedList = new List<SolutionItem> (); foreach (Section sec in projectSections) { monitor.Step (1); Match match = ProjectRegex.Match (lines [sec.Start]); if (!match.Success) { LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project definition on line number #{0} in file '{1}'. Ignoring.", sec.Start + 1, fileName)); continue; } try { // Valid guid? new Guid (match.Groups [1].Value); } catch (FormatException) { //Use default guid as projectGuid LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project type guid '{0}' on line #{1}. Ignoring.", match.Groups [1].Value, sec.Start + 1)); continue; } string projTypeGuid = match.Groups [1].Value.ToUpper (); string projectName = match.Groups [2].Value; string projectPath = match.Groups [3].Value; string projectGuid = match.Groups [4].Value.ToUpper (); List<string> projLines; if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) { //Solution folder SolutionFolder sfolder = new SolutionFolder (); sfolder.Name = projectName; MSBuildProjectService.InitializeItemHandler (sfolder); MSBuildProjectService.SetId (sfolder, projectGuid); projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DeserializeSolutionItem (sol, sfolder, projLines); foreach (string f in ReadFolderFiles (projLines)) sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f)); SlnData slnData = new SlnData (); slnData.Extra = projLines.ToArray (); sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData; items.Add (projectGuid, sfolder); sortedList.Add (sfolder); continue; } if (projectPath.StartsWith("http://")) { monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.", fileName, sec.Start + 1, projectPath)); data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count)); continue; } string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath); if (String.IsNullOrEmpty (path)) { monitor.ReportWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); LoggingService.LogWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); continue; } projectPath = Path.GetFullPath (path); SolutionEntityItem item = null; try { if (sol.IsSolutionItemEnabled (projectPath)) { item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate { return MSBuildProjectService.LoadItem (monitor, projectPath, format, projTypeGuid, projectGuid); }); if (item == null) { throw new UnknownSolutionItemTypeException (projTypeGuid); } } else { var uitem = new UnloadedSolutionItem () { FileName = projectPath }; var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } } catch (Exception e) { // If we get a TargetInvocationException from using Activator.CreateInstance we // need to unwrap the real exception while (e is TargetInvocationException) e = ((TargetInvocationException) e).InnerException; bool loadAsProject = false; if (e is UnknownSolutionItemTypeException) { var name = ((UnknownSolutionItemTypeException)e).TypeName; var relPath = new FilePath (path).ToRelative (sol.BaseDirectory); if (!string.IsNullOrEmpty (name)) { var guids = name.Split (';'); var projectInfo = MSBuildProjectService.GetUnknownProjectTypeInfo (guids, fileName); if (projectInfo != null) { loadAsProject = projectInfo.LoadFiles; LoggingService.LogWarning (string.Format ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ())); monitor.ReportWarning (GettextCatalog.GetString ("Could not load {0} project '{1}'. {2}", projectInfo.Name, relPath, projectInfo.GetInstructions ())); } else { LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type '{1}'", relPath, name)); monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", relPath, name)); } } else { LoggingService.LogWarning (string.Format ("Could not load project '{0}' with unknown item type", relPath)); monitor.ReportWarning (GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", relPath)); } } else if (e is UserException) { var ex = (UserException) e; LoggingService.LogError ("{0}: {1}", ex.Message, ex.Details); monitor.ReportError (string.Format ("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.Details), null); } else { LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e); monitor.ReportWarning (GettextCatalog.GetString ( "Error while trying to load the project '{0}': {1}", projectPath, e.Message)); } SolutionEntityItem uitem; if (loadAsProject) { uitem = new UnknownProject () { FileName = projectPath, LoadError = e.Message, }; } else { uitem = new UnknownSolutionItem () { FileName = projectPath, LoadError = e.Message, }; } var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } MSBuildHandler handler = (MSBuildHandler) item.ItemHandler; projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DataItem it = GetSolutionItemData (projLines); handler.UnresolvedProjectDependencies = ReadSolutionItemDependencies (projLines); handler.SlnProjectContent = projLines.ToArray (); handler.ReadSlnData (it); if (!items.ContainsKey (projectGuid)) { items.Add (projectGuid, item); sortedList.Add (item); data.ItemsByGuid [projectGuid] = item; } else { monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null); } } monitor.EndTask (); if (globals != null && globals.Contains ("NestedProjects")) { LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor); globals.Remove ("NestedProjects"); } // Resolve project dependencies foreach (var it in items.Values.OfType<SolutionEntityItem> ()) { MSBuildHandler handler = (MSBuildHandler) it.ItemHandler; if (handler.UnresolvedProjectDependencies != null) { foreach (var id in handler.UnresolvedProjectDependencies.ToArray ()) { SolutionItem dep; if (items.TryGetValue (id, out dep) && dep is SolutionEntityItem) { handler.UnresolvedProjectDependencies.Remove (id); it.ItemDependencies.Add ((SolutionEntityItem)dep); } } if (handler.UnresolvedProjectDependencies.Count == 0) handler.UnresolvedProjectDependencies = null; } } //Add top level folders and projects to the main folder foreach (SolutionItem ce in sortedList) { if (ce.ParentFolder == null) folder.Items.Add (ce); } //FIXME: This can be just SolutionConfiguration also! if (globals != null) { if (globals.Contains ("SolutionConfigurationPlatforms")) { LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("SolutionConfigurationPlatforms"); } if (globals.Contains ("ProjectConfigurationPlatforms")) { LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("ProjectConfigurationPlatforms"); } if (globals.Contains ("MonoDevelopProperties")) { LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines, sol, monitor); globals.Remove ("MonoDevelopProperties"); } ArrayList toRemove = new ArrayList (); foreach (DictionaryEntry e in globals) { string name = (string) e.Key; if (name.StartsWith ("MonoDevelopProperties.")) { int i = name.IndexOf ('.'); LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor); toRemove.Add (e.Key); } } foreach (object key in toRemove) globals.Remove (key); } //Save the global sections that we dont use List<string> globalLines = new List<string> (); foreach (Section sec in globals.Values) globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count)); data.GlobalExtra = globalLines; monitor.EndTask (); // When reloading a project, keep the solution data and item id sol.SolutionItemAdded += delegate(object sender, SolutionItemChangeEventArgs e) { if (e.Reloading) { ItemSlnData.TransferData (e.ReplacedItem, e.SolutionItem); var ih = e.SolutionItem.ItemHandler as MSBuildHandler; if (ih != null) ih.ItemId = e.ReplacedItem.ItemId; } }; return folder; }
public override void ReportWarning(string message) { base.ReportWarning(message); statusMonitor.ReportWarning(message); }
protected void GetContents (MonoDevelop.Projects.Project project, MonoDevelop.Prj2Make.Schema.Csproj.File[] Include, ProjectFileCollection files, IProgressMonitor monitor) { if (Include == null || Include.Length == 0) return; // Iterate through the file collection of the csproj file foreach(MonoDevelop.Prj2Make.Schema.Csproj.File fl in Include) { ProjectFile flOut = new ProjectFile (); string name; if ((fl.Link == null) || (fl.Link.Length == 0)) { name = MapPath (project.BaseDirectory, fl.RelPath); } else { name = MapPath (null, fl.Link); } if (name == null) { monitor.ReportWarning (GettextCatalog.GetString ("Can't import file: ") + fl.RelPath); continue; } flOut.Name = name; // Adding here as GetDefaultResourceIdInternal needs flOut.Project files.Add (flOut); switch (fl.SubType) { case "Code": flOut.Subtype = Subtype.Code; break; } switch (fl.BuildAction) { case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.Compile: flOut.BuildAction = BuildAction.Compile; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.Content: flOut.BuildAction = BuildAction.Content; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.EmbeddedResource: flOut.BuildAction = BuildAction.EmbeddedResource; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.None: flOut.BuildAction = BuildAction.None; break; } // DependentUpon is relative to flOut flOut.DependsOn = MapPath (Path.GetDirectoryName (flOut.Name), fl.DependentUpon); flOut.Data = ""; } }
public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) { FSharpCompilerParameters compilerParameters = (FSharpCompilerParameters)configuration.CompilationParameters ?? new FSharpCompilerParameters (); FSharpProjectParameters projectParameters = (FSharpProjectParameters)configuration.ProjectParameters ?? new FSharpProjectParameters (); string outputName = configuration.CompiledOutputName; TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime; DotNetProject project = configuration.ParentItem as DotNetProject; if (project != null) runtime = project.TargetRuntime; StringBuilder sb = new StringBuilder (); List<string> gacRoots = new List<string> (); sb.AppendFormat ("--out:{0}", outputName); sb.AppendLine (); HashSet<string> alreadyAddedReference = new HashSet<string> (); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName (lib.Reference) is DotNetProject)) continue; foreach (string fileName in lib.GetReferencedFileNames (configSelector)) { switch (lib.ReferenceType) { case ReferenceType.Gac: SystemPackage pkg = lib.Package; if (pkg == null) { string msg = string.Format (GettextCatalog.GetString ("{0} could not be found or is invalid."), lib.Reference); monitor.ReportWarning (msg); continue; } string referencedName = pkg.IsCorePackage ? Path.GetFileName (fileName) : fileName; if (!alreadyAddedReference.Contains (referencedName)) { alreadyAddedReference.Add (referencedName); AppendQuoted (sb, "--reference:", referencedName); } if (pkg.GacRoot != null && !gacRoots.Contains (pkg.GacRoot)) gacRoots.Add (pkg.GacRoot); if (!string.IsNullOrEmpty (pkg.Requires)) { foreach (string requiredPackage in pkg.Requires.Split(' ')) { SystemPackage rpkg = runtime.AssemblyContext.GetPackage (requiredPackage); if (rpkg == null) continue; foreach (SystemAssembly assembly in rpkg.Assemblies) { if (alreadyAddedReference.Contains (assembly.Location)) continue; alreadyAddedReference.Add (assembly.Location); AppendQuoted (sb, "--reference:", assembly.Location); } } } break; default:// AppendQuoted (sb, "--reference:", fileName); break; } } } // THINK!! WNH sb.Append ("/warn:");sb.Append (compilerParameters.WarningLevel.ToString ()); // sb.AppendLine (); if (configuration.SignAssembly) { if (File.Exists (configuration.AssemblyKeyFile)) AppendQuoted (sb, "--keyfile:", configuration.AssemblyKeyFile); } if (configuration.DebugMode) { // WNH REVIEW sb.AppendLine ("/debug:+"); // sb.AppendLine ("/debug:full"); sb.AppendLine ("-g"); } // mcs default is + but others might not be <<<<< what about FSC default??? WNH if (compilerParameters.Optimize) sb.AppendLine ("--optimize+"); else sb.AppendLine ("--optimize-"); bool hasWin32Res = !string.IsNullOrEmpty (projectParameters.Win32Resource) && File.Exists (projectParameters.Win32Resource); if (hasWin32Res) AppendQuoted (sb, "--win32res:", projectParameters.Win32Resource); if (!string.IsNullOrEmpty (projectParameters.Win32Icon) && File.Exists (projectParameters.Win32Icon)) { if (hasWin32Res) { monitor.ReportWarning ("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon."); } else { AppendQuoted (sb, "--win32icon:", projectParameters.Win32Icon); } } if (projectParameters.CodePage != 0) // WNH RIP OUT??? sb.AppendLine ("--codepage:" + projectParameters.CodePage); else if (runtime is MonoTargetRuntime) sb.AppendLine ("--utf8output"); // if (compilerParameters.UnsafeCode) WNH RIP OUT?? // sb.AppendLine ("-unsafe"); // if (compilerParameters.NoStdLib) // sb.AppendLine ("-nostdlib"); if (!string.IsNullOrEmpty (compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower () != "anycpu") { //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation ("Mono.Debugger.Soft", null) == null) { LoggingService.LogWarning ("Mono runtime '" + runtime.DisplayName + "' appears to be too old to support the 'platform' F# compiler flag."); } else { sb.AppendLine ("--platform:" + compilerParameters.PlatformTarget); } } if (compilerParameters.TreatWarningsAsErrors) { sb.AppendLine ("--all-warnings-as-errors"); if (!string.IsNullOrEmpty (compilerParameters.WarningsNotAsErrors)) sb.AppendLine ("-warnaserror-:" + compilerParameters.WarningsNotAsErrors); } if (compilerParameters.DefineSymbols.Length > 0) { string define_str = string.Join (";", compilerParameters.DefineSymbols.Split (new char [] {',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries)); if (define_str.Length > 0) { // WNH AppendQuoted (sb, "--define:", define_str); // WNH REVIEW!!!! // WNH AppendQuoted (sb, "--define:", define_str); // WNH REVIEW!!!! sb.AppendFormat("--define:{0}", define_str); // WNH sb.AppendLine (); } } CompileTarget ctarget = configuration.CompileTarget; switch (ctarget) { case CompileTarget.Exe: sb.AppendLine ("--target:exe"); break; case CompileTarget.WinExe: sb.AppendLine ("--target:winexe"); break; case CompileTarget.Library: sb.AppendLine ("--target:library"); break; } foreach (ProjectFile finfo in projectItems.GetAll<ProjectFile> ()) { if (finfo.Subtype == Subtype.Directory) continue; switch (finfo.BuildAction) { case "Compile": // WNH AppendQuoted (sb, "", finfo.Name); sb.AppendLine (finfo.Name); // WNH break; case "EmbeddedResource": string fname = finfo.Name; if (string.Compare (Path.GetExtension (fname), ".resx", true) == 0) fname = Path.ChangeExtension (fname, ".resources"); sb.Append ('"');sb.Append ("--resource:"); sb.Append (fname);sb.Append (',');sb.Append (finfo.ResourceId); sb.Append ('"');sb.AppendLine (); break; default: continue; } } if (compilerParameters.GenerateXmlDocumentation) AppendQuoted (sb, "--doc:", Path.ChangeExtension (outputName, ".xml")); if (!string.IsNullOrEmpty (compilerParameters.AdditionalArguments)) sb.AppendLine (compilerParameters.AdditionalArguments); if (!string.IsNullOrEmpty (compilerParameters.NoWarnings)) AppendQuoted (sb, "--no-warn:", compilerParameters.NoWarnings); // WNH can't be a list on FSC!!!! FIX!!! if (runtime.RuntimeId == "MS.NET") sb.AppendLine ("--fullpaths"); string output = ""; string error = ""; string compilerName; try { compilerName = GetCompilerName (runtime, configuration.TargetFramework); } catch (Exception e) { string message = "Could not obtain a F# compiler"; monitor.ReportError (message, e); return null; } monitor.Log.WriteLine (compilerName + sb.ToString ().Replace ('\n',' ')); string workingDir = "."; if (configuration.ParentItem != null) { workingDir = configuration.ParentItem.BaseDirectory; if (workingDir == null) // Dummy projects created for single files have no filename // and so no BaseDirectory. // This is a workaround for a bug in // ProcessStartInfo.WorkingDirectory - not able to handle null workingDir = "."; } // Log the fsc command line LoggingService.LogInfo (compilerName + " " + sb.ToString ()); // Compile! Dictionary<string,string> envVars = runtime.GetToolsEnvironmentVariables (project.TargetFramework); int exitCode = DoCompilation (compilerName, sb.ToString(), workingDir, envVars, gacRoots, ref output, ref error); BuildResult result = ParseOutput (output, error); if (result.CompilerOutput.Trim ().Length != 0) monitor.Log.WriteLine (result.CompilerOutput); // If compiler crashes, output entire error string if (result.ErrorCount == 0 && exitCode != 0) { try { monitor.Log.Write (File.ReadAllText (error)); } catch (IOException) { } result.AddError ("The compiler appears to have crashed. Check the build output pad for details."); } else { FileService.DeleteFile (output); FileService.DeleteFile (error); } return result; }
protected override BuildResult OnBuild (IProgressMonitor monitor, ConfigurationSelector configuration) { DotNetProject project = Project; bool hasBuildableFiles = false; foreach (ProjectFile pf in project.Files) { if (pf.BuildAction == BuildAction.Compile || pf.BuildAction == BuildAction.EmbeddedResource) { hasBuildableFiles = true; break; } } if (!hasBuildableFiles) return new BuildResult (); if (project.LanguageBinding == null) { BuildResult langres = new BuildResult (); string msg = GettextCatalog.GetString ("Unknown language '{0}'. You may need to install an additional add-in to support this language.", project.LanguageName); langres.AddError (msg); monitor.ReportError (msg, null); return langres; } BuildResult refres = null; HashSet<ProjectItem> itemsToExclude = new HashSet<ProjectItem> (); foreach (ProjectReference pr in project.References) { if (pr.ReferenceType == ReferenceType.Project) { // Ignore non-dotnet projects Project p = project.ParentSolution != null ? project.ParentSolution.FindProjectByName (pr.Reference) : null; if (p != null && !(p is DotNetProject)) continue; if (p == null || pr.GetReferencedFileNames (configuration).Length == 0) { if (refres == null) refres = new BuildResult (); string msg = GettextCatalog.GetString ("Referenced project '{0}' not found in the solution.", pr.Reference); monitor.ReportWarning (msg); refres.AddWarning (msg); } } if (!pr.IsValid) { if (refres == null) refres = new BuildResult (); string msg; if (!pr.IsExactVersion && pr.SpecificVersion) { msg = GettextCatalog.GetString ("Reference '{0}' not found on system. Using '{1}' instead.", pr.StoredReference, pr.Reference); monitor.ReportWarning (msg); refres.AddWarning (msg); } else { bool errorsFound = false; foreach (string asm in pr.GetReferencedFileNames (configuration)) { if (!File.Exists (asm)) { msg = GettextCatalog.GetString ("Assembly '{0}' not found. Make sure that the assembly exists in disk. If the reference is required to build the project you may get compilation errors.", Path.GetFileName (asm)); refres.AddWarning (msg); monitor.ReportWarning (msg); errorsFound = true; itemsToExclude.Add (pr); } } msg = null; if (!errorsFound) { msg = GettextCatalog.GetString ("The reference '{0}' is not valid for the target framework of the project.", pr.StoredReference, pr.Reference); monitor.ReportWarning (msg); refres.AddWarning (msg); itemsToExclude.Add (pr); } } } } DotNetProjectConfiguration conf = (DotNetProjectConfiguration) project.GetConfiguration (configuration); // Create a copy of the data needed to compile the project. // This data can be modified by extensions. // Also filter out items whose condition evaluates to false BuildData buildData = new BuildData (); ProjectParserContext ctx = new ProjectParserContext (project, conf); buildData.Items = new ProjectItemCollection (); foreach (ProjectItem item in project.Items) { if (!itemsToExclude.Contains (item) && (string.IsNullOrEmpty (item.Condition) || ConditionParser.ParseAndEvaluate (item.Condition, ctx))) buildData.Items.Add (item); } buildData.Configuration = (DotNetProjectConfiguration) conf.Clone (); buildData.Configuration.SetParentItem (project); buildData.ConfigurationSelector = configuration; return ProjectExtensionUtil.Compile (monitor, project, buildData, delegate { ProjectItemCollection items = buildData.Items; BuildResult res = BuildResources (buildData.Configuration, ref items, monitor); if (res != null) return res; res = project.LanguageBinding.Compile (items, buildData.Configuration, buildData.ConfigurationSelector, monitor); if (refres != null) { refres.Append (res); return refres; } else return res; }); }
public object ReadFile(string fileName, IProgressMonitor monitor) { XmlTextReader reader = new XmlTextReader (new StreamReader (fileName)); reader.MoveToContent (); string version = reader.GetAttribute ("version"); if (version == null) version = reader.GetAttribute ("fileversion"); DataSerializer serializer = new DataSerializer (Runtime.ProjectService.DataContext, fileName); IProjectReader projectReader = null; if (version == "1.0" || version == "1") { string tempFile = Path.GetTempFileName(); ConvertXml.Convert(fileName, Runtime.Properties.DataDirectory + Path.DirectorySeparatorChar + "ConversionStyleSheets" + Path.DirectorySeparatorChar + "ConvertPrjx10to11.xsl", tempFile); reader.Close (); StreamReader sr = new StreamReader (tempFile); string fdata = sr.ReadToEnd (); sr.Close (); File.Delete (tempFile); reader = new XmlTextReader (new StringReader (fdata)); projectReader = new ProjectReaderV1 (serializer); } else if (version == "1.1") { projectReader = new ProjectReaderV1 (serializer); } else if (version == "2.0") { projectReader = new ProjectReaderV2 (serializer); } if (version != "2.0") monitor.ReportWarning (string.Format (GettextCatalog.GetString ("The file '{0}' is using an old project file format. It will be automatically converted to the current format."), fileName)); try { monitor.BeginTask (string.Format (GettextCatalog.GetString ("Loading project: {0}"), fileName), 1); if (projectReader != null) return projectReader.ReadProject (reader); else throw new UnknownProjectVersionException (fileName, version); } catch (Exception ex) { monitor.ReportError (string.Format (GettextCatalog.GetString ("Could not load project: {0}"), fileName), ex); throw; } finally { monitor.EndTask (); reader.Close (); } }
//ExtendedProperties // Per config // Platform : Eg. Any CPU // SolutionConfigurationPlatforms // SolutionFolder LoadSolution (Solution sol, string fileName, MSBuildFileFormat format, IProgressMonitor monitor) { string headerComment; string version = GetSlnFileVersion (fileName, out headerComment); ListDictionary globals = null; SolutionFolder folder = null; SlnData data = null; List<Section> projectSections = null; List<string> lines = null; FileFormat projectFormat = Services.ProjectService.FileFormats.GetFileFormat (format); monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1); //Parse the .sln file using (StreamReader reader = new StreamReader(fileName)) { sol.FileName = fileName; sol.ConvertToFormat (projectFormat, false); folder = sol.RootFolder; sol.Version = "0.1"; //FIXME: data = new SlnData (); folder.ExtendedProperties [typeof (SlnFileFormat)] = data; data.VersionString = version; data.HeaderComment = headerComment; string s = null; projectSections = new List<Section> (); lines = new List<string> (); globals = new ListDictionary (); //Parse while (reader.Peek () >= 0) { s = GetNextLine (reader, lines).Trim (); if (String.Compare (s, "Global", true) == 0) { ParseGlobal (reader, lines, globals); continue; } if (s.StartsWith ("Project")) { Section sec = new Section (); projectSections.Add (sec); sec.Start = lines.Count - 1; int e = ReadUntil ("EndProject", reader, lines); sec.Count = (e < 0) ? 1 : (e - sec.Start + 1); continue; } } } monitor.BeginTask("Loading projects ..", projectSections.Count + 1); Dictionary<string, SolutionItem> items = new Dictionary<string, SolutionItem> (); List<SolutionItem> sortedList = new List<SolutionItem> (); foreach (Section sec in projectSections) { monitor.Step (1); Match match = ProjectRegex.Match (lines [sec.Start]); if (!match.Success) { LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project definition on line number #{0} in file '{1}'. Ignoring.", sec.Start + 1, fileName)); continue; } try { // Valid guid? new Guid (match.Groups [1].Value); } catch (FormatException) { //Use default guid as projectGuid LoggingService.LogDebug (GettextCatalog.GetString ( "Invalid Project type guid '{0}' on line #{1}. Ignoring.", match.Groups [1].Value, sec.Start + 1)); continue; } string projTypeGuid = match.Groups [1].Value.ToUpper (); string projectName = match.Groups [2].Value; string projectPath = match.Groups [3].Value; string projectGuid = match.Groups [4].Value; if (projTypeGuid == MSBuildProjectService.FolderTypeGuid) { //Solution folder SolutionFolder sfolder = new SolutionFolder (); sfolder.Name = projectName; MSBuildProjectService.InitializeItemHandler (sfolder); MSBuildProjectService.SetId (sfolder, projectGuid); List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DeserializeSolutionItem (sol, sfolder, projLines); foreach (string f in ReadFolderFiles (projLines)) sfolder.Files.Add (MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), f)); SlnData slnData = new SlnData (); slnData.Extra = projLines.ToArray (); sfolder.ExtendedProperties [typeof (SlnFileFormat)] = slnData; items.Add (projectGuid, sfolder); sortedList.Add (sfolder); continue; } if (projectPath.StartsWith("http://")) { monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.", fileName, sec.Start + 1, projectPath)); data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count)); continue; } string path = MSBuildProjectService.FromMSBuildPath (Path.GetDirectoryName (fileName), projectPath); if (String.IsNullOrEmpty (path)) { monitor.ReportWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); LoggingService.LogWarning (GettextCatalog.GetString ( "Invalid project path found in {0} : {1}", fileName, projectPath)); continue; } projectPath = Path.GetFullPath (path); SolutionEntityItem item = null; try { item = ProjectExtensionUtil.LoadSolutionItem (monitor, projectPath, delegate { return MSBuildProjectService.LoadItem (monitor, projectPath, projTypeGuid, projectGuid); }); if (item == null) { LoggingService.LogWarning (GettextCatalog.GetString ( "Unknown project type guid '{0}' on line #{1}. Ignoring.", projTypeGuid, sec.Start + 1)); monitor.ReportWarning (GettextCatalog.GetString ( "{0}({1}): Unsupported or unrecognized project : '{2}'.", fileName, sec.Start + 1, projectPath)); continue; } MSBuildProjectHandler handler = (MSBuildProjectHandler) item.ItemHandler; List<string> projLines = lines.GetRange (sec.Start + 1, sec.Count - 2); DataItem it = GetSolutionItemData (projLines); handler.SlnProjectContent = projLines.ToArray (); handler.ReadSlnData (it); } catch (Exception e) { if (e is UnknownSolutionItemTypeException) { var name = ((UnknownSolutionItemTypeException)e).TypeName; LoggingService.LogWarning (!string.IsNullOrEmpty (name)? string.Format ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name) : string.Format ("Could not load project '{0}' with unknown item type", projectPath)); monitor.ReportWarning (!string.IsNullOrEmpty (name)? GettextCatalog.GetString ("Could not load project '{0}' with unknown item type '{1}'", projectPath, name) : GettextCatalog.GetString ("Could not load project '{0}' with unknown item type", projectPath)); } else { LoggingService.LogError (string.Format ("Error while trying to load the project {0}", projectPath), e); monitor.ReportWarning (GettextCatalog.GetString ( "Error while trying to load the project '{0}': {1}", projectPath, e.Message)); } var uitem = new UnknownSolutionItem () { FileName = projectPath, LoadError = e.Message, }; var h = new MSBuildHandler (projTypeGuid, projectGuid) { Item = uitem, }; uitem.SetItemHandler (h); item = uitem; } if (!items.ContainsKey (projectGuid)) { items.Add (projectGuid, item); sortedList.Add (item); data.ItemsByGuid [projectGuid] = item; } else { monitor.ReportError (GettextCatalog.GetString ("Invalid solution file. There are two projects with the same GUID. The project {0} will be ignored.", projectPath), null); } } monitor.EndTask (); if (globals != null && globals.Contains ("NestedProjects")) { LoadNestedProjects (globals ["NestedProjects"] as Section, lines, items, monitor); globals.Remove ("NestedProjects"); } //Add top level folders and projects to the main folder foreach (SolutionItem ce in sortedList) { if (ce.ParentFolder == null) folder.Items.Add (ce); } //FIXME: This can be just SolutionConfiguration also! if (globals != null) { if (globals.Contains ("SolutionConfigurationPlatforms")) { LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("SolutionConfigurationPlatforms"); } if (globals.Contains ("ProjectConfigurationPlatforms")) { LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines, sol, monitor); globals.Remove ("ProjectConfigurationPlatforms"); } if (globals.Contains ("MonoDevelopProperties")) { LoadMonoDevelopProperties (globals ["MonoDevelopProperties"] as Section, lines, sol, monitor); globals.Remove ("MonoDevelopProperties"); } ArrayList toRemove = new ArrayList (); foreach (DictionaryEntry e in globals) { string name = (string) e.Key; if (name.StartsWith ("MonoDevelopProperties.")) { int i = name.IndexOf ('.'); LoadMonoDevelopConfigurationProperties (name.Substring (i+1), (Section)e.Value, lines, sol, monitor); toRemove.Add (e.Key); } } foreach (object key in toRemove) globals.Remove (key); } //Save the global sections that we dont use List<string> globalLines = new List<string> (); foreach (Section sec in globals.Values) globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count)); data.GlobalExtra = globalLines; monitor.EndTask (); return folder; }
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 (); } }
static bool SyncFile (IProgressMonitor monitor, XcodeSyncBackContext context, XcodeSyncFileBackJob file) { if (!Directory.Exists (file.Original.ParentDirectory)) Directory.CreateDirectory (file.Original.ParentDirectory); var tempFile = file.Original.ParentDirectory.Combine (".#" + file.Original.ParentDirectory.FileName); FilePath path = context.ProjectDir.Combine (file.SyncedRelative); if (File.Exists (path)) { File.Copy (path, tempFile); FileService.SystemRename (tempFile, file.Original); DateTime mtime = File.GetLastWriteTime (file.Original); context.SetSyncTime (file.SyncedRelative, mtime); return true; } else { monitor.ReportWarning (string.Format ("'{0}' does not exist.", file.SyncedRelative)); return false; } }
void RecDeleteDir(IProgressMonitor monitor, string path) { if (Directory.GetFiles (path).Length != 0) return; foreach (string dir in Directory.GetDirectories (path)) RecDeleteDir (monitor, dir); try { Directory.Delete (path); } catch { monitor.ReportWarning ("Directory " + path + " could not be deleted."); } }
public virtual void UpdateCatalog(TranslationProject project, Catalog catalog, IProgressMonitor monitor, string fileName) { string text = File.ReadAllText(fileName); string relativeFileName = MonoDevelop.Core.FileService.AbsoluteToRelativePath(project.BaseDirectory, fileName); string fileNamePrefix = relativeFileName + ":"; if (String.IsNullOrEmpty(text)) { return; } // Get a list of all excluded regions List <Match> excludeMatches = new List <Match> (); foreach (Regex regex in excluded) { foreach (Match m in regex.Matches(text)) { excludeMatches.Add(m); } } // Sort the list by match index excludeMatches.Sort(delegate(Match a, Match b) { return(a.Index.CompareTo(b.Index)); }); // Remove from the list all regions which start in an excluded region int pos = 0; for (int n = 0; n < excludeMatches.Count; n++) { Match m = excludeMatches [n]; if (m.Index < pos) { excludeMatches.RemoveAt(n); n--; } else { pos = m.Index + m.Length; } } foreach (RegexInfo ri in regexes) { int lineNumber = 0; int oldIndex = 0; foreach (Match match in ri.Regex.Matches(text)) { // Ignore matches inside excluded regions bool ignore = false; foreach (Match em in excludeMatches) { if (match.Index >= em.Index && match.Index < em.Index + em.Length) { ignore = true; LoggingService.LogDebug("Excluded Gettext string '{0}' in file '{1}'", match.Groups[ri.ValueGroupIndex].Value, fileName); break; } } if (ignore) { continue; } string mt = match.Groups[ri.ValueGroupIndex].Value; if (mt.Length == 0) { continue; } foreach (TransformInfo ti in transforms) { mt = ti.Regex.Replace(mt, ti.ReplaceText); } try { mt = StringEscaping.UnEscape(ri.EscapeMode, mt); } catch (FormatException fex) { monitor.ReportWarning("Error unescaping string '" + mt + "': " + fex.Message); continue; } if (mt.Trim().Length == 0) { continue; } //get the plural string if it's a plural form and apply transforms string pt = ri.PluralGroupIndex != -1 ? match.Groups[ri.PluralGroupIndex].Value : null; if (pt != null) { foreach (TransformInfo ti in transforms) { pt = ti.Regex.Replace(pt, ti.ReplaceText); } } //add to the catalog CatalogEntry entry = catalog.AddItem(mt, pt); lineNumber += GetLineCount(text, oldIndex, match.Index); oldIndex = match.Index; entry.AddReference(fileNamePrefix + lineNumber); } } }
public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) { var compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters (); var projectParameters = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters (); FilePath outputName = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName (); //make sure that the output file is writable if (File.Exists (outputName)) { bool isWriteable = false; int count = 0; do { try { outputName.MakeWritable (); using (var stream = File.OpenWrite (outputName)) { isWriteable = true; } } catch (Exception) { Thread.Sleep (20); } } while (count++ < 5 && !isWriteable); if (!isWriteable) { MessageService.ShowError (string.Format (GettextCatalog.GetString ("Can't lock file: {0}."), outputName)); return null; } } //get the runtime TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime; DotNetProject project = configuration.ParentItem as DotNetProject; if (project != null) runtime = project.TargetRuntime; //get the compiler name string compilerName; try { compilerName = GetCompilerName (runtime, configuration.TargetFramework); } catch (Exception e) { string message = "Could not obtain a C# compiler"; monitor.ReportError (message, e); return null; } var sb = new StringBuilder (); HashSet<string> alreadyAddedReference = new HashSet<string> (); var monoRuntime = runtime as MonoTargetRuntime; if (!compilerParameters.NoStdLib && (monoRuntime == null || monoRuntime.HasMultitargetingMcs)) { string corlib = project.AssemblyContext.GetAssemblyFullName ("mscorlib", project.TargetFramework); if (corlib != null) { corlib = project.AssemblyContext.GetAssemblyLocation (corlib, project.TargetFramework); } if (corlib == null) { var br = new BuildResult (); br.AddError (string.Format ("Could not find mscorlib for framework {0}", project.TargetFramework.Id)); return br; } AppendQuoted (sb, "/r:", corlib); sb.AppendLine ("-nostdlib"); } List<string> gacRoots = new List<string> (); sb.AppendFormat ("\"/out:{0}\"", outputName); sb.AppendLine (); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { if (lib.ReferenceType == ReferenceType.Project) { var ownerProject = lib.OwnerProject; if (ownerProject != null) { var parentSolution = ownerProject.ParentSolution; if (parentSolution != null && !(parentSolution.FindProjectByName (lib.Reference) is DotNetProject)) continue; } } string refPrefix = string.IsNullOrEmpty (lib.Aliases) ? "" : lib.Aliases + "="; foreach (string fileName in lib.GetReferencedFileNames (configSelector)) { switch (lib.ReferenceType) { case ReferenceType.Package: SystemPackage pkg = lib.Package; if (pkg == null) { string msg = string.Format (GettextCatalog.GetString ("{0} could not be found or is invalid."), lib.Reference); monitor.ReportWarning (msg); continue; } if (alreadyAddedReference.Add (fileName)) AppendQuoted (sb, "/r:", refPrefix + fileName); if (pkg.GacRoot != null && !gacRoots.Contains (pkg.GacRoot)) gacRoots.Add (pkg.GacRoot); if (!string.IsNullOrEmpty (pkg.Requires)) { foreach (string requiredPackage in pkg.Requires.Split(' ')) { SystemPackage rpkg = runtime.AssemblyContext.GetPackage (requiredPackage); if (rpkg == null) continue; foreach (SystemAssembly assembly in rpkg.Assemblies) { if (alreadyAddedReference.Add (assembly.Location)) AppendQuoted (sb, "/r:", assembly.Location); } } } break; default: if (alreadyAddedReference.Add (fileName)) AppendQuoted (sb, "/r:", refPrefix + fileName); break; } } } if (alreadyAddedReference.Any (reference => SystemAssemblyService.ContainsReferenceToSystemRuntime (reference))) { LoggingService.LogInfo ("Found PCLv2 assembly."); var facades = runtime.FindFacadeAssembliesForPCL (project.TargetFramework); foreach (var facade in facades) AppendQuoted (sb, "/r:", facade); } string sysCore = project.AssemblyContext.GetAssemblyFullName ("System.Core", project.TargetFramework); if (sysCore != null && !alreadyAddedReference.Contains (sysCore)) { var asm = project.AssemblyContext.GetAssemblyFromFullName (sysCore, null, project.TargetFramework); if (asm != null) AppendQuoted (sb, "/r:", asm.Location); } sb.AppendLine ("/nologo"); sb.Append ("/warn:");sb.Append (compilerParameters.WarningLevel.ToString ()); sb.AppendLine (); if (configuration.SignAssembly) { if (File.Exists (configuration.AssemblyKeyFile)) AppendQuoted (sb, "/keyfile:", configuration.AssemblyKeyFile); if (configuration.DelaySign) sb.AppendLine ("/delaySign"); } var debugType = compilerParameters.DebugType; if (string.IsNullOrEmpty (debugType)) { debugType = configuration.DebugMode ? "full" : "none"; } else if (string.Equals (debugType, "pdbonly", StringComparison.OrdinalIgnoreCase)) { //old Mono compilers don't support pdbonly if (monoRuntime != null && !monoRuntime.HasMultitargetingMcs) debugType = "full"; } if (!string.Equals (debugType, "none", StringComparison.OrdinalIgnoreCase)) { sb.AppendLine ("/debug:" + debugType); } if (compilerParameters.LangVersion != LangVersion.Default) { var langVersionString = CSharpCompilerParameters.TryLangVersionToString (compilerParameters.LangVersion); if (langVersionString == null) { string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString () + "'"; monitor.ReportError (message, null); LoggingService.LogError (message); return null; } sb.AppendLine ("/langversion:" + langVersionString); } // mcs default is + but others might not be if (compilerParameters.Optimize) sb.AppendLine ("/optimize+"); else sb.AppendLine ("/optimize-"); bool hasWin32Res = !string.IsNullOrEmpty (projectParameters.Win32Resource) && File.Exists (projectParameters.Win32Resource); if (hasWin32Res) AppendQuoted (sb, "/win32res:", projectParameters.Win32Resource); if (!string.IsNullOrEmpty (projectParameters.Win32Icon) && File.Exists (projectParameters.Win32Icon)) { if (hasWin32Res) { monitor.ReportWarning ("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon."); } else { AppendQuoted (sb, "/win32icon:", projectParameters.Win32Icon); } } if (projectParameters.CodePage != 0) sb.AppendLine ("/codepage:" + projectParameters.CodePage); else if (runtime is MonoTargetRuntime) sb.AppendLine ("/codepage:utf8"); if (compilerParameters.UnsafeCode) sb.AppendLine ("-unsafe"); if (compilerParameters.NoStdLib) sb.AppendLine ("-nostdlib"); if (!string.IsNullOrEmpty (compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower () != "anycpu") { //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation ("Mono.Debugger.Soft", null) == null) { LoggingService.LogWarning ("Mono runtime '" + runtime.DisplayName + "' appears to be too old to support the 'platform' C# compiler flag."); } else { sb.AppendLine ("/platform:" + compilerParameters.PlatformTarget); } } if (compilerParameters.TreatWarningsAsErrors) { sb.AppendLine ("-warnaserror"); if (!string.IsNullOrEmpty (compilerParameters.WarningsNotAsErrors)) sb.AppendLine ("-warnaserror-:" + compilerParameters.WarningsNotAsErrors); } foreach (var define in configuration.GetDefineSymbols ()) { AppendQuoted (sb, "/define:", define); sb.AppendLine (); } CompileTarget ctarget = configuration.CompileTarget; if (!string.IsNullOrEmpty (projectParameters.MainClass)) { sb.AppendLine ("/main:" + projectParameters.MainClass); // mcs does not allow providing a Main class when compiling a dll // As a workaround, we compile as WinExe (although the output will still // have a .dll extension). if (ctarget == CompileTarget.Library) ctarget = CompileTarget.WinExe; } switch (ctarget) { case CompileTarget.Exe: sb.AppendLine ("/t:exe"); break; case CompileTarget.WinExe: sb.AppendLine ("/t:winexe"); break; case CompileTarget.Library: sb.AppendLine ("/t:library"); break; } foreach (ProjectFile finfo in projectItems.GetAll<ProjectFile> ()) { if (finfo.Subtype == Subtype.Directory) continue; switch (finfo.BuildAction) { case "Compile": AppendQuoted (sb, "", finfo.Name); break; case "EmbeddedResource": string fname = finfo.Name; if (string.Compare (Path.GetExtension (fname), ".resx", StringComparison.OrdinalIgnoreCase) == 0) fname = Path.ChangeExtension (fname, ".resources"); sb.Append ('"');sb.Append ("/res:"); sb.Append (fname);sb.Append (',');sb.Append (finfo.ResourceId); sb.Append ('"');sb.AppendLine (); break; default: continue; } } if (!compilerParameters.DocumentationFile.IsNullOrEmpty) AppendQuoted (sb, "/doc:", compilerParameters.DocumentationFile); if (!string.IsNullOrEmpty (compilerParameters.NoWarnings)) AppendQuoted (sb, "/nowarn:", compilerParameters.NoWarnings); if (runtime.RuntimeId == "MS.NET") { sb.AppendLine("/fullpaths"); sb.AppendLine("/utf8output"); } string output = ""; string error = ""; File.WriteAllText (responseFileName, sb.ToString ()); monitor.Log.WriteLine (compilerName + " /noconfig " + sb.ToString ().Replace ('\n',' ')); // Dummy projects created for single files have no filename // and so no BaseDirectory. string workingDir = null; if (configuration.ParentItem != null) workingDir = configuration.ParentItem.BaseDirectory; LoggingService.LogInfo (compilerName + " " + sb); ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment (project.TargetFramework); string cargs = "/noconfig @\"" + responseFileName + "\""; int exitCode = DoCompilation (monitor, compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error); BuildResult result = ParseOutput (workingDir, output, error); if (result.CompilerOutput.Trim ().Length != 0) monitor.Log.WriteLine (result.CompilerOutput); //if compiler crashes, output entire error string if (result.ErrorCount == 0 && exitCode != 0) { try { monitor.Log.Write (File.ReadAllText (error)); } catch (IOException) { } result.AddError ("The compiler appears to have crashed. Check the build output pad for details."); LoggingService.LogError ("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'", responseFileName, output, error); } else { FileService.DeleteFile (responseFileName); FileService.DeleteFile (output); FileService.DeleteFile (error); } return result; }
void BuildDone(IProgressMonitor monitor, ICompilerResult result) { lastResult = result; monitor.Log.WriteLine (); monitor.Log.WriteLine (String.Format (GettextCatalog.GetString ("---------------------- Done ----------------------"))); foreach (CompilerError err in result.CompilerResults.Errors) { Runtime.TaskService.AddTask (new Task(null, err)); } if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) { monitor.ReportSuccess (GettextCatalog.GetString ("Build successful.")); } else if (result.ErrorCount == 0 && result.WarningCount > 0) { monitor.ReportWarning (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount)); } else if (result.ErrorCount > 0) { monitor.ReportError (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount), null); } else { monitor.ReportError (String.Format (GettextCatalog.GetString ("Build failed.")), null); } OnEndBuild (lastResult.FailedBuildCount == 0); }
//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; }
internal override void PrepareUninstall (IProgressMonitor monitor, AddinStore service) { iaddin = service.Registry.GetAddin (info.Id, true); if (iaddin == null) throw new InstallException (string.Format ("The add-in '{0}' is not installed.", info.Name)); AddinDescription conf = iaddin.Description; string basePath = Path.GetDirectoryName (conf.AddinFile); if (!File.Exists (iaddin.AddinFile)) { monitor.ReportWarning (string.Format ("The add-in '{0}' is scheduled for uninstalling, but the add-in file could not be found.", info.Name)); return; } if (!service.HasWriteAccess (iaddin.AddinFile)) throw new InstallException (AddinStore.GetUninstallErrorNoRoot (info)); foreach (string relPath in conf.AllFiles) { string path = Path.Combine (basePath, relPath); if (!File.Exists (path)) continue; if (!service.HasWriteAccess (path)) throw new InstallException (AddinStore.GetUninstallErrorNoRoot (info)); } tempFolder = CreateTempFolder (); CopyAddinFiles (monitor, conf, iaddin.AddinFile, tempFolder); }
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; }
internal override void PrepareUninstall(IProgressMonitor monitor, AddinStore service) { iaddin = service.Registry.GetAddin (info.Id, true); if (iaddin == null) throw new InstallException (string.Format ("The add-in '{0}' is not installed.", info.Name)); AddinDescription conf = iaddin.Description; if (!File.Exists (iaddin.AddinFile)) { monitor.ReportWarning (string.Format ("The add-in '{0}' is scheduled for uninstalling, but the add-in file could not be found.", info.Name)); return; } // The add-in is a core application add-in. It can't be uninstalled, so it will be disabled. if (!service.IsUserAddin (iaddin.AddinFile)) { disablingOnUninstall = true; return; } // If the add-in assemblies are loaded, or if there is any file with a write lock, delay the uninstallation HashSet<string> files = new HashSet<string> (GetInstalledFiles (conf)); if (AddinManager.CheckAssembliesLoaded (files) || files.Any (f => HasWriteLock (f))) { uninstallingLoaded = true; return; } if (!service.HasWriteAccess (iaddin.AddinFile)) throw new InstallException (AddinStore.GetUninstallErrorNoRoot (info)); foreach (string path in GetInstalledFiles (conf)) { if (!service.HasWriteAccess (path)) throw new InstallException (AddinStore.GetUninstallErrorNoRoot (info)); } tempFolder = CreateTempFolder (); CopyAddinFiles (monitor, conf, iaddin.AddinFile, tempFolder); }
protected void GetReferences (Project project, MonoDevelop.Prj2Make.Schema.Csproj.Reference[] References, ProjectReferenceCollection references, IProgressMonitor monitor) { if (References == null || References.Length == 0) return; monitor.BeginTask (null, 5 + References.Length); try { // Get the GAC path string strBasePathMono1_0 = GetPackageDirectory ("mono", "mono/1.0"); monitor.Step (1); string strBasePathGtkSharp = GetPackageDirectory ("gtk-sharp", "mono/gtk-sharp"); monitor.Step (1); string strBasePathGtkSharp2_0 = GetPackageDirectory ("gtk-sharp-2.0", "mono/gtk-sharp-2.0"); monitor.Step (1); string strBasePathGeckoSharp = GetPackageDirectory ("gecko-sharp", "mono/gecko-sharp"); monitor.Step (1); string strBasePathGeckoSharp2_0 = GetPackageDirectory ("gecko-sharp-2.0", "mono/gecko-sharp-2.0"); string[] monoLibs = new string [] { strBasePathMono1_0, strBasePathGtkSharp2_0, strBasePathGtkSharp, strBasePathGeckoSharp2_0, strBasePathGeckoSharp }; // Iterate through the reference collection of the csproj file foreach (MonoDevelop.Prj2Make.Schema.Csproj.Reference rf in References) { monitor.Step (1); ProjectReference rfOut = null; if (rf.Package != null && rf.Package.Length != 0) { rfOut = new ProjectReference (MonoDevelop.Projects.ReferenceType.Project, Path.GetFileName (rf.Name)); rfOut.LocalCopy = true; references.Add (rfOut); } else if (rf.AssemblyName != null) { string rname = rf.AssemblyName; if (rname == "System.XML") rname = "System.Xml"; string oref = Runtime.SystemAssemblyService.DefaultAssemblyContext.GetAssemblyFullName (rname, fx); if (oref == null) { if (rf.HintPath != null) { string asm = MapPath (project.ItemDirectory, rf.HintPath); if (!System.IO.File.Exists (asm)) monitor.ReportWarning (GettextCatalog.GetString ("Referenced assembly not found: ") + asm); ProjectReference aref = new ProjectReference (MonoDevelop.Projects.ReferenceType.Assembly, asm); references.Add (aref); continue; } monitor.ReportWarning (GettextCatalog.GetString ("Assembly reference could not be imported: ") + rf.AssemblyName); continue; } rfOut = new ProjectReference (MonoDevelop.Projects.ReferenceType.Gac, oref); rfOut.LocalCopy = true; references.Add (rfOut); } else if (rf.HintPath != null) { // HACK - under Unix filenames are case sensitive // Under Windows there's no agreement on Xml vs XML ;-) if (Path.GetFileName (rf.HintPath) == "System.XML.dll") { ProjectReference pref = GetMonoReferece (strBasePathMono1_0, "System.Xml.dll"); if (pref != null) { references.Add (pref); continue; } } else { foreach (string libDir in monoLibs) { if (libDir == null) continue; if (rf.HintPath == null) continue; rfOut = GetMonoReferece (libDir, rf.HintPath); if (rfOut != null) break; } if (rfOut == null) { rfOut = new ProjectReference (MonoDevelop.Projects.ReferenceType.Gac, Path.GetFileName (rf.HintPath)); rfOut.LocalCopy = true; } references.Add (rfOut); } } else { monitor.ReportWarning (GettextCatalog.GetString ("Assembly reference could not be imported: ") + rf.Name); } } } finally { monitor.EndTask (); } }
public static BuildResult Compile (ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) { CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters (); CSharpProjectParameters projectParameters = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters (); string outputName = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName(); if (File.Exists (outputName)) { bool isWriteable = false; int count = 0; do { try { using (var stream = File.OpenWrite (outputName)) { isWriteable = true; } } catch (Exception) { Thread.Sleep (20); } } while (count++ < 5 && !isWriteable); if (!isWriteable) { MessageService.ShowError (string.Format (GettextCatalog.GetString ("Can't lock file: {0}."), outputName)); return null; } } TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime; DotNetProject project = configuration.ParentItem as DotNetProject; if (project != null) runtime = project.TargetRuntime; StringBuilder sb = new StringBuilder (); List<string> gacRoots = new List<string> (); sb.AppendFormat ("\"/out:{0}\"", outputName); sb.AppendLine (); HashSet<string> alreadyAddedReference = new HashSet<string> (); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName (lib.Reference) is DotNetProject)) continue; foreach (string fileName in lib.GetReferencedFileNames (configSelector)) { switch (lib.ReferenceType) { case ReferenceType.Gac: SystemPackage pkg = lib.Package; if (pkg == null) { string msg = string.Format (GettextCatalog.GetString ("{0} could not be found or is invalid."), lib.Reference); monitor.ReportWarning (msg); continue; } if (alreadyAddedReference.Add (fileName)) AppendQuoted (sb, "/r:", fileName); if (pkg.GacRoot != null && !gacRoots.Contains (pkg.GacRoot)) gacRoots.Add (pkg.GacRoot); if (!string.IsNullOrEmpty (pkg.Requires)) { foreach (string requiredPackage in pkg.Requires.Split(' ')) { SystemPackage rpkg = runtime.AssemblyContext.GetPackage (requiredPackage); if (rpkg == null) continue; foreach (SystemAssembly assembly in rpkg.Assemblies) { if (alreadyAddedReference.Add (assembly.Location)) AppendQuoted (sb, "/r:", assembly.Location); } } } break; default: if (alreadyAddedReference.Add (fileName)) AppendQuoted (sb, "/r:", fileName); break; } } } sb.AppendLine ("/nologo"); sb.Append ("/warn:");sb.Append (compilerParameters.WarningLevel.ToString ()); sb.AppendLine (); if (configuration.SignAssembly) { if (File.Exists (configuration.AssemblyKeyFile)) AppendQuoted (sb, "/keyfile:", configuration.AssemblyKeyFile); } if (configuration.DebugMode) { sb.AppendLine ("/debug:+"); sb.AppendLine ("/debug:full"); } switch (compilerParameters.LangVersion) { case LangVersion.Default: break; case LangVersion.ISO_1: sb.AppendLine ("/langversion:ISO-1"); break; case LangVersion.ISO_2: sb.AppendLine ("/langversion:ISO-2"); break; default: string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString () + "'"; monitor.ReportError (message, null); LoggingService.LogError (message); return null; } // mcs default is + but others might not be if (compilerParameters.Optimize) sb.AppendLine ("/optimize+"); else sb.AppendLine ("/optimize-"); bool hasWin32Res = !string.IsNullOrEmpty (projectParameters.Win32Resource) && File.Exists (projectParameters.Win32Resource); if (hasWin32Res) AppendQuoted (sb, "/win32res:", projectParameters.Win32Resource); if (!string.IsNullOrEmpty (projectParameters.Win32Icon) && File.Exists (projectParameters.Win32Icon)) { if (hasWin32Res) { monitor.ReportWarning ("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon."); } else { AppendQuoted (sb, "/win32icon:", projectParameters.Win32Icon); } } if (projectParameters.CodePage != 0) sb.AppendLine ("/codepage:" + projectParameters.CodePage); else if (runtime is MonoTargetRuntime) sb.AppendLine ("/codepage:utf8"); if (compilerParameters.UnsafeCode) sb.AppendLine ("-unsafe"); if (compilerParameters.NoStdLib) sb.AppendLine ("-nostdlib"); if (!string.IsNullOrEmpty (compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower () != "anycpu") { //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation ("Mono.Debugger.Soft", null) == null) { LoggingService.LogWarning ("Mono runtime '" + runtime.DisplayName + "' appears to be too old to support the 'platform' C# compiler flag."); } else { sb.AppendLine ("/platform:" + compilerParameters.PlatformTarget); } } if (compilerParameters.TreatWarningsAsErrors) { sb.AppendLine ("-warnaserror"); if (!string.IsNullOrEmpty (compilerParameters.WarningsNotAsErrors)) sb.AppendLine ("-warnaserror-:" + compilerParameters.WarningsNotAsErrors); } if (compilerParameters.DefineSymbols.Length > 0) { string define_str = string.Join (";", compilerParameters.DefineSymbols.Split (new char [] {',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries)); if (define_str.Length > 0) { AppendQuoted (sb, "/define:", define_str); sb.AppendLine (); } } CompileTarget ctarget = configuration.CompileTarget; if (!string.IsNullOrEmpty (projectParameters.MainClass)) { sb.AppendLine ("/main:" + projectParameters.MainClass); // mcs does not allow providing a Main class when compiling a dll // As a workaround, we compile as WinExe (although the output will still // have a .dll extension). if (ctarget == CompileTarget.Library) ctarget = CompileTarget.WinExe; } switch (ctarget) { case CompileTarget.Exe: sb.AppendLine ("/t:exe"); break; case CompileTarget.WinExe: sb.AppendLine ("/t:winexe"); break; case CompileTarget.Library: sb.AppendLine ("/t:library"); break; } foreach (ProjectFile finfo in projectItems.GetAll<ProjectFile> ()) { if (finfo.Subtype == Subtype.Directory) continue; switch (finfo.BuildAction) { case "Compile": AppendQuoted (sb, "", finfo.Name); break; case "EmbeddedResource": string fname = finfo.Name; if (string.Compare (Path.GetExtension (fname), ".resx", true) == 0) fname = Path.ChangeExtension (fname, ".resources"); sb.Append ('"');sb.Append ("/res:"); sb.Append (fname);sb.Append (',');sb.Append (finfo.ResourceId); sb.Append ('"');sb.AppendLine (); break; default: continue; } } if (compilerParameters.GenerateXmlDocumentation) AppendQuoted (sb, "/doc:", Path.ChangeExtension (outputName, ".xml")); if (!string.IsNullOrEmpty (compilerParameters.AdditionalArguments)) sb.AppendLine (compilerParameters.AdditionalArguments); if (!string.IsNullOrEmpty (compilerParameters.NoWarnings)) AppendQuoted (sb, "/nowarn:", compilerParameters.NoWarnings); if (runtime.RuntimeId == "MS.NET") { sb.AppendLine("/fullpaths"); sb.AppendLine("/utf8output"); } string output = ""; string error = ""; File.WriteAllText (responseFileName, sb.ToString ()); string compilerName; try { compilerName = GetCompilerName (runtime, configuration.TargetFramework); } catch (Exception e) { string message = "Could not obtain a C# compiler"; monitor.ReportError (message, e); return null; } monitor.Log.WriteLine (compilerName + " /noconfig " + sb.ToString ().Replace ('\n',' ')); string workingDir = "."; if (configuration.ParentItem != null) { workingDir = configuration.ParentItem.BaseDirectory; if (workingDir == null) // Dummy projects created for single files have no filename // and so no BaseDirectory. // This is a workaround for a bug in // ProcessStartInfo.WorkingDirectory - not able to handle null workingDir = "."; } LoggingService.LogInfo (compilerName + " " + sb.ToString ()); ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment (project.TargetFramework); string cargs = "/noconfig @\"" + responseFileName + "\""; int exitCode = DoCompilation (compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error); BuildResult result = ParseOutput (output, error); if (result.CompilerOutput.Trim ().Length != 0) monitor.Log.WriteLine (result.CompilerOutput); //if compiler crashes, output entire error string if (result.ErrorCount == 0 && exitCode != 0) { try { monitor.Log.Write (File.ReadAllText (error)); } catch (IOException) { } result.AddError ("The compiler appears to have crashed. Check the build output pad for details."); LoggingService.LogError ("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'", responseFileName, output, error); } else { FileService.DeleteFile (responseFileName); FileService.DeleteFile (output); FileService.DeleteFile (error); } return result; }
void CheckForPackageUpdates ( IProgressMonitor progressMonitor, ProgressMonitorStatusMessage progressMessage, PackageUpdatesEventMonitor eventMonitor) { updatedPackagesInSolution.CheckForUpdates (); if (updatedPackagesInSolution.AnyUpdates ()) { progressMonitor.ReportSuccess (GettextCatalog.GetString ("Package updates are available.")); } else if (eventMonitor.WarningReported) { progressMonitor.ReportWarning (progressMessage.Warning); } else { progressMonitor.ReportSuccess (progressMessage.Success); } }
/// <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 { type.BaseCliType = defaultNamespace + "." + provider.CreateValidIdentifier(type.BaseObjCType); monitor.ReportWarning(string.Format("Failed to resolve Objective-C type {0} to CLI type on type {1}", type.BaseObjCType, type.ObjCName)); } } // 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); monitor.ReportWarning(string.Format("Failed to resolve Objective-C type {0} to CLI type on outlet {1} on type {2}", outlet.ObjCType, outlet.ObjCName, type.ObjCName)); } } // 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); monitor.ReportWarning(string.Format("Failed to resolve Objective-C type {0} to CLI type on action parameter {1} for action {2} on type {3}", param.ObjCType, param.Name, action.ObjCName, type.ObjCName)); } } } }
protected SolutionItemConfiguration CreateConfigurationBlock (MonoDevelop.Projects.DotNetProject project, Config ConfigBlock, string AssemblyName, string OuputType, IProgressMonitor monitor) { DotNetProjectConfiguration confObj = project.CreateConfiguration (ConfigBlock.Name) as DotNetProjectConfiguration; confObj.RunWithWarnings = false; confObj.DebugMode = ConfigBlock.DebugSymbols; project.CompileTarget = (CompileTarget) Enum.Parse (typeof(CompileTarget), OuputType, true); string dir = MapPath (project.BaseDirectory, ConfigBlock.OutputPath); if (dir == null) { dir = Path.Combine ("bin", ConfigBlock.Name); monitor.ReportWarning (string.Format (GettextCatalog.GetString ("Output directory '{0}' can't be mapped to a local directory. The directory '{1}' will be used instead"), ConfigBlock.OutputPath, dir)); } confObj.OutputDirectory = dir; confObj.OutputAssembly = AssemblyName; CSharpCompilerParameters compilerParams = new CSharpCompilerParameters (); compilerParams.WarningLevel = ConfigBlock.WarningLevel; compilerParams.NoWarnings = ""; compilerParams.Optimize = ConfigBlock.Optimize; compilerParams.DefineSymbols = ConfigBlock.DefineConstants; compilerParams.UnsafeCode = ConfigBlock.AllowUnsafeBlocks; compilerParams.GenerateOverflowChecks = ConfigBlock.CheckForOverflowUnderflow; return confObj; }
/// <summary> /// Validates the schema. /// </summary> public static XmlSchema ValidateSchema (IProgressMonitor monitor, string xml, string fileName) { monitor.BeginTask (GettextCatalog.GetString ("Validating schema..."), 1); bool error = false; XmlSchema schema = null; try { StringReader stringReader = new StringReader (xml); XmlTextReader xmlReader = new XmlTextReader (stringReader); xmlReader.XmlResolver = null; ValidationEventHandler callback = delegate (object source, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { monitor.ReportWarning (args.Message); } else { monitor.ReportError (args.Message, args.Exception); error = true; } AddTask (fileName, args.Message, args.Exception.LinePosition, args.Exception.LineNumber, (args.Severity == XmlSeverityType.Warning)? TaskSeverity.Warning : TaskSeverity.Error); }; schema = XmlSchema.Read (xmlReader, callback); XmlSchemaSet sset = new XmlSchemaSet (); sset.Add (schema); sset.ValidationEventHandler += callback; sset.Compile (); } catch (XmlSchemaException ex) { monitor.ReportError (ex.Message, ex); AddTask (fileName, ex.Message, ex.LinePosition, ex.LineNumber,TaskSeverity.Error); error = true; } 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 ("Schema is valid.")); } monitor.EndTask (); return error? null: schema; }
public void ReportWarning(string message) { monitor.ReportWarning(message); }
public virtual void UpdateCatalog (TranslationProject project, Catalog catalog, IProgressMonitor monitor, string fileName) { string text = File.ReadAllText (fileName); string relativeFileName = MonoDevelop.Core.FileService.AbsoluteToRelativePath (project.BaseDirectory, fileName); string fileNamePrefix = relativeFileName + ":"; if (String.IsNullOrEmpty (text)) return; // Get a list of all excluded regions List<Match> excludeMatches = new List<Match> (); foreach (Regex regex in excluded) { foreach (Match m in regex.Matches (text)) excludeMatches.Add (m); } // Sort the list by match index excludeMatches.Sort (delegate (Match a, Match b) { return a.Index.CompareTo (b.Index); }); // Remove from the list all regions which start in an excluded region int pos=0; for (int n=0; n<excludeMatches.Count; n++) { Match m = excludeMatches [n]; if (m.Index < pos) { excludeMatches.RemoveAt (n); n--; } else { pos = m.Index + m.Length; } } foreach (RegexInfo ri in regexes) { int lineNumber = 0; int oldIndex = 0; foreach (Match match in ri.Regex.Matches (text)) { // Ignore matches inside excluded regions bool ignore = false; foreach (Match em in excludeMatches) { if (match.Index >= em.Index && match.Index < em.Index + em.Length) { ignore = true; LoggingService.LogDebug ("Excluded Gettext string '{0}' in file '{1}'", match.Groups[ri.ValueGroupIndex].Value, fileName); break; } } if (ignore) continue; string mt = match.Groups[ri.ValueGroupIndex].Value; if (mt.Length == 0) continue; foreach (TransformInfo ti in transforms) mt = ti.Regex.Replace (mt, ti.ReplaceText); try { mt = StringEscaping.UnEscape (ri.EscapeMode, mt); } catch (FormatException fex) { monitor.ReportWarning ("Error unescaping string '" + mt + "': " + fex.Message); continue; } if (mt.Trim().Length == 0) continue; //get the plural string if it's a plural form and apply transforms string pt = ri.PluralGroupIndex != -1 ? match.Groups[ri.PluralGroupIndex].Value : null; if (pt != null) foreach (TransformInfo ti in transforms) pt = ti.Regex.Replace (pt, ti.ReplaceText); //add to the catalog CatalogEntry entry = catalog.AddItem (mt, pt); lineNumber += GetLineCount (text, oldIndex, match.Index); oldIndex = match.Index; entry.AddReference (fileNamePrefix + lineNumber); } } }
public Makefile Deploy(AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor) { generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile; monitor.BeginTask(GettextCatalog.GetString( "Creating {0} for Project {1}", generateAutotools ? "Makefile.am" : "Makefile", entry.Name), 1); Makefile makefile = new Makefile(); try { if (!CanDeploy(entry, generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile)) { throw new Exception(GettextCatalog.GetString("Not a deployable project.")); } Project project = entry as Project; TemplateEngine templateEngine = new TemplateEngine(); ISimpleAutotoolsSetup setup = FindSetupForProject(project); // Handle files to be deployed deployDirs = new Dictionary <string, StringBuilder> (); deployFileVars = new Dictionary <string, string> (); builtFiles = new List <string> (); deployFileCopyVars = new StringBuilder(); deployFileCopyTargets = new StringBuilder(); //used only for simple makefile generation templateFilesTargets = null; installTarget = null; installDeps = null; installDirs = null; uninstallTarget = null; // handle configuration specific variables conf_vars = new StringBuilder(); // grab all project files files = new StringBuilder(); res_files = new StringBuilder(); extras = new StringBuilder(); datafiles = new StringBuilder(); Set <string> extraFiles = new Set <string> (); string includes = String.Empty; string references, dllReferences; DotNetProject netProject = project as DotNetProject; ProcessProjectReferences(netProject, out references, out dllReferences, ctx); templateEngine.Variables["REFERENCES"] = references; templateEngine.Variables["DLL_REFERENCES"] = dllReferences; templateEngine.Variables["WARNING"] = "Warning: This is an automatically generated file, do not edit!"; DotNetProject dotnetProject = entry as DotNetProject; if (dotnetProject != null) { string resgen = "resgen"; if (System.Environment.Version.Major >= 2) { switch (dotnetProject.TargetFramework.ClrVersion) { case ClrVersion.Net_1_1: resgen = "resgen1"; break; default: resgen = "resgen2"; break; } } templateEngine.Variables ["RESGEN"] = resgen; } string pfpath = null; foreach (ProjectFile projectFile in project.Files) { pfpath = FileService.NormalizeRelativePath(projectFile.FilePath.ToRelative(project.BaseDirectory)); switch (projectFile.BuildAction) { case BuildAction.Compile: if (projectFile.Subtype != Subtype.Code) { continue; } files.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath)); break; case BuildAction.Content: case BuildAction.None: extraFiles.Add(MakefileData.ToMakefilePath(pfpath)); break; case BuildAction.EmbeddedResource: if (!projectFile.FilePath.IsChildPathOf(ctx.BaseDirectory)) { // file is not within directory hierarchy, copy it in string rdir = Path.Combine(Path.GetDirectoryName(project.FileName), resourcedir); if (!Directory.Exists(rdir)) { Directory.CreateDirectory(rdir); } string newPath = Path.Combine(rdir, Path.GetFileName(projectFile.FilePath)); FileService.CopyFile(projectFile.FilePath, newPath); pfpath = project.GetRelativeChildPath(newPath); pfpath = FileService.NormalizeRelativePath(pfpath); } if (!String.IsNullOrEmpty(projectFile.ResourceId) && projectFile.ResourceId != Path.GetFileName(pfpath)) { res_files.AppendFormat("\\\n\t{0},{1} ", MakefileData.ToMakefilePath(pfpath), MakefileData.EscapeString(projectFile.ResourceId)); } else { res_files.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath)); } break; case "FileCopy": datafiles.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(pfpath)); break; } } if (!generateAutotools) { templateFilesTargets = new StringBuilder(); installTarget = new StringBuilder(); uninstallTarget = new StringBuilder(); installDeps = new StringBuilder(); installDirs = new List <string> (); customCommands = new StringBuilder(); string programFilesDir = ctx.DeployContext.GetDirectory(TargetDirectory.ProgramFiles); //FIXME:temp programFilesDir = TranslateDir(programFilesDir); installDirs.Add(programFilesDir); installTarget.Append("\tmake pre-install-local-hook prefix=$(prefix)\n"); installTarget.Append("\tmake install-satellite-assemblies prefix=$(prefix)\n"); installTarget.AppendFormat("\tmkdir -p '$(DESTDIR){0}'\n", programFilesDir); installTarget.AppendFormat("\t$(call cp,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir); installTarget.AppendFormat("\t$(call cp,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir); //remove dir? uninstallTarget.Append("\tmake pre-uninstall-local-hook prefix=$(prefix)\n"); uninstallTarget.Append("\tmake uninstall-satellite-assemblies prefix=$(prefix)\n"); uninstallTarget.AppendFormat("\t$(call rm,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir); uninstallTarget.AppendFormat("\t$(call rm,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir); installDeps.Append(" $(ASSEMBLY) $(ASSEMBLY_MDB)"); conf_vars.AppendFormat("srcdir=.\n"); conf_vars.AppendFormat("top_srcdir={0}\n\n", FileService.AbsoluteToRelativePath(project.BaseDirectory, ctx.TargetSolution.BaseDirectory)); conf_vars.AppendFormat("include $(top_srcdir)/config.make\n\n"); // Don't emit for top level project makefile(eg. pdn.make), as it would be // included by top level solution makefile if (ctx.TargetSolution.BaseDirectory != project.BaseDirectory) { string customhooks = Path.Combine(project.BaseDirectory, "custom-hooks.make"); bool include = File.Exists(customhooks); includes = "include $(top_srcdir)/Makefile.include\n"; includes += String.Format("{0}include $(srcdir)/custom-hooks.make\n\n", include ? "" : "#"); if (include) { makefile.SetVariable("EXTRA_DIST", "$(srcdir)/custom-hooks.make"); } } } bool buildEnabled; List <ConfigSection> configSections = new List <ConfigSection> (); allDeployVars = new Dictionary <string, DeployFileData> (); foreach (SolutionConfiguration combineConfig in ctx.TargetSolution.Configurations) { DotNetProjectConfiguration config = GetProjectConfig(combineConfig.Id, project, out buildEnabled) as DotNetProjectConfiguration; if (config == null) { continue; } ConfigSection configSection = new ConfigSection(combineConfig.Id); string assembly = MakefileData.GetUnixPath(project.GetRelativeChildPath(config.CompiledOutputName)); configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_COMPILER_COMMAND = {0}\n", setup.GetCompilerCommand(project, config.Id)); configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_COMPILER_FLAGS = {0}\n", setup.GetCompilerFlags(project, config.Id)); // add check for compiler command in configure.ac ctx.AddCommandCheck(setup.GetCompilerCommand(project, config.Id)); configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY = {0}\n", AutotoolsContext.EscapeStringForAutomake(assembly)); configSection.BuildVariablesBuilder.AppendFormat("ASSEMBLY_MDB = {0}\n", config.DebugMode ? "$(ASSEMBLY).mdb" : String.Empty); string target; switch (config.CompileTarget) { case CompileTarget.Exe: target = "exe"; break; case CompileTarget.Library: target = "library"; break; case CompileTarget.WinExe: target = "winexe"; break; case CompileTarget.Module: target = "module"; break; default: throw new Exception(GettextCatalog.GetString("Unknown target {0}", config.CompileTarget)); } configSection.BuildVariablesBuilder.AppendFormat("COMPILE_TARGET = {0}\n", target); // for project references, we need a ref to the dll for the current configuration StringWriter projectReferences = new StringWriter(); string pref = null; foreach (ProjectReference reference in netProject.References) { if (reference.ReferenceType != ReferenceType.Project) { continue; } Project refp = GetProjectFromName(reference.Reference, ctx.TargetSolution); if (!(refp is DotNetProject)) { continue; } DotNetProjectConfiguration dnpc = GetProjectConfig(combineConfig.Id, refp, out buildEnabled) as DotNetProjectConfiguration; if (dnpc == null) { throw new Exception(GettextCatalog.GetString ("Could not add reference to project '{0}'", refp.Name)); } projectReferences.WriteLine(" \\"); projectReferences.Write("\t"); pref = project.GetRelativeChildPath(dnpc.CompiledOutputName); projectReferences.Write(MakefileData.ToMakefilePath(pref)); } configSection.BuildVariablesBuilder.AppendFormat("PROJECT_REFERENCES = {0}\n", projectReferences.ToString()); string buildDir = project.GetRelativeChildPath(config.OutputDirectory); configSection.BuildVariablesBuilder.AppendFormat("BUILD_DIR = {0}\n", MakefileData.ToMakefilePath(buildDir)); // Register files built by this configuration. // Built files won't be distributed. foreach (string bfile in builtFiles) { ctx.AddBuiltFile(Path.Combine(config.OutputDirectory, bfile)); } DeployFileCollection deployFiles = DeployService.GetDeployFiles( ctx.DeployContext, new SolutionItem[] { project }, config.Selector); ProcessDeployFilesForConfig(deployFiles, project, configSection, ctx, config); configSections.Add(configSection); if (!generateAutotools) { EmitCustomCommandTargets(config.CustomCommands, project, customCommands, combineConfig.Id, new CustomCommandType [] { CustomCommandType.BeforeBuild, CustomCommandType.AfterBuild, CustomCommandType.BeforeClean, CustomCommandType.AfterClean }, monitor); } else { if (config.CustomCommands.Count > 0) { monitor.ReportWarning(GettextCatalog.GetString("Custom commands are not supported for autotools based makefiles. Ignoring.")); } } // Register files generated by the compiler ctx.AddBuiltFile(project.GetOutputFileName(combineConfig.Selector)); if (config.DebugMode) { ctx.AddBuiltFile(project.GetOutputFileName(combineConfig.Selector) + ".mdb"); } if (config.SignAssembly) { string spath = project.GetRelativeChildPath(config.AssemblyKeyFile); spath = FileService.NormalizeRelativePath(spath); extraFiles.Add(MakefileData.ToMakefilePath(spath)); } if (buildEnabled && pkgs.Count > 0) { ctx.AddRequiredPackages(combineConfig.Id, pkgs); } } foreach (string ef in extraFiles) { extras.AppendFormat("\\\n\t{0} ", ef); } Dictionary <string, DeployFileData> commonDeployVars = new Dictionary <string, DeployFileData> (allDeployVars); foreach (ConfigSection configSection in configSections) { List <string> toRemove = new List <string> (); foreach (KeyValuePair <string, DeployFileData> pair in commonDeployVars) { if (!configSection.DeployFileVars.ContainsKey(pair.Key)) { toRemove.Add(pair.Key); } } foreach (string s in toRemove) { commonDeployVars.Remove(s); } } //emit the config sections here.. to conf_vars foreach (ConfigSection configSection in configSections) { conf_vars.AppendFormat(generateAutotools ? "if ENABLE_{0}\n" : "ifeq ($(CONFIG),{0})\n", ctx.EscapeAndUpperConfigName(configSection.Name)); conf_vars.Append(configSection.BuildVariablesBuilder.ToString()); conf_vars.Append("\n"); if (ctx.Switches != null) { foreach (Switch s in ctx.Switches) { conf_vars.AppendLine(string.Format(@"if ENABLE_{0} ASSEMBLY_COMPILER_FLAGS += -define:{1} endif", s.SwitchName.Replace('-', '_').ToUpperInvariant(), s.Define)); } } foreach (KeyValuePair <string, DeployFileData> pair in allDeployVars) { string targetDeployVar = pair.Key; if (pair.Value.File.ContainsPathReferences) { //Template files are not handled per-config continue; } if (configSection.DeployFileVars.ContainsKey(targetDeployVar)) { //use the dfile from the config section DeployFile dfile = configSection.DeployFileVars [targetDeployVar]; string fname = MakefileData.ToMakefilePath( FileService.AbsoluteToRelativePath( Path.GetFullPath(project.BaseDirectory), Path.GetFullPath(dfile.SourcePath))); conf_vars.AppendFormat("{0}_SOURCE={1}\n", targetDeployVar, fname); if (!commonDeployVars.ContainsKey(targetDeployVar)) { //FOO_DLL=$(BUILD_DIR)/foo.dll conf_vars.AppendFormat("{0}=$(BUILD_DIR)/{1}\n", targetDeployVar, MakefileData.ToMakefilePath(dfile.RelativeTargetPath)); } } else { // not common and not part of @configSection conf_vars.AppendFormat("{0}=\n", pair.Key); } } conf_vars.Append("\nendif\n\n"); } conf_vars.AppendFormat("AL={0}\n", (dotnetProject.TargetFramework.ClrVersion == ClrVersion.Net_2_0) ? "al2" : "al"); conf_vars.AppendFormat("SATELLITE_ASSEMBLY_NAME=$(notdir $(basename $(ASSEMBLY))).resources.dll\n"); foreach (KeyValuePair <string, DeployFileData> pair in allDeployVars) { HandleDeployFile(pair.Value, pair.Key, project, ctx); if (commonDeployVars.ContainsKey(pair.Key)) { //FOO_DLL=$(BUILD_DIR)/foo.dll deployFileCopyVars.AppendFormat("{0} = $(BUILD_DIR)/{1}\n", pair.Key, MakefileData.ToMakefilePath(pair.Value.File.RelativeTargetPath)); } } conf_vars.Append('\n'); StringBuilder vars = new StringBuilder(); foreach (KeyValuePair <string, StringBuilder> pair in deployDirs) { //PROGRAM_FILES= .. etc conf_vars.AppendFormat("{0} = {1} \n\n", pair.Key, pair.Value.ToString()); //Build list of deploy dir variables vars.AppendFormat("$({0}) ", pair.Key); } if (!generateAutotools) { installTarget.Insert(0, String.Format("install-local:{0}\n", installDeps.ToString())); installTarget.Append("\tmake post-install-local-hook prefix=$(prefix)\n"); uninstallTarget.Insert(0, String.Format("uninstall-local:{0}\n", installDeps.ToString())); uninstallTarget.Append("\tmake post-uninstall-local-hook prefix=$(prefix)\n"); } if (!generateAutotools && customCommands.Length > 0) { customCommands.Insert(0, "# Targets for Custom commands\n"); } templateEngine.Variables["CONFIG_VARS"] = conf_vars.ToString(); templateEngine.Variables["DEPLOY_FILE_VARS"] = vars.ToString(); templateEngine.Variables["COPY_DEPLOY_FILES_VARS"] = deployFileCopyVars.ToString(); templateEngine.Variables["COPY_DEPLOY_FILES_TARGETS"] = deployFileCopyTargets.ToString(); templateEngine.Variables["ALL_TARGET"] = (ctx.TargetSolution.BaseDirectory == project.BaseDirectory) ? "all-local" : "all"; templateEngine.Variables["INCLUDES"] = includes; templateEngine.Variables["FILES"] = files.ToString(); templateEngine.Variables["RESOURCES"] = res_files.ToString(); templateEngine.Variables["EXTRAS"] = extras.ToString(); templateEngine.Variables["DATA_FILES"] = datafiles.ToString(); templateEngine.Variables["CLEANFILES"] = vars.ToString(); if (!generateAutotools) { templateEngine.Variables["TEMPLATE_FILES_TARGETS"] = templateFilesTargets.ToString(); templateEngine.Variables["INSTALL_TARGET"] = installTarget.ToString(); templateEngine.Variables["UNINSTALL_TARGET"] = uninstallTarget.ToString(); templateEngine.Variables["CUSTOM_COMMAND_TARGETS"] = customCommands.ToString(); } // Create project specific makefile Stream stream = ctx.GetTemplateStream( generateAutotools ? "Makefile.am.project.template" : "Makefile.noauto.project.template"); StreamReader reader = new StreamReader(stream); string txt = templateEngine.Process(reader); reader.Close(); makefile.Append(txt); monitor.Step(1); } finally { monitor.EndTask(); } return(makefile); }
/// <summary> /// Copies resource files from the Xcode project (back) to the MonoDevelop project directory. /// </summary> /// <param name='monitor'> /// A progress monitor. /// </param> /// <param name='context'> /// The sync context. /// </param> void CopyFilesToMD (IProgressMonitor monitor, XcodeSyncBackContext context) { if (context.FileSyncJobs.Count == 0) return; monitor.BeginStepTask ("Copying files from Xcode back to MonoDevelop...", context.FileSyncJobs.Count, 1); foreach (var file in context.FileSyncJobs) { monitor.Log.WriteLine ("Copying {0} file from Xcode: {1}", file.IsFreshlyAdded ? "new" : "changed", file.SyncedRelative); if (!Directory.Exists (file.Original.ParentDirectory)) Directory.CreateDirectory (file.Original.ParentDirectory); var tempFile = file.Original.ParentDirectory.Combine (".#" + file.Original.ParentDirectory.FileName); FilePath path = context.ProjectDir.Combine (file.SyncedRelative); if (File.Exists (path)) { File.Copy (path, tempFile); FileService.SystemRename (tempFile, file.Original); DateTime mtime = File.GetLastWriteTime (file.Original); context.SetSyncTime (file.SyncedRelative, mtime); } else { monitor.ReportWarning (string.Format ("'{0}' does not exist.", file.SyncedRelative)); } monitor.Step (1); } monitor.EndTask (); }
public Makefile Deploy (AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor) { generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile; monitor.BeginTask ( GettextCatalog.GetString ( "Creating {0} for Project {1}", generateAutotools ? "Makefile.am" : "Makefile", entry.Name), 1 ); Makefile makefile = new Makefile (); try { if ( !CanDeploy (entry, generateAutotools ? MakefileType.AutotoolsMakefile : MakefileType.SimpleMakefile) ) throw new Exception ( GettextCatalog.GetString ("Not a deployable project.") ); Project project = entry as Project; TemplateEngine templateEngine = new TemplateEngine(); ISimpleAutotoolsSetup setup = FindSetupForProject ( project ); // Handle files to be deployed deployDirs = new Dictionary<string, StringBuilder> (); deployFileVars = new Dictionary<string, string> (); builtFiles = new List<string> (); deployFileCopyVars = new StringBuilder (); deployFileCopyTargets = new StringBuilder (); //used only for simple makefile generation templateFilesTargets = null; installTarget = null; installDeps = null; installDirs = null; uninstallTarget = null; // handle configuration specific variables conf_vars = new StringBuilder (); // grab all project files files = new StringBuilder (); res_files = new StringBuilder (); extras = new StringBuilder (); datafiles = new StringBuilder (); Set<string> extraFiles = new Set<string> (); string includes = String.Empty; string references, dllReferences; DotNetProject netProject = project as DotNetProject; ProcessProjectReferences (netProject, out references, out dllReferences, ctx); templateEngine.Variables["REFERENCES"] = references; templateEngine.Variables["DLL_REFERENCES"] = dllReferences; templateEngine.Variables["WARNING"] = "Warning: This is an automatically generated file, do not edit!"; DotNetProject dotnetProject = entry as DotNetProject; if (dotnetProject != null) { string resgen = "resgen"; if (System.Environment.Version.Major >= 2) { switch (dotnetProject.TargetFramework.ClrVersion) { case ClrVersion.Net_1_1: resgen = "resgen1"; break; default: resgen = "resgen2"; break; } } templateEngine.Variables ["RESGEN"] = resgen; } string pfpath = null; foreach (ProjectFile projectFile in project.Files) { pfpath = FileService.NormalizeRelativePath (projectFile.FilePath.ToRelative (project.BaseDirectory)); switch ( projectFile.BuildAction ) { case BuildAction.Compile: if ( projectFile.Subtype != Subtype.Code ) continue; files.AppendFormat ( "\\\n\t{0} ", MakefileData.ToMakefilePath (pfpath)); break; case BuildAction.Content: case BuildAction.None: extraFiles.Add (MakefileData.ToMakefilePath (pfpath)); break; case BuildAction.EmbeddedResource: if ( !projectFile.FilePath.IsChildPathOf ( ctx.BaseDirectory ) ) { // file is not within directory hierarchy, copy it in string rdir = Path.Combine (Path.GetDirectoryName (project.FileName), resourcedir); if ( !Directory.Exists ( rdir ) ) Directory.CreateDirectory ( rdir ); string newPath = Path.Combine (rdir, Path.GetFileName ( projectFile.FilePath )); FileService.CopyFile ( projectFile.FilePath, newPath ) ; pfpath = project.GetRelativeChildPath (newPath); pfpath = FileService.NormalizeRelativePath (pfpath); } if (!String.IsNullOrEmpty (projectFile.ResourceId) && projectFile.ResourceId != Path.GetFileName (pfpath)) res_files.AppendFormat ("\\\n\t{0},{1} ", MakefileData.ToMakefilePath (pfpath), MakefileData.EscapeString (projectFile.ResourceId)); else res_files.AppendFormat ("\\\n\t{0} ", MakefileData.ToMakefilePath (pfpath)); break; case "FileCopy": datafiles.AppendFormat ("\\\n\t{0} ", MakefileData.ToMakefilePath (pfpath)); break; } } if (!generateAutotools) { templateFilesTargets = new StringBuilder (); installTarget = new StringBuilder (); uninstallTarget = new StringBuilder (); installDeps = new StringBuilder (); installDirs = new List<string> (); customCommands = new StringBuilder (); string programFilesDir = ctx.DeployContext.GetDirectory (TargetDirectory.ProgramFiles); //FIXME:temp programFilesDir = TranslateDir (programFilesDir); installDirs.Add (programFilesDir); installTarget.Append ("\tmake pre-install-local-hook prefix=$(prefix)\n"); installTarget.Append ("\tmake install-satellite-assemblies prefix=$(prefix)\n"); installTarget.AppendFormat ("\tmkdir -p '$(DESTDIR){0}'\n", programFilesDir); installTarget.AppendFormat ("\t$(call cp,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir); installTarget.AppendFormat ("\t$(call cp,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir); //remove dir? uninstallTarget.Append ("\tmake pre-uninstall-local-hook prefix=$(prefix)\n"); uninstallTarget.Append ("\tmake uninstall-satellite-assemblies prefix=$(prefix)\n"); uninstallTarget.AppendFormat ("\t$(call rm,$(ASSEMBLY),$(DESTDIR){0})\n", programFilesDir); uninstallTarget.AppendFormat ("\t$(call rm,$(ASSEMBLY_MDB),$(DESTDIR){0})\n", programFilesDir); installDeps.Append (" $(ASSEMBLY) $(ASSEMBLY_MDB)"); conf_vars.AppendFormat ("srcdir=.\n"); conf_vars.AppendFormat ("top_srcdir={0}\n\n", FileService.AbsoluteToRelativePath (project.BaseDirectory, ctx.TargetSolution.BaseDirectory)); conf_vars.AppendFormat ("include $(top_srcdir)/config.make\n\n"); // Don't emit for top level project makefile(eg. pdn.make), as it would be // included by top level solution makefile if (ctx.TargetSolution.BaseDirectory != project.BaseDirectory){ string customhooks = Path.Combine (project.BaseDirectory, "custom-hooks.make"); bool include = File.Exists (customhooks); includes = "include $(top_srcdir)/Makefile.include\n"; includes += String.Format ("{0}include $(srcdir)/custom-hooks.make\n\n", include ? "" : "#"); if (include) makefile.SetVariable ("EXTRA_DIST", "$(srcdir)/custom-hooks.make"); } } bool buildEnabled; List<ConfigSection> configSections = new List<ConfigSection> (); allDeployVars = new Dictionary<string, DeployFileData> (); foreach (SolutionConfiguration combineConfig in ctx.TargetSolution.Configurations) { DotNetProjectConfiguration config = GetProjectConfig (combineConfig.Id, project, out buildEnabled) as DotNetProjectConfiguration; if (config == null) continue; ConfigSection configSection = new ConfigSection (combineConfig.Id); string assembly = MakefileData.GetUnixPath (project.GetRelativeChildPath (config.CompiledOutputName)); configSection.BuildVariablesBuilder.AppendFormat ("ASSEMBLY_COMPILER_COMMAND = {0}\n", setup.GetCompilerCommand ( project, config.Id ) ); configSection.BuildVariablesBuilder.AppendFormat ("ASSEMBLY_COMPILER_FLAGS = {0}\n", setup.GetCompilerFlags ( project, config.Id ) ); // add check for compiler command in configure.ac ctx.AddCommandCheck ( setup.GetCompilerCommand ( project, config.Id ) ); configSection.BuildVariablesBuilder.AppendFormat ("ASSEMBLY = {0}\n", AutotoolsContext.EscapeStringForAutomake (assembly)); configSection.BuildVariablesBuilder.AppendFormat ("ASSEMBLY_MDB = {0}\n", config.DebugMode ? "$(ASSEMBLY).mdb" : String.Empty); string target; switch (config.CompileTarget) { case CompileTarget.Exe: target = "exe"; break; case CompileTarget.Library: target = "library"; break; case CompileTarget.WinExe: target = "winexe"; break; case CompileTarget.Module: target = "module"; break; default: throw new Exception( GettextCatalog.GetString ("Unknown target {0}", config.CompileTarget ) ); } configSection.BuildVariablesBuilder.AppendFormat ( "COMPILE_TARGET = {0}\n", target ); // for project references, we need a ref to the dll for the current configuration StringWriter projectReferences = new StringWriter(); string pref = null; foreach (ProjectReference reference in netProject.References) { if (reference.ReferenceType != ReferenceType.Project) continue; Project refp = GetProjectFromName (reference.Reference, ctx.TargetSolution); if (!(refp is DotNetProject)) continue; DotNetProjectConfiguration dnpc = GetProjectConfig (combineConfig.Id, refp, out buildEnabled) as DotNetProjectConfiguration; if ( dnpc == null ) throw new Exception ( GettextCatalog.GetString ("Could not add reference to project '{0}'", refp.Name) ); projectReferences.WriteLine (" \\"); projectReferences.Write ("\t"); pref = project.GetRelativeChildPath (dnpc.CompiledOutputName); projectReferences.Write (MakefileData.ToMakefilePath (pref)); } configSection.BuildVariablesBuilder.AppendFormat ( "PROJECT_REFERENCES = {0}\n", projectReferences.ToString() ); string buildDir = project.GetRelativeChildPath (config.OutputDirectory); configSection.BuildVariablesBuilder.AppendFormat ("BUILD_DIR = {0}\n", MakefileData.ToMakefilePath (buildDir)); // Register files built by this configuration. // Built files won't be distributed. foreach (string bfile in builtFiles) ctx.AddBuiltFile (Path.Combine (config.OutputDirectory, bfile)); DeployFileCollection deployFiles = DeployService.GetDeployFiles ( ctx.DeployContext, new SolutionItem[] { project }, config.Selector); ProcessDeployFilesForConfig (deployFiles, project, configSection, ctx, config); configSections.Add (configSection); if (!generateAutotools) { EmitCustomCommandTargets (config.CustomCommands, project, customCommands, combineConfig.Id, new CustomCommandType [] { CustomCommandType.BeforeBuild, CustomCommandType.AfterBuild, CustomCommandType.BeforeClean, CustomCommandType.AfterClean}, monitor); } else { if (config.CustomCommands.Count > 0) monitor.ReportWarning (GettextCatalog.GetString ("Custom commands are not supported for autotools based makefiles. Ignoring.")); } // Register files generated by the compiler ctx.AddBuiltFile (project.GetOutputFileName (combineConfig.Selector)); if (config.DebugMode) ctx.AddBuiltFile (project.GetOutputFileName (combineConfig.Selector) + ".mdb"); if (config.SignAssembly) { string spath = project.GetRelativeChildPath (config.AssemblyKeyFile); spath = FileService.NormalizeRelativePath (spath); extraFiles.Add (MakefileData.ToMakefilePath (spath)); } if (buildEnabled && pkgs.Count > 0) ctx.AddRequiredPackages (combineConfig.Id, pkgs); } foreach (string ef in extraFiles) extras.AppendFormat ("\\\n\t{0} ", ef); Dictionary<string, DeployFileData> commonDeployVars = new Dictionary<string, DeployFileData> (allDeployVars); foreach (ConfigSection configSection in configSections) { List<string> toRemove = new List<string> (); foreach (KeyValuePair<string, DeployFileData> pair in commonDeployVars) { if (!configSection.DeployFileVars.ContainsKey (pair.Key)) toRemove.Add (pair.Key); } foreach (string s in toRemove) commonDeployVars.Remove (s); } //emit the config sections here.. to conf_vars foreach (ConfigSection configSection in configSections) { conf_vars.AppendFormat (generateAutotools ? "if ENABLE_{0}\n" : "ifeq ($(CONFIG),{0})\n", ctx.EscapeAndUpperConfigName (configSection.Name)); conf_vars.Append (configSection.BuildVariablesBuilder.ToString ()); conf_vars.Append ("\n"); if (ctx.Switches != null) { foreach (Switch s in ctx.Switches) { conf_vars.AppendLine (string.Format (@"if ENABLE_{0} ASSEMBLY_COMPILER_FLAGS += -define:{1} endif", s.SwitchName.Replace ('-', '_').ToUpperInvariant (), s.Define)); } } foreach (KeyValuePair<string, DeployFileData> pair in allDeployVars) { string targetDeployVar = pair.Key; if (pair.Value.File.ContainsPathReferences) //Template files are not handled per-config continue; if (configSection.DeployFileVars.ContainsKey (targetDeployVar)) { //use the dfile from the config section DeployFile dfile = configSection.DeployFileVars [targetDeployVar]; string fname = MakefileData.ToMakefilePath ( FileService.AbsoluteToRelativePath ( Path.GetFullPath (project.BaseDirectory), Path.GetFullPath (dfile.SourcePath))); conf_vars.AppendFormat ("{0}_SOURCE={1}\n", targetDeployVar, fname); if (!commonDeployVars.ContainsKey (targetDeployVar)) { //FOO_DLL=$(BUILD_DIR)/foo.dll conf_vars.AppendFormat ("{0}=$(BUILD_DIR)/{1}\n", targetDeployVar, MakefileData.ToMakefilePath (dfile.RelativeTargetPath)); } } else { // not common and not part of @configSection conf_vars.AppendFormat ("{0}=\n", pair.Key); } } conf_vars.Append ( "\nendif\n\n" ); } conf_vars.AppendFormat ("AL={0}\n", (dotnetProject.TargetFramework.ClrVersion == ClrVersion.Net_2_0) ? "al2" : "al"); conf_vars.AppendFormat ("SATELLITE_ASSEMBLY_NAME=$(notdir $(basename $(ASSEMBLY))).resources.dll\n"); foreach (KeyValuePair<string, DeployFileData> pair in allDeployVars) { HandleDeployFile (pair.Value, pair.Key, project, ctx); if (commonDeployVars.ContainsKey (pair.Key)) { //FOO_DLL=$(BUILD_DIR)/foo.dll deployFileCopyVars.AppendFormat ("{0} = $(BUILD_DIR)/{1}\n", pair.Key, MakefileData.ToMakefilePath (pair.Value.File.RelativeTargetPath)); } } conf_vars.Append ('\n'); StringBuilder vars = new StringBuilder (); foreach (KeyValuePair<string, StringBuilder> pair in deployDirs) { //PROGRAM_FILES= .. etc conf_vars.AppendFormat ("{0} = {1} \n\n", pair.Key, pair.Value.ToString ()); //Build list of deploy dir variables vars.AppendFormat ("$({0}) ", pair.Key); } if (!generateAutotools) { installTarget.Insert (0, String.Format ("install-local:{0}\n", installDeps.ToString ())); installTarget.Append ("\tmake post-install-local-hook prefix=$(prefix)\n"); uninstallTarget.Insert (0, String.Format ("uninstall-local:{0}\n", installDeps.ToString ())); uninstallTarget.Append ("\tmake post-uninstall-local-hook prefix=$(prefix)\n"); } if (!generateAutotools && customCommands.Length > 0) customCommands.Insert (0, "# Targets for Custom commands\n"); templateEngine.Variables["CONFIG_VARS"] = conf_vars.ToString (); templateEngine.Variables["DEPLOY_FILE_VARS"] = vars.ToString (); templateEngine.Variables["COPY_DEPLOY_FILES_VARS"] = deployFileCopyVars.ToString(); templateEngine.Variables["COPY_DEPLOY_FILES_TARGETS"] = deployFileCopyTargets.ToString(); templateEngine.Variables["ALL_TARGET"] = (ctx.TargetSolution.BaseDirectory == project.BaseDirectory) ? "all-local" : "all"; templateEngine.Variables["INCLUDES"] = includes; templateEngine.Variables["FILES"] = files.ToString(); templateEngine.Variables["RESOURCES"] = res_files.ToString(); templateEngine.Variables["EXTRAS"] = extras.ToString(); templateEngine.Variables["DATA_FILES"] = datafiles.ToString(); templateEngine.Variables["CLEANFILES"] = vars.ToString (); if (!generateAutotools) { templateEngine.Variables["TEMPLATE_FILES_TARGETS"] = templateFilesTargets.ToString(); templateEngine.Variables["INSTALL_TARGET"] = installTarget.ToString(); templateEngine.Variables["UNINSTALL_TARGET"] = uninstallTarget.ToString(); templateEngine.Variables["CUSTOM_COMMAND_TARGETS"] = customCommands.ToString(); } // Create project specific makefile Stream stream = ctx.GetTemplateStream ( generateAutotools ? "Makefile.am.project.template" : "Makefile.noauto.project.template"); StreamReader reader = new StreamReader (stream); string txt = templateEngine.Process ( reader ); reader.Close(); makefile.Append ( txt ); monitor.Step (1); } finally { monitor.EndTask (); } return makefile; }
/// <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 { type.BaseCliType = defaultNamespace + "." + provider.CreateValidIdentifier (type.BaseObjCType); monitor.ReportWarning (string.Format ("Failed to resolve Objective-C type {0} to CLI type on type {1}", type.BaseObjCType, type.ObjCName)); } } // 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); monitor.ReportWarning (string.Format ("Failed to resolve Objective-C type {0} to CLI type on outlet {1} on type {2}", outlet.ObjCType, outlet.ObjCName, type.ObjCName)); } } // 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); monitor.ReportWarning (string.Format ("Failed to resolve Objective-C type {0} to CLI type on action parameter {1} for action {2} on type {3}", param.ObjCType, param.Name, action.ObjCName, type.ObjCName)); } } } }
public Solution MsSlnToCmbxHelper(string slnFileName, IProgressMonitor monitor) { Solution solution = new Solution(); monitor.BeginTask(GettextCatalog.GetString("Importing solution"), 2); try { // We invoke the ParseSolution // by passing the file obtained ParseSolution(slnFileName, monitor); // Create all of the prjx files form the csproj files monitor.BeginTask(null, projNameInfo.Values.Count * 2); foreach (CsprojInfo pi in projNameInfo.Values) { string mappedPath = MapPath(Path.GetDirectoryName(slnFileName), pi.csprojpath); if (mappedPath == null) { monitor.Step(2); monitor.ReportWarning(GettextCatalog.GetString("Project file not found: ") + pi.csprojpath); continue; } SolutionEntityItem prj; if (pi.NeedsConversion) { prj = CreatePrjxFromCsproj(mappedPath, monitor); } else { prj = (DotNetProject)Services.ProjectService.ReadSolutionItem(monitor, mappedPath); } if (prj == null) { return(null); } monitor.Step(1); solution.RootFolder.Items.Add(prj); foreach (ItemConfiguration conf in prj.Configurations) { if (!solution.GetConfigurations().Contains(conf.Id)) { solution.AddConfiguration(conf.Id, false); } } monitor.Step(1); } monitor.EndTask(); monitor.Step(1); solution.SetLocation(Path.GetDirectoryName(slnFileName), Path.GetFileNameWithoutExtension(slnFileName)); monitor.Step(1); return(solution); } catch (Exception e) { monitor.ReportError(GettextCatalog.GetString("The solution could not be imported."), e); throw; } finally { monitor.EndTask(); } }
public static BuildResult Compile(ProjectItemCollection projectItems, DotNetProjectConfiguration configuration, ConfigurationSelector configSelector, IProgressMonitor monitor) { CSharpCompilerParameters compilerParameters = (CSharpCompilerParameters)configuration.CompilationParameters ?? new CSharpCompilerParameters(); CSharpProjectParameters projectParameters = (CSharpProjectParameters)configuration.ProjectParameters ?? new CSharpProjectParameters(); string outputName = configuration.CompiledOutputName; string responseFileName = Path.GetTempFileName(); TargetRuntime runtime = MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime; DotNetProject project = configuration.ParentItem as DotNetProject; if (project != null) { runtime = project.TargetRuntime; } StringBuilder sb = new StringBuilder(); List <string> gacRoots = new List <string> (); sb.AppendFormat("\"/out:{0}\"", outputName); sb.AppendLine(); HashSet <string> alreadyAddedReference = new HashSet <string> (); foreach (ProjectReference lib in projectItems.GetAll <ProjectReference> ()) { if (lib.ReferenceType == ReferenceType.Project && !(lib.OwnerProject.ParentSolution.FindProjectByName(lib.Reference) is DotNetProject)) { continue; } foreach (string fileName in lib.GetReferencedFileNames(configSelector)) { switch (lib.ReferenceType) { case ReferenceType.Gac: SystemPackage pkg = lib.Package; if (pkg == null) { string msg = string.Format(GettextCatalog.GetString("{0} could not be found or is invalid."), lib.Reference); monitor.ReportWarning(msg); continue; } if (alreadyAddedReference.Add(fileName)) { AppendQuoted(sb, "/r:", fileName); } if (pkg.GacRoot != null && !gacRoots.Contains(pkg.GacRoot)) { gacRoots.Add(pkg.GacRoot); } if (!string.IsNullOrEmpty(pkg.Requires)) { foreach (string requiredPackage in pkg.Requires.Split(' ')) { SystemPackage rpkg = runtime.AssemblyContext.GetPackage(requiredPackage); if (rpkg == null) { continue; } foreach (SystemAssembly assembly in rpkg.Assemblies) { if (alreadyAddedReference.Add(assembly.Location)) { AppendQuoted(sb, "/r:", assembly.Location); } } } } break; default: if (alreadyAddedReference.Add(fileName)) { AppendQuoted(sb, "/r:", fileName); } break; } } } sb.AppendLine("/nologo"); sb.Append("/warn:"); sb.Append(compilerParameters.WarningLevel.ToString()); sb.AppendLine(); if (configuration.SignAssembly) { if (File.Exists(configuration.AssemblyKeyFile)) { AppendQuoted(sb, "/keyfile:", configuration.AssemblyKeyFile); } } if (configuration.DebugMode) { sb.AppendLine("/debug:+"); sb.AppendLine("/debug:full"); } switch (compilerParameters.LangVersion) { case LangVersion.Default: break; case LangVersion.ISO_1: sb.AppendLine("/langversion:ISO-1"); break; case LangVersion.ISO_2: sb.AppendLine("/langversion:ISO-2"); break; default: string message = "Invalid LangVersion enum value '" + compilerParameters.LangVersion.ToString() + "'"; monitor.ReportError(message, null); LoggingService.LogError(message); return(null); } // mcs default is + but others might not be if (compilerParameters.Optimize) { sb.AppendLine("/optimize+"); } else { sb.AppendLine("/optimize-"); } bool hasWin32Res = !string.IsNullOrEmpty(projectParameters.Win32Resource) && File.Exists(projectParameters.Win32Resource); if (hasWin32Res) { AppendQuoted(sb, "/win32res:", projectParameters.Win32Resource); } if (!string.IsNullOrEmpty(projectParameters.Win32Icon) && File.Exists(projectParameters.Win32Icon)) { if (hasWin32Res) { monitor.ReportWarning("Both Win32 icon and Win32 resource cannot be specified. Ignoring the icon."); } else { AppendQuoted(sb, "/win32icon:", projectParameters.Win32Icon); } } if (projectParameters.CodePage != 0) { sb.AppendLine("/codepage:" + projectParameters.CodePage); } else if (runtime is MonoTargetRuntime) { sb.AppendLine("/codepage:utf8"); } if (compilerParameters.UnsafeCode) { sb.AppendLine("-unsafe"); } if (compilerParameters.NoStdLib) { sb.AppendLine("-nostdlib"); } if (!string.IsNullOrEmpty(compilerParameters.PlatformTarget) && compilerParameters.PlatformTarget.ToLower() != "anycpu") { //HACK: to ignore the platform flag for Mono <= 2.4, because gmcs didn't support it if (runtime.RuntimeId == "Mono" && runtime.AssemblyContext.GetAssemblyLocation("Mono.Debugger.Soft", null) == null) { LoggingService.LogWarning("Mono runtime '" + runtime.DisplayName + "' appears to be too old to support the 'platform' C# compiler flag."); } else { sb.AppendLine("/platform:" + compilerParameters.PlatformTarget); } } if (compilerParameters.TreatWarningsAsErrors) { sb.AppendLine("-warnaserror"); if (!string.IsNullOrEmpty(compilerParameters.WarningsNotAsErrors)) { sb.AppendLine("-warnaserror-:" + compilerParameters.WarningsNotAsErrors); } } if (compilerParameters.DefineSymbols.Length > 0) { string define_str = string.Join(";", compilerParameters.DefineSymbols.Split(new char [] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries)); if (define_str.Length > 0) { AppendQuoted(sb, "/define:", define_str); sb.AppendLine(); } } CompileTarget ctarget = configuration.CompileTarget; if (!string.IsNullOrEmpty(projectParameters.MainClass)) { sb.AppendLine("/main:" + projectParameters.MainClass); // mcs does not allow providing a Main class when compiling a dll // As a workaround, we compile as WinExe (although the output will still // have a .dll extension). if (ctarget == CompileTarget.Library) { ctarget = CompileTarget.WinExe; } } switch (ctarget) { case CompileTarget.Exe: sb.AppendLine("/t:exe"); break; case CompileTarget.WinExe: sb.AppendLine("/t:winexe"); break; case CompileTarget.Library: sb.AppendLine("/t:library"); break; } foreach (ProjectFile finfo in projectItems.GetAll <ProjectFile> ()) { if (finfo.Subtype == Subtype.Directory) { continue; } switch (finfo.BuildAction) { case "Compile": AppendQuoted(sb, "", finfo.Name); break; case "EmbeddedResource": string fname = finfo.Name; if (string.Compare(Path.GetExtension(fname), ".resx", true) == 0) { fname = Path.ChangeExtension(fname, ".resources"); } sb.Append('"'); sb.Append("/res:"); sb.Append(fname); sb.Append(','); sb.Append(finfo.ResourceId); sb.Append('"'); sb.AppendLine(); break; default: continue; } } if (compilerParameters.GenerateXmlDocumentation) { AppendQuoted(sb, "/doc:", Path.ChangeExtension(outputName, ".xml")); } if (!string.IsNullOrEmpty(compilerParameters.AdditionalArguments)) { sb.AppendLine(compilerParameters.AdditionalArguments); } if (!string.IsNullOrEmpty(compilerParameters.NoWarnings)) { AppendQuoted(sb, "/nowarn:", compilerParameters.NoWarnings); } if (runtime.RuntimeId == "MS.NET") { sb.AppendLine("/fullpaths"); sb.AppendLine("/utf8output"); } string output = ""; string error = ""; File.WriteAllText(responseFileName, sb.ToString()); string compilerName; try { compilerName = GetCompilerName(runtime, configuration.TargetFramework); } catch (Exception e) { string message = "Could not obtain a C# compiler"; monitor.ReportError(message, e); return(null); } monitor.Log.WriteLine(compilerName + " /noconfig " + sb.ToString().Replace('\n', ' ')); string workingDir = "."; if (configuration.ParentItem != null) { workingDir = configuration.ParentItem.BaseDirectory; if (workingDir == null) { // Dummy projects created for single files have no filename // and so no BaseDirectory. // This is a workaround for a bug in // ProcessStartInfo.WorkingDirectory - not able to handle null workingDir = "."; } } LoggingService.LogInfo(compilerName + " " + sb.ToString()); ExecutionEnvironment envVars = runtime.GetToolsExecutionEnvironment(project.TargetFramework); string cargs = "/noconfig @\"" + responseFileName + "\""; int exitCode = DoCompilation(compilerName, cargs, workingDir, envVars, gacRoots, ref output, ref error); BuildResult result = ParseOutput(output, error); if (result.CompilerOutput.Trim().Length != 0) { monitor.Log.WriteLine(result.CompilerOutput); } //if compiler crashes, output entire error string if (result.ErrorCount == 0 && exitCode != 0) { try { monitor.Log.Write(File.ReadAllText(error)); } catch (IOException) { } result.AddError("The compiler appears to have crashed. Check the build output pad for details."); LoggingService.LogError("C# compiler crashed. Response file '{0}', stdout file '{1}', stderr file '{2}'", responseFileName, output, error); } else { FileService.DeleteFile(responseFileName); FileService.DeleteFile(output); FileService.DeleteFile(error); } return(result); }
protected void GetReferences(Project project, MonoDevelop.Prj2Make.Schema.Csproj.Reference[] References, ProjectReferenceCollection references, IProgressMonitor monitor) { if (References == null || References.Length == 0) { return; } monitor.BeginTask(null, 5 + References.Length); try { // Get the GAC path string strBasePathMono1_0 = GetPackageDirectory("mono", "mono/1.0"); monitor.Step(1); string strBasePathGtkSharp = GetPackageDirectory("gtk-sharp", "mono/gtk-sharp"); monitor.Step(1); string strBasePathGtkSharp2_0 = GetPackageDirectory("gtk-sharp-2.0", "mono/gtk-sharp-2.0"); monitor.Step(1); string strBasePathGeckoSharp = GetPackageDirectory("gecko-sharp", "mono/gecko-sharp"); monitor.Step(1); string strBasePathGeckoSharp2_0 = GetPackageDirectory("gecko-sharp-2.0", "mono/gecko-sharp-2.0"); string[] monoLibs = new string [] { strBasePathMono1_0, strBasePathGtkSharp2_0, strBasePathGtkSharp, strBasePathGeckoSharp2_0, strBasePathGeckoSharp }; // Iterate through the reference collection of the csproj file foreach (MonoDevelop.Prj2Make.Schema.Csproj.Reference rf in References) { monitor.Step(1); ProjectReference rfOut = null; if (rf.Package != null && rf.Package.Length != 0) { rfOut = new ProjectReference(MonoDevelop.Projects.ReferenceType.Project, Path.GetFileName(rf.Name)); rfOut.LocalCopy = true; references.Add(rfOut); } else if (rf.AssemblyName != null) { string rname = rf.AssemblyName; if (rname == "System.XML") { rname = "System.Xml"; } string oref = Runtime.SystemAssemblyService.DefaultAssemblyContext.GetAssemblyFullName(rname, fx); if (oref == null) { if (rf.HintPath != null) { string asm = MapPath(project.ItemDirectory, rf.HintPath); if (!System.IO.File.Exists(asm)) { monitor.ReportWarning(GettextCatalog.GetString("Referenced assembly not found: ") + asm); } ProjectReference aref = new ProjectReference(MonoDevelop.Projects.ReferenceType.Assembly, asm); references.Add(aref); continue; } monitor.ReportWarning(GettextCatalog.GetString("Assembly reference could not be imported: ") + rf.AssemblyName); continue; } rfOut = new ProjectReference(MonoDevelop.Projects.ReferenceType.Gac, oref); rfOut.LocalCopy = true; references.Add(rfOut); } else if (rf.HintPath != null) { // HACK - under Unix filenames are case sensitive // Under Windows there's no agreement on Xml vs XML ;-) if (Path.GetFileName(rf.HintPath) == "System.XML.dll") { ProjectReference pref = GetMonoReferece(strBasePathMono1_0, "System.Xml.dll"); if (pref != null) { references.Add(pref); continue; } } else { foreach (string libDir in monoLibs) { if (libDir == null) { continue; } if (rf.HintPath == null) { continue; } rfOut = GetMonoReferece(libDir, rf.HintPath); if (rfOut != null) { break; } } if (rfOut == null) { rfOut = new ProjectReference(MonoDevelop.Projects.ReferenceType.Gac, Path.GetFileName(rf.HintPath)); rfOut.LocalCopy = true; } references.Add(rfOut); } } else { monitor.ReportWarning(GettextCatalog.GetString("Assembly reference could not be imported: ") + rf.Name); } } } finally { monitor.EndTask(); } }
protected override BuildResult OnBuild(IProgressMonitor monitor, ConfigurationSelector configuration) { if (!Project.InternalCheckNeedsBuild(configuration)) { monitor.Log.WriteLine(GettextCatalog.GetString("Skipping project since output files are up to date")); return(new BuildResult()); } DotNetProject project = Project; if (!project.TargetRuntime.IsInstalled(project.TargetFramework)) { BuildResult res = new BuildResult(); res.AddError(GettextCatalog.GetString("Framework '{0}' not installed.", project.TargetFramework.Name)); return(res); } bool hasBuildableFiles = false; foreach (ProjectFile pf in project.Files) { if (pf.BuildAction == BuildAction.Compile || pf.BuildAction == BuildAction.EmbeddedResource) { hasBuildableFiles = true; break; } } if (!hasBuildableFiles) { return(new BuildResult()); } if (project.LanguageBinding == null) { BuildResult langres = new BuildResult(); string msg = GettextCatalog.GetString("Unknown language '{0}'. You may need to install an additional add-in to support this language.", project.LanguageName); langres.AddError(msg); monitor.ReportError(msg, null); return(langres); } BuildResult refres = null; HashSet <ProjectItem> itemsToExclude = new HashSet <ProjectItem> (); foreach (ProjectReference pr in project.References) { if (pr.ReferenceType == ReferenceType.Project) { // Ignore non-dotnet projects Project p = project.ParentSolution != null?project.ParentSolution.FindProjectByName(pr.Reference) : null; if (p != null && !(p is DotNetProject)) { continue; } if (p == null || pr.GetReferencedFileNames(configuration).Length == 0) { if (refres == null) { refres = new BuildResult(); } string msg = GettextCatalog.GetString("Referenced project '{0}' not found in the solution.", pr.Reference); monitor.ReportWarning(msg); refres.AddWarning(msg); } } if (!pr.IsValid) { if (refres == null) { refres = new BuildResult(); } string msg; if (!pr.IsExactVersion && pr.SpecificVersion) { msg = GettextCatalog.GetString("Reference '{0}' not found on system. Using '{1}' instead.", pr.StoredReference, pr.Reference); monitor.ReportWarning(msg); refres.AddWarning(msg); } else { bool errorsFound = false; foreach (string asm in pr.GetReferencedFileNames(configuration)) { if (!File.Exists(asm)) { msg = GettextCatalog.GetString("Assembly '{0}' not found. Make sure that the assembly exists in disk. If the reference is required to build the project you may get compilation errors.", Path.GetFileName(asm)); refres.AddWarning(msg); monitor.ReportWarning(msg); errorsFound = true; itemsToExclude.Add(pr); } } msg = null; if (!errorsFound) { msg = GettextCatalog.GetString("The reference '{0}' is not valid for the target framework of the project.", pr.StoredReference, pr.Reference); monitor.ReportWarning(msg); refres.AddWarning(msg); itemsToExclude.Add(pr); } } } } DotNetProjectConfiguration conf = (DotNetProjectConfiguration)project.GetConfiguration(configuration); // Create a copy of the data needed to compile the project. // This data can be modified by extensions. // Also filter out items whose condition evaluates to false BuildData buildData = new BuildData(); ProjectParserContext ctx = new ProjectParserContext(project, conf); buildData.Items = new ProjectItemCollection(); foreach (ProjectItem item in project.Items) { if (!itemsToExclude.Contains(item) && (string.IsNullOrEmpty(item.Condition) || ConditionParser.ParseAndEvaluate(item.Condition, ctx))) { buildData.Items.Add(item); } } buildData.Configuration = (DotNetProjectConfiguration)conf.Clone(); buildData.Configuration.SetParentItem(project); buildData.ConfigurationSelector = configuration; return(ProjectExtensionUtil.Compile(monitor, project, buildData, delegate { ProjectItemCollection items = buildData.Items; BuildResult res = BuildResources(buildData.Configuration, ref items, monitor); if (res != null) { return res; } res = project.LanguageBinding.Compile(items, buildData.Configuration, buildData.ConfigurationSelector, monitor); if (refres != null) { refres.Append(res); return refres; } else { return res; } })); }
protected void GetContents(MonoDevelop.Projects.Project project, MonoDevelop.Prj2Make.Schema.Csproj.File[] Include, ProjectFileCollection files, IProgressMonitor monitor) { if (Include == null || Include.Length == 0) { return; } // Iterate through the file collection of the csproj file foreach (MonoDevelop.Prj2Make.Schema.Csproj.File fl in Include) { ProjectFile flOut = new ProjectFile(); string name; if ((fl.Link == null) || (fl.Link.Length == 0)) { name = MapPath(project.BaseDirectory, fl.RelPath); } else { name = MapPath(null, fl.Link); } if (name == null) { monitor.ReportWarning(GettextCatalog.GetString("Can't import file: ") + fl.RelPath); continue; } flOut.Name = name; // Adding here as GetDefaultResourceIdInternal needs flOut.Project files.Add(flOut); switch (fl.SubType) { case "Code": flOut.Subtype = Subtype.Code; break; } switch (fl.BuildAction) { case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.Compile: flOut.BuildAction = BuildAction.Compile; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.Content: flOut.BuildAction = BuildAction.Content; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.EmbeddedResource: flOut.BuildAction = BuildAction.EmbeddedResource; break; case MonoDevelop.Prj2Make.Schema.Csproj.FileBuildAction.None: flOut.BuildAction = BuildAction.None; break; } // DependentUpon is relative to flOut flOut.DependsOn = MapPath(Path.GetDirectoryName(flOut.Name), fl.DependentUpon); flOut.Data = ""; } }
protected void Warn(string logtext) { tracker.ReportWarning(logtext); }
void EmitCustomCommandTargets (CustomCommandCollection commands, Project project, StringBuilder builder, string configName, CustomCommandType[] types, IProgressMonitor monitor) { bool warned = false; configName = configName.ToUpper (); foreach (CustomCommandType type in types) { bool targetEmitted = false; for (int i = 0; i < commands.Count; i ++) { CustomCommand cmd = commands [i]; if (cmd.Type != type) { if (!warned && Array.IndexOf (types, cmd.Type) < 0) { //Warn (only once) if unsupported custom command is found, StringBuilder types_list = new StringBuilder (); foreach (CustomCommandType t in types) types_list.AppendFormat ("{0}, ", t); monitor.ReportWarning (GettextCatalog.GetString ( "Custom commands of only the following types are supported: {0}.", types_list.ToString ())); warned = true; } continue; } if (!targetEmitted) { builder.AppendFormat ("{0}_{1}:\n", configName, type.ToString ()); targetEmitted = true; } string dir, exe, args; ResolveCustomCommand (project, cmd, out dir, out exe, out args); builder.AppendFormat ("\t(cd {0} && {1} {2})\n", dir, exe, args); } if (targetEmitted) builder.Append ("\n"); } }
internal override void CommitUninstall (IProgressMonitor monitor, AddinStore service) { if (tempFolder == null) return; monitor.Log.WriteLine ("Uninstalling " + info.Name + " v" + info.Version); AddinDescription conf = iaddin.Description; string basePath = Path.GetDirectoryName (conf.AddinFile); foreach (string relPath in conf.AllFiles) { string path = Path.Combine (basePath, relPath); if (!File.Exists (path)) continue; File.Delete (path); } File.Delete (iaddin.AddinFile); if (Directory.GetFiles (basePath).Length == 0) { try { Directory.Delete (basePath); } catch { monitor.ReportWarning ("Directory " + basePath + " could not be deleted."); } } monitor.Log.WriteLine ("Done"); }
public Solution MsSlnToCmbxHelper (string slnFileName, IProgressMonitor monitor) { Solution solution = new Solution(); monitor.BeginTask (GettextCatalog.GetString ("Importing solution"), 2); try { // We invoke the ParseSolution // by passing the file obtained ParseSolution (slnFileName, monitor); // Create all of the prjx files form the csproj files monitor.BeginTask (null, projNameInfo.Values.Count * 2); foreach (CsprojInfo pi in projNameInfo.Values) { string mappedPath = MapPath (Path.GetDirectoryName (slnFileName), pi.csprojpath); if (mappedPath == null) { monitor.Step (2); monitor.ReportWarning (GettextCatalog.GetString ("Project file not found: ") + pi.csprojpath); continue; } SolutionEntityItem prj; if (pi.NeedsConversion) prj = CreatePrjxFromCsproj (mappedPath, monitor); else prj = (DotNetProject) Services.ProjectService.ReadSolutionItem (monitor, mappedPath); if (prj == null) return null; monitor.Step (1); solution.RootFolder.Items.Add (prj); foreach (ItemConfiguration conf in prj.Configurations) { if (!solution.GetConfigurations ().Contains (conf.Id)) solution.AddConfiguration (conf.Id, false); } monitor.Step (1); } monitor.EndTask (); monitor.Step (1); solution.SetLocation (Path.GetDirectoryName (slnFileName), Path.GetFileNameWithoutExtension(slnFileName)); monitor.Step (1); return solution; } catch (Exception e) { monitor.ReportError (GettextCatalog.GetString ("The solution could not be imported."), e); throw; } finally { monitor.EndTask (); } }