Skip to content

Instantly share code, notes, and snippets.

@anuraj
Last active August 29, 2015 14:15
Show Gist options
  • Save anuraj/bd39d8c6f46a0af4380b to your computer and use it in GitHub Desktop.
Save anuraj/bd39d8c6f46a0af4380b to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
namespace kmonitor
{
class Program
{
private static DateTime _lastRead = DateTime.MinValue;
static void Main(string[] args)
{
var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
var fileSystemWatcher = new FileSystemWatcher(currentDirectory);
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
fileSystemWatcher.Created += new FileSystemEventHandler(OnChanged);
fileSystemWatcher.Deleted += new FileSystemEventHandler(OnChanged);
fileSystemWatcher.EnableRaisingEvents = true;
Console.WriteLine("Starting server");
StartProcess("k --watch web");
Console.WriteLine("Press \'q\' to quit the web monitor.");
while (Console.Read() != 'q') ;
}
private static Process StartProcess(string arguments)
{
var filename = "cmd.exe";
var processStartInfo = new ProcessStartInfo(filename, " /C " + arguments);
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.UseShellExecute = false;
var process = Process.Start(processStartInfo);
process.EnableRaisingEvents = true;
process.OutputDataReceived += (o, dre) =>
{
Console.WriteLine(dre.Data);
};
process.BeginOutputReadLine();
return process;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != _lastRead)
{
var extension = Path.GetExtension(e.Name);
if (extension.Equals(".json"))
{
Console.WriteLine("{0} file modified. Package restore starting", e.Name);
var process = StartProcess("kpm restore");
process.WaitForExit();
if (process.ExitCode == 0)
{
Console.WriteLine("Package restore completed successfully. Restarting server.");
process = StartProcess("k --watch web");
process.WaitForExit();
}
else
{
Console.WriteLine("Package restore failed. Please make sure your {0} file is valid.", e.Name);
}
}
else
{
Console.WriteLine("{0} file modified. Restarting server", e.Name);
var process = StartProcess("k --watch web");
process.WaitForExit();
if (process.ExitCode != 0)
{
Console.WriteLine("Server restart failed. Please make sure you can compile {0} file.", e.Name);
}
}
_lastRead = lastWriteTime;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment