using System;
using System.Diagnostics;
using System.IO;
namespace TGServerService
{
// Some useful functions for triggering pre action events
sealed partial class ServerInstance
{
///
/// The instance directory for Preaction handlers
///
const string EventFolder = "EventHandlers/";
///
/// Creates the
///
void InitEventHandlers()
{
Directory.CreateDirectory(RelativePath(EventFolder));
}
///
/// Gets the path of an event given an
///
/// The name of the event
/// The path to the event handler
string GetEventPath(string eventName)
{
return string.Format("{0}{1}.bat", RelativePath(EventFolder), eventName);
}
///
/// Check if an event handler for exists
///
/// The name of the event
/// if the event handler exists, otherwise
bool EventHandlerExists(string eventName)
{
return File.Exists(GetEventPath(eventName));
}
///
/// Runs an event named if it exists
///
/// The name of the event
/// if the event handler exists and failed to run, otherwise
bool HandleEvent(string eventName)
{
if (!EventHandlerExists(eventName))
{
// We don't need a handler, so let's just fail silently.
return true;
}
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = GetEventPath(eventName),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
process.Start();
process.WaitForExit();
var stdout = process.StandardOutput.ReadToEnd();
var stderr = process.StandardError.ReadToEnd();
var success = process.ExitCode == 0;
var eventData = String.Format("Preaction Event: {0} @ {1} ran. Stdout:\n{2}\nStderr:\n{3}", eventName, GetEventPath(eventName), stdout, stderr);
if (success)
WriteInfo(eventData, EventID.PreactionEvent);
else
WriteWarning(eventData, EventID.PreactionFail);
return success;
}
///
/// Run the "precompile" event
///
/// if the event handler exists and failed to run, otherwise
public bool PrecompileHook()
{
return HandleEvent("precompile");
}
///
/// Run the "postcompile" event
///
/// if the event handler exists and failed to run, otherwise
public bool PostcompileHook()
{
return HandleEvent("postcompile");
}
}
}