1
0
mirror of https://github.com/chylex/Code-Statistics.git synced 2025-04-09 19:15:41 +02:00

Add line and character counting to Java handler

This commit is contained in:
chylex 2015-09-09 15:31:58 +02:00
parent 8f997253af
commit 4f57b76b30
3 changed files with 33 additions and 6 deletions
CodeStatistics/Handlers/Objects

View File

@ -1,19 +1,43 @@
using CodeStatistics.Input;
using System.Text.RegularExpressions;
using System.Linq;
namespace CodeStatistics.Handlers.Objects.Java{
static class JavaParser{
private static readonly Regex commentOneLine = new Regex(@"//.*",RegexOptions.Compiled);
private static readonly Regex commentMultiLine = new Regex(@"/\*(?:.|\n)*?\*/",RegexOptions.Compiled);
public static void Parse(File file, JavaStatistics stats){
string filePlain = file.Read();
string fileParsed = commentMultiLine.Replace(commentOneLine.Replace(filePlain,""),"");
public static void Parse(string fileContents, JavaStatistics stats){
string fileParsed = commentMultiLine.Replace(commentOneLine.Replace(fileContents,""),"");
string[] linesPlain = filePlain.Split('\n'); // lines are always \n
string[] linesParsed = fileParsed.Split('\n'); // ^
string[] linesPlain = fileContents.Split('\n').Select(line => line.TrimEnd()).Where(line => line.Length > 0).ToArray(); // lines are always \n
string[] linesParsed = fileParsed.Split('\n').Select(line => line.TrimEnd()).Where(line => line.Length > 0).ToArray(); // ^
// Package
string package = null;
if (linesParsed.FirstOrDefault(line => line.ExtractBoth("package ",";",out package)) == null)return; // should not happen, but what if...
stats.Packages.Add(package);
// Lines
int totalLines = linesPlain.Count(line => !line.TrimStart().Equals("{"));
stats.LinesTotal += totalLines;
// Characters
int spaces = 0;
int totalCharacters = linesPlain.Select(line => {
string noSpaces = line.TrimStart(' ');
int diff = line.Length-noSpaces.Length;
if (diff > 0 && spaces == 0)spaces = diff;
if (diff > 0)line = noSpaces.PadLeft(noSpaces.Length+diff/spaces,'\t'); // replaces spaces with tabs
return line.Length;
}).Sum();
stats.CharactersTotal += totalCharacters;
}
}
}

View File

@ -3,5 +3,8 @@
namespace CodeStatistics.Handlers.Objects.Java{
class JavaStatistics{
public HashSet<string> Packages = new HashSet<string>();
public int LinesTotal = 0;
public long CharactersTotal = 0;
}
}

View File

@ -11,7 +11,7 @@ namespace CodeStatistics.Handlers.Objects{
}
public override void Handle(File file){
JavaParser.Parse(file,stats);
JavaParser.Parse(file.Read(),stats);
}
public override IHandlerTab[] GenerateTabs(){