Nerfed/Nerfed.Compiler/Compiler.cs

82 lines
2.5 KiB
C#

using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Nerfed.Compiler;
public static class Compiler
{
public static bool Compile(string projectFilePath, string configuration = "Debug")
{
string projectDirectory = Path.GetDirectoryName(projectFilePath);
if (!File.Exists(projectFilePath))
{
Console.WriteLine($"ERROR: Project file not found at {projectDirectory}.");
return false;
}
if (!Project.Open(projectFilePath, out Project project))
{
return false;
}
// TODO: Check project version, to make sure we can compile it or something...
// Generate solution.
Generator.GenerateSolution(projectDirectory, project, out string solutionFilePath);
// Compile solution.
ProcessStartInfo processInfo = new()
{
WorkingDirectory = Path.GetDirectoryName(solutionFilePath),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
};
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
processInfo.FileName = "/bin/bash";
processInfo.Arguments = $"-c \"dotnet build '{Path.GetFileName(solutionFilePath)}'\"" + (string.IsNullOrWhiteSpace(configuration) ? $" --configuration {configuration}" : "");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
processInfo.FileName = "cmd.exe";
processInfo.Arguments = $"/c dotnet build \"{Path.GetFileName(solutionFilePath)}\"" + (string.IsNullOrWhiteSpace(configuration) ? $" --configuration {configuration}" : "");
}
else
{
Console.WriteLine($"ERROR: Platform not supported!");
return false;
}
Process process = Process.Start(processInfo) ?? throw new Exception();
process.OutputDataReceived += (sender, dataArgs) => {
string data = dataArgs.Data;
if (data is null)
{
return;
}
Console.WriteLine(data);
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.ErrorDataReceived += (sender, dataArgs) => {
if (dataArgs.Data is not null)
{
Console.WriteLine(dataArgs.Data);
}
};
process.WaitForExit();
int exitCode = process.ExitCode;
process.Close();
return true;
}
}