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
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
namespace testMSBuild
{
class Program
{
//const string msbuildRoot = "/usr/lib/mono/msbuild/Current/bin/";
const string msbuildRoot = "/usr/share/dotnet/sdk/3.1.101/";
//const string msbuildRoot = "/mnt/data/src/microsoft/msbuild/artifacts/bin/bootstrap/netcoreapp2.1/MSBuild/";
const string toolsVersion = "Current";
static void Main (string [] args)
{
/*var nativeSharedMethod = typeof (SolutionFile).Assembly.GetType ("Microsoft.Build.Shared.NativeMethodsShared");
var isMonoField = nativeSharedMethod.GetField ("_isMono", BindingFlags.Static | BindingFlags.NonPublic);
isMonoField.SetValue (null, true);*/
//Environment.SetEnvironmentVariable (MSBUILD_EXE_PATH, "/usr/share/dotnet/sdk/3.1.101/MSBuild.dll");
Environment.SetEnvironmentVariable ("MSBUILD_EXE_PATH", Path.Combine(msbuildRoot, "MSBuild.dll"));
Environment.SetEnvironmentVariable ("MSBUILD_NUGET_PATH", "/home/jp/.nuget/packages");
//Environment.SetEnvironmentVariable ("COREHOST_TRACE", "1");
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += msbuildAssembliesResolve;
compile ();
}
static Assembly msbuildAssembliesResolve (object sender, ResolveEventArgs args)
{
string assemblyPath = Path.Combine (msbuildRoot, new AssemblyName (args.Name).Name + ".dll");
/*Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine ($"Probing: {assemblyPath}");
Console.ResetColor ();*/
if (!File.Exists (assemblyPath)) return null;
Assembly assembly = Assembly.LoadFrom (assemblyPath);
return assembly;
}
static void compile ()
{
//Console.WriteLine ($"{Microsoft.Build. BuildEnvironmentHelper.Instance.CurrentMSBuildExePath}");
string slnPath = "/mnt/devel/glfw-sharp/glfw-sharp.sln";//<--- change here can be another VS type ex: .vcxproj
//string slnPath = "/mnt/devel/vke.net/vke.net.sln";//<--- change here can be another VS type ex: .vcxproj
//string csprojPath = "/mnt/devel/glfw-sharp/glfw-sharp.csproj";
//ILogger Logger = new BasicLogger ();
ILogger Logger = new Microsoft.Build.Logging.ConsoleLogger ();
Logger.Verbosity = LoggerVerbosity.Minimal;
//Logger.Parameters = "V=DIAG;consoleloggerparameters:ShowEventId";
ProjectCollection projectCollection = new ProjectCollection ();
projectCollection.DefaultToolsVersion = toolsVersion;
//projectCollection.IsBuildEnabled = false;
//projectCollection.LoadProject (projectFileName);
SolutionFile sln = SolutionFile.Parse (slnPath);
/*foreach (ProjectInSolution pis in sln.ProjectsInOrder) {
Console.WriteLine ($"{pis.ProjectName} {pis.RelativePath} {pis.ProjectType}");
}*/
//Project project = new Project (projectCollection);
BuildParameters buildParams = new BuildParameters (projectCollection);
buildParams.Loggers = new List<ILogger> () { Logger };
//buildParams.DefaultToolsVersion = "Current";
//buildParams.DetailedSummary = true;
//buildParams.LogInitialPropertiesAndItems = true;
//buildParams.LogTaskInputs = true;
buildParams.ResetCaches = false;
Dictionary<String, String> globalProperties = new Dictionary<String, String> ();
globalProperties ["Configuration"] = sln.GetDefaultConfigurationName ();
globalProperties ["Platform"] = sln.GetDefaultPlatformName ();
//globalProperties ["RollForward"] = "none";
//globalProperties ["_IsRollForwardSupported"] = "false";
//globalProperties ["GenerateRuntimeConfigurationFiles"] = "true";
//globalProperties ["NuGetPackageRoot"] = "/home/jp/.nuget/packages";
//globalProperties ["RoslynTargetsPath"] = Path.Combine (msbuildRoot, "Roslyn/");
//globalProperties ["MSBuildSDKsPath"] = Path.Combine (msbuildRoot, "Sdks/");
//globalProperties ["AdditionalLibPaths"] = msbuildRoot;
//globalProperties ["AssemblySearchPaths"] = msbuildRoot;
//globalProperty.Add ("CSharpCoreTargetsPath", "/usr/share/dotnet/sdk/3.1.101/Roslyn/Microsoft.CSharp.Core.targets");
/*ProjectInstance pinst = new ProjectInstance (csprojPath, globalProperties, "Current");
if (pinst.Build (new String [] { "Build" }, buildParams.Loggers, out System.Collections.Generic.IDictionary<string, Microsoft.Build.Execution.TargetResult> targetOutputs))
Console.WriteLine ("Success");
ProjectRootElement pre = pinst.ToProjectRootElement ();*/
//List <Project> projects = new List<Project> ();
//projectCollection.ProjectAdded += (sender, e) => {
// // pc = sender as ProjectCollection;
// // Console.ForegroundColor = ConsoleColor.Yellow;
// // Console.WriteLine ($"Proj added: {e.ProjectRootElement} {e.ProjectRootElement.FullPath}");
// // Console.ResetColor ();
// Project p = new Project (e.ProjectRootElement);//, globalProperties, toolsVersion, projectCollection);
// // //projects.Add (p);
// Console.WriteLine ($"\nEvaluated properties:");
// foreach (var pi in p.Properties)
// Console.WriteLine ($"\t{pi.Name} = {pi.EvaluatedValue}");
// Console.WriteLine ("");
// // //foreach (ProjectItem pi in p.AllEvaluatedItems)
// // //Console.WriteLine ($"{pi.ItemType} {pi.EvaluatedInclude}");
// // /*foreach (GlobResult gr in p.GetAllGlobs()) {
// // foreach (string g in gr.IncludeGlobs) {
// // Console.WriteLine ($"\t\t{g}");
// // }
//};
//};
BuildManager.DefaultBuildManager.ResetCaches ();
//string[] targetsToBuild = { "ResolveAssemblyReferences" };
string [] targetsToBuild = { "restore", "build"};
//string [] targetsToBuild = { "Rebuild" };
//globalProperties ["Configuration"] = "ReleaseSpirVTasks";
BuildRequestData buildRequest = new BuildRequestData (slnPath, globalProperties, "Current", targetsToBuild, null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build (buildParams, buildRequest);
if (buildResult.OverallResult == BuildResultCode.Success) {
Console.WriteLine ("Build succes.");
} else {
foreach (var item in buildResult.ResultsByTarget) {
Console.WriteLine ($"{item.Key} -> {item.Value.ResultCode} {item.Value.ToString()}");
}
Console.WriteLine ("Error: " + buildResult.Exception);
}
//Console.WriteLine ($"proj count: {}");
//MessageBox.Show (Logger.GetLogString ());
/*foreach (Project p in buildParams. ..LoadedProjects) {
foreach (ProjectItem pi in p.AllEvaluatedItems) {
Console.WriteLine ($"{pi.ItemType} {pi}");
}
}*/
}
}
public class FileLogger : ILogger
{
public LoggerVerbosity Verbosity { get => throw new NotImplementedException (); set => throw new NotImplementedException (); }
public string Parameters { get => throw new NotImplementedException (); set => throw new NotImplementedException (); }
Stream log;
StreamWriter sw;
public void Initialize (IEventSource eventSource)
{
log = new FileStream ("buildlog.txt", FileMode.Create);
sw = new StreamWriter (log);
eventSource.MessageRaised += (sender, e) => sw.WriteLine ($"{e.Message}");
eventSource.BuildStarted += (sender, e) => sw.WriteLine("Build started");
eventSource.BuildFinished += (sender, e) => sw.WriteLine ("Build finished");
}
public void Shutdown ()
{
log.Flush ();
sw.Dispose ();
log.Dispose ();
}
}
public class BasicLogger : ILogger
{
public LoggerVerbosity Verbosity { get; set; }
public string Parameters { get; set; }
public void Initialize (IEventSource eventSource)
{
//eventSource.ProjectStarted += (sender, e) => Console.WriteLine ($"Building project: {e.Message}");
//eventSource.ProjectFinished += (sender, e) => Console.WriteLine ($"Done project: {e.Message}");
eventSource.ErrorRaised += (sender, e) => {
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine ($"{e.Message}");
Console.ResetColor ();
};
eventSource.TargetStarted += (sender, e) => {
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine ($"Target start: {e.TargetName}<-{e.ParentTarget} {e.Message}");
Console.ResetColor ();
};
eventSource.TargetFinished += (sender, e) => {
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine ($"\tDone {e.TargetName} ({e.Succeeded}) : {e.Message}");
Console.ResetColor ();
};
eventSource.MessageRaised += (sender, e) => {
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine ($"{e.HelpKeyword} {e.Message}");
Console.ResetColor ();
};
//eventSource.AnyEventRaised += (sender, e) => Console.WriteLine ($"{e.Timestamp}:{e.SenderName}=>{e.Message}");
//eventSource.BuildStarted += (sender, e) => Console.WriteLine("Build started");
eventSource.BuildFinished += (sender, e) => Console.WriteLine ("Build finished");
}
public void Shutdown ()
{
}
}
//public class BasicLogger : ILogger
// {
// MemoryStream streamMem = new MemoryStream ();
// /// <summary>
// /// Initialize is guaranteed to be called by MSBuild at the start of the build
// /// before any events are raised.
// /// </summary>
// public override void Initialize (IEventSource eventSource)
// {
// try {
// // Open the file
// this.streamWriter = new StreamWriter (streamMem);
// //this.streamWriter = new StreamWriter(logFile);
// } catch (Exception ex) {
// if
// (
// ex is UnauthorizedAccessException
// || ex is ArgumentNullException
// || ex is PathTooLongException
// || ex is DirectoryNotFoundException
// || ex is NotSupportedException
// || ex is ArgumentException
// || ex is SecurityException
// || ex is IOException
// ) {
// throw new LoggerException ("Failed to create log file: " + ex.Message);
// } else {
// // Unexpected failure
// throw;
// }
// }
// // For brevity, we'll only register for certain event types. Loggers can also
// // register to handle TargetStarted/Finished and other events.
// eventSource.ProjectStarted += new ProjectStartedEventHandler (eventSource_ProjectStarted);
// eventSource.TaskStarted += new TaskStartedEventHandler (eventSource_TaskStarted);
// eventSource.MessageRaised += new BuildMessageEventHandler (eventSource_MessageRaised);
// eventSource.WarningRaised += new BuildWarningEventHandler (eventSource_WarningRaised);
// eventSource.ErrorRaised += new BuildErrorEventHandler (eventSource_ErrorRaised);
// eventSource.ProjectFinished += new ProjectFinishedEventHandler (eventSource_ProjectFinished);
// }
// void eventSource_ErrorRaised (object sender, BuildErrorEventArgs e)
// {
// // BuildErrorEventArgs adds LineNumber, ColumnNumber, File, amongst other parameters
// string line = String.Format (": ERROR {0}({1},{2}): ", e.File, e.LineNumber, e.ColumnNumber);
// WriteLineWithSenderAndMessage (line, e);
// }
// void eventSource_WarningRaised (object sender, BuildWarningEventArgs e)
// {
// // BuildWarningEventArgs adds LineNumber, ColumnNumber, File, amongst other parameters
// string line = String.Format (": Warning {0}({1},{2}): ", e.File, e.LineNumber, e.ColumnNumber);
// WriteLineWithSenderAndMessage (line, e);
// }
// void eventSource_MessageRaised (object sender, BuildMessageEventArgs e)
// {
// // BuildMessageEventArgs adds Importance to BuildEventArgs
// // Let's take account of the verbosity setting we've been passed in deciding whether to log the message
// if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast (LoggerVerbosity.Minimal))
// || (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast (LoggerVerbosity.Normal))
// || (e.Importance == MessageImportance.Low && IsVerbosityAtLeast (LoggerVerbosity.Detailed))
// ) {
// WriteLineWithSenderAndMessage (String.Empty, e);
// }
// }
// void eventSource_TaskStarted (object sender, TaskStartedEventArgs e)
// {
// // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
// // To keep this log clean, this logger will ignore these events.
// }
// void eventSource_ProjectStarted (object sender, ProjectStartedEventArgs e)
// {
// // ProjectStartedEventArgs adds ProjectFile, TargetNames
// // Just the regular message string is good enough here, so just display that.
// WriteLine (String.Empty, e);
// indent++;
// }
// void eventSource_ProjectFinished (object sender, ProjectFinishedEventArgs e)
// {
// // The regular message string is good enough here too.
// indent--;
// WriteLine (String.Empty, e);
// }
// /// <summary>
// /// Write a line to the log, adding the SenderName and Message
// /// (these parameters are on all MSBuild event argument objects)
// /// </summary>
// private void WriteLineWithSenderAndMessage (string line, BuildEventArgs e)
// {
// if (0 == String.Compare (e.SenderName, "MSBuild", true /*ignore case*/)) {
// // Well, if the sender name is MSBuild, let's leave it out for prettiness
// WriteLine (line, e);
// } else {
// WriteLine (e.SenderName + ": " + line, e);
// }
// }
// /// <summary>
// /// Just write a line to the log
// /// </summary>
// private void WriteLine (string line, BuildEventArgs e)
// {
// for (int i = indent; i > 0; i--) {
// streamWriter.Write ("\t");
// }
// streamWriter.WriteLine (line + e.Message);
// }
// public string GetLogString ()
// {
// var sr = new StreamReader (streamMem);
// var myStr = sr.ReadToEnd ();
// return myStr;
// }
// /// <summary>
// /// Shutdown() is guaranteed to be called by MSBuild at the end of the build, after all
// /// events have been raised.
// /// </summary>
// ///
// ///
// public override void Shutdown ()
// {
// streamWriter.Flush ();
// streamMem.Position = 0;
// }
// private StreamWriter streamWriter;
// private int indent;
//}
}
|