5
// Ankit Jain <jankit@novell.com>
7
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
9
// Permission is hereby granted, free of charge, to any person obtaining
10
// a copy of this software and associated documentation files (the
11
// "Software"), to deal in the Software without restriction, including
12
// without limitation the rights to use, copy, modify, merge, publish,
13
// distribute, sublicense, and/or sell copies of the Software, and to
14
// permit persons to whom the Software is furnished to do so, subject to
15
// the following conditions:
17
// The above copyright notice and this permission notice shall be
18
// included in all copies or substantial portions of the Software.
20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30
using System.Collections;
31
using System.Collections.Generic;
32
using System.Collections.Specialized;
33
using System.Globalization;
36
using System.Text.RegularExpressions;
39
using MonoDevelop.Projects;
40
using MonoDevelop.Projects.Serialization;
41
using MonoDevelop.Core;
42
using MonoDevelop.Core.ProgressMonitoring;
43
using MonoDevelop.Ide.Gui;
45
namespace MonoDevelop.Prj2Make
47
internal class SlnFileFormat
49
static string folderTypeGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
51
static SlnFileFormat ()
53
IdeApp.Initialized += delegate (object sender, EventArgs args) {
54
IdeApp.ProjectOperations.AddingEntryToCombine += new AddEntryEventHandler (HandleAddEntry);
58
public string GetValidFormatName (object obj, string fileName)
60
return Path.ChangeExtension (fileName, ".sln");
63
public bool CanReadFile (string file)
65
if (String.Compare (Path.GetExtension (file), ".sln", true) != 0)
68
string version = GetSlnFileVersion (file, out tmp);
69
return version == "9.00" || version == "10.00";
72
public bool CanWriteFile (object obj)
74
return obj is Combine;
77
public System.Collections.Specialized.StringCollection GetExportFiles (object obj)
79
Combine c = obj as Combine;
80
if (c != null && !c.IsRoot && c.ParentCombine.FileFormat is MSBuildFileFormat)
82
return new System.Collections.Specialized.StringCollection ();
87
public void WriteFile (string file, object obj, IProgressMonitor monitor)
89
Combine c = obj as Combine;
93
if (!c.IsRoot && c.ParentCombine.FileFormat is MSBuildFileFormat)
94
// Ignore a non-root combine if its parent is a msbuild solution
95
// Eg. if parent is a mds, then this should get emitted as the
99
string tmpfilename = String.Empty;
101
monitor.BeginTask (GettextCatalog.GetString ("Saving solution: {0}", file), 1);
103
if (File.Exists (file))
104
tmpfilename = Path.GetTempFileName ();
105
} catch (IOException) {
108
if (tmpfilename == String.Empty) {
109
WriteFileInternal (file, c, monitor);
111
WriteFileInternal (tmpfilename, c, monitor);
113
File.Move (tmpfilename, file);
115
} catch (Exception ex) {
116
monitor.ReportError (GettextCatalog.GetString ("Could not save solution: {0}", file), ex);
117
LoggingService.LogError (GettextCatalog.GetString ("Could not save solution: {0}", file), ex);
119
if (!String.IsNullOrEmpty (tmpfilename))
120
File.Delete (tmpfilename);
127
void WriteFileInternal (string file, Combine c, IProgressMonitor monitor)
129
using (StreamWriter sw = new StreamWriter (file, false, Encoding.UTF8)) {
132
SlnData slnData = GetSlnData (c);
133
if (slnData == null) {
134
// If a non-msbuild project is being converted by just
135
// changing the fileformat, then create the SlnData for it
136
slnData = new SlnData ();
137
c.ExtendedProperties [typeof (SlnFileFormat)] = slnData;
142
sw.WriteLine ("Microsoft Visual Studio Solution File, Format Version " + slnData.VersionString);
143
sw.WriteLine (slnData.HeaderComment);
146
monitor.BeginTask (GettextCatalog.GetString ("Saving projects"), 1);
147
WriteProjects (c, c.BaseDirectory, sw, monitor);
150
//Write the lines for unknownProjects
151
foreach (string l in slnData.UnknownProjects)
155
sw.WriteLine ("Global");
157
//Write SolutionConfigurationPlatforms
158
//FIXME: SolutionConfigurations?
159
sw.WriteLine ("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
161
foreach (CombineConfiguration config in c.Configurations)
162
sw.WriteLine ("\t\t{0} = {0}", config.Name);
164
sw.WriteLine ("\tEndGlobalSection");
166
//Write ProjectConfigurationPlatforms
167
sw.WriteLine ("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
169
List<string> list = new List<string> ();
170
WriteProjectConfigurations (c, list, 0, null);
172
list.Sort (StringComparer.Create (CultureInfo.InvariantCulture, true));
173
foreach (string s in list)
176
//Write lines for projects we couldn't load
177
if (slnData.SectionExtras.ContainsKey ("ProjectConfigurationPlatforms")) {
178
foreach (string s in slnData.SectionExtras ["ProjectConfigurationPlatforms"])
179
sw.WriteLine ("\t\t{0}", s);
182
sw.WriteLine ("\tEndGlobalSection");
184
//Write Nested Projects
185
sw.WriteLine ("\tGlobalSection(NestedProjects) = preSolution");
186
WriteNestedProjects (c, c, sw);
187
sw.WriteLine ("\tEndGlobalSection");
190
if (slnData.GlobalExtra != null) {
191
foreach (string s in slnData.GlobalExtra)
195
sw.WriteLine ("EndGlobal");
199
void WriteProjects (Combine combine, string baseDirectory, StreamWriter writer, IProgressMonitor monitor)
201
monitor.BeginStepTask (GettextCatalog.GetString ("Saving projects"), combine.Entries.Count, 1);
202
foreach (CombineEntry ce in combine.Entries) {
203
Combine c = ce as Combine;
205
List<string> l = null;
208
DotNetProject project = ce as DotNetProject;
209
if (project == null) {
210
monitor.ReportWarning (GettextCatalog.GetString (
211
"Error saving project ({0}) : Only DotNetProjects can be part of a MSBuild solution. Ignoring.", ce.Name));
216
if (!MSBuildFileFormat.LanguageTypeGuids.ContainsKey (project.LanguageName)) {
217
// FIXME: Should not happen, temp
218
monitor.ReportWarning (GettextCatalog.GetString ("Saving for project {0} not supported. Ignoring.",
224
IFileFormat ff = project.FileFormat;
225
if (! (ff is MSBuildFileFormat)) {
226
// Convert to a msbuild file format
227
project.FileFormat = new MSBuildFileFormat ();
228
project.FileName = project.FileFormat.GetValidFormatName (project, project.FileName);
231
project.Save (monitor);
233
MSBuildData msbData = Utils.GetMSBuildData (project);
235
//This should not happen as project.Save would've added this
236
throw new Exception (String.Format (
237
"INTERNAL ERROR: Project named '{0}', filename = {1}, does not have a 'data' object.",
238
project.Name, project.FileName));
242
writer.WriteLine (@"Project(""{0}"") = ""{1}"", ""{2}"", ""{3}""",
243
MSBuildFileFormat.LanguageTypeGuids [project.LanguageName],
245
FileService.NormalizeRelativePath (FileService.AbsoluteToRelativePath (
246
baseDirectory, project.FileName)).Replace ('/', '\\'),
250
SlnData slnData = GetSlnData (c);
251
if (slnData == null) {
253
slnData = new SlnData ();
254
c.ExtendedProperties [typeof (SlnFileFormat)] = slnData;
255
SlnData data = GetSlnData (combine);
257
slnData.VersionString = data.VersionString;
258
slnData.HeaderComment = data.HeaderComment;
264
writer.WriteLine (@"Project(""{0}"") = ""{1}"", ""{2}"", ""{3}""",
272
foreach (string s in l)
273
writer.WriteLine (s);
276
writer.WriteLine ("EndProject");
278
WriteProjects (c, baseDirectory, writer, monitor);
284
void WriteProjectConfigurations (Combine c, List<string> list, int ind, string config)
286
foreach (CombineConfiguration cc in c.Configurations) {
287
string rootConfigName = config ?? cc.Name;
288
if (cc.Name != rootConfigName)
291
foreach (CombineConfigurationEntry cce in cc.Entries) {
292
DotNetProject p = cce.Entry as DotNetProject;
294
Combine combine = cce.Entry as Combine;
298
//FIXME: Bug in md :/ Workaround, setting the config name explicitly
299
//Solution folder's cce.ConfigurationName doesn't get set
300
if (String.IsNullOrEmpty (cce.ConfigurationName)) {
301
if (combine.GetConfiguration (rootConfigName) != null)
302
cce.ConfigurationName = rootConfigName;
305
if (cce.ConfigurationName != rootConfigName) {
306
//Sln folder's config must match the root,
307
//so that its the same throughout the tree
308
//this ensures that _all_ the projects are
309
//relative to rootconfigname
310
//FIXME: Could be either:
311
// 1. Invalid setting
312
// 2. New imported project, which doesn't yet have
313
// a config named rootConfigName
314
LoggingService.LogDebug ("Known Problem: Invalid setting. Ignoring.");
318
WriteProjectConfigurations (combine, list, ind + 1, cc.Name);
325
MSBuildData data = Utils.GetMSBuildData (p);
326
list.Add (String.Format (
327
"\t\t{0}.{1}.ActiveCfg = {2}", data.Guid, cc.Name, cce.ConfigurationName));
330
list.Add (String.Format (
331
"\t\t{0}.{1}.Build.0 = {2}", data.Guid, cc.Name, cce.ConfigurationName));
336
void WriteNestedProjects (Combine combine, Combine root, StreamWriter writer)
338
foreach (CombineEntry ce in combine.Entries) {
339
Combine c = ce as Combine;
340
if (c == null || c.ParentCombine == null)
343
WriteNestedProjects (c, root, writer);
346
SlnData data = GetSlnData (combine);
348
throw new Exception (String.Format (
349
"INTERNAL ERROR: Solution named '{0}', filename = {1}, does not have a 'data' object.",
350
combine.Name, combine.FileName));
352
string containerGuid = data.Guid;
353
foreach (CombineEntry ce in combine.Entries) {
354
if (ce.ParentCombine == root)
357
string containeeGuid = null;
359
SlnData slnData = GetSlnData (ce);
360
containeeGuid = slnData.Guid;
362
MSBuildData msbData = Utils.GetMSBuildData (ce);
363
containeeGuid = msbData.Guid;
366
writer.WriteLine (@"{0}{1} = {2}", "\t\t", containeeGuid, containerGuid);
371
public object ReadFile (string fileName, IProgressMonitor monitor)
373
Combine combine = null;
374
if (fileName == null || monitor == null)
378
monitor.BeginTask (string.Format (GettextCatalog.GetString ("Loading solution: {0}"), fileName), 1);
379
combine = LoadSolution (fileName, monitor);
380
SetHandlers (combine, true);
381
} catch (Exception ex) {
382
monitor.ReportError (GettextCatalog.GetString ("Could not load solution: {0}", fileName), ex);
393
// Platform : Eg. Any CPU
394
// SolutionConfigurationPlatforms
396
Combine LoadSolution (string fileName, IProgressMonitor monitor)
398
string headerComment;
399
string version = GetSlnFileVersion (fileName, out headerComment);
400
if (version != "9.00" && version != "10.00")
401
throw new UnknownProjectVersionException (fileName, version);
403
ListDictionary globals = null;
404
Combine combine = null;
406
List<Section> projectSections = null;
407
List<string> lines = null;
409
monitor.BeginTask (GettextCatalog.GetString ("Loading solution: {0}", fileName), 1);
410
//Parse the .sln file
411
using (StreamReader reader = new StreamReader(fileName)) {
412
combine = new Combine ();
413
combine.Name = Path.GetFileNameWithoutExtension (fileName);
414
combine.FileName = fileName;
415
combine.Version = "0.1"; //FIXME:
416
combine.FileFormat = new MSBuildFileFormat ();
417
data = new SlnData ();
418
combine.ExtendedProperties [typeof (SlnFileFormat)] = data;
419
data.VersionString = version;
420
data.HeaderComment = headerComment;
423
projectSections = new List<Section> ();
424
lines = new List<string> ();
425
globals = new ListDictionary ();
427
while (reader.Peek () >= 0) {
428
s = GetNextLine (reader, lines).Trim ();
430
if (String.Compare (s, "Global", true) == 0) {
431
ParseGlobal (reader, lines, globals);
435
if (s.StartsWith ("Project")) {
436
Section sec = new Section ();
437
projectSections.Add (sec);
439
sec.Start = lines.Count - 1;
441
int e = ReadUntil ("EndProject", reader, lines);
442
sec.Count = (e < 0) ? 1 : (e - sec.Start + 1);
449
monitor.BeginTask("Loading projects ..", projectSections.Count + 1);
450
Dictionary<string, CombineEntry> entries = new Dictionary<string, CombineEntry> ();
451
foreach (Section sec in projectSections) {
453
Match match = ProjectRegex.Match (lines [sec.Start]);
454
if (!match.Success) {
455
LoggingService.LogDebug (GettextCatalog.GetString (
456
"Invalid Project definition on line number #{0} in file '{1}'. Ignoring.",
465
new Guid (match.Groups [1].Value);
466
} catch (FormatException) {
467
//Use default guid as projectGuid
468
LoggingService.LogDebug (GettextCatalog.GetString (
469
"Invalid Project type guid '{0}' on line #{1}. Ignoring.",
470
match.Groups [1].Value,
475
string projTypeGuid = match.Groups [1].Value.ToUpper ();
476
string projectName = match.Groups [2].Value;
477
string projectPath = match.Groups [3].Value;
478
string projectGuid = match.Groups [4].Value;
480
if (projTypeGuid == folderTypeGuid) {
482
SolutionFolder folder = new SolutionFolder ();
483
folder.Name = projectName;
484
folder.FileName = projectPath;
485
folder.Version = "0.1"; //FIXME:
486
folder.FileFormat = new MSBuildFileFormat ();
488
SlnData slnData = new SlnData (projectGuid);
489
folder.ExtendedProperties [typeof (SlnFileFormat)] = slnData;
490
slnData.VersionString = data.VersionString;
491
slnData.HeaderComment = data.HeaderComment;
493
slnData.Extra = lines.GetRange (sec.Start + 1, sec.Count - 2);
495
entries [projectGuid] = folder;
500
if (!MSBuildFileFormat.LanguageTypeGuids.ContainsValue (projTypeGuid)) {
501
LoggingService.LogWarning (GettextCatalog.GetString (
502
"Unknown project type guid '{0}' on line #{1}. Ignoring.",
505
monitor.ReportWarning (GettextCatalog.GetString (
506
"{0}({1}): Unsupported or unrecognized project : '{2}'. See logs.",
507
fileName, sec.Start + 1, projectPath));
511
if (projectPath.StartsWith("http://")) {
512
monitor.ReportWarning (GettextCatalog.GetString (
513
"{0}({1}): Projects with non-local source (http://...) not supported. '{2}'.",
514
fileName, sec.Start + 1, projectPath));
515
data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count));
519
DotNetProject project = null;
520
string path = SlnMaker.MapPath (Path.GetDirectoryName (fileName), projectPath);
521
if (String.IsNullOrEmpty (path)) {
522
monitor.ReportWarning (GettextCatalog.GetString (
523
"Invalid project path found in {0} : {1}", fileName, projectPath));
524
LoggingService.LogWarning (GettextCatalog.GetString (
525
"Invalid project path found in {0} : {1}", fileName, projectPath));
530
projectPath = Path.GetFullPath (path);
532
project = Services.ProjectService.ReadCombineEntry (projectPath, monitor) as DotNetProject;
533
if (project == null) {
534
LoggingService.LogError ("Internal Error: Didn't get the expected DotNetProject for {0} project.",
539
MSBuildData msdata = Utils.GetMSBuildData (project);
540
entries [projectGuid] = project;
541
data.ProjectsByGuid [msdata.Guid] = project;
543
msdata.Extra = lines.GetRange (sec.Start + 1, sec.Count - 2);
544
} catch (Exception e) {
545
LoggingService.LogError (GettextCatalog.GetString (
546
"Error while trying to load the project {0}. Exception : {1}",
547
projectPath, e.ToString ()));
548
monitor.ReportWarning (GettextCatalog.GetString (
549
"Error while trying to load the project {0}. Exception : {1}", projectPath, e.Message));
552
data.UnknownProjects.AddRange (lines.GetRange (sec.Start, sec.Count));
557
if (globals != null && globals.Contains ("NestedProjects")) {
558
LoadNestedProjects (globals ["NestedProjects"] as Section, lines, entries, monitor);
559
globals.Remove ("NestedProjects");
562
//Add top level folders and projects to the main combine
563
foreach (CombineEntry ce in entries.Values) {
564
if (ce.ParentCombine == null)
565
combine.Entries.Add (ce);
568
//Resolve project references
569
List<ProjectReference> toRemove = new List<ProjectReference> ();
570
List<ProjectReference> toAdd = new List<ProjectReference> ();
571
foreach (Project p in combine.GetAllProjects ()) {
574
MSBuildData msbuildData = Utils.GetMSBuildData (p);
575
if (msbuildData == null)
578
foreach (ProjectReference pref in p.ProjectReferences) {
579
if (pref.ReferenceType != ReferenceType.Project)
582
Project rp = combine.FindProject (pref.Reference);
587
XmlElement elem = msbuildData.ProjectReferenceElements [pref];
592
if (elem ["Project"] == null)
595
string guid = elem ["Project"].InnerText.Trim ();
596
if (!data.ProjectsByGuid.ContainsKey (guid))
600
rp = data.ProjectsByGuid [guid];
601
ProjectReference newRef = new ProjectReference (ReferenceType.Project, rp.Name);
604
XmlElement clonedElement = (XmlElement) elem.Clone ();
605
elem.ParentNode.InsertAfter (clonedElement, elem);
606
msbuildData.ProjectReferenceElements [newRef] = clonedElement;
609
foreach (ProjectReference pref in toRemove) {
610
p.ProjectReferences.Remove (pref);
611
msbuildData.ProjectReferenceElements.Remove (pref);
614
foreach (ProjectReference pref in toAdd)
615
p.ProjectReferences.Add (pref);
618
//FIXME: This can be just SolutionConfiguration also!
619
if (globals != null) {
620
if (globals.Contains ("SolutionConfigurationPlatforms")) {
621
LoadSolutionConfigurations (globals ["SolutionConfigurationPlatforms"] as Section, lines,
623
globals.Remove ("SolutionConfigurationPlatforms");
626
if (globals.Contains ("ProjectConfigurationPlatforms")) {
627
LoadProjectConfigurationMappings (globals ["ProjectConfigurationPlatforms"] as Section, lines,
629
globals.Remove ("ProjectConfigurationPlatforms");
633
//Save the global sections that we dont use
634
List<string> globalLines = new List<string> ();
635
foreach (Section sec in globals.Values)
636
globalLines.InsertRange (globalLines.Count, lines.GetRange (sec.Start, sec.Count));
638
data.GlobalExtra = globalLines;
643
void ParseGlobal (StreamReader reader, List<string> lines, ListDictionary dict)
645
//Process GlobalSection-s
646
while (reader.Peek () >= 0) {
647
string s = GetNextLine (reader, lines).Trim ();
652
Match m = GlobalSectionRegex.Match (s);
654
if (String.Compare (s, "EndGlobal", true) == 0)
660
Section sec = new Section (m.Groups [1].Value, m.Groups [2].Value, lines.Count - 1, 1);
661
dict [sec.Key] = sec;
663
sec.Count = ReadUntil ("EndGlobalSection", reader, lines) - sec.Start + 1;
664
//FIXME: sec.Count == -1 : No EndGlobalSection found, ignore entry?
668
void LoadProjectConfigurationMappings (Section sec, List<string> lines, Combine sln, IProgressMonitor monitor)
670
if (sec == null || String.Compare (sec.Val, "postSolution", true) != 0)
673
List<CombineConfigurationEntry> noBuildList = new List<CombineConfigurationEntry> ();
674
Dictionary<string, CombineConfigurationEntry> cache = new Dictionary<string, CombineConfigurationEntry> ();
675
Dictionary<string, string> ignoredProjects = new Dictionary<string, string> ();
676
SlnData slnData = GetSlnData (sln);
678
List<string> extras = new List<string> ();
680
for (int i = 0; i < sec.Count - 2; i ++) {
681
int lineNum = i + sec.Start + 1;
682
string s = lines [lineNum].Trim ();
686
// {projectGuid}.SolutionConfigName|SolutionPlatform.ActiveCfg = ProjConfigName|ProjPlatform
687
// {projectGuid}.SolutionConfigName|SolutionPlatform.Build.0 = ProjConfigName|ProjPlatform
689
string [] parts = s.Split (new char [] {'='}, 2);
690
if (parts.Length < 2) {
691
LoggingService.LogDebug ("{0} ({1}) : Invalid format. Ignoring", sln.FileName, lineNum + 1);
696
string projConfig = parts [1].Trim ();
698
string left = parts [0].Trim ();
699
if (left.EndsWith (".ActiveCfg")) {
700
action = "ActiveCfg";
701
left = left.Substring (0, left.Length - 10);
702
} else if (left.EndsWith (".Build.0")) {
704
left = left.Substring (0, left.Length - 8);
706
LoggingService.LogWarning (GettextCatalog.GetString ("{0} ({1}) : Unknown action. Only ActiveCfg & Build.0 supported.",
707
sln.FileName, lineNum + 1));
711
string [] t = left.Split (new char [] {'.'}, 2);
713
LoggingService.LogDebug ("{0} ({1}) : Invalid format of the left side. Ignoring",
714
sln.FileName, lineNum + 1);
718
string projGuid = t [0];
719
string slnConfig = t [1];
721
if (!slnData.ProjectsByGuid.ContainsKey (projGuid)) {
722
if (ignoredProjects.ContainsKey (projGuid))
726
LoggingService.LogWarning (GettextCatalog.GetString ("{0} ({1}) : Project with guid = '{2}' not found or not loaded. Ignoring",
727
sln.FileName, lineNum + 1, projGuid));
728
ignoredProjects [projGuid] = projGuid;
732
DotNetProject project = slnData.ProjectsByGuid [projGuid];
734
string key = projGuid + "." + slnConfig;
735
CombineConfigurationEntry combineConfigEntry = null;
736
if (cache.ContainsKey (key)) {
737
combineConfigEntry = cache [key];
739
combineConfigEntry = GetConfigEntryForProject (sln, slnConfig, project);
740
cache [key] = combineConfigEntry;
743
/* If both ActiveCfg & Build.0 entries are missing
744
* for a project, then default values :
745
* ActiveCfg : same as the solution config
749
* if Build (true/false) for the project will
750
* will depend on presence/absence of Build.0 entry
752
if (String.Compare (action, "ActiveCfg", false) == 0) {
753
combineConfigEntry.ConfigurationName = projConfig;
754
noBuildList.Add (combineConfigEntry);
755
} else if (String.Compare (action, "Build.0", false) == 0) {
756
noBuildList.Remove (combineConfigEntry);
759
extras.RemoveAt (extras.Count - 1);
762
slnData.SectionExtras ["ProjectConfigurationPlatforms"] = extras;
764
foreach (CombineConfigurationEntry e in noBuildList) {
765
//Mark (build=false) of all projects for which
766
//ActiveCfg was found but no Build.0
771
/* Finds a CombineConfigurationEntry corresponding to the @configName for a project (@projectName)
773
CombineConfigurationEntry GetConfigEntryForProject (Combine combine, string configName, Project project)
775
if (project.ParentCombine == null)
776
throw new Exception (String.Format (
777
"INTERNAL ERROR: project {0} is not part of any combine", project.Name));
779
CombineConfigurationEntry ret = GetConfigEntry (project, configName);
781
//Ensure the corresponding entries exist all the way
782
//upto the RootCombine
783
Combine parent = project.ParentCombine;
784
while (!parent.IsRoot && parent.ParentCombine != null) {
785
CombineConfigurationEntry p = GetConfigEntry (parent, configName);
786
if (p.ConfigurationName != configName)
787
p.ConfigurationName = configName;
788
parent = parent.ParentCombine;
794
/* Gets the CombineConfigurationEntry corresponding to the @entry in its parentCombine's
795
* CombineConfiguration. Creates the required bits if not present */
796
CombineConfigurationEntry GetConfigEntry (CombineEntry entry, string configName)
798
Combine parent = entry.ParentCombine;
799
CombineConfiguration combineConfig = parent.GetConfiguration (configName) as CombineConfiguration;
800
if (combineConfig == null) {
801
combineConfig = (CombineConfiguration) parent.CreateConfiguration (configName);
802
parent.Configurations.Add (combineConfig);
805
foreach (CombineConfigurationEntry cce in combineConfig.Entries) {
806
if (cce.Entry == entry)
810
return combineConfig.AddEntry (entry);
813
void LoadSolutionConfigurations (Section sec, List<string> lines, Combine combine, IProgressMonitor monitor)
815
if (sec == null || String.Compare (sec.Val, "preSolution", true) != 0)
818
for (int i = 0; i < sec.Count - 2; i ++) {
819
//FIXME: expects both key and val to be on the same line
820
int lineNum = i + sec.Start + 1;
821
string s = lines [lineNum].Trim ();
826
KeyValuePair<string, string> pair = SplitKeyValue (s);
828
if (pair.Key.IndexOf ('|') < 0) {
829
//Config must of the form ConfigName|Platform
830
LoggingService.LogError (GettextCatalog.GetString ("{0} ({1}) : Invalid config name '{2}'", combine.FileName, lineNum + 1, pair.Key));
834
CombineConfiguration config = (CombineConfiguration)
835
combine.GetConfiguration (pair.Key);
837
if (config == null) {
838
config = (CombineConfiguration)
839
combine.CreateConfiguration (pair.Key);
840
combine.Configurations.Add (config);
845
void LoadNestedProjects (Section sec, List<string> lines,
846
Dictionary<string, CombineEntry> entries, IProgressMonitor monitor)
848
if (sec == null || String.Compare (sec.Val, "preSolution", true) != 0)
851
for (int i = 0; i < sec.Count - 2; i ++) {
852
KeyValuePair<string, string> pair = SplitKeyValue (lines [i + sec.Start + 1].Trim ());
854
if (!entries.ContainsKey (pair.Value)) {
855
//Container not found
856
LoggingService.LogWarning (GettextCatalog.GetString ("Project with guid '{0}' not found.", pair.Value));
860
if (!entries.ContainsKey (pair.Key)) {
861
//Containee not found
862
LoggingService.LogWarning (GettextCatalog.GetString ("Project with guid '{0}' not found.", pair.Key));
866
Combine folder = entries [pair.Value] as Combine;
870
folder.Entries.Add (entries [pair.Key]);
874
string GetNextLine (StreamReader reader, List<string> list)
876
if (reader.Peek () < 0)
879
string ret = reader.ReadLine ();
884
int ReadUntil (string end, StreamReader reader, List<string> lines)
887
while (reader.Peek () >= 0) {
888
string s = GetNextLine (reader, lines);
890
if (String.Compare (s.Trim (), end, true) == 0)
891
return (lines.Count - 1);
898
KeyValuePair<string, string> SplitKeyValue (string s)
900
string [] pair = s.Split (new char [] {'='}, 2);
901
string key = pair [0].Trim ();
902
string val = String.Empty;
903
if (pair.Length == 2)
904
val = pair [1].Trim ();
906
return new KeyValuePair<string, string> (key, val);
909
// Utility function to determine the sln file version
910
string GetSlnFileVersion(string strInSlnFile, out string headerComment)
912
string strVersion = null;
913
string strInput = null;
914
headerComment = null;
916
StreamReader reader = new StreamReader(strInSlnFile);
918
strInput = reader.ReadLine();
919
if (strInput == null)
922
match = SlnVersionRegex.Match(strInput);
923
if (!match.Success) {
924
strInput = reader.ReadLine();
925
if (strInput == null)
927
match = SlnVersionRegex.Match (strInput);
932
strVersion = match.Groups[1].Value;
933
headerComment = reader.ReadLine ();
942
static SlnData GetSlnData (CombineEntry entry)
944
if (entry.ExtendedProperties.Contains (typeof (SlnFileFormat)))
945
return entry.ExtendedProperties [typeof (SlnFileFormat)] as SlnData;
950
public static void HandleAddEntry (object s, AddEntryEventArgs args)
952
if (GetSlnData (args.Combine) == null)
955
IFileFormat msformat = new MSBuildFileFormat ();
957
if (!msformat.CanReadFile (args.FileName)) {
958
if (!IdeApp.Services.MessageService.AskQuestion (GettextCatalog.GetString (
959
"The project file {0} must be converted to msbuild format to be added " +
960
"to a msbuild solution. Convert?", args.FileName), "Conversion required")) {
965
// vs2005 solution/project
969
IProgressMonitor monitor = new NullProgressMonitor ();
970
IFileFormat slnff = new VS2003SlnFileFormat ();
971
IFileFormat prjff = new VS2003ProjectFileFormat ();
973
if (slnff.CanReadFile (args.FileName)) {
975
Combine c = VS2003SlnFileFormat.ImportSlnAsMSBuild (args.FileName);
978
args.FileName = c.FileName;
979
} else if (prjff.CanReadFile (args.FileName)) {
982
DotNetProject proj = VS2003ProjectFileFormat.ImportCsprojAsMSBuild (args.FileName);
983
args.FileName = proj.FileName;
985
CombineEntry ce = Services.ProjectService.ReadCombineEntry (args.FileName, monitor);
986
ConvertToMSBuild (ce);
987
args.FileName = ce.FileName;
992
internal static void SetHandlers (Combine combine, bool setEntries)
995
foreach (CombineEntry ce in combine.Entries) {
996
Combine c = ce as Combine;
1000
SetHandlers (c, setEntries);
1004
combine.EntryAdded += HandleCombineEntryAdded;
1007
static void HandleCombineEntryAdded (object sender, CombineEntryEventArgs e)
1010
// ReadFile for Sln/MSBuildFileFormat set the handlers
1011
ConvertToMSBuild (e.CombineEntry);
1013
Combine rootSln = e.CombineEntry.RootCombine;
1014
SlnData rootSlnData = GetSlnData (rootSln);
1015
SlnData slnData = GetSlnData (e.CombineEntry);
1016
if (slnData != null) {
1017
foreach (KeyValuePair<string, DotNetProject> pair in slnData.ProjectsByGuid)
1018
rootSlnData.ProjectsByGuid [pair.Key] = pair.Value;
1020
//Add guid for the new project
1021
MSBuildData msdata = Utils.GetMSBuildData (e.CombineEntry);
1022
DotNetProject project = e.CombineEntry as DotNetProject;
1023
if (project != null && msdata != null)
1025
rootSlnData.ProjectsByGuid [msdata.Guid] = project;
1028
//FIXME: Can't call this now as we don't extend Combine :/
1029
//rootSln.NotifyModified ();
1030
//Need some other solution, for now, hack -
1031
rootSln.FileName = rootSln.FileName;
1032
} catch (Exception ex) {
1033
LoggingService.LogDebug ("HandleCombineEntryAdded : {0}", ex);
1037
internal static void ConvertToMSBuild (CombineEntry ce)
1039
MSBuildFileFormat msformat = new MSBuildFileFormat ();
1040
if (!msformat.CanReadFile (ce.FileName)) {
1042
ce.FileFormat = msformat;
1043
ce.FileName = msformat.GetValidFormatName (ce, ce.FileName);
1045
// Save will create the required SlnData, MSBuildData
1046
// objects, create the new guids for the projects _and_ the
1048
ce.Save (new NullProgressMonitor ());
1049
// Writing out again might be required to fix
1050
// project references which have changed (filenames
1051
// changed due to the conversion)
1056
static Regex projectRegex = null;
1057
internal static Regex ProjectRegex {
1059
if (projectRegex == null)
1060
projectRegex = new Regex(@"Project\(""(\{[^}]*\})""\) = ""(.*)"", ""(.*)"", ""(\{[^{]*\})""");
1061
return projectRegex;
1065
static Regex globalSectionRegex = null;
1066
static Regex GlobalSectionRegex {
1068
if (globalSectionRegex == null)
1069
globalSectionRegex = new Regex (@"GlobalSection\s*\(([^)]*)\)\s*=\s*(\w*)");
1070
return globalSectionRegex;
1074
static Regex slnVersionRegex = null;
1075
internal static Regex SlnVersionRegex {
1077
if (slnVersionRegex == null)
1078
slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
1079
return slnVersionRegex;
1089
public int Start = -1; //Line number
1090
public int Count = 0;
1096
public Section (string Key, string Val, int Start, int Count)
1105
class SolutionFolder : Combine {
1106
public override bool NeedsReload {
1107
get { return false; }