Skip to content

Commit b7740ac

Browse files
committed
refactor: streamline file name handling and output path management in CoreUtils and DependencyGraphGenerator
1 parent 22ddad3 commit b7740ac

10 files changed

Lines changed: 157 additions & 117 deletions

CodeLineCounter.Tests/CoreUtilsTests.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,13 +130,10 @@ public void ParseArguments_handles_invalid_format_option()
130130
Console.SetOut(sw);
131131
result = CoreUtils.ParseArguments(args);
132132
sortieConsole = sw.ToString();
133+
Assert.Equal(CoreUtils.ExportFormat.CSV, result.Format);
134+
Assert.Contains("Invalid format", sortieConsole.ToString());
133135
}
134136

135-
// Assert
136-
Assert.Equal(CoreUtils.ExportFormat.CSV, result.Format);
137-
Assert.Contains("Invalid format", sortieConsole.ToString());
138-
139-
140137
}
141138

142139
[Fact]

CodeLineCounter.Tests/DataExporterTests.cs

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,13 @@ public void Export_SingleItem_CreatesFileWithCorrectExtension(CoreUtils.ExportFo
2323
Console.SetOut(sw);
2424
// Arrange
2525
var testItem = new TestClass { Id = 1, Name = "Test" };
26-
var filePath = Path.Combine(_testDirectory, "test");
26+
var filePath = "test";
2727

2828
// Act
29-
DataExporter.Export(filePath, testItem, format);
29+
DataExporter.Export(filePath, _testDirectory, testItem, format);
3030

3131
// Assert
32-
Assert.True(File.Exists(filePath + expectedExtension));
32+
Assert.True(File.Exists(Path.Combine(_testDirectory, filePath + expectedExtension)));
3333
}
3434

3535
[Theory]
@@ -48,7 +48,7 @@ public void ExportCollection_WithMultipleItems_CreatesFile(CoreUtils.ExportForma
4848
var filePath = Path.Combine(_testDirectory, "collection");
4949

5050
// Act
51-
DataExporter.ExportCollection(filePath, items, format);
51+
DataExporter.ExportCollection(filePath, _testDirectory, items, format);
5252

5353
// Assert
5454
Assert.True(File.Exists(filePath + expectedExtension));
@@ -71,10 +71,19 @@ public void ExportMetrics_CreatesFileWithCorrectData()
7171
{ "Project2", 200 }
7272
};
7373
var duplications = new List<DuplicationCode>();
74-
var filePath = Path.Combine(_testDirectory, "metrics");
74+
var filePath = "metrics";
75+
AnalysisResult result = new AnalysisResult
76+
{
77+
Metrics = metrics,
78+
ProjectTotals = projectTotals,
79+
DuplicationMap = duplications,
80+
DependencyList = new List<DependencyRelation>(),
81+
TotalLines = 300,
82+
SolutionFileName = "TestSolution"
83+
};
7584

7685
// Act
77-
DataExporter.ExportMetrics(filePath, metrics, projectTotals, 300, duplications, ".", CoreUtils.ExportFormat.CSV);
86+
DataExporter.ExportMetrics(filePath, _testDirectory, result, ".",CoreUtils.ExportFormat.CSV);
7887

7988
// Assert
8089
Assert.True(File.Exists(filePath + ".csv"));
@@ -91,10 +100,10 @@ public void ExportDuplications_CreatesFileWithCorrectData()
91100
new() { CodeHash = "hash1", FilePath = "file1.cs", MethodName = "method1", StartLine = 10, NbLines = 20 },
92101
new() { CodeHash = "hash2", FilePath = "file2.cs", MethodName = "method2", StartLine = 8, NbLines = 10 }
93102
};
94-
var filePath = Path.Combine(_testDirectory, "duplications");
103+
var filePath = "duplications";
95104

96105
// Act
97-
DataExporter.ExportDuplications(filePath, duplications, CoreUtils.ExportFormat.CSV);
106+
DataExporter.ExportDuplications(filePath, _testDirectory, duplications, CoreUtils.ExportFormat.CSV);
98107

99108
// Assert
100109
Assert.True(File.Exists(filePath + ".csv"));
@@ -246,14 +255,14 @@ public async Task export_dependencies_creates_files_in_correct_formats()
246255
new DependencyRelation { SourceClass = "ClassA", SourceNamespace = "NamespaceA", SourceAssembly = "AssemblyA", TargetClass = "ClassB", TargetNamespace = "NamespaceB", TargetAssembly = "AssemblyB", FilePath = "file1.cs", StartLine = 10 },
247256
};
248257

249-
var testFilePath = Path.Combine(Path.GetFullPath("."),"test_export.dot");
258+
var testFilePath = "test_export.dot";
250259
var format = CoreUtils.ExportFormat.JSON;
251260

252261
// Act
253-
await DataExporter.ExportDependencies(testFilePath, dependencies, format);
262+
await DataExporter.ExportDependencies(testFilePath, _testDirectory, dependencies, format);
254263

255264
// Assert
256-
string expectedJsonPath = CoreUtils.GetExportFileNameWithExtension(testFilePath, format);
265+
string expectedJsonPath = Path.Combine(_testDirectory, CoreUtils.GetExportFileNameWithExtension(testFilePath, format));
257266
string expectedDotPath = Path.ChangeExtension(expectedJsonPath, ".dot");
258267

259268
Assert.True(File.Exists(expectedJsonPath));
@@ -285,17 +294,20 @@ public async Task export_dependencies_creates_files_in_correct_formats()
285294
[Fact]
286295
public void export_collection_throws_when_filepath_null()
287296
{
288-
using var sw = new StringWriter();
289-
Console.SetOut(sw);
290-
// Arrange
291-
string? filePath = null;
292-
var testData = new List<TestClass> { new TestClass { Id = 1, Name = "Test" } };
293-
var format = CoreUtils.ExportFormat.CSV;
294-
295-
// Act & Assert
296-
var exception = Assert.Throws<ArgumentException>(() =>
297-
DataExporter.ExportCollection(filePath, testData, format));
298-
Assert.Equal("File path cannot be null or empty (Parameter 'filePath')", exception.Message);
297+
using (var sw = new StringWriter())
298+
{
299+
Console.SetOut(sw);
300+
// Arrange
301+
string? filePath = null;
302+
var testData = new List<TestClass> { new TestClass { Id = 1, Name = "Test" } };
303+
var format = CoreUtils.ExportFormat.CSV;
304+
305+
// Act & Assert
306+
var exception = Assert.Throws<ArgumentException>(() =>
307+
DataExporter.ExportCollection(filePath, _testDirectory, testData, format));
308+
Assert.Contains("File path cannot be null or empty", exception.Message);
309+
}
310+
299311
}
300312

301313
protected virtual void Dispose(bool disposing)

CodeLineCounter.Tests/DependencyGraphGeneratorTests.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,15 @@ public async Task generate_graph_with_valid_dependencies_creates_dot_file()
2929
new DependencyRelation { SourceClass = "ClassB", SourceNamespace = "NamespaceB", SourceAssembly = "AssemblyB", TargetClass = "ClassC", TargetNamespace = "NamespaceB", TargetAssembly = "AssemblyB", FilePath = "path/to/file", StartLine = 1}
3030
};
3131

32-
string outputPath = Path.Combine(_testDirectory, "test_graph.dot");
32+
string fileName = "test_graph.dot";
33+
34+
string outputPath = Path.Combine(_testDirectory, fileName);
3335

3436
// Act
3537

3638
DotGraph graph = DependencyGraphGenerator.GenerateGraphOnly(dependencies);
3739
Directory.CreateDirectory(_testDirectory);
38-
await DependencyGraphGenerator.CompileGraphAndWriteToFile(outputPath, graph);
40+
await DependencyGraphGenerator.CompileGraphAndWriteToFile(fileName,_testDirectory, graph);
3941

4042
// Assert
4143
Assert.True(File.Exists(outputPath));
@@ -56,11 +58,12 @@ public async Task generate_graph_with_empty_dependencies_creates_empty_graph()
5658

5759
// Arrange
5860
var dependencies = new List<DependencyRelation>();
59-
string outputPath = Path.Combine(_testDirectory, "empty_graph.dot");
61+
string filename = "empty_graph.dot";
62+
string outputPath = Path.Combine(_testDirectory, filename);
6063

6164
// Act
6265
DotGraph graph = DependencyGraphGenerator.GenerateGraphOnly(dependencies);
63-
await DependencyGraphGenerator.CompileGraphAndWriteToFile(outputPath, graph);
66+
await DependencyGraphGenerator.CompileGraphAndWriteToFile(filename, _testDirectory, graph);
6467

6568
// Assert
6669
Assert.True(File.Exists(outputPath));

CodeLineCounter.Tests/JsonHandlerTests.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ public TestClass(int id, string name)
3030
[Fact]
3131
public void deserialize_valid_json_file_returns_expected_objects()
3232
{
33-
using StringWriter consoleOutput = new();
34-
Console.SetOut(consoleOutput);
33+
using (StringWriter consoleOutput = new()){
34+
Console.SetOut(consoleOutput);
3535

3636
// Arrange
3737
var testFilePath = Path.Combine(_testDirectory, "test.json");
@@ -47,6 +47,9 @@ public void deserialize_valid_json_file_returns_expected_objects()
4747
Assert.Equal(expectedData[0].Name, result.First().Name);
4848

4949
File.Delete(testFilePath);
50+
51+
}
52+
5053
}
5154

5255
protected virtual void Dispose(bool disposing)

CodeLineCounter.Tests/SolutionAnalyzerTests.cs

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,37 +20,44 @@ public SolutionAnalyzerTest()
2020
public void analyze_and_export_solution_succeeds_with_valid_inputs()
2121
{
2222
// Arrange
23-
using var sw = new StringWriter();
24-
Console.SetOut(sw);
2523
var basePath = FileUtils.GetBasePath();
2624
var solutionPath = Path.GetFullPath(Path.Combine(basePath, "..", "..", "..", ".."));
2725
solutionPath = Path.Combine(solutionPath, "CodeLineCounter.sln");
28-
26+
2927
var verbose = false;
3028
var format = CoreUtils.ExportFormat.JSON;
3129

3230
// Act & Assert
33-
var exception = Record.Exception(() =>
31+
using (var sw = new StringWriter())
32+
{
33+
Console.SetOut(sw);
34+
var exception = Record.Exception(() =>
3435
SolutionAnalyzer.AnalyzeAndExportSolution(solutionPath, verbose, format));
3536

36-
Assert.Null(exception);
37+
Assert.Null(exception);
38+
}
3739
}
3840

3941
[Fact]
4042
public void analyze_and_export_solution_throws_on_invalid_path()
4143
{
4244
// Arrange
43-
using var sw = new StringWriter();
44-
Console.SetOut(sw);
45+
4546
var invalidPath = "";
4647
var verbose = false;
4748
var format = CoreUtils.ExportFormat.JSON;
4849

4950
// Act & Assert
50-
var exception = Assert.Throws<UnauthorizedAccessException>(() =>
51+
using (var sw = new StringWriter())
52+
{
53+
Console.SetOut(sw);
54+
var exception = Assert.Throws<UnauthorizedAccessException>(() =>
5155
SolutionAnalyzer.AnalyzeAndExportSolution(invalidPath, verbose, format));
5256

53-
Assert.Contains("Access to the path '' is denied.", exception.Message);
57+
Assert.Contains("Access to the path '' is denied.", exception.Message);
58+
59+
}
60+
5461
}
5562

5663
[Fact]
@@ -60,19 +67,23 @@ public void PerformAnalysis_ShouldReturnCorrectAnalysisResult()
6067
var basePath = FileUtils.GetBasePath();
6168
var solutionPath = Path.GetFullPath(Path.Combine(basePath, "..", "..", "..", ".."));
6269
solutionPath = Path.Combine(solutionPath, "CodeLineCounter.sln");
63-
using var sw = new StringWriter();
64-
Console.SetOut(sw);
65-
Console.WriteLine($"Constructed solution path: {solutionPath}");
66-
Assert.True(File.Exists(solutionPath), $"The solution file '{solutionPath}' does not exist.");
67-
Console.WriteLine($"Constructed solution path: {solutionPath}");
68-
Assert.True(File.Exists(solutionPath), $"The solution file '{solutionPath}' does not exist.");
70+
using (var sw = new StringWriter())
71+
{
72+
Console.SetOut(sw);
73+
Console.WriteLine($"Constructed solution path: {solutionPath}");
74+
Assert.True(File.Exists(solutionPath), $"The solution file '{solutionPath}' does not exist.");
75+
Console.WriteLine($"Constructed solution path: {solutionPath}");
76+
Assert.True(File.Exists(solutionPath), $"The solution file '{solutionPath}' does not exist.");
6977

70-
// Act
71-
var result = SolutionAnalyzer.PerformAnalysis(solutionPath);
78+
// Act
79+
var result = SolutionAnalyzer.PerformAnalysis(solutionPath);
80+
81+
// Assert
82+
Assert.NotNull(result);
83+
Assert.Equal("CodeLineCounter.sln", result.SolutionFileName);
84+
85+
}
7286

73-
// Assert
74-
Assert.NotNull(result);
75-
Assert.Equal("CodeLineCounter.sln", result.SolutionFileName);
7687
}
7788

7889
[Fact]
@@ -188,12 +199,13 @@ public void export_results_with_valid_input_exports_all_files()
188199
{
189200
Console.SetOut(sw);
190201
SolutionAnalyzer.ExportResults(result, solutionPath, format);
202+
// Assert
203+
Assert.True(File.Exists("TestSolution-CodeMetrics.csv"));
204+
Assert.True(File.Exists("TestSolution-CodeDuplications.csv"));
205+
Assert.True(File.Exists("TestSolution-CodeDependencies.csv"));
191206
}
192207

193-
// Assert
194-
Assert.True(File.Exists("TestSolution-CodeMetrics.csv"));
195-
Assert.True(File.Exists("TestSolution-CodeDuplications.csv"));
196-
Assert.True(File.Exists("TestSolution-CodeDependencies.csv"));
208+
197209
}
198210

199211
protected virtual void Dispose(bool disposing)

CodeLineCounter/Services/DependencyGraphGenerator.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ private static void GroupByNamespace(Dictionary<string, (int incoming, int outgo
163163
}
164164
}
165165

166-
public static async Task CompileGraphAndWriteToFile(string outputPath, DotGraph graph)
166+
public static async Task CompileGraphAndWriteToFile(string fileName,string outputPath, DotGraph graph)
167167
{
168168
// Use memory buffer
169169
using var memoryStream = new MemoryStream();
@@ -178,7 +178,7 @@ public static async Task CompileGraphAndWriteToFile(string outputPath, DotGraph
178178
await writer.FlushAsync(); // Ensure all data is written to memory
179179

180180
memoryStream.Position = 0; // Reset position to start
181-
using var fileStream = File.Create(outputPath);
181+
using var fileStream = File.Create(Path.Combine(outputPath, fileName));
182182
await memoryStream.CopyToAsync(fileStream); // Write complete buffer to file
183183
}
184184

@@ -223,6 +223,5 @@ public static string RemoveQuotes(string str)
223223
{
224224
return str.Replace("\"", "");
225225
}
226-
227226
}
228227
}

CodeLineCounter/Services/SolutionAnalyzer.cs

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,22 @@ public static void ExportResults(AnalysisResult result, string solutionPath, Cor
7171

7272
// Export metrics
7373
string metricsFileName = $"{baseFileName}-CodeMetrics";
74-
string metricsOutputPath = CoreUtils.GetExportFileNameWithExtension(metricsFileName, format, outputPath);
74+
metricsFileName = CoreUtils.GetExportFileNameWithExtension(metricsFileName, format);
75+
if (string.IsNullOrEmpty(outputPath))
76+
{
77+
outputPath = ".";
78+
}
79+
80+
string metricsOutputPath = outputPath != null
81+
? Path.Combine(outputPath, metricsFileName)
82+
: metricsFileName;
7583

7684
// Export duplications
7785
string duplicationsFileName = $"{baseFileName}-CodeDuplication";
78-
string duplicationsOutputPath = CoreUtils.GetExportFileNameWithExtension(duplicationsFileName, format, outputPath);
86+
duplicationsFileName = CoreUtils.GetExportFileNameWithExtension(duplicationsFileName, format);
87+
string duplicationsOutputPath = outputPath != null
88+
? Path.Combine(outputPath, duplicationsFileName)
89+
: duplicationsFileName;
7990
// Export des duplications...
8091

8192
// Export dependencies graph
@@ -88,19 +99,19 @@ public static void ExportResults(AnalysisResult result, string solutionPath, Cor
8899
{
89100
Parallel.Invoke(
90101
() => DataExporter.ExportMetrics(
91-
metricsOutputPath,
92-
result.Metrics,
93-
result.ProjectTotals,
94-
result.TotalLines,
95-
result.DuplicationMap,
102+
metricsFileName,
103+
outputPath ??".",
104+
result,
96105
solutionPath,
97106
format),
98107
() => DataExporter.ExportDuplications(
99-
duplicationsOutputPath,
108+
duplicationsFileName,
109+
outputPath ?? ".",
100110
result.DuplicationMap,
101111
format),
102112
async () => await DataExporter.ExportDependencies(
103-
graphOutputPath,
113+
graphFileName,
114+
outputPath ?? ".",
104115
result.DependencyList,
105116
format)
106117
);

CodeLineCounter/Utils/CoreUtils.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,13 +138,14 @@ public static void DisplaySolutions(List<string> solutionFiles)
138138
}
139139
}
140140

141-
public static string GetExportFileNameWithExtension(string filePath, ExportFormat format, string? outputPath = null)
141+
public static string GetExportFileNameWithExtension(string filePath, ExportFormat format)
142142
{
143-
string fileName = Path.GetFileName(filePath);
144143
if (filePath == null)
145144
{
146-
filePath = ".";
145+
filePath = "export.";
147146
}
147+
string fileName = Path.GetFileName(filePath);
148+
148149
string newExtension = format switch
149150
{
150151
ExportFormat.CSV => ".csv",
@@ -172,9 +173,7 @@ public static string GetExportFileNameWithExtension(string filePath, ExportForma
172173
}
173174

174175
// If an output directory is specified, combine the path
175-
return outputPath != null
176-
? Path.Combine(Path.GetFullPath(outputPath), fileName)
177-
: Path.Combine(Path.GetDirectoryName(filePath) ?? Path.GetFullPath("."), fileName);
176+
return fileName;
178177
}
179178
}
180179
}

0 commit comments

Comments
 (0)