Skip to content

Instantly share code, notes, and snippets.

@bennage
Created March 16, 2012 22:43
Show Gist options
  • Save bennage/2053352 to your computer and use it in GitHub Desktop.
Save bennage/2053352 to your computer and use it in GitHub Desktop.
quick and dirty for normalizing all the line endings in project (curse you autocrlf!)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NormalizeLineEndings
{
internal class Program
{
private static readonly Regex pattern = new Regex("[^\r](\n)|^\n", RegexOptions.Multiline);
private static readonly string[] extensions = new[]
{
"cs", "css", "csproj", "sln", "txt", "targets", "md",
"cshtml", "js", "config"
};
private static void Main(string[] args)
{
const string root = @"\path\to\root";
var set = from fsi in Children(new DirectoryInfo(root))
where fsi is FileInfo
&& extensions.Contains(fsi.Extension.Replace(".", ""))
select fsi;
set.Cast<FileInfo>().ToList().ForEach(ConvertEndings);
Console.WriteLine("** complete **");
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
private static IEnumerable<FileSystemInfo> Children(DirectoryInfo parent)
{
var items = parent.GetFileSystemInfos();
var children = from item in items
where item is DirectoryInfo
&& !item.Name.StartsWith(".git")
select Children((DirectoryInfo) item);
return items.Concat(children.SelectMany(x => x));
}
private static void ConvertEndings(FileInfo fileInfo)
{
string content;
using (var fs = fileInfo.OpenRead())
using (var reader = new StreamReader(fs))
{
content = reader.ReadToEnd();
}
if (!pattern.IsMatch(content)) return;
Console.WriteLine(fileInfo.Name);
content = pattern.Replace(content, m => m.Value.Replace("\n", Environment.NewLine));
using (var fs = fileInfo.OpenWrite())
using (var writer = new StreamWriter(fs))
{
writer.Write(content);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment