2 // Consumes the order.xml file that contains a list of all the assemblies to build
3 // and produces a solution and the csproj files for it
5 // Currently this hardcodes a set of assemblies to build, the net-4.x series, but
6 // it can be extended to handle the command line tools.
9 // * This fails to find matches for "System" and "System.xml" when processing the
10 // RabbitMQ executable, likely, because we do not process executables yet
12 // * Has not been tested in a while with the command line tools
16 using System.Collections.Generic;
18 using System.Globalization;
19 using System.Xml.Linq;
20 using System.Xml.XPath;
25 Library, Exe, Module, WinExe
28 public enum LanguageVersion {
38 public static readonly string NewLine = "\r\n"; //Environment.NewLine; // "\n";
39 public SlnGenerator (string formatVersion = "2012")
41 switch (formatVersion) {
43 this.header = MakeHeader ("10.00", "2008");
46 this.header = MakeHeader ("12.00", "2012");
51 const string project_start = "Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = \"{0}\", \"{1}\", \"{2}\""; // Note: No need to double up on {} around {2}
52 const string project_end = "EndProject";
54 public List<MsbuildGenerator.VsCsproj> libraries = new List<MsbuildGenerator.VsCsproj> ();
57 string MakeHeader (string formatVersion, string yearTag)
59 return string.Format ("Microsoft Visual Studio Solution File, Format Version {0}" + NewLine + "# Visual Studio {1}", formatVersion, yearTag);
62 public void Add (MsbuildGenerator.VsCsproj vsproj)
65 libraries.Add (vsproj);
66 } catch (Exception ex) {
67 Console.WriteLine (ex);
71 public void Write (string filename)
73 var fullPath = Path.GetDirectoryName (filename) + "/";
75 using (var sln = new StreamWriter (filename)) {
77 sln.WriteLine (header);
78 foreach (var proj in libraries) {
79 var unixProjFile = proj.csProjFilename.Replace ("\\", "/");
80 var fullProjPath = Path.GetFullPath (unixProjFile);
81 sln.WriteLine (project_start, proj.library, MsbuildGenerator.GetRelativePath (fullPath, fullProjPath), proj.projectGuid);
82 sln.WriteLine (project_end);
84 sln.WriteLine ("Global");
86 sln.WriteLine ("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
87 sln.WriteLine ("\t\tDebug|Any CPU = Debug|Any CPU");
88 sln.WriteLine ("\t\tRelease|Any CPU = Release|Any CPU");
89 sln.WriteLine ("\tEndGlobalSection");
91 sln.WriteLine ("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
92 foreach (var proj in libraries) {
93 var guid = proj.projectGuid;
94 sln.WriteLine ("\t\t{0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", guid);
95 sln.WriteLine ("\t\t{0}.Debug|Any CPU.Build.0 = Debug|Any CPU", guid);
96 sln.WriteLine ("\t\t{0}.Release|Any CPU.ActiveCfg = Release|Any CPU", guid);
97 sln.WriteLine ("\t\t{0}.Release|Any CPU.Build.0 = Release|Any CPU", guid);
99 sln.WriteLine ("\tEndGlobalSection");
101 sln.WriteLine ("\tGlobalSection(SolutionProperties) = preSolution");
102 sln.WriteLine ("\t\tHideSolutionNode = FALSE");
103 sln.WriteLine ("\tEndGlobalSection");
105 sln.WriteLine ("EndGlobal");
109 internal bool ContainsProjectIdentifier (string projId)
111 return libraries.FindIndex (x => (x.library == projId)) >= 0;
114 public int Count { get { return libraries.Count; } }
117 class MsbuildGenerator {
118 static readonly string NewLine = SlnGenerator.NewLine;
119 static XmlNamespaceManager xmlns;
121 public const string profile_2_0 = "_2_0";
122 public const string profile_3_5 = "_3_5";
123 public const string profile_4_0 = "_4_0";
124 public const string profile_4_x = "_4_x";
128 Console.WriteLine ("Invalid argument");
131 static string template;
132 static MsbuildGenerator ()
134 using (var input = new StreamReader ("csproj.tmpl")) {
135 template = input.ReadToEnd ();
138 xmlns = new XmlNamespaceManager (new NameTable ());
139 xmlns.AddNamespace ("x", "http://schemas.microsoft.com/developer/msbuild/2003");
142 // The directory as specified in order.xml
149 public string CsprojFilename;
152 // Our base directory, this is relative to our exectution point mono/msvc/scripts
156 public string LibraryOutput, AbsoluteLibraryOutput;
158 public MsbuildGenerator (XElement xproject)
160 this.xproject = xproject;
161 dir = xproject.Attribute ("dir").Value;
162 library = xproject.Attribute ("library").Value;
163 CsprojFilename = "..\\..\\mcs\\" + dir + "\\" + library + ".csproj";
164 LibraryOutput = xproject.Element ("library_output").Value;
166 projectGuid = LookupOrGenerateGuid ();
167 fx_version = xproject.Element ("fx_version").Value;
168 Csproj = new VsCsproj () {
169 csProjFilename = this.CsprojFilename,
170 projectGuid = this.projectGuid,
171 library_output = this.LibraryOutput,
172 fx_version = double.Parse (fx_version),
173 library = this.library,
174 MsbuildGenerator = this
179 class_dir = "../class/";
180 base_dir = "../../mcs/mcs";
184 foreach (char c in dir) {
186 mcs_topdir = "..//" + mcs_topdir;
188 class_dir = mcs_topdir.Substring (3);
190 base_dir = Path.Combine ("..", "..", "mcs", dir);
192 AbsoluteLibraryOutput = Path.GetFullPath (Path.Combine (base_dir, LibraryOutput));
195 string LookupOrGenerateGuid ()
197 var projectFile = NativeName (CsprojFilename);
198 if (File.Exists (projectFile)){
199 var doc = XDocument.Load (projectFile);
200 return doc.XPathSelectElement ("x:Project/x:PropertyGroup/x:ProjectGuid", xmlns).Value;
202 return "{" + Guid.NewGuid ().ToString ().ToUpper () + "}";
207 StringBuilder defines = new StringBuilder ();
208 bool Optimize = true;
209 bool want_debugging_support = false;
211 Dictionary<string, string> embedded_resources = new Dictionary<string, string> ();
212 List<string> warning_as_error = new List<string> ();
213 List<int> ignore_warning = new List<int> ();
214 bool load_default_config = true;
216 List<string> references = new List<string> ();
217 List<string> libs = new List<string> ();
218 List<string> reference_aliases = new List<string> ();
219 bool showWarnings = true;
222 #pragma warning disable 0219, 0414
223 int WarningLevel = 4;
225 bool Checked = false;
226 bool WarningsAreErrors;
227 bool VerifyClsCompliance = true;
228 string win32IconFile;
229 string StrongNameKeyFile;
230 bool copyLocal = true;
231 Target Target = Target.Library;
232 string TargetExt = ".exe";
234 string StrongNameKeyContainer;
235 bool StrongNameDelaySign = false;
236 LanguageVersion Version = LanguageVersion.Default;
239 // Class directory, relative to
241 #pragma warning restore 0219,414
243 readonly char [] argument_value_separator = new char [] { ';', ',' };
246 // This parses the -arg and /arg options to the compiler, even if the strings
247 // in the following text use "/arg" on the strings.
249 bool CSCParseOption (string option, ref string [] args)
251 int idx = option.IndexOf (':');
258 arg = option.Substring (0, idx);
260 value = option.Substring (idx + 1);
263 switch (arg.ToLower (CultureInfo.InvariantCulture)) {
275 Target = Target.WinExe;
279 Target = Target.Library;
284 Target = Target.Module;
285 TargetExt = ".netmodule";
294 if (value.Length == 0) {
296 Environment.Exit (1);
314 case "/incremental+":
315 case "/incremental-":
321 if (value.Length == 0) {
323 Environment.Exit (1);
326 foreach (string d in value.Split (argument_value_separator)) {
327 if (defines.Length != 0)
328 defines.Append (";");
337 // We should collect data, runtime, etc and store in the file specified
341 case "/linkresource":
344 bool embeded = arg [1] == 'r' || arg [1] == 'R';
345 string [] s = value.Split (argument_value_separator);
348 if (s [0].Length == 0)
350 embedded_resources [s [0]] = Path.GetFileName (s [0]);
353 embedded_resources [s [0]] = s [1];
356 Console.WriteLine ("Does not support this method yet: {0}", arg);
357 Environment.Exit (1);
360 Console.WriteLine ("Wrong number of arguments for option `{0}'", option);
361 Environment.Exit (1);
368 Console.WriteLine ("/recurse not supported");
369 Environment.Exit (1);
374 if (value.Length == 0) {
375 Console.WriteLine ("-reference requires an argument");
376 Environment.Exit (1);
379 string [] refs = value.Split (argument_value_separator);
380 foreach (string r in refs) {
382 int index = val.IndexOf ('=');
384 reference_aliases.Add (r);
389 references.Add (val);
402 Console.WriteLine ("{0} = not supported", arg);
410 win32IconFile = value;
414 want_debugging_support = false;
419 want_debugging_support = true;
436 VerifyClsCompliance = false;
449 case "/warnaserror+":
450 if (value.Length == 0) {
451 WarningsAreErrors = true;
453 foreach (string wid in value.Split (argument_value_separator))
454 warning_as_error.Add (wid);
459 // Console.WriteLine ("Warning ignoring /runtime:v4");
462 case "/warnaserror-":
463 if (value.Length == 0) {
464 WarningsAreErrors = false;
466 foreach (string wid in value.Split (argument_value_separator))
467 warning_as_error.Remove (wid);
472 WarningLevel = Int32.Parse (value);
478 if (value.Length == 0) {
479 Console.WriteLine ("/nowarn requires an argument");
480 Environment.Exit (1);
483 warns = value.Split (argument_value_separator);
484 foreach (string wc in warns) {
486 if (wc.Trim ().Length == 0)
489 int warn = Int32.Parse (wc);
491 throw new ArgumentOutOfRangeException ("warn");
493 ignore_warning.Add (warn);
495 Console.WriteLine (String.Format ("`{0}' is not a valid warning number", wc));
496 Environment.Exit (1);
503 load_default_config = false;
519 if (value == String.Empty) {
520 Console.WriteLine ("{0} requires an argument", arg);
521 Environment.Exit (1);
523 StrongNameKeyFile = value;
525 case "/keycontainer":
526 if (value == String.Empty) {
527 Console.WriteLine ("{0} requires an argument", arg);
528 Environment.Exit (1);
530 StrongNameKeyContainer = value;
534 StrongNameDelaySign = true;
537 StrongNameDelaySign = false;
541 switch (value.ToLower (CultureInfo.InvariantCulture)) {
543 Version = LanguageVersion.ISO_1;
547 Version = LanguageVersion.Default;
550 Version = LanguageVersion.ISO_2;
553 Version = LanguageVersion.Future;
556 Console.WriteLine ("Invalid option `{0}' for /langversion. It must be either `ISO-1', `ISO-2' or `Default'", value);
557 Environment.Exit (1);
567 case "/-getresourcestrings":
571 Console.WriteLine ("Failing with : {0}", arg);
575 static string [] LoadArgs (string file)
578 var args = new List<string> ();
581 f = new StreamReader (file);
586 StringBuilder sb = new StringBuilder ();
588 while ((line = f.ReadLine ()) != null) {
591 for (int i = 0; i < t; i++) {
594 if (c == '"' || c == '\'') {
597 for (i++; i < t; i++) {
604 } else if (c == ' ') {
606 args.Add (sb.ToString ());
613 args.Add (sb.ToString ());
618 string [] ret_value = new string [args.Count];
619 args.CopyTo (ret_value, 0);
624 static string Load (string f)
626 var native = NativeName (f);
628 if (File.Exists (native)) {
629 using (var sr = new StreamReader (native)) {
630 return sr.ReadToEnd ();
636 public static string NativeName (string path)
638 if (System.IO.Path.DirectorySeparatorChar == '/')
639 return path.Replace ("\\", "/");
641 return path.Replace ("/", "\\");
644 public class VsCsproj {
645 public string projectGuid;
646 public string output;
647 public string library_output;
648 public string csProjFilename;
649 public double fx_version;
650 public List<VsCsproj> projReferences = new List<VsCsproj> ();
651 public string library;
652 public MsbuildGenerator MsbuildGenerator;
655 public VsCsproj Csproj;
657 public VsCsproj Generate (string library_output, Dictionary<string,MsbuildGenerator> projects, bool showWarnings = false)
659 var generatedProjFile = NativeName (Csproj.csProjFilename);
660 //Console.WriteLine ("Generating: {0}", generatedProjFile);
662 string boot, flags, output_name, built_sources, response, profile;
664 boot = xproject.Element ("boot").Value;
665 flags = xproject.Element ("flags").Value;
666 output_name = xproject.Element ("output").Value;
667 if (output_name.EndsWith (".exe"))
669 built_sources = xproject.Element ("built_sources").Value;
670 response = xproject.Element ("response").Value;
672 profile = xproject.Element ("profile").Value;
673 if (string.IsNullOrEmpty (response)) {
674 // Address the issue where entries are missing the fx_version
675 // Should be fixed in the Makefile or elsewhere; this is a workaround
676 //<fx_version>basic</fx_version>
677 //<profile>./../build/deps/mcs.exe.sources.response</profile>
678 //<response></response>
680 profile = fx_version;
681 if (response.Contains ("build") || response.Contains ("basic") || response.Contains (profile_2_0)) {
683 if (response.Contains (profile_2_0)) profile = "net_2_0";
684 } if (response.Contains ("build") || response.Contains ("basic") || response.Contains (profile_2_0)) {
686 } else if (response.Contains (profile_3_5)) {
689 } else if (response.Contains (profile_4_0)) {
692 } else if (response.Contains (profile_4_x)) {
698 // Prebuild code, might be in inputs, check:
699 // inputs/LIBRARY.pre
701 string prebuild = GenerateStep (library, ".pre", "PreBuildEvent");
702 string postbuild = GenerateStep (library, ".post", "PostBuildEvent");
704 var all_args = new Queue<string []> ();
705 all_args.Enqueue (flags.Split ());
706 while (all_args.Count > 0) {
707 string [] f = all_args.Dequeue ();
709 for (int i = 0; i < f.Length; i++) {
710 if (f [i].Length > 0 && f [i][0] == '-')
711 f [i] = "/" + f [i].Substring (1);
713 if (f [i] [0] == '@') {
714 string [] extra_args;
715 string response_file = f [i].Substring (1);
717 var resp_file_full = Path.Combine (base_dir, response_file);
718 extra_args = LoadArgs (resp_file_full);
719 if (extra_args == null) {
720 Console.WriteLine ($"{library_output}: Unable to open response file: {resp_file_full}");
721 Environment.Exit (1);
724 all_args.Enqueue (extra_args);
728 if (CSCParseOption (f [i], ref f))
730 Console.WriteLine ("{library_output}: Failure with {0}", f [i]);
731 Environment.Exit (1);
735 string [] source_files;
736 using (var reader = new StreamReader (NativeName (base_dir + "\\" + response))) {
737 source_files = reader.ReadToEnd ().Split ();
740 Array.Sort (source_files);
742 StringBuilder sources = new StringBuilder ();
743 foreach (string s in source_files) {
747 string src = s.Replace ("/", "\\");
748 if (src.StartsWith (@"Test\..\"))
749 src = src.Substring (8, src.Length - 8);
751 sources.AppendFormat (" <Compile Include=\"{0}\" />" + NewLine, src);
754 source_files = built_sources.Split ();
755 Array.Sort (source_files);
757 foreach (string s in source_files) {
761 string src = s.Replace ("/", "\\");
762 if (src.StartsWith (@"Test\..\"))
763 src = src.Substring (8, src.Length - 8);
765 sources.AppendFormat (" <Compile Include=\"{0}\" />" + NewLine, src);
767 sources.Remove (sources.Length - 1, 1);
769 //if (library == "corlib-build") // otherwise, does not compile on fx_version == 4.0
771 // references.Add("System.dll");
772 // references.Add("System.Xml.dll");
775 //if (library == "System.Core-build") // otherwise, slow compile. May be a transient need.
777 // this.ignore_warning.Add(1685);
778 // this.ignore_warning.Add(0436);
781 var refs = new StringBuilder ();
783 bool is_test = response.Contains ("_test_");
785 // F:\src\mono\mcs\class\lib\net_2_0\nunit.framework.dll
786 // F:\src\mono\mcs\class\SomeProject\SomeProject_test_-net_2_0.csproj
787 var nunitLibPath = string.Format (@"..\lib\{0}\nunit.framework.dll", profile);
788 refs.Append (string.Format (" <Reference Include=\"{0}\" />" + NewLine, nunitLibPath));
791 var resources = new StringBuilder ();
792 if (embedded_resources.Count > 0) {
793 resources.AppendFormat (" <ItemGroup>" + NewLine);
794 foreach (var dk in embedded_resources) {
796 if (source.EndsWith (".resources"))
797 source = source.Replace (".resources", ".resx");
799 // try to find a pre-built resource, and use that instead of trying to build it
800 if (source.EndsWith (".resx")) {
801 var probe_prebuilt = Path.Combine (base_dir, source.Replace (".resx", ".resources.prebuilt"));
802 if (File.Exists (probe_prebuilt)) {
804 source = GetRelativePath (base_dir + "/", probe_prebuilt);
807 resources.AppendFormat (" <EmbeddedResource Include=\"{0}\">" + NewLine, source);
808 resources.AppendFormat (" <LogicalName>{0}</LogicalName>" + NewLine, dk.Value);
809 resources.AppendFormat (" </EmbeddedResource>" + NewLine);
811 resources.AppendFormat (" </ItemGroup>" + NewLine);
815 if (references.Count > 0 || reference_aliases.Count > 0) {
816 // -r:mscorlib.dll -r:System.dll
817 //<ProjectReference Include="..\corlib\corlib-basic.csproj">
818 // <Project>{155aef28-c81f-405d-9072-9d52780e3e70}</Project>
819 // <Name>corlib-basic</Name>
820 //</ProjectReference>
821 //<ProjectReference Include="..\System\System-basic.csproj">
822 // <Project>{2094e859-db2f-481f-9630-f89d31d9ed48}</Project>
823 // <Name>System-basic</Name>
824 //</ProjectReference>
825 var refdistinct = references.Distinct ();
826 foreach (string reference in refdistinct) {
828 var match = GetMatchingCsproj (library_output, reference, projects);
830 AddProjectReference (refs, Csproj, match, reference, null);
833 Console.WriteLine ("{0}: Could not find a matching project reference for {1}", library, Path.GetFileName (reference));
834 Console.WriteLine (" --> Adding reference with hintpath instead");
836 refs.Append (" <Reference Include=\"" + reference + "\">" + NewLine);
837 refs.Append (" <SpecificVersion>False</SpecificVersion>" + NewLine);
838 refs.Append (" <HintPath>" + reference + "</HintPath>" + NewLine);
839 refs.Append (" <Private>False</Private>" + NewLine);
840 refs.Append (" </Reference>" + NewLine);
844 foreach (string r in reference_aliases) {
845 int index = r.IndexOf ('=');
846 string alias = r.Substring (0, index);
847 string assembly = r.Substring (index + 1);
848 var match = GetMatchingCsproj (library_output, assembly, projects, explicitPath: true);
850 AddProjectReference (refs, Csproj, match, r, alias);
852 throw new NotSupportedException (string.Format ("From {0}, could not find a matching project reference for {1}", library, r));
853 refs.Append (" <Reference Include=\"" + assembly + "\">" + NewLine);
854 refs.Append (" <SpecificVersion>False</SpecificVersion>" + NewLine);
855 refs.Append (" <HintPath>" + r + "</HintPath>" + NewLine);
856 refs.Append (" <Aliases>" + alias + "</Aliases>" + NewLine);
857 refs.Append (" </Reference>" + NewLine);
864 // ../class/lib/build/tmp/System.Xml.dll [No longer possible, we should be removing this from order.xml]
865 // /class/lib/basic/System.Core.dll
866 // <library_output>mcs.exe</library_output>
867 string build_output_dir;
868 if (LibraryOutput.Contains ("/"))
869 build_output_dir = Path.GetDirectoryName (LibraryOutput);
871 build_output_dir = "bin\\Debug\\" + library;
873 bool basic_or_build = (library.Contains ("-basic") || library.Contains ("-build"));
876 // Replace the template values
879 string strongNameSection = "";
880 if (StrongNameKeyFile != null){
881 strongNameSection = String.Format (
882 " <PropertyGroup>" + NewLine +
883 " <SignAssembly>true</SignAssembly>" + NewLine +
885 " </PropertyGroup>" + NewLine +
886 " <PropertyGroup>" + NewLine +
887 " <AssemblyOriginatorKeyFile>{0}</AssemblyOriginatorKeyFile>" + NewLine +
888 " </PropertyGroup>", StrongNameKeyFile, StrongNameDelaySign ? " <DelaySign>true</DelaySign>" + NewLine : "");
890 Csproj.output = template.
891 Replace ("@OUTPUTTYPE@", Target == Target.Library ? "Library" : "Exe").
892 Replace ("@SIGNATURE@", strongNameSection).
893 Replace ("@PROJECTGUID@", Csproj.projectGuid).
894 Replace ("@DEFINES@", defines.ToString ()).
895 Replace ("@DISABLEDWARNINGS@", string.Join (",", (from i in ignore_warning select i.ToString ()).ToArray ())).
896 //Replace("@NOSTDLIB@", (basic_or_build || (!StdLib)) ? "<NoStdLib>true</NoStdLib>" : string.Empty).
897 Replace ("@NOSTDLIB@", "<NoStdLib>" + (!StdLib).ToString () + "</NoStdLib>").
898 Replace ("@NOCONFIG@", "<NoConfig>" + (!load_default_config).ToString () + "</NoConfig>").
899 Replace ("@ALLOWUNSAFE@", Unsafe ? "<AllowUnsafeBlocks>true</AllowUnsafeBlocks>" : "").
900 Replace ("@FX_VERSION", fx_version).
901 Replace ("@ASSEMBLYNAME@", Path.GetFileNameWithoutExtension (output_name)).
902 Replace ("@OUTPUTDIR@", build_output_dir).
903 Replace ("@OUTPUTSUFFIX@", Path.GetFileName (build_output_dir)).
904 Replace ("@DEFINECONSTANTS@", defines.ToString ()).
905 Replace ("@DEBUG@", want_debugging_support ? "true" : "false").
906 Replace ("@DEBUGTYPE@", want_debugging_support ? "full" : "pdbonly").
907 Replace ("@REFERENCES@", refs.ToString ()).
908 Replace ("@PREBUILD@", prebuild).
909 Replace ("@POSTBUILD@", postbuild).
910 Replace ("@STARTUPOBJECT@", main == null ? "" : $"<StartupObject>{main}</StartupObject>").
911 //Replace ("@ADDITIONALLIBPATHS@", String.Format ("<AdditionalLibPaths>{0}</AdditionalLibPaths>", string.Join (",", libs.ToArray ()))).
912 Replace ("@ADDITIONALLIBPATHS@", String.Empty).
913 Replace ("@RESOURCES@", resources.ToString ()).
914 Replace ("@OPTIMIZE@", Optimize ? "true" : "false").
915 Replace ("@SOURCES@", sources.ToString ());
917 //Console.WriteLine ("Generated {0}", ofile.Replace ("\\", "/"));
918 using (var o = new StreamWriter (generatedProjFile)) {
919 o.WriteLine (Csproj.output);
925 string GenerateStep (string library, string suffix, string eventKey)
927 string target = Load (library + suffix);
928 string target_windows, target_unix;
930 int q = library.IndexOf ("-");
932 target = target + Load (library.Substring (0, q) + suffix);
934 if (target.IndexOf ("@MONO@") != -1){
935 target_unix = target.Replace ("@MONO@", "mono").Replace ("@CAT@", "cat");
936 target_windows = target.Replace ("@MONO@", "").Replace ("@CAT@", "type");
938 target_unix = target.Replace ("jay.exe", "jay");
939 target_windows = target;
941 target_unix = target_unix.Replace ("@COPY@", "cp");
942 target_windows = target_unix.Replace ("@COPY@", "copy");
944 target_unix = target_unix.Replace ("\r", "");
945 const string condition_unix = "Condition=\" '$(OS)' != 'Windows_NT' \"";
946 const string condition_windows = "Condition=\" '$(OS)' == 'Windows_NT' \"";
948 $" <{eventKey} {condition_unix}>\n{target_unix}\n </{eventKey}>{NewLine}" +
949 $" <{eventKey} {condition_windows}>{NewLine}{target_windows}{NewLine} </{eventKey}>";
953 void AddProjectReference (StringBuilder refs, VsCsproj result, MsbuildGenerator match, string r, string alias)
955 refs.AppendFormat (" <ProjectReference Include=\"{0}\">{1}", GetRelativePath (result.csProjFilename, match.CsprojFilename), NewLine);
956 refs.Append (" <Project>" + match.projectGuid + "</Project>" + NewLine);
957 refs.Append (" <Name>" + Path.GetFileNameWithoutExtension (match.CsprojFilename.Replace ('\\', Path.DirectorySeparatorChar)) + "</Name>" + NewLine);
959 refs.Append (" <Aliases>" + alias + "</Aliases>");
960 refs.Append (" </ProjectReference>" + NewLine);
961 if (!result.projReferences.Contains (match.Csproj))
962 result.projReferences.Add (match.Csproj);
965 public static string GetRelativePath (string from, string to)
967 from = from.Replace ("\\", "/");
968 to = to.Replace ("\\", "/");
969 var fromUri = new Uri (Path.GetFullPath (from));
970 var toUri = new Uri (Path.GetFullPath (to));
972 var ret = fromUri.MakeRelativeUri (toUri).ToString ().Replace ("%5C", "\x5c");
976 MsbuildGenerator GetMatchingCsproj (string library_output, string dllReferenceName, Dictionary<string,MsbuildGenerator> projects, bool explicitPath = false)
978 // libDir would be "./../../class/lib/net_4_x for example
980 if (!dllReferenceName.EndsWith (".dll") && !dllReferenceName.EndsWith (".exe"))
981 dllReferenceName += ".dll";
983 var probe = Path.GetFullPath (Path.Combine (base_dir, dllReferenceName));
984 foreach (var project in projects){
985 if (probe == project.Value.AbsoluteLibraryOutput)
986 return project.Value;
989 // not explicit, search for the library in the lib path order specified
991 foreach (var libDir in libs) {
992 var abs = Path.GetFullPath (Path.Combine (base_dir, libDir));
993 foreach (var project in projects){
994 probe = Path.Combine (abs, dllReferenceName);
996 if (probe == project.Value.AbsoluteLibraryOutput)
997 return project.Value;
1001 // Last attempt, try to find the library in all the projects
1002 foreach (var project in projects) {
1003 if (project.Value.AbsoluteLibraryOutput.EndsWith (dllReferenceName))
1004 return project.Value;
1007 var ljoined = String.Join (", ", libs);
1008 Console.WriteLine ($"{library_output}: did not find referenced {dllReferenceName} with libs={ljoined}");
1009 foreach (var p in projects) {
1010 Console.WriteLine ("{0}", p.Value.AbsoluteLibraryOutput);
1017 public class Driver {
1019 static IEnumerable<XElement> GetProjects (bool full = false)
1021 XDocument doc = XDocument.Load ("order.xml");
1022 foreach (XElement project in doc.Root.Elements ()) {
1023 string dir = project.Attribute ("dir").Value;
1024 string library = project.Attribute ("library").Value;
1025 var profile = project.Element ("profile").Value;
1028 // Skip facades for now, the tool doesn't know how to deal with them yet.
1029 if (dir.Contains ("Facades"))
1032 // These are currently broken, skip until they're fixed.
1033 if (dir.StartsWith ("mcs") || dir.Contains ("apigen"))
1037 // Do only class libraries for now
1039 if (!(dir.StartsWith ("class") || dir.StartsWith ("mcs") || dir.StartsWith ("basic")))
1043 if (!library.Contains ("tests"))
1044 yield return project;
1049 // Do not do 2.1, it is not working yet
1050 // Do not do basic, as there is no point (requires a system mcs to be installed).
1052 if (library.Contains ("moonlight") || library.Contains ("-basic") || library.EndsWith ("bootstrap") || library.Contains ("build"))
1055 // The next ones are to make debugging easier for now
1056 if (profile == "basic")
1059 // For now -- problem is, our resolver currently only considers the assembly name, and we ahve
1060 // conflicing 2.0 and 2.4 versions so for now, we just skip the nunit20 versions
1061 if (dir.Contains ("nunit20"))
1065 if (profile != "net_4_x" || library.Contains ("tests"))
1068 //Console.WriteLine ("Going to handle {0}", library);
1069 yield return project;
1073 static void Main (string [] args)
1075 if (!File.Exists ("genproj.cs")) {
1076 Console.WriteLine ("This command must be executed from mono/msvc/scripts");
1077 Environment.Exit (1);
1080 if (args.Length == 1 && args [0].ToLower ().Contains ("-h")) {
1081 Console.WriteLine ("Usage:");
1082 Console.WriteLine ("genproj.exe [visual_studio_release] [output_full_solutions]");
1083 Console.WriteLine ("If output_full_solutions is false, only the main System*.dll");
1084 Console.WriteLine (" assemblies (and dependencies) is included in the solution.");
1085 Console.WriteLine ("Example:");
1086 Console.WriteLine ("genproj.exe 2012 false");
1087 Console.WriteLine ("genproj.exe with no arguments is equivalent to 'genproj.exe 2012 true'\n\n");
1088 Console.WriteLine ("genproj.exe deps");
1089 Console.WriteLine ("Generates a Makefile dependency file from the projects input");
1090 Environment.Exit (0);
1093 var slnVersion = (args.Length > 0) ? args [0] : "2012";
1094 bool fullSolutions = (args.Length > 1) ? bool.Parse (args [1]) : true;
1096 // To generate makefile depenedencies
1097 var makefileDeps = (args.Length > 0 && args [0] == "deps");
1099 var sln_gen = new SlnGenerator (slnVersion);
1100 var four_five_sln_gen = new SlnGenerator (slnVersion);
1101 var projects = new Dictionary<string,MsbuildGenerator> ();
1103 var duplicates = new List<string> ();
1104 foreach (var project in GetProjects (makefileDeps)) {
1105 var library_output = project.Element ("library_output").Value;
1106 projects [library_output] = new MsbuildGenerator (project);
1108 foreach (var project in GetProjects (makefileDeps)){
1109 var library_output = project.Element ("library_output").Value;
1110 //Console.WriteLine ("=== {0} ===", library_output);
1111 var gen = projects [library_output];
1113 var csproj = gen.Generate (library_output, projects);
1114 var csprojFilename = csproj.csProjFilename;
1115 if (!sln_gen.ContainsProjectIdentifier (csproj.library)) {
1116 sln_gen.Add (csproj);
1118 duplicates.Add (csprojFilename);
1121 } catch (Exception e) {
1122 Console.WriteLine ("Error in {0}\n{1}", project, e);
1126 Func<MsbuildGenerator.VsCsproj, bool> additionalFilter;
1127 additionalFilter = fullSolutions ? (Func<MsbuildGenerator.VsCsproj, bool>)null : IsCommonLibrary;
1129 FillSolution (four_five_sln_gen, MsbuildGenerator.profile_4_x, projects.Values, additionalFilter);
1131 if (duplicates.Count () > 0) {
1132 var sb = new StringBuilder ();
1133 sb.AppendLine ("WARNING: Skipped some project references, apparent duplicates in order.xml:");
1134 foreach (var item in duplicates) {
1135 sb.AppendLine (item);
1137 Console.WriteLine (sb.ToString ());
1140 WriteSolution (four_five_sln_gen, Path.Combine ("..", "..", MakeSolutionName (MsbuildGenerator.profile_4_x)));
1143 const string classDirPrefix = "./../../";
1144 Console.WriteLine ("here {0}", sln_gen.libraries.Count);
1145 foreach (var p in sln_gen.libraries){
1146 string rebasedOutput = RebaseToClassDirectory (MsbuildGenerator.GetRelativePath ("../../mcs/class", p.library_output));
1148 Console.Write ("{0}: ", rebasedOutput);
1149 foreach (var r in p.projReferences){
1150 var lo = r.library_output;
1151 if (lo.StartsWith (classDirPrefix))
1152 lo = lo.Substring (classDirPrefix.Length);
1154 lo = "<<ERROR-dependency is not a class library>>";
1155 Console.Write ("{0} ", lo);
1157 Console.Write ("\n\t(cd {0}; make {1})", p.MsbuildGenerator.dir, p.library_output);
1158 Console.WriteLine ("\n");
1162 // A few other optional solutions
1163 // Solutions with 'everything' and the most common libraries used in development may be of interest
1164 //WriteSolution (sln_gen, "./mcs_full.sln");
1165 //WriteSolution (small_full_sln_gen, "small_full.sln");
1166 // The following may be useful if lacking visual studio or MonoDevelop, to bootstrap mono compiler self-hosting
1167 //WriteSolution (basic_sln_gen, "mcs_basic.sln");
1168 //WriteSolution (build_sln_gen, "mcs_build.sln");
1171 // Rebases a path, assuming that execution is taking place in the "class" subdirectory,
1172 // so it strips ../class/ from a path, which is a no-op
1173 static string RebaseToClassDirectory (string path)
1175 const string prefix = "../class/";
1176 int p = path.IndexOf (prefix);
1179 return path.Substring (0, p) + path.Substring (p+prefix.Length);
1183 static string MakeSolutionName (string profileTag)
1185 return "net" + profileTag + ".sln";
1188 static void FillSolution (SlnGenerator solution, string profileString, IEnumerable<MsbuildGenerator> projects, Func<MsbuildGenerator.VsCsproj, bool> additionalFilter = null)
1190 foreach (var generator in projects) {
1191 var vsCsproj = generator.Csproj;
1192 if (!vsCsproj.library.Contains (profileString))
1194 if (additionalFilter != null && !additionalFilter (vsCsproj))
1196 var csprojFilename = vsCsproj.csProjFilename;
1197 if (!solution.ContainsProjectIdentifier (vsCsproj.library)) {
1198 solution.Add (vsCsproj);
1199 RecursiveAddProj (solution, vsCsproj);
1204 static void RecursiveAddProj (SlnGenerator solution, MsbuildGenerator.VsCsproj vsCsproj, int recursiveDepth = 1)
1206 const int max_recursive = 16;
1207 if (recursiveDepth > max_recursive) throw new Exception (string.Format ("Reached {0} levels of project dependency", max_recursive));
1208 foreach (var projRef in vsCsproj.projReferences) {
1209 if (!solution.ContainsProjectIdentifier (projRef.library)) {
1210 solution.Add (projRef);
1211 RecursiveAddProj (solution, projRef, recursiveDepth + 1);
1216 static void WriteSolution (SlnGenerator sln_gen, string slnfilename)
1218 Console.WriteLine (String.Format ("Writing solution {1}, with {0} projects", sln_gen.Count, slnfilename));
1219 sln_gen.Write (slnfilename);
1222 static bool IsCommonLibrary (MsbuildGenerator.VsCsproj proj)
1224 var library = proj.library;
1225 //if (library.Contains ("-basic"))
1227 //if (library.Contains ("-build"))
1229 //if (library.StartsWith ("corlib"))
1231 if (library.StartsWith ("System-"))
1233 if (library.StartsWith ("System.Xml"))
1235 if (library.StartsWith ("System.Secu"))
1237 if (library.StartsWith ("System.Configuration"))
1239 if (library.StartsWith ("System.Core"))
1241 //if (library.StartsWith ("Mono."))