Skip to content

Instantly share code, notes, and snippets.

@jmrnilsson
Created June 7, 2019 16:11
Show Gist options
  • Save jmrnilsson/814f745a7dee77f232cb9ad8db730fe4 to your computer and use it in GitHub Desktop.
Save jmrnilsson/814f745a7dee77f232cb9ad8db730fe4 to your computer and use it in GitHub Desktop.
LinefeedPurger - Detects all invalid LF files in C# (.cs) files from git top-level - .NETCore
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace LinefeedPurger
{
class Program
{
static void Main(string[] args)
{
string gitTopLevel = GitTopLevel();
Console.WriteLine($"||\tAssuming top level: {gitTopLevel}");
var csFiles = new List<string>();
GetCsFiles(gitTopLevel, ref csFiles);
Console.WriteLine($"||\tAssuming files: {csFiles}");
foreach (string csFile in csFiles)
{
string fileName = csFile.Replace("/", "\\");
string content = File.ReadAllText(fileName);
content = Regex.Replace(content, "\r\n", "_");
if (Regex.IsMatch(content, "\n", RegexOptions.Multiline))
{
Console.WriteLine($"EE\tMatches LF: {fileName}");
}
else
{
Console.WriteLine($"||\tMatches CRLF: {fileName}");
}
}
}
private static void GetCsFiles(string path, ref List<string> csFiles)
{
try
{
foreach (string d in Directory.GetDirectories(path))
{
foreach (string f in Directory.GetFiles(d))
{
if (Regex.IsMatch(f, "\\.cs$"))
{
csFiles.Add(f);
}
}
GetCsFiles(d, ref csFiles);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static string GitTopLevel()
{
return GitCommand("rev-parse --show-toplevel");
}
private static string GitCommand(string command)
{
var stderr = new StringBuilder();
var stdout = new StringBuilder();
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "git";
startInfo.Arguments = command;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
using (Process process = Process.Start(startInfo))
{
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
stdout.AppendLine(line);
Console.WriteLine(line);
}
while (!process.StandardError.EndOfStream)
{
string line = process.StandardError.ReadLine();
stderr.AppendLine(line);
Console.WriteLine(line);
}
process.WaitForExit();
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
return stdout.ToString().Trim() + stderr.ToString().Trim();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment