aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Prebuild/src/Core/Targets/MonoDevelopTarget.cs
blob: 85fe2db9227d9ba7d4674e8092c064f7f1452a64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#region BSD License
/*
Copyright (c) 2004 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions
  and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
  and the following disclaimer in the documentation and/or other materials provided with the
  distribution.
* The name of the author may not be used to endorse or promote products derived from this software
  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

using Prebuild.Core.Attributes;
using Prebuild.Core.Interfaces;
using Prebuild.Core.Nodes;
using Prebuild.Core.Utilities;

namespace Prebuild.Core.Targets
{
    /// <summary>
    ///
    /// </summary>
    [Target("monodev")]
    public class MonoDevelopTarget : ITarget
    {
        #region Fields

        private Kernel m_Kernel;

        #endregion

        #region Private Methods

        private static string PrependPath(string path)
        {
            string tmpPath = Helper.NormalizePath(path, '/');
            Regex regex = new Regex(@"(\w):/(\w+)");
            Match match = regex.Match(tmpPath);
            if(match.Success || tmpPath[0] == '.' || tmpPath[0] == '/')
            {
                tmpPath = Helper.NormalizePath(tmpPath);
            }
            else
            {
                tmpPath = Helper.NormalizePath("./" + tmpPath);
            }

            return tmpPath;
        }

        private static string BuildReference(SolutionNode solution, ReferenceNode refr)
        {
            string ret = "<ProjectReference type=\"";
            if(solution.ProjectsTable.ContainsKey(refr.Name))
            {
                ret += "Project\"";
                ret += " localcopy=\"" + refr.LocalCopy.ToString() +  "\" refto=\"" + refr.Name + "\" />";
            }
            else
            {
                ProjectNode project = (ProjectNode)refr.Parent;
                string fileRef = FindFileReference(refr.Name, project);

                if(refr.Path != null || fileRef != null)
                {
                    ret += "Assembly\" refto=\"";

                    string finalPath = (refr.Path != null) ? Helper.MakeFilePath(refr.Path, refr.Name, "dll") : fileRef;

                    ret += finalPath;
                    ret += "\" localcopy=\"" + refr.LocalCopy.ToString() + "\" />";
                    return ret;
                }

                ret += "Gac\"";
                ret += " localcopy=\"" + refr.LocalCopy.ToString() + "\"";
                ret += " refto=\"";
                try
                {
                    /*
                    Day changed to 28 Mar 2007
                    ...
                    08:09 < cj> is there anything that replaces Assembly.LoadFromPartialName() ?
                    08:09 < jonp> no
                    08:10 < jonp> in their infinite wisdom [sic], microsoft decided that the
                                  ability to load any assembly version by-name was an inherently
                                  bad idea
                    08:11 < cj> I'm thinking of a bunch of four-letter words right now...
                    08:11 < cj> security through making it difficult for the developer!!!
                    08:12 < jonp> just use the Obsolete API
                    08:12 < jonp> it should still work
                    08:12 < cj> alrighty.
                    08:12 < jonp> you just get warnings when using it
                    */
                    Assembly assem = Assembly.LoadWithPartialName(refr.Name);
                    ret += assem.FullName;
                    //ret += refr.Name;
                }
                catch (System.NullReferenceException e)
                {
                    e.ToString();
                    ret += refr.Name;
                }
                ret += "\" />";
            }

            return ret;
        }

        private static string FindFileReference(string refName, ProjectNode project)
        {
            foreach(ReferencePathNode refPath in project.ReferencePaths)
            {
                string fullPath = Helper.MakeFilePath(refPath.Path, refName, "dll");

                if(File.Exists(fullPath))
                {
                    return fullPath;
                }
            }

            return null;
        }

        /// <summary>
        /// Gets the XML doc file.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="conf">The conf.</param>
        /// <returns></returns>
        public static string GenerateXmlDocFile(ProjectNode project, ConfigurationNode conf)
        {
            if( conf == null )
            {
                throw new ArgumentNullException("conf");
            }
            if( project == null )
            {
                throw new ArgumentNullException("project");
            }
            string docFile = (string)conf.Options["XmlDocFile"];
            if(docFile != null && docFile.Length == 0)//default to assembly name if not specified
            {
                return "False";
            }
            return "True";
        }

        private void WriteProject(SolutionNode solution, ProjectNode project)
        {
            string csComp = "Mcs";
            string netRuntime = "Mono";
            if(project.Runtime == ClrRuntime.Microsoft)
            {
                csComp = "Csc";
                netRuntime = "MsNet";
            }

            string projFile = Helper.MakeFilePath(project.FullPath, project.Name, "mdp");
            StreamWriter ss = new StreamWriter(projFile);

            m_Kernel.CurrentWorkingDirectory.Push();
            Helper.SetCurrentDir(Path.GetDirectoryName(projFile));

            using(ss)
            {
                ss.WriteLine(
                    "<Project name=\"{0}\" description=\"\" standardNamespace=\"{1}\" newfilesearch=\"None\" enableviewstate=\"True\" fileversion=\"2.0\" language=\"C#\" clr-version=\"Net_2_0\" ctype=\"DotNetProject\">",
                    project.Name,
                    project.RootNamespace
                    );

                                int count = 0;

                ss.WriteLine("  <Configurations active=\"{0}\">", solution.ActiveConfig);

                foreach(ConfigurationNode conf in project.Configurations)
                {
                    ss.WriteLine("    <Configuration name=\"{0}\" ctype=\"DotNetProjectConfiguration\">", conf.Name);
                    ss.Write("      <Output");
                    ss.Write(" directory=\"{0}\"", Helper.EndPath(Helper.NormalizePath(".\\" + conf.Options["OutputPath"].ToString())));
                    ss.Write(" assembly=\"{0}\"", project.AssemblyName);
                    ss.Write(" executeScript=\"{0}\"", conf.Options["RunScript"]);
                    //ss.Write(" executeBeforeBuild=\"{0}\"", conf.Options["PreBuildEvent"]);
                    //ss.Write(" executeAfterBuild=\"{0}\"", conf.Options["PostBuildEvent"]);
                    if (conf.Options["PreBuildEvent"] != null && conf.Options["PreBuildEvent"].ToString().Length != 0)
                    {
                        ss.Write(" executeBeforeBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PreBuildEvent"].ToString()));
                    }
                    else
                    {
                        ss.Write(" executeBeforeBuild=\"{0}\"", conf.Options["PreBuildEvent"]);
                    }
                    if (conf.Options["PostBuildEvent"] != null && conf.Options["PostBuildEvent"].ToString().Length != 0)
                    {
                        ss.Write(" executeAfterBuild=\"{0}\"", Helper.NormalizePath(conf.Options["PostBuildEvent"].ToString()));
                    }
                    else
                    {
                        ss.Write(" executeAfterBuild=\"{0}\"", conf.Options["PostBuildEvent"]);
                    }
                    ss.Write(" executeBeforeBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
                    ss.Write(" executeAfterBuildArguments=\"{0}\"", conf.Options["PreBuildEventArgs"]);
                    ss.WriteLine(" />");

                    ss.Write("      <Build");
                    ss.Write(" debugmode=\"True\"");
                    if (project.Type == ProjectType.WinExe)
                    {
                        ss.Write(" target=\"{0}\"", ProjectType.Exe.ToString());
                    }
                    else
                    {
                        ss.Write(" target=\"{0}\"", project.Type);
                    }
                    ss.WriteLine(" />");

                    ss.Write("      <Execution");
                    ss.Write(" runwithwarnings=\"{0}\"", !conf.Options.WarningsAsErrors);
                    ss.Write(" consolepause=\"True\"");
                    ss.Write(" runtime=\"{0}\"", netRuntime);
                    ss.Write(" clr-version=\"Net_2_0\"");
                    ss.WriteLine(" />");

                    ss.Write("      <CodeGeneration");
                    ss.Write(" compiler=\"{0}\"", csComp);
                    ss.Write(" warninglevel=\"{0}\"", conf.Options["WarningLevel"]);
                    ss.Write(" nowarn=\"{0}\"", conf.Options["SuppressWarnings"]);
                    ss.Write(" includedebuginformation=\"{0}\"", conf.Options["DebugInformation"]);
                    ss.Write(" optimize=\"{0}\"", conf.Options["OptimizeCode"]);
                    ss.Write(" unsafecodeallowed=\"{0}\"", conf.Options["AllowUnsafe"]);
                    ss.Write(" generateoverflowchecks=\"{0}\"", conf.Options["CheckUnderflowOverflow"]);
                    ss.Write(" mainclass=\"{0}\"", project.StartupObject);
                    ss.Write(" target=\"{0}\"", project.Type);
                    ss.Write(" definesymbols=\"{0}\"", conf.Options["CompilerDefines"]);
                    ss.Write(" generatexmldocumentation=\"{0}\"", GenerateXmlDocFile(project, conf));
                    ss.Write(" win32Icon=\"{0}\"", project.AppIcon);
                    ss.Write(" ctype=\"CSharpCompilerParameters\"");
                    ss.WriteLine(" />");
                    ss.WriteLine("    </Configuration>");

                    count++;
                }
                ss.WriteLine("  </Configurations>");

                ss.Write("  <DeploymentInformation");
                ss.Write(" target=\"\"");
                ss.Write(" script=\"\"");
                ss.Write(" strategy=\"File\"");
                ss.WriteLine(">");
                ss.WriteLine("    <excludeFiles />");
                ss.WriteLine("  </DeploymentInformation>");

                ss.WriteLine("  <Contents>");
                foreach(string file in project.Files)
                {
                     string buildAction;
                    string dependson = "";
                    string resource_id = "";
                    string copyToOutput = "";

                    switch(project.Files.GetBuildAction(file))
                    {
                        case BuildAction.None:
                            buildAction = "Nothing";
                            break;

                        case BuildAction.Content:
                            buildAction = "Exclude";
                            break;

                        case BuildAction.EmbeddedResource:
                            buildAction = "EmbedAsResource";
                            break;

                        default:
                            buildAction = "Compile";
                            break;
                    }

                    if (project.Files.GetCopyToOutput(file) != CopyToOutput.Never)
                            buildAction = "FileCopy";

                    // Sort of a hack, we try and resolve the path and make it relative, if we can.
                    string extension = Path.GetExtension(file);
                    string designer_format = string.Format(".Designer{0}", extension);

                    if (file.EndsWith(designer_format))
                    {
                        string basename = file.Substring(0, file.LastIndexOf(designer_format));
                        string[] extensions = new string[] { ".cs", ".resx", ".settings" };

                        foreach(string ext in extensions)
                        {
                            if (project.Files.Contains(basename + ext))
                            {
                                dependson = string.Format(" dependson=\"{0}{1}\"", basename, ext);
                                break;
                            }
                        }
                    }
                    if (extension == ".resx")
                    {
                        buildAction = "EmbedAsResource";
                        string basename = file.Substring(0, file.LastIndexOf(".resx"));

                        // Visual Studio type resx + form dependency
                        if (project.Files.Contains(basename + ".cs"))
                        {
                            dependson = string.Format(" dependson=\"{0}{1}\"", basename, ".cs");
                        }

                        // We need to specify a resources file name to avoid MissingManifestResourceExceptions
                        // in libraries that are built.
                        resource_id = string.Format(" resource_id=\"{0}.{1}.resources\"",
                                project.AssemblyName, basename.Replace("/", "."));
                    }

                    switch(project.Files.GetCopyToOutput(file))
                    {
                        case CopyToOutput.Always:
                            copyToOutput = string.Format(" copyToOutputDirectory=\"Always\"");
                            break;
                        case CopyToOutput.PreserveNewest:
                            copyToOutput = string.Format(" copyToOutputDirectory=\"PreserveNewest\"");
                            break;
                    }

                     // Sort of a hack, we try and resolve the path and make it relative, if we can.
                     string filePath = PrependPath(file);
                    ss.WriteLine("    <File name=\"{0}\" subtype=\"Code\" buildaction=\"{1}\"{2}{3}{4} />",
                                 filePath, buildAction, dependson, resource_id, copyToOutput);
                }
                ss.WriteLine("  </Contents>");

                ss.WriteLine("  <References>");
                foreach(ReferenceNode refr in project.References)
                {
                    ss.WriteLine("    {0}", BuildReference(solution, refr));
                }
                ss.WriteLine("  </References>");


                ss.WriteLine("</Project>");
            }

            m_Kernel.CurrentWorkingDirectory.Pop();
        }

        private void WriteCombine(SolutionNode solution)
        {
            m_Kernel.Log.Write("Creating MonoDevelop combine and project files");
            foreach(ProjectNode project in solution.Projects)
            {
                if(m_Kernel.AllowProject(project.FilterGroups))
                {
                    m_Kernel.Log.Write("...Creating project: {0}", project.Name);
                    WriteProject(solution, project);
                }
            }

            m_Kernel.Log.Write("");
            string combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "mds");
            StreamWriter ss = new StreamWriter(combFile);

            m_Kernel.CurrentWorkingDirectory.Push();
            Helper.SetCurrentDir(Path.GetDirectoryName(combFile));

            int count = 0;

            using(ss)
            {
                ss.WriteLine("<Combine name=\"{0}\" fileversion=\"2.0\" description=\"\">", solution.Name);

                count = 0;
                foreach(ConfigurationNode conf in solution.Configurations)
                {
                    if(count == 0)
                    {
                        ss.WriteLine("  <Configurations active=\"{0}\">", conf.Name);
                    }

                    ss.WriteLine("    <Configuration name=\"{0}\" ctype=\"CombineConfiguration\">", conf.Name);
                    foreach(ProjectNode project in solution.Projects)
                    {
                        ss.WriteLine("      <Entry configuration=\"{1}\" build=\"True\" name=\"{0}\" />", project.Name, conf.Name);
                    }
                    ss.WriteLine("    </Configuration>");

                    count++;
                }
                ss.WriteLine("  </Configurations>");

                count = 0;

                foreach(ProjectNode project in solution.Projects)
                {
                    if(count == 0)
                        ss.WriteLine("  <StartMode startupentry=\"{0}\" single=\"True\">", project.Name);

                    ss.WriteLine("    <Execute type=\"None\" entry=\"{0}\" />", project.Name);
                    count++;
                }
                ss.WriteLine("  </StartMode>");

                ss.WriteLine("  <Entries>");
                foreach(ProjectNode project in solution.Projects)
                {
                    string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
                    ss.WriteLine("    <Entry filename=\"{0}\" />",
                        Helper.MakeFilePath(path, project.Name, "mdp"));
                }
                ss.WriteLine("  </Entries>");

                ss.WriteLine("</Combine>");
            }

            m_Kernel.CurrentWorkingDirectory.Pop();
        }

        private void CleanProject(ProjectNode project)
        {
            m_Kernel.Log.Write("...Cleaning project: {0}", project.Name);
            string projectFile = Helper.MakeFilePath(project.FullPath, project.Name, "mdp");
            Helper.DeleteIfExists(projectFile);
        }

        private void CleanSolution(SolutionNode solution)
        {
            m_Kernel.Log.Write("Cleaning MonoDevelop combine and project files for", solution.Name);

            string slnFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "mds");
            Helper.DeleteIfExists(slnFile);

            foreach(ProjectNode project in solution.Projects)
            {
                CleanProject(project);
            }

            m_Kernel.Log.Write("");
        }

        #endregion

        #region ITarget Members

        /// <summary>
        /// Writes the specified kern.
        /// </summary>
        /// <param name="kern">The kern.</param>
        public void Write(Kernel kern)
        {
            if( kern == null )
            {
                throw new ArgumentNullException("kern");
            }
            m_Kernel = kern;
            foreach(SolutionNode solution in kern.Solutions)
            {
                WriteCombine(solution);
            }
            m_Kernel = null;
        }

        /// <summary>
        /// Cleans the specified kern.
        /// </summary>
        /// <param name="kern">The kern.</param>
        public virtual void Clean(Kernel kern)
        {
            if( kern == null )
            {
                throw new ArgumentNullException("kern");
            }
            m_Kernel = kern;
            foreach(SolutionNode sol in kern.Solutions)
            {
                CleanSolution(sol);
            }
            m_Kernel = null;
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get
            {
                return "sharpdev";
            }
        }

        #endregion
    }
}