Example #1
0
        public void AddBuiltFile(string filePath)
        {
            string fpath = FileService.GetFullPath(filePath);
            string bd    = FileService.GetFullPath(BaseDirectory);

            if (fpath.StartsWith(bd + Path.DirectorySeparatorChar) || fpath == bd)
            {
                string rel = FileService.AbsoluteToRelativePath(bd, fpath);
                rel = FileService.NormalizeRelativePath(rel);
                rel = "$(top_builddir)" + Path.DirectorySeparatorChar + rel;
                builtFiles.Add(rel);
            }
        }
        public override void ActivateItem()
        {
            StockIconsNode    node = (StockIconsNode)CurrentNode.DataItem;
            GtkDesignInfo     info = GtkDesignInfo.FromProject(node.Project);
            GuiBuilderProject gp   = info.GuiBuilderProject;

            Stetic.Project sp = gp.SteticProject;
            sp.ImagesRootPath     = FileService.AbsoluteToRelativePath(info.GtkGuiFolder, gp.Project.BaseDirectory);
            sp.ImportFileCallback = delegate(string file) {
                return(GuiBuilderService.ImportFile(gp.Project, file));
            };
            sp.EditIcons();
            gp.Save(true);
        }
Example #3
0
        string GetName()
        {
            if (ConfigFile.ParentDirectory == WorkspaceFileObject.BaseDirectory)
            {
                return(ConfigFile.FileName);
            }

            if (!ConfigFile.IsChildPathOf(WorkspaceFileObject.BaseDirectory))
            {
                return(ConfigFile.FileName);
            }

            return(FileService.AbsoluteToRelativePath(WorkspaceFileObject.BaseDirectory, ConfigFile));
        }
        public static string DecodePath(SolutionEntityItem item, string path)
        {
            IPathHandler ph = item.GetItemHandler() as IPathHandler;

            if (ph != null)
            {
                return(ph.DecodePath(path));
            }
            else
            {
                string basePath = Path.GetDirectoryName(item.FileName);
                return(FileService.AbsoluteToRelativePath(basePath, path));
            }
        }
Example #5
0
        static DocumentUserPrefs CreateDocumentPrefs(UserPreferencesEventArgs args, Document document)
        {
            string path = (string)document.OriginalFileName ?? document.FileName;

            var dp = new DocumentUserPrefs();

            dp.FileName = FileService.AbsoluteToRelativePath(args.Item.BaseDirectory, path);
            if (document.GetContent <ITextView> () is ITextView view)
            {
                var pos  = view.Caret.Position.BufferPosition;
                var line = pos.Snapshot.GetLineFromPosition(pos.Position);
                dp.Line   = line.LineNumber + 1;
                dp.Column = pos.Position - line.Start + 1;
            }
            return(dp);
        }
Example #6
0
        void OnStoringWorkspaceUserPreferences(object s, UserPreferencesEventArgs args)
        {
            WorkbenchUserPrefs prefs = new WorkbenchUserPrefs();

            foreach (Document document in Documents)
            {
                if (!String.IsNullOrEmpty(document.FileName))
                {
                    DocumentUserPrefs dp = new DocumentUserPrefs();
                    dp.FileName = FileService.AbsoluteToRelativePath(args.Item.BaseDirectory, document.FileName);
                    if (document.Editor != null)
                    {
                        dp.Line   = document.Editor.Caret.Line;
                        dp.Column = document.Editor.Caret.Column;
                    }
                    prefs.Files.Add(dp);
                }
            }

            foreach (Pad pad in Pads)
            {
                IMementoCapable mc = pad.GetMementoCapable();
                if (mc != null)
                {
                    ICustomXmlSerializer mem = mc.Memento;
                    if (mem != null)
                    {
                        PadUserPrefs data = new PadUserPrefs();
                        data.Id = pad.Id;
                        StringWriter  w  = new StringWriter();
                        XmlTextWriter tw = new XmlTextWriter(w);
                        mem.WriteTo(tw);
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(w.ToString());
                        data.State = doc.DocumentElement;
                        prefs.Pads.Add(data);
                    }
                }
            }

            if (ActiveDocument != null)
            {
                prefs.ActiveDocument = FileService.AbsoluteToRelativePath(args.Item.BaseDirectory, ActiveDocument.FileName);
            }

            args.Properties.SetValue("MonoDevelop.Ide.Workbench", prefs);
        }
Example #7
0
        DataCollection ICustomDataItem.Serialize(ITypeSerializer handler)
        {
            DataCollection data  = handler.Serialize(this);
            DataItem       items = new DataItem();

            items.Name        = "Items";
            items.UniqueNames = false;
            string baseDir = Path.GetDirectoryName(handler.SerializationContext.BaseFile);

            foreach (WorkspaceItem it in Items)
            {
                DataValue item = new DataValue("Item", FileService.AbsoluteToRelativePath(baseDir, it.FileName));
                items.ItemData.Add(item);
            }
            data.Add(items);
            return(data);
        }
        void AddFile(string fileName)
        {
            string   relativePath = FileService.AbsoluteToRelativePath(project.BaseDirectory, fileName);
            TreeIter iter         = GetPath(System.IO.Path.GetDirectoryName(relativePath));

            object[] values = new object[] {
                DesktopService.GetPixbufForFile(fileName, IconSize.Menu),
                null,
                System.IO.Path.GetFileName(fileName),
                fileName,
                false
            };
            if (!store.IterIsValid(iter))
            {
                store.AppendValues(values);
                return;
            }
            store.AppendValues(iter, values);
        }
        public override bool AddToProject(SolutionItem policyParent, Project project,
                                          string language, string directory, string name)
        {
            bool addedSomething = false;

            directory = Path.Combine(directory, dirName);
            if (templates.Count == 0)
            {
                string relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, directory);
                if (project.AddDirectory(relPath) != null)
                {
                    addedSomething = true;
                }
            }

            foreach (FileDescriptionTemplate t in templates)
            {
                addedSomething |= t.AddToProject(policyParent, project, language, directory, name);
            }
            return(addedSomething);
        }
Example #10
0
        public override void DeleteItem()
        {
            GuiBuilderWindow w  = (GuiBuilderWindow)CurrentNode.DataItem;
            string           fn = FileService.AbsoluteToRelativePath(w.Project.Project.BaseDirectory, w.SourceCodeFile);

            using (ConfirmWindowDeleteDialog dialog = new ConfirmWindowDeleteDialog(w.Name, fn, w.RootWidget)) {
                if (dialog.Run() == (int)Gtk.ResponseType.Yes)
                {
                    if (dialog.DeleteFile)
                    {
                        ProjectFile file = w.Project.Project.GetProjectFile(w.SourceCodeFile);
                        if (file != null)
                        {
                            w.Project.Project.Files.Remove(file);
                        }
                    }
                    w.Project.Remove(w);
                    w.Project.SaveProject(false);
                    IdeApp.ProjectOperations.SaveAsync(w.Project.Project);
                }
            }
        }
        protected virtual void OnButtonBrowseClicked(object sender, System.EventArgs e)
        {
            var dlg = new SelectFileDialog(GettextCatalog.GetString("Select File"))
            {
                CurrentFolder  = entry.BaseDirectory,
                SelectMultiple = false,
                TransientFor   = this.Toplevel as Gtk.Window,
            };

            if (!dlg.Run())
            {
                return;
            }
            if (System.IO.Path.IsPathRooted(dlg.SelectedFile))
            {
                entryCommand.Text = FileService.AbsoluteToRelativePath(entry.BaseDirectory, dlg.SelectedFile);
            }
            else
            {
                entryCommand.Text = dlg.SelectedFile;
            }
        }
        void ResultPathDataFunc(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
        {
            if (TreeIter.Zero.Equals(iter))
            {
                return;
            }
            var pathRenderer = (CellRendererText)cell;
            var searchResult = (SearchResult)store.GetValue(iter, SearchResultColumn);

            if (searchResult == null)
            {
                return;
            }
            string pathMarkup = searchResult.PathMarkup;

            if (pathMarkup == null)
            {
                bool didRead = (bool)store.GetValue(iter, DidReadColumn);

                var    fileName         = searchResult.FileName;
                string baseSolutionPath = null;
                if (pathMode == PathMode.Relative)
                {
                    var workspace = IdeApp.Workspace;
                    var solutions = workspace != null?workspace.GetAllSolutions() : null;

                    baseSolutionPath = solutions != null && solutions.Count == 1 ? solutions [0].BaseDirectory : null;
                }
                var finalFileName = baseSolutionPath == null ? fileName :
                                    FileService.AbsoluteToRelativePath(baseSolutionPath, fileName);
                var directory = System.IO.Path.GetDirectoryName(finalFileName);

                pathMarkup = MarkupText(directory, didRead);
                searchResult.PathMarkup = pathMarkup;
            }
            pathRenderer.Markup = pathMarkup;
        }
Example #13
0
        public string GetRelativePath(Project project, string path, bool isGenerated)
        {
            string fpath = Path.GetFullPath(path);
            string bd    = Path.GetFullPath(project.BaseDirectory);

            if (fpath.StartsWith(bd + Path.DirectorySeparatorChar) || fpath == bd)
            {
                string rel = FileService.AbsoluteToRelativePath(bd, fpath);
                rel = FileService.NormalizeRelativePath(rel);
                if (isGenerated)
                {
                    return(rel);
                }
                else
                {
                    return("$(srcdir)" + Path.DirectorySeparatorChar + rel);
                }
            }
            bd = Path.GetFullPath(BaseDirectory);
            if (fpath.StartsWith(bd + Path.DirectorySeparatorChar) || fpath == bd)
            {
                string rel = FileService.AbsoluteToRelativePath(bd, fpath);
                rel = FileService.NormalizeRelativePath(rel);
                string file = "$(top_builddir)" + Path.DirectorySeparatorChar + rel;
                if (builtFiles.Contains(file))
                {
                    return(file);
                }
                else
                {
                    globalFilesReferences.Add(file);
                    return("$(top_srcdir)" + Path.DirectorySeparatorChar + rel);
                }
            }
            throw new InvalidOperationException("The project '" + project.Name + "' references the file '" + Path.GetFileName(path) + "' which is located outside the solution directory.");
        }
Example #14
0
        public override async Task <bool> AddToProjectAsync(SolutionFolderItem policyParent, Project project,
                                                            string language, string directory, string name)
        {
            bool addedSomething = false;

            directory = Path.Combine(directory, dirName);
            if (templates.Count == 0)
            {
                string relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, directory);
                if (project.AddDirectory(relPath) != null)
                {
                    addedSomething = true;
                }
            }

            foreach (FileDescriptionTemplate t in templates)
            {
                if (t.EvaluateCreateCondition())
                {
                    addedSomething |= await t.AddToProjectAsync(policyParent, project, language, directory, name);
                }
            }
            return(addedSomething);
        }
		public void IncludeToProject ()
		{
			Set<SolutionEntityItem> projects = new Set<SolutionEntityItem> ();
			foreach (ITreeNavigator node in CurrentNodes) {
				Project project = node.GetParentDataItem (typeof(Project), true) as Project;
				if (node.HasChildren ()) {
					List<SystemFile> filesToAdd = new List<SystemFile> ();
					ITreeNavigator nav = node.Clone ();
					GetFiles (nav, filesToAdd);
	
					foreach (SystemFile file in filesToAdd)
						project.AddFile (file.Path);

					projects.Add (project);
				} else {
					ProjectFolder pf = node.DataItem as ProjectFolder;
					if (pf != null) {
						project.AddDirectory (FileService.AbsoluteToRelativePath (project.BaseDirectory, pf.Path));
						projects.Add (project);
					}
				}
			}
			IdeApp.ProjectOperations.Save (projects);
		}
Example #16
0
        void OnStoringWorkspaceUserPreferences(object s, UserPreferencesEventArgs args)
        {
            WorkbenchUserPrefs prefs = new WorkbenchUserPrefs();
            var nbId = 0;
            var fwId = 1;

            foreach (var window in DockWindow.GetAllWindows())
            {
                int x, y;
                window.GetPosition(out x, out y);
                var fwp = new FloatingWindowUserPrefs {
                    WindowId = fwId,
                    X        = x,
                    Y        = y,
                    Width    = window.Allocation.Width,
                    Height   = window.Allocation.Height
                };

                foreach (var nb in window.Container.GetNotebooks())
                {
                    AddNotebookDocuments(args, fwp.Files, nb, nbId++);
                }

                if (fwp.Files.Count > 0)
                {
                    prefs.FloatingWindows.Add(fwp);
                    fwId++;
                }
            }

            var mainContainer = workbench.TabControl.Container;

            foreach (var nb in mainContainer.GetNotebooks())
            {
                AddNotebookDocuments(args, prefs.Files, nb, nbId++);
            }

            foreach (Pad pad in Pads)
            {
                IMementoCapable mc = pad.GetMementoCapable();
                if (mc != null)
                {
                    ICustomXmlSerializer mem = mc.Memento;
                    if (mem != null)
                    {
                        PadUserPrefs data = new PadUserPrefs();
                        data.Id = pad.Id;
                        StringWriter  w  = new StringWriter();
                        XmlTextWriter tw = new XmlTextWriter(w);
                        mem.WriteTo(tw);
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(w.ToString());
                        data.State = doc.DocumentElement;
                        prefs.Pads.Add(data);
                    }
                }
            }

            if (ActiveDocument != null)
            {
                prefs.ActiveDocument = FileService.AbsoluteToRelativePath(args.Item.BaseDirectory, ActiveDocument.FileName);
            }

            args.Properties.SetValue("MonoDevelop.Ide.Workbench", prefs);
        }
Example #17
0
        public static TooltipInformation CreateTooltipInformation(ICompilation compilation, CSharpUnresolvedFile file, CSharpResolver resolver, TextEditorData textEditorData, MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy formattingPolicy, IEntity entity, bool smartWrap, bool createFooter = false)
        {
            var tooltipInfo = new TooltipInformation();

            if (resolver == null)
            {
                resolver = file != null?file.GetResolver(compilation, textEditorData.Caret.Location) : new CSharpResolver(compilation);
            }
            var sig = new SignatureMarkupCreator(resolver, formattingPolicy.CreateOptions());

            sig.BreakLineAfterReturnType = smartWrap;
            try {
                tooltipInfo.SignatureMarkup = sig.GetMarkup(entity);
            } catch (Exception e) {
                LoggingService.LogError("Got exception while creating markup for :" + entity, e);
                return(new TooltipInformation());
            }
            tooltipInfo.SummaryMarkup = AmbienceService.GetSummaryMarkup(entity) ?? "";

            if (entity is IMember)
            {
                var evt = (IMember)entity;
                if (evt.ReturnType.Kind == TypeKind.Delegate)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Delegate Info"), sig.GetDelegateInfo(evt.ReturnType));
                }
            }
            if (entity is IMethod)
            {
                var method = (IMethod)entity;
                if (method.IsExtensionMethod)
                {
                    tooltipInfo.AddCategory(GettextCatalog.GetString("Extension Method from"), method.DeclaringTypeDefinition.FullName);
                }
            }
            if (createFooter)
            {
                if (entity is IType)
                {
                    var type = entity as IType;
                    var def  = type.GetDefinition();
                    if (def != null)
                    {
                        if (!string.IsNullOrEmpty(def.ParentAssembly.AssemblyName))
                        {
                            var project = def.GetSourceProject();
                            if (project != null)
                            {
                                var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, def.Region.FileName);
                                tooltipInfo.FooterMarkup = "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(def.ParentAssembly.AssemblyName)) + "</small>" + Environment.NewLine +
                                                           "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), def.Region.Begin.Line) + "</small>";
                            }
                        }
                    }
                }
                else if (entity.DeclaringTypeDefinition != null)
                {
                    var project = entity.DeclaringTypeDefinition.GetSourceProject();
                    if (project != null)
                    {
                        var relPath = FileService.AbsoluteToRelativePath(project.BaseDirectory, entity.Region.FileName);
                        tooltipInfo.FooterMarkup =
                            "<small>" + GettextCatalog.GetString("Project:\t{0}", AmbienceService.EscapeText(project.Name)) + "</small>" + Environment.NewLine +
                            "<small>" + GettextCatalog.GetString("From:\t{0}", AmbienceService.EscapeText(entity.DeclaringType.FullName)) + "</small>" + Environment.NewLine +
                            "<small>" + GettextCatalog.GetString("File:\t\t{0} (line {1})", AmbienceService.EscapeText(relPath), entity.Region.Begin.Line) + "</small>";
                    }
                }
            }
            return(tooltipInfo);
        }
        void ProcessProjectReferences(DotNetProject project, out string references, out string dllReferences, AutotoolsContext ctx)
        {
            StringWriter refWriter    = new StringWriter();
            StringWriter dllRefWriter = new StringWriter();

            pkgs = new Set <SystemPackage> ();

            // grab pkg-config references
            foreach (ProjectReference reference in project.References)
            {
                if (reference.ReferenceType == ReferenceType.Package)
                {
                    // Get pkg-config keys
                    SystemPackage pkg = reference.Package;
                    if (pkg != null && !pkg.IsCorePackage)
                    {
                        if (pkgs.Contains(pkg))
                        {
                            continue;
                        }
                        pkgs.Add(pkg);

                        refWriter.WriteLine(" \\");
                        if (generateAutotools)
                        {
                            refWriter.Write("\t$(");
                            refWriter.Write(AutotoolsContext.GetPkgConfigVariable(pkg.Name));
                            refWriter.Write("_LIBS)");
                        }
                        else
                        {
                            refWriter.Write("\t-pkg:{0}", pkg.Name);
                        }
                        pkgs.Add(pkg);
                    }
                    else
                    {
                        refWriter.WriteLine(" \\");                                             // store all refs for easy access
                        AssemblyName assembly = SystemAssemblyService.ParseAssemblyName(reference.Reference);
                        refWriter.Write("\t" + assembly.Name);
                        refWriter.Write("");
                    }
                }
                else if (reference.ReferenceType == ReferenceType.Assembly)
                {
                    string assemblyPath = Path.GetFullPath(reference.Reference);

                    dllRefWriter.WriteLine(" \\");
                    dllRefWriter.Write("\t");

                    ctx.AddGlobalReferencedFile(MakefileData.ToMakefilePath(FileService.AbsoluteToRelativePath(
                                                                                Path.GetFullPath(ctx.BaseDirectory), assemblyPath)));
                    dllRefWriter.Write(MakefileData.ToMakefilePath(FileService.AbsoluteToRelativePath(
                                                                       project.BaseDirectory, assemblyPath)));
                }
                else if (reference.ReferenceType == ReferenceType.Project)
                {
                    continue;                     // handled per-config
                }
                else
                {
                    throw new Exception(GettextCatalog.GetString("Project reference type '{0}' not supported yet",
                                                                 reference.ReferenceType.ToString()));
                }
            }

            references    = refWriter.ToString();
            dllReferences = dllRefWriter.ToString();
        }
        void CreateConfigureDotAC(Solution solution, string defaultConf, IProgressMonitor monitor, AutotoolsContext context)
        {
            monitor.Log.WriteLine(GettextCatalog.GetString("Creating configure.ac"));
            TemplateEngine templateEngine = new TemplateEngine();

            templateEngine.Variables["WARNING"] = "Warning: This is an automatically generated file, do not edit!";

            // add solution configuration options
            StringBuilder config_options = new StringBuilder();

            foreach (SolutionConfiguration config in solution.Configurations)
            {
                string name   = context.EscapeAndUpperConfigName(config.Id).ToLower();
                string def    = config.Id == defaultConf ? "YES" : "NO";
                string ac_var = "enable_" + name;

                // test to see if a configuration was enabled
                config_options.AppendFormat("AC_ARG_ENABLE({0},\n", name);
                config_options.AppendFormat("	AC_HELP_STRING([--enable-{0}],\n", name);
                config_options.AppendFormat("		[Use '{0}' Configuration [default={1}]]),\n", context.EscapeAndUpperConfigName(config.Id), def);
                config_options.AppendFormat("		{0}=yes, {0}=no)\n", ac_var);
                config_options.AppendFormat("AM_CONDITIONAL({0}, test x${1} = xyes)\n", ac_var.ToUpper(), ac_var);

                // if yes, populate some vars
                config_options.AppendFormat("if test \"x${0}\" = \"xyes\" ; then\n", ac_var);
//				AppendConfigVariables ( combine, config.Name, config_options );
                config_options.Append("	CONFIG_REQUESTED=\"yes\"\nfi\n");
            }

            // if no configuration was specified, set to default (if there is a default)
            if (defaultConf != null)
            {
                config_options.Append("if test -z \"$CONFIG_REQUESTED\" ; then\n");
//				AppendConfigVariables ( combine, defaultConf, config_options );
                config_options.AppendFormat("	AM_CONDITIONAL(ENABLE_{0}, true)\n", context.EscapeAndUpperConfigName(defaultConf));
                config_options.AppendFormat("\tenable_{0}=yes\n", context.EscapeAndUpperConfigName(defaultConf).ToLower());
                config_options.Append("fi\n");
            }

            // Add specific user switch
            if (switchs != null)
            {
                foreach (Switch s in switchs)
                {
                    string name = s.SwitchName.ToLowerInvariant();

                    config_options.AppendLine(string.Format(@"AC_ARG_ENABLE({0},
	AC_HELP_STRING([--enable-{0}],
		[{1}]),
		enable_{2}=yes, enable_{2}=no)
AM_CONDITIONAL(ENABLE_{3}, test x$enable_{2} = xyes)",
                                                            name, s.HelpStr, name.Replace('-', '_'), name.Replace('-', '_').ToUpperInvariant()));
                }
            }

            templateEngine.Variables ["CONFIG_OPTIONS"] = config_options.ToString();

            // build compiler checks
            StringBuilder compiler_checks = new StringBuilder();

            foreach (string compiler in context.GetCommandChecks())
            {
                compiler_checks.AppendFormat("AC_PATH_PROG({0}, {1}, no)\n", compiler.ToUpper(), compiler);
                compiler_checks.AppendFormat("if test \"x${0}\" = \"xno\"; then\n", compiler.ToUpper());
                compiler_checks.AppendFormat("        AC_MSG_ERROR([{0} Not found])\n", compiler);
                compiler_checks.Append("fi\n");
            }
            templateEngine.Variables["COMPILER_CHECKS"] = compiler_checks.ToString();

            // build list of *.in files
            StringBuilder configFiles = new StringBuilder();
            string        tmpmf       = null;

            foreach (string makefile in context.GetAutoConfFiles())
            {
                tmpmf = FileService.AbsoluteToRelativePath(solution_dir, makefile);
                if (PlatformID.Unix != Environment.OSVersion.Platform)
                {
                    tmpmf = tmpmf.Replace("\\", "/");
                }

                AutotoolsContext.CheckSpaces(tmpmf);
                configFiles.Append(FileService.NormalizeRelativePath(tmpmf));
                configFiles.Append("\n");
            }
            templateEngine.Variables["CONFIG_FILES"] = configFiles.ToString();

            // build list of pkgconfig checks we must make
            StringWriter packageChecks = new StringWriter();

            packageChecks.WriteLine("dnl package checks, common for all configs");
            Set <SystemPackage> commonPackages = context.GetCommonRequiredPackages();

            foreach (SystemPackage pkg in commonPackages)
            {
                packageChecks.WriteLine("PKG_CHECK_MODULES([{0}], [{1}])", AutotoolsContext.GetPkgConfigVariable(pkg.Name), pkg.Name);
            }

            packageChecks.WriteLine("\ndnl package checks, per config");
            foreach (SolutionConfiguration config in solution.Configurations)
            {
                Set <SystemPackage> pkgs = context.GetRequiredPackages(config.Id, true);
                if (pkgs == null || pkgs.Count == 0)
                {
                    continue;
                }

                packageChecks.WriteLine(@"if test ""x$enable_{0}"" = ""xyes""; then",
                                        context.EscapeAndUpperConfigName(config.Id).ToLower());

                foreach (SystemPackage pkg in pkgs)
                {
                    packageChecks.WriteLine("\tPKG_CHECK_MODULES([{0}], [{1}])", AutotoolsContext.GetPkgConfigVariable(pkg.Name), pkg.Name);
                }
                packageChecks.WriteLine("fi");
            }
            templateEngine.Variables["PACKAGE_CHECKS"] = packageChecks.ToString();
            templateEngine.Variables["SOLUTION_NAME"]  = solution_name;
            templateEngine.Variables["VERSION"]        = solution_version;

            string configureFileName = Path.Combine(solution_dir, "configure.ac");

            StreamWriter writer = new StreamWriter(configureFileName);
            Stream       stream = context.GetTemplateStream("configure.ac.template");
            StreamReader reader = new StreamReader(stream);

            templateEngine.Process(reader, writer);

            reader.Close();
            writer.Close();
            context.AddGeneratedFile(configureFileName);
        }
 string GetRelativePath(string path)
 {
     return(FileService.AbsoluteToRelativePath(project.BaseDirectory, path));
 }
        public Makefile Deploy(AutotoolsContext ctx, SolutionFolderItem entry, ProgressMonitor 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!";

                if (entry is DotNetProject dotnetProject)
                {
                    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.DebugSymbols ? "$(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 = reference.ResolveProject(ctx.TargetSolution);
                        if (refp == null)
                        {
                            throw new Exception(GettextCatalog.GetString("Couldn't find referenced project '{0}'", reference.Reference));
                        }
                        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 SolutionFolderItem[] { 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.DebugSymbols)
                    {
                        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=al\n");
                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);
        }
Example #22
0
        public static async Task IncludeBundleAsync(this Project currentProject, FigmaBundle bundle, bool includeImages = false, bool savesInProject = true)
        {
            Ide.IdeApp.Workbench.StatusBar.ShowMessage("Including files into current project…");

            var figmaFolder = Path.Combine(currentProject.BaseDirectory.FullPath, FigmaBundle.FigmaDirectoryName);

            if (!currentProject.PathExistsInProject(figmaFolder))
            {
                //we add figma folder in the case doesn't exists
                currentProject.AddDirectory(FileService.AbsoluteToRelativePath(currentProject.BaseDirectory, figmaFolder));
            }

            //now we need to add the content
            //bundle
            var fullBundlePath = bundle.DirectoryPath;

            if (!currentProject.PathExistsInProject(fullBundlePath))
            {
                currentProject.AddDirectory(FileService.AbsoluteToRelativePath(currentProject.BaseDirectory, fullBundlePath));
            }

            //manifest
            var manifestFullDirectoryPath = bundle.ManifestFilePath;

            if (!currentProject.PathExistsInProject(manifestFullDirectoryPath))
            {
                currentProject.AddFile(manifestFullDirectoryPath);
            }


            //document
            var documentFullDirectoryPath = bundle.DocumentFilePath;

            if (!currentProject.PathExistsInProject(documentFullDirectoryPath))
            {
                currentProject.AddFile(documentFullDirectoryPath);
            }

            //TODO: images are not enabled by now
            if (includeImages)
            {
                //resources
                var resourcesDirectoryPath = bundle.ResourcesDirectoryPath;
                currentProject.AddDirectory(FileService.AbsoluteToRelativePath(currentProject.BaseDirectory, resourcesDirectoryPath));

                //we add to the project for each resource inside the
                //foreach (var image in Directory.EnumerateFiles (resourcesDirectoryPath, "*.png")) {
                //	currentProject.AddFile (image);
                //}

                var images = Directory.EnumerateFiles(resourcesDirectoryPath, $"*{FigmaBundle.ImageFormat}").Select(s => new FilePath(s));

                foreach (var item in images)
                {
                    if (!currentProject.PathExistsInProject(item))
                    {
                        var projectFile = new ProjectFile(item, BuildAction.BundleResource);
                        projectFile.Metadata.SetValue("LogicalName", projectFile.ResourceId, "");
                        currentProject.AddFile(projectFile);
                    }
                }
            }
            if (savesInProject)
            {
                await IdeApp.ProjectOperations.SaveAsync(currentProject);
            }
        }
        // Handle unique deploy files, emits non-perconfig stuff, like targets for deploy files,
        // un/install commands
        void HandleDeployFile(DeployFileData data, string targetDeployVar, Project project, AutotoolsContext ctx)
        {
            DeployFile dfile = data.File;
            string     dependencyDeployFile = null;         //Dependency for the deployfile target

            if (dfile.ContainsPathReferences)
            {
                // Template file, copy to .in file
                string full_fname = Path.Combine(project.BaseDirectory, Path.GetFileName(dfile.RelativeTargetPath));
                string fname      = full_fname;
                string infname    = fname + ".in";
                if (File.Exists(infname) && project.IsFileInProject(infname))
                {
                    string datadir = Path.Combine(project.BaseDirectory, "data");
                    if (!Directory.Exists(datadir))
                    {
                        Directory.CreateDirectory(datadir);
                    }
                    infname = Path.Combine(datadir, Path.GetFileName(dfile.RelativeTargetPath) + ".in");
                }

                //Absolute path required
                File.Copy(dfile.SourcePath, infname, true);

                //Path relative to TargetCombine
                fname = FileService.NormalizeRelativePath(
                    FileService.AbsoluteToRelativePath(ctx.TargetSolution.BaseDirectory, full_fname));
                infname = fname + ".in";
                ctx.AddAutoconfFile(MakefileData.ToMakefilePath(fname));
                ctx.AddGeneratedFile(full_fname + ".in");

                //Path relative to project
                fname = FileService.NormalizeRelativePath(
                    FileService.AbsoluteToRelativePath(project.BaseDirectory, full_fname));
                infname = fname + ".in";
                extras.AppendFormat("\\\n\t{0} ", MakefileData.ToMakefilePath(infname));

                //dependencyDeployFile here should be filename relative to the project
                dependencyDeployFile = fname;
            }
            else
            {
                dependencyDeployFile = String.Format("$({0}_SOURCE)", targetDeployVar);
            }

            builtFiles.Add(Path.GetFileName(dfile.RelativeTargetPath));

            if (dfile.ContainsPathReferences)
            {
                deployFileCopyTargets.AppendFormat("$(eval $(call emit-deploy-wrapper,{0},{1}{2}))\n",
                                                   targetDeployVar,
                                                   MakefileData.ToMakefilePath(dependencyDeployFile),
                                                   (dfile.FileAttributes & DeployFileAttributes.Executable) != 0 ? ",x" : String.Empty);
            }
            else
            {
                // The emit-deploy-target macro copies the deployable file to the output directory.
                // This is not needed if the file is already there (e.g. for an .mdb file)
                if (Path.GetFullPath(dfile.SourcePath) != Path.GetFullPath(Path.Combine(data.Configuration.OutputDirectory, dfile.RelativeTargetPath)))
                {
                    deployFileCopyTargets.AppendFormat("$(eval $(call emit-deploy-target,{0}))\n", targetDeployVar);
                }
            }

            switch (dfile.TargetDirectoryID)
            {
            case TargetDirectory.Gac:
                // TODO
                break;

            default:
                string var;
                if (dfile.TargetDirectoryID != TargetDirectory.Binaries)
                {
                    string ddir = FileService.NormalizeRelativePath(dfile.RelativeTargetPath.ParentDirectory.ToString().Trim('/', ' '));
                    if (ddir.Length > 0)
                    {
                        ddir = "/" + ddir;
                    }
                    var = ctx.GetDeployDirectoryVar(dfile.TargetDirectoryID + ddir);
                }
                else
                {
                    var = "BINARIES";
                }

                StringBuilder sb;
                if (!deployDirs.TryGetValue(var, out sb))
                {
                    sb = new StringBuilder();
                    deployDirs [var] = sb;
                }
                sb.AppendFormat("\\\n\t$({0}) ", targetDeployVar);
                break;
            }

            if (!generateAutotools)
            {
                string installDir = Path.GetDirectoryName(ctx.DeployContext.GetResolvedPath(dfile.TargetDirectoryID, dfile.RelativeTargetPath));
                //FIXME: temp
                installDir = TranslateDir(installDir);

                if (!installDirs.Contains(installDir))
                {
                    installTarget.AppendFormat("\tmkdir -p '$(DESTDIR){0}'\n", installDir);
                    installDirs.Add(installDir);
                }

                installTarget.AppendFormat("\t$(call cp,$({0}),$(DESTDIR){1})\n", targetDeployVar, installDir);
                uninstallTarget.AppendFormat("\t$(call rm,$({1}),$(DESTDIR){0})\n", installDir, targetDeployVar);
            }
        }
 public void TestGetRelativePath()
 {
     Assert.AreEqual(@"blub", FileService.AbsoluteToRelativePath(@"/a", @"/a/blub"));
 }
Example #25
0
        public virtual DataCollection Serialize(object obj, ITypeSerializer handler)
        {
            if (obj is ProjectFile)
            {
                ProjectFile    pf   = (ProjectFile)obj;
                DataCollection data = handler.Serialize(obj);

                //Map the Content build action to the old FileCopy action if CopyToOutputDirectory is set
                if (pf.BuildAction == BuildAction.Content && pf.CopyToOutputDirectory != FileCopyMode.None)
                {
                    DataValue value = data ["buildaction"] as DataValue;
                    if (value != null)
                    {
                        data.Remove(value);
                        data.Add(new DataValue("buildaction", "FileCopy"));
                        data.Extract("copyToOutputDirectory");
                    }
                }
                // Don't store the resource id if it matches the default.
                if (pf.BuildAction == BuildAction.EmbeddedResource && pf.ResourceId != Path.GetFileName(pf.FilePath))
                {
                    data.Add(new DataValue("resource_id", pf.ResourceId));
                }
                return(data);
            }
            else if (obj is SolutionEntityItem)
            {
                DotNetProject project = obj as DotNetProject;
                if (project != null)
                {
                    foreach (DotNetProjectConfiguration config in project.Configurations)
                    {
                        config.ExtendedProperties ["Build/target"] = project.CompileTarget.ToString();
                    }
                }
                DataCollection     data = handler.Serialize(obj);
                SolutionEntityItem item = (SolutionEntityItem)obj;
                if (item.DefaultConfiguration != null)
                {
                    DataItem confItem = data ["Configurations"] as DataItem;
                    if (confItem != null)
                    {
                        confItem.UniqueNames = true;
                        if (item.ParentSolution != null)
                        {
                            confItem.ItemData.Add(new DataValue("active", item.ParentSolution.DefaultConfigurationId));
                        }
                    }
                }
                if (project != null)
                {
                    data.Extract("targetFramework");
                    data.Add(new DataValue("targetFramework", project.TargetFramework.Id.ToLegacyIdString()));
                }
                WriteItems(handler, (SolutionEntityItem)obj, data);
                return(data);
            }
            else if (obj is ProjectReference)
            {
                ProjectReference pref  = (ProjectReference)obj;
                DataCollection   data  = handler.Serialize(obj);
                string           refto = pref.Reference;
                if (pref.ReferenceType == ReferenceType.Assembly)
                {
                    string basePath = Path.GetDirectoryName(handler.SerializationContext.BaseFile);
                    refto = FileService.AbsoluteToRelativePath(basePath, refto);
                }
                else if (pref.ReferenceType == ReferenceType.Gac && pref.LoadedReference != null)
                {
                    refto = pref.LoadedReference;
                }

                data.Add(new DataValue("refto", refto));
                return(data);
            }
            return(handler.Serialize(obj));
        }
 public void TestGetRelativePathCase3()
 {
     Assert.AreEqual(@"../a/blub", FileService.AbsoluteToRelativePath(@"/hello", @"/a/blub"));
 }
        public string LocalToVirtualPath(string filename)
        {
            string rel = FileService.AbsoluteToRelativePath(BaseDirectory, filename);

            return("~/" + rel.Replace(Path.DirectorySeparatorChar, '/'));
        }
 public void TestGetRelativePathCase4()
 {
     Assert.AreEqual(@".", FileService.AbsoluteToRelativePath(@"/aa/bb/cc", @"/aa/bb/cc"));
 }
        public Makefile Deploy(AutotoolsContext ctx, SolutionItem entry, IProgressMonitor monitor)
        {
            generateAutotools = ctx.MakefileType == MakefileType.AutotoolsMakefile;

            monitor.BeginTask(GettextCatalog.GetString(
                                  "Creating {0} for Solution {1}",
                                  generateAutotools ? "Makefile.am" : "Makefile", entry.Name), 1);

            Makefile      solutionMakefile = new Makefile();
            StringBuilder solutionTop      = new StringBuilder();

            try
            {
                SolutionFolder solutionFolder  = (SolutionFolder)entry;
                string         targetDirectory = solutionFolder.BaseDirectory;

                StringBuilder subdirs = new StringBuilder();
                subdirs.Append("#Warning: This is an automatically generated file, do not edit!\n");

                if (!generateAutotools)
                {
                    solutionTop.AppendFormat("top_srcdir={0}\n", FileService.AbsoluteToRelativePath(
                                                 entry.BaseDirectory, ctx.TargetSolution.BaseDirectory));
                    solutionTop.Append("include $(top_srcdir)/config.make\n");
                    solutionTop.Append("include $(top_srcdir)/Makefile.include\n");
                    solutionTop.Append("include $(top_srcdir)/rules.make\n\n");
                    solutionTop.Append("#include $(top_srcdir)/custom-hooks.make\n\n");
                }

                ArrayList children = new ArrayList();
                foreach (SolutionConfiguration config in solutionFolder.ParentSolution.Configurations)
                {
                    if (!ctx.IsSupportedConfiguration(config.Id))
                    {
                        continue;
                    }

                    if (generateAutotools)
                    {
                        subdirs.AppendFormat("if {0}\n", "ENABLE_" + ctx.EscapeAndUpperConfigName(config.Id));
                    }
                    else
                    {
                        subdirs.AppendFormat("ifeq ($(CONFIG),{0})\n", ctx.EscapeAndUpperConfigName(config.Id));
                    }

                    subdirs.Append(" SUBDIRS = ");

                    foreach (SolutionItem ce in CalculateSubDirOrder(ctx, solutionFolder, config))
                    {
                        string baseDirectory;
                        if (!(ce is SolutionEntityItem) && !(ce is SolutionFolder))
                        {
                            continue;
                        }

                        // Ignore projects which can't be deployed
                        IMakefileHandler handler = AutotoolsContext.GetMakefileHandler(ce, ctx.MakefileType);
                        if (handler == null)
                        {
                            continue;
                        }

                        baseDirectory = ce.BaseDirectory;

                        if (solutionFolder.BaseDirectory == baseDirectory)
                        {
                            subdirs.Append(" . ");
                        }
                        else
                        {
                            if (!baseDirectory.StartsWith(solutionFolder.BaseDirectory))
                            {
                                throw new Exception(GettextCatalog.GetString(
                                                        "Child projects must be in sub-directories of their parent"));
                            }

                            // add the subdirectory to the list
                            string path = FileService.AbsoluteToRelativePath(targetDirectory, baseDirectory);
                            if (path.StartsWith("." + Path.DirectorySeparatorChar))
                            {
                                path = path.Substring(2);
                            }

                            AutotoolsContext.CheckSpaces(path);
                            subdirs.Append(" ");
                            subdirs.Append(AutotoolsContext.EscapeStringForAutomake(path));
                        }

                        if (!children.Contains(ce))
                        {
                            children.Add(ce);
                        }
                    }
                    subdirs.Append("\nendif\n");
                }
                solutionTop.Append(subdirs.ToString());

                string includedProject = null;

                // deploy recursively
                foreach (SolutionItem ce in children)
                {
                    IMakefileHandler handler = AutotoolsContext.GetMakefileHandler(ce, ctx.MakefileType);
                    Makefile         makefile;
                    string           outpath;
                    if (handler != null && handler.CanDeploy(ce, ctx.MakefileType))
                    {
                        ctx.RegisterBuiltProject(ce);
                        makefile = handler.Deploy(ctx, ce, monitor);

                        if (targetDirectory == ce.BaseDirectory)
                        {
                            if (includedProject != null)
                            {
                                throw new Exception(GettextCatalog.GetString(
                                                        "More than 1 project in the same directory as the top-level solution is not supported."));
                            }

                            // project is in the solution directory
                            string projectMakefileName = ce.Name + ".make";
                            includedProject = String.Format("include {0}", projectMakefileName);
                            outpath         = Path.Combine(targetDirectory, projectMakefileName);
                            ctx.AddGeneratedFile(outpath);

                            if (!generateAutotools)
                            {
                                solutionMakefile.SetVariable("EXTRA_DIST", projectMakefileName);
                            }
                        }
                        else
                        {
                            makefile.AppendToVariable("EXTRA_DIST", generateAutotools ? String.Empty : "Makefile");
                            outpath = Path.Combine(ce.BaseDirectory, "Makefile");
                            if (generateAutotools)
                            {
                                ctx.AddAutoconfFile(outpath);
                                outpath = outpath + ".am";
                            }
                            else
                            {
                                makefile.Append("install: install-local\nuninstall: uninstall-local\nclean: clean-local\n");
                                if (ce is SolutionFolder)
                                {
                                    //non TargetCombine
                                    makefile.Append("dist-local: dist-local-recursive\n");
                                }
                                else
                                {
                                    makefile.Append("include $(top_srcdir)/rules.make\n");
                                }
                            }
                            ctx.AddGeneratedFile(outpath);
                        }

                        StreamWriter writer = new StreamWriter(outpath);
                        makefile.Write(writer);
                        writer.Close();
                    }
                    else
                    {
                        monitor.Log.WriteLine("Project '{0}' skipped.", ce.Name);
                    }
                }

                if (includedProject != null)
                {
                    solutionTop.Append(GettextCatalog.GetString("\n# Include project specific makefile\n"));
                    solutionTop.Append(includedProject);
                }

                if (generateAutotools)
                {
                    solutionMakefile.Append(solutionTop.ToString());
                }
                else
                {
                    TemplateEngine templateEngine = new TemplateEngine();
                    templateEngine.Variables ["MAKEFILE_SOLUTION_TOP"] = solutionTop.ToString();

                    Stream       stream = ctx.GetTemplateStream("Makefile.solution.template");
                    StreamReader reader = new StreamReader(stream);
                    StringWriter sw     = new StringWriter();

                    templateEngine.Process(reader, sw);
                    reader.Close();

                    solutionMakefile.Append(sw.ToString());

                    if (solutionFolder.IsRoot)
                    {
                        // Emit dist and distcheck targets only for TargetCombine
                        reader = new StreamReader(Path.Combine(ctx.TemplateDir, "make-dist.targets"));
                        solutionMakefile.Append(reader.ReadToEnd());
                        reader.Close();
                    }
                }

                monitor.Step(1);
            }
            finally
            {
                monitor.EndTask();
            }
            return(solutionMakefile);
        }
 public void TestGetRelativeGoSeveralUpCaseAtEnd()
 {
     Assert.AreEqual(@"../..", FileService.AbsoluteToRelativePath(@"/aa/bb/cc/dd", @"/aa/bb"));
 }