-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProjectStatsHistoryStore.cs
More file actions
99 lines (79 loc) · 2.92 KB
/
Copy pathProjectStatsHistoryStore.cs
File metadata and controls
99 lines (79 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System.Text.Json;
namespace LinesOfCodeCounter;
public sealed class ProjectStatsHistoryStore
{
readonly string filePath;
readonly List<ProjectStatsSnapshot> snapshots = [];
public ProjectStatsHistoryStore()
{
string appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string folder = Path.Combine(appData, "LinesOfCodeCounter");
_ = Directory.CreateDirectory(folder);
filePath = Path.Combine(folder, "project-stats-history.json");
Load();
}
public static string NormalizeFolderPath(string folderPath)
{
if(string.IsNullOrWhiteSpace(folderPath))
return "";
string fullPath = Path.GetFullPath(folderPath.Trim());
fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return fullPath.ToUpperInvariant();
}
public void Add(ProjectStatsSnapshot snapshot)
{
if(snapshot == null || string.IsNullOrWhiteSpace(snapshot.FolderKey))
return;
snapshots.Add(snapshot);
Save();
}
public IReadOnlyList<ProjectStatsSnapshot> GetSnapshots(string folderPath)
{
string key = NormalizeFolderPath(folderPath);
return string.IsNullOrWhiteSpace(key)
? Array.Empty<ProjectStatsSnapshot>()
: snapshots
.Where(x => string.Equals(x.FolderKey, key, StringComparison.OrdinalIgnoreCase))
.OrderBy(x => x.CapturedAtUtc)
.ToList();
}
public IReadOnlyList<ProjectStatsDailyPoint> GetDailyAverages(string folderPath) => GetSnapshots(folderPath)
.GroupBy(x => x.CapturedAtUtc.ToLocalTime().Date)
.OrderBy(x => x.Key)
.Select(x => new ProjectStatsDailyPoint
{
Day = x.Key,
Samples = x.Count(),
AverageFiles = x.Average(y => y.TotalFiles),
AverageLines = x.Average(y => y.TotalLines),
AverageCharacters = x.Average(y => y.TotalCharacters),
AverageLinesPerFile = x.Average(y => y.AverageLinesPerFile),
AverageCharactersPerLine = x.Average(y => y.AverageCharactersPerLine),
})
.ToList();
void Load()
{
snapshots.Clear();
if(!File.Exists(filePath))
return;
try
{
string json = File.ReadAllText(filePath);
List<ProjectStatsSnapshot>? loaded = JsonSerializer.Deserialize<List<ProjectStatsSnapshot>>(json);
if(loaded != null)
snapshots.AddRange(loaded.Where(x => !string.IsNullOrWhiteSpace(x.FolderKey)));
}
catch
{
}
}
void Save()
{
JsonSerializerOptions options = new()
{
WriteIndented = true,
};
string json = JsonSerializer.Serialize(snapshots, options);
File.WriteAllText(filePath, json);
}
}