Skip to content

Instantly share code, notes, and snippets.

@tpokorra
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpokorra/f14c28fbc15cff838718 to your computer and use it in GitHub Desktop.
Save tpokorra/f14c28fbc15cff838718 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text;
namespace indent
{
class main
{
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory, "*.cs", SearchOption.AllDirectories);
foreach (string fileName in fileEntries)
{
ProcessFile(fileName);
}
}
static bool WithBOF(string filename)
{
byte[] buffer = new byte[5];
FileStream file = new FileStream(filename, FileMode.Open);
file.Read(buffer, 0, 5);
file.Close();
Encoding enc = null;
if ((buffer[0] == 0xef) && (buffer[1] == 0xbb) && (buffer[2] == 0xbf))
{
enc = Encoding.UTF8;
}
else if ((buffer[0] == 0xfe) && (buffer[1] == 0xff))
{
enc = Encoding.Unicode;
}
else if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0xfe) && (buffer[3] == 0xff))
{
enc = Encoding.UTF32;
}
else if ((buffer[0] == 0x2b) && (buffer[1] == 0x2f) && (buffer[2] == 0x76))
{
enc = Encoding.UTF7;
}
return enc != null;
}
// fix namespace indent
public static void ProcessFile(string path)
{
bool changed = false;
Encoding enc = new UTF8Encoding(WithBOF(path));
using (StreamReader sr = new StreamReader(path))
{
using (StreamWriter sw = new StreamWriter(path + ".new", false, enc))
{
int countBrackets = 0;
string indent = string.Empty;
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.StartsWith("namespace "))
{
sw.WriteLine(line);
sw.WriteLine(sr.ReadLine());
line = sr.ReadLine();
while (line.Length == 0)
{
sw.WriteLine();
line = sr.ReadLine();
}
if (!line.StartsWith(" "))
{
changed = true;
indent = " ";
}
}
if (line.Trim() == "{")
{
countBrackets++;
}
else if (line.Trim() == "}")
{
countBrackets--;
if (countBrackets == 0)
{
indent = String.Empty;
}
}
if (sr.EndOfStream)
{
sw.Write(line);
}
else if (line.StartsWith("// ") || line.StartsWith("#") || line.Trim().Length == 0)
{
sw.WriteLine(line);
}
else
{
sw.WriteLine(indent + line);
}
}
}
if (changed)
{
Console.WriteLine("Processed file '{0}'.", path);
File.Delete(path);
File.Move(path + ".new", path);
}
else
{
File.Delete(path + ".new");
}
}
}
public static void Main(string[] args)
{
ProcessDirectory("csharp/ICT");
}
}
}
@tpokorra
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment