-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
221 lines (198 loc) · 9.31 KB
/
Program.cs
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
using System.Xml.XPath;
using System.Xml.Linq;
using System.Xml.Xsl;
using System.Linq;
using System.Xml;
using System.IO;
using System;
using System.Text;
namespace dotnet_sort
{
class Program
{
static void Main(string[] args)
{
if (args.Contains("-h") || args.Contains("--help"))
{
WriteHelp();
return;
}
try
{
var options = ParseArgs(args);
Console.WriteLine(options);
var codeFiles = new string[] { };
var projectFiles = new string[] { };
if (options.To == ApplyEnum.IMPORTS || options.To == ApplyEnum.REFERENCES_IMPORTS)
codeFiles = options.PathIsFile ? new[] { options.Path } : Directory.GetFiles(options.Path, "*.cs", SearchOption.AllDirectories);
if (options.To == ApplyEnum.REFERENCES || options.To == ApplyEnum.REFERENCES_IMPORTS)
projectFiles = options.PathIsFile ? new[] { options.Path } : Directory.GetFiles(options.Path, "*.csproj", SearchOption.AllDirectories);
foreach (var codeFile in codeFiles)
{
SortImports(codeFile, options.Sort);
}
var xslt = GetCompiledTransform(options.Sort);
foreach (var projectFile in projectFiles)
{
SortReferences(projectFile, xslt);
}
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message + "\n");
WriteHelp();
}
}
private static XslCompiledTransform GetCompiledTransform(SortEnum sort)
{
string xsltFile = "";
switch (sort)
{
case SortEnum.ALPHABETICALLY_ASCENDING: xsltFile = "Sort-a.xsl"; break;
case SortEnum.ALPHABETICALLY_DESCENDENTLY: xsltFile = "Sort-ad.xsl"; break;
case SortEnum.LENGTH_ASCENDING: xsltFile = "Sort-l.xsl"; break;
case SortEnum.LENGTH_DESCENDENTLY: xsltFile = "Sort-ld.xsl"; break;
}
var xslt = new XslCompiledTransform();
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("dotnet_sort." + xsltFile))
{
using (var reader = XmlReader.Create(stream))
{
xslt.Load(reader);
return xslt;
}
}
}
private static void SortReferences(string filePath, XslCompiledTransform xslt)
{
Console.Write($"Sorting.. {filePath}");
using (StringWriter sw = new StringWriter())
{
var doc = XDocument.Parse(System.IO.File.ReadAllText(filePath));
xslt.Transform(doc.CreateNavigator(), null, sw);
File.WriteAllText(filePath, sw.ToString());
}
Console.WriteLine("\t done");
}
private static void SortImports(string filePath, SortEnum sort)
{
Console.Write($"Sorting.. {filePath}");
var file = new StreamReader(filePath, Encoding.UTF8);
var linesToSort = new List<string>();
var restOfFile = "";
string line;
string pattern = @"^using.*;";
while ((line = file.ReadLine()) != null && Regex.Match(line, pattern).Success)
{
linesToSort.Add(line);
}
if(linesToSort.Count == 0) {
Console.WriteLine("\t not necessary");
return;
}
restOfFile = line + "\r\n" + file.ReadToEnd();
file.Close();
switch (sort)
{
case SortEnum.ALPHABETICALLY_ASCENDING:
linesToSort = linesToSort.OrderBy(x => x).ToList(); break;
case SortEnum.ALPHABETICALLY_DESCENDENTLY:
linesToSort = linesToSort.OrderByDescending(x => x).ToList(); break;
case SortEnum.LENGTH_ASCENDING:
linesToSort = linesToSort.OrderBy(x => x.Length).ToList(); break;
case SortEnum.LENGTH_DESCENDENTLY:
linesToSort = linesToSort.OrderByDescending(x => x.Length).ToList(); break;
}
//Write lines
using (StreamWriter writer = new System.IO.StreamWriter(filePath, false, Encoding.UTF8))
{
foreach (var strLine in linesToSort)
writer.WriteLine(strLine);
writer.Write(restOfFile);
writer.Close();
}
Console.WriteLine("\t done");
}
private static Apply ParseArgs(string[] args)
{
var validOptions = new[] { "-p", "--path", "-s", "-a" };
var options = new Apply();
foreach (var argItem in args)
{
var kv = argItem.Split("=");
if (!validOptions.Contains(kv[0])) throw new ArgumentException($"Unknown option {argItem}");
if (kv.Count() != 2) continue;
switch (kv[0])
{
case "-p":
case "--path":
options.Path = kv[1];
break;
case "-a":
switch (kv[1])
{
case "r": options.To = ApplyEnum.REFERENCES; break;
case "i": options.To = ApplyEnum.IMPORTS; break;
case "ri":
case "ir": options.To = ApplyEnum.REFERENCES_IMPORTS; break;
default: throw new ArgumentException($"Unknown value to option -a={kv[1]}");
}
break;
case "-s":
switch (kv[1])
{
case "a": options.Sort = SortEnum.ALPHABETICALLY_ASCENDING; break;
case "ad": options.Sort = SortEnum.ALPHABETICALLY_DESCENDENTLY; break;
case "l": options.Sort = SortEnum.LENGTH_ASCENDING; break;
case "ld": options.Sort = SortEnum.LENGTH_DESCENDENTLY; break;
default: throw new ArgumentException($"Unknown value to option -l={kv[1]}");
}
break;
}
}
options.Path = Path.GetFullPath(options.Path);
var isFile = File.Exists(options.Path);
var isDirectory = Directory.Exists(options.Path);
if (isFile && options.To == ApplyEnum.REFERENCES && !Path.GetExtension(options.Path).Equals(".csproj", StringComparison.OrdinalIgnoreCase))
throw new ArgumentException($"Only accept *.csproj files, actual {options.Path}.");
if (!isFile && !isDirectory)
throw new ArgumentException($"The path {options.Path} not found.");
if (isFile && options.To == ApplyEnum.REFERENCES_IMPORTS)
throw new ArgumentException($"The path {options.Path} is a file, expected directory.");
options.PathIsFile = isFile;
return options;
}
private static void WriteHelp()
{
var versionString = Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion
.ToString();
Console.WriteLine($"dotnet-sort v{versionString}");
Console.WriteLine("A global .NET Core tool for ordering alphabetically, length, the references of packages or imports in your .NET Core and .NET Standard projects.");
Console.WriteLine("");
Console.WriteLine("Usage:");
Console.WriteLine(" dotnet-sort [options]");
Console.WriteLine("");
Console.WriteLine("Options:");
Console.WriteLine(" -h, --help Show command line help.");
Console.WriteLine(" -p, --path Path where found the *.csproj or *.cs files (defaults to the current directory).");
Console.WriteLine(" -a <APPLY> Apply to references or imports.");
Console.WriteLine(" Examples:");
Console.WriteLine(" Sorting only references on *.csproj: -a=r");
Console.WriteLine(" Sorting only imports on *.cs: -a=i");
Console.WriteLine(" Sorting references and imports on *.cs: -a=ri");
Console.WriteLine("");
Console.WriteLine(" -s <MODE> Sort by length/alphabetically");
Console.WriteLine(" Examples:");
Console.WriteLine(" alphabetically ascending (default): -s=a");
Console.WriteLine(" alphabetically descendently: -s=ad");
Console.WriteLine(" length ascending: -s=l");
Console.WriteLine(" length descendently: -s=ld");
}
}
}