-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathProgram.GenerateCodeDispatcher.cs
More file actions
76 lines (64 loc) · 3.23 KB
/
Program.GenerateCodeDispatcher.cs
File metadata and controls
76 lines (64 loc) · 3.23 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Alba.CsConsoleFormat.Fluent;
using Xml.Schema.Linq.Extensions;
namespace LinqToXsd
{
public static partial class Program
{
/// <summary>
/// Handles the logic for generating code.
/// </summary>
internal static class GenerateCodeDispatcher
{
/// <summary>
/// Writes generated code for to multiple output files, inferred by <see cref="GenerateOptions.Output"/>.
/// </summary>
internal static void HandleWriteOutputToMultipleFiles(GenerateOptions options, Dictionary<string, string> codeUnits)
{
var possibleOutputFolder = options.Output;
PrintLn($"Outputting {codeUnits.Count} files...".Gray());
foreach (var kvp in codeUnits)
{
var outputFilename = Path.GetFileName(kvp.Key);
if (!outputFilename.EndsWith(".cs"))
outputFilename += ".cs";
string outputFilePath = possibleOutputFolder == "-1"
? Path.Combine(Path.GetDirectoryName(kvp.Key), outputFilename)
: possibleOutputFolder.IsNotEmpty()
? Path.Combine(possibleOutputFolder, outputFilename)
: Path.GetFullPath(outputFilename);
var fullPathOfContainingDir = Path.GetDirectoryName(outputFilePath);
if (!Directory.Exists(fullPathOfContainingDir))
{
PrintLn($"Creating directory: {fullPathOfContainingDir}".Yellow());
Directory.CreateDirectory(fullPathOfContainingDir);
}
PrintLn($"{kvp.Key} => {outputFilePath}".Gray());
using var outputFileStream = File.Open(outputFilePath, FileMode.Create, FileAccess.ReadWrite);
using var fileWriter = new StreamWriter(outputFileStream);
fileWriter.Write(kvp.Value);
}
}
/// <summary>
/// Writes generated code to a single output file.
/// </summary>
/// <param name="options"></param>
/// <param name="textWriters"></param>
internal static void HandleWriteOutputToSingleFile(GenerateOptions options, Dictionary<string, string> codeUnits)
{
var outputFile = options.Output;
// add .cs extension to filename if it doesn't have it already.
var target = outputFile.EndsWith(".cs") ? outputFile : $"{outputFile}.cs";
var extractFileNameOnlyFunctor = new Func<string, string>(k => $"'{Path.GetFileName(k)}'");
PrintLn($"{codeUnits.Keys.ToDelimitedString(extractFileNameOnlyFunctor).Yellow()}");
PrintLn($"\toutput to \n{target}");
using var fileStream = File.Open(target, FileMode.Create, FileAccess.ReadWrite);
using var fileWriter = new StreamWriter(fileStream, Encoding.UTF8);
foreach (var kvp in codeUnits) fileWriter.Write(kvp.Value);
}
}
}
}