-
Notifications
You must be signed in to change notification settings - Fork 15
/
EnsureOrderAndIndent.java
394 lines (365 loc) · 15.1 KB
/
EnsureOrderAndIndent.java
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package org.codehaus.mojo.tidy.task;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.asList;
import static java.util.Arrays.fill;
import static org.codehaus.mojo.tidy.task.XMLEventReaderFactory.createEventReaderForPom;
import static org.codehaus.plexus.util.StringUtils.countMatches;
import static org.codehaus.plexus.util.StringUtils.isWhitespace;
import static org.codehaus.plexus.util.StringUtils.repeat;
class EnsureOrderAndIndent
implements TidyTask
{
private static final List<SectionSorter> SECTION_SORTERS = asList(
new SectionSorter( "/project", new NodeGroup( "modelVersion" ), new NodeGroup( "parent" ),
new NodeGroup( "groupId", "artifactId", "version", "packaging" ),
new NodeGroup( "name", "description", "url", "inceptionYear", "organization", "licenses" ),
new NodeGroup( "developers", "contributors" ), new NodeGroup( "mailingLists" ),
new NodeGroup( "prerequisites" ), new NodeGroup( "modules" ),
new NodeGroup( "scm", "issueManagement", "ciManagement", "distributionManagement" ),
new NodeGroup( "properties" ), new NodeGroup( "dependencyManagement", "dependencies" ),
new NodeGroup( "repositories", "pluginRepositories" ), new NodeGroup( "build" ),
new NodeGroup( "reporting" ), new NodeGroup( "profiles" ) ),
new SectionSorter( "/project/build", new NodeGroup( "defaultGoal", "sourceDirectory", "scriptSourceDirectory",
"testSourceDirectory", "directory", "outputDirectory",
"testOutputDirectory", "finalName", "filters", "resources",
"testResources", "pluginManagement", "plugins",
"extensions" ) ),
new SectionSorter( "dependency", new NodeGroup( "groupId", "artifactId", "version", "type", "classifier",
"scope", "systemPath", "exclusions", "optional" ) ),
new SectionSorter( "dependency/exclusions/exclusion", new NodeGroup( "groupId", "artifactId" ) ),
new SectionSorter( "build/extensions/extension", new NodeGroup( "groupId", "artifactId", "version" ) ),
new SectionSorter( "/project/parent", new NodeGroup( "groupId", "artifactId", "version", "relativePath" ) ),
new SectionSorter( "plugin", new NodeGroup( "groupId", "artifactId", "version" ) ),
new SectionSorter( "/project/distributionManagement/relocation", new NodeGroup( "groupId", "artifactId", "version" ) ) );
@Override
public String tidyPom( String pom, Format format )
throws XMLStreamException
{
for ( SectionSorter sorter : SECTION_SORTERS )
{
pom = sorter.sortSections( pom, format );
}
return pom;
}
private static class SectionSorter
{
final String scope;
final NodeGroup[] groups;
final List<String> sequence;
SectionSorter( String scope, NodeGroup... groups )
{
this.scope = scope;
this.groups = groups;
this.sequence = calculateSequence( groups );
}
List<String> calculateSequence( NodeGroup[] groups )
{
List<String> sequence = new ArrayList<String>();
for ( NodeGroup group : groups )
{
sequence.addAll( group.nodes );
}
return sequence;
}
String sortSections( String pom, Format format )
throws XMLStreamException
{
XMLEventReader reader = createEventReaderForPom( pom );
String path = "";
int posFirstUnformatted = 0;
StringBuilder tidyPom = new StringBuilder();
while ( reader.hasNext() )
{
XMLEvent event = reader.nextEvent();
if ( event.isStartElement() )
{
path += "/" + event.asStartElement().getName().getLocalPart();
if ( isStartElementOfScope( path ) )
{
int pos = getPosOfNextEvent( reader );
tidyPom.append( pom.substring( posFirstUnformatted, pos ) );
tidyPom.append( formatSection( reader, pom, format ) );
posFirstUnformatted = getPosOfNextEvent( reader );
}
}
else if ( event.isEndElement() )
{
path = substringBeforeLast( path, "/" );
}
}
tidyPom.append( pom.substring( posFirstUnformatted ) );
return tidyPom.toString();
}
private boolean isStartElementOfScope( String path )
{
if ( scope.startsWith( "/" ) )
{
return path.equals( scope );
}
else
{
return path.endsWith( scope );
}
}
private String formatSection( XMLEventReader reader, String pom, Format format )
throws XMLStreamException
{
int startOfSection = getPosOfNextEvent( reader );
int[] starts = new int[sequence.size()];
int[] ends = new int[sequence.size()];
XMLEvent endScope = calculateStartsAndEnds( reader, starts, ends );
return formatSection( reader, pom, format, startOfSection, starts, ends, endScope );
}
private XMLEvent calculateStartsAndEnds( XMLEventReader reader, int[] starts, int[] ends )
throws XMLStreamException
{
fill( starts, Integer.MAX_VALUE );
fill( ends, -1 );
int level = 0;
while ( reader.hasNext() )
{
XMLEvent event = reader.nextEvent();
if ( event.isStartElement() )
{
++level;
if ( level == 1 )
{
QName name = event.asStartElement().getName();
if ( hasToBeSorted( name ) )
{
int i = getSequenceIndex( name );
starts[i] = event.getLocation().getCharacterOffset();
}
}
}
else if ( event.isEndElement() )
{
if ( level == 0 )
{
return event;
}
else if ( level == 1 )
{
QName name = event.asEndElement().getName();
if ( hasToBeSorted( name ) )
{
int i = getSequenceIndex( name );
ends[i] = getPosOfNextEvent( reader );
}
}
--level;
}
}
throw new RuntimeException( "End element missing." );
}
private boolean hasToBeSorted( QName nodeName )
{
String name = nodeName.getLocalPart();
return sequence.contains( name );
}
private int getSequenceIndex( QName nodeName )
{
String name = nodeName.getLocalPart();
if ( sequence.contains( name ) )
{
return sequence.indexOf( name );
}
else
{
throw new IllegalArgumentException(
"The path '" + nodeName + " does not specify an element of the sequence " + sequence
+ "." );
}
}
private String formatSection( XMLEventReader reader, String pom, Format format, int startOfSection,
int[] starts, int[] ends, XMLEvent endScope )
throws XMLStreamException
{
String outdent = calculateOutdent( pom, endScope );
String indent = calculateIndent( pom, starts );
int first = calculateFirst( starts, pom );
StringBuilder output = new StringBuilder();
output.append( pom.substring( startOfSection, first ).trim() );
int i = 0;
boolean firstGroupStarted = false;
for ( NodeGroup group : groups )
{
boolean groupStarted = false;
for ( String node : group.nodes )
{
if ( starts[i] != Integer.MAX_VALUE )
{
if ( firstGroupStarted && !groupStarted )
{
output.append( format.getLineSeparator() );
}
addTextIfNotEmpty( output, indent, getPrecedingText( pom, starts[i], ends ), format );
addTextIfNotEmpty( output, indent, pom.substring( starts[i], ends[i] ), format );
firstGroupStarted = groupStarted = true;
}
++i;
}
}
int last = calculateLast( ends );
int afterSection = getPosOfNextEvent( reader );
int offsetEndElement = endScope.getLocation().getCharacterOffset();
addTextIfNotEmpty( output, indent, pom.substring( last, offsetEndElement ), format );
addTextIfNotEmpty( output, outdent, pom.substring( offsetEndElement, afterSection ), format );
return output.toString();
}
private String calculateOutdent( String pom, XMLEvent endScope )
{
String before = pom.substring( 0, endScope.getLocation().getCharacterOffset() );
return substringAfterLast( before, "\n" );
}
private int calculateFirst( int[] starts, String pom )
{
int first = pom.length();
for ( int start : starts )
{
first = min( first, start );
}
return first;
}
private int calculateLast( int[] ends )
{
int last = 0;
for ( int end : ends )
{
last = max( last, end );
}
return last;
}
private String calculateIndent( String input, int[] starts )
{
int numNodesWithSpaceIndent = 0;
int numNodesWithTabIndent = 0;
int spaceIndentTotal = 0;
int tabIndentTotal = 0;
for ( int start : starts )
{
if ( start != Integer.MAX_VALUE )
{
String indent = calculateIndent( input, start );
if ( !indent.isEmpty() )
{
int numTabs = countMatches( indent, "\t" );
if ( numTabs == indent.length() )
{
++numNodesWithTabIndent;
tabIndentTotal += numTabs;
}
else if ( !indent.contains( "\t" ) )
{
++numNodesWithSpaceIndent;
spaceIndentTotal += indent.length();
}
}
}
}
if ( numNodesWithSpaceIndent == 0 && numNodesWithTabIndent == 0 )
{
return " ";
}
else if ( numNodesWithSpaceIndent > numNodesWithTabIndent )
{
int averageIndent = spaceIndentTotal / numNodesWithSpaceIndent;
return repeat( " ", averageIndent );
}
else
{
int averageIndent = tabIndentTotal / numNodesWithTabIndent;
return repeat( "\t", averageIndent );
}
}
private String calculateIndent( String input, int startOfTag )
{
for ( int i = startOfTag; i > 1; --i )
{
String character = input.substring( i - 1, i );
if ( !isWhitespace( character ) || "\n".equals( character ) || "\r".equals( character ) )
{
return input.substring( i, startOfTag );
}
}
return input;
}
private String getPrecedingText( String pom, int start, int[] ends )
{
int startPrecedingText = -1;
for ( int end : ends )
{
if ( end < start )
{
startPrecedingText = max( startPrecedingText, end );
}
}
if ( startPrecedingText != -1 )
{
return pom.substring( startPrecedingText, start );
}
else
{
return "";
}
}
private void addTextIfNotEmpty( StringBuilder output, String indent, String text, Format format )
{
String trimmedText = text.trim();
if ( trimmedText.length() != 0 )
{
output.append( format.getLineSeparator() );
output.append( indent );
output.append( trimmedText );
}
}
private int getPosOfNextEvent( XMLEventReader reader )
throws XMLStreamException
{
return reader.peek().getLocation().getCharacterOffset();
}
private String substringBeforeLast( String str, String separator )
{
int endIndex = str.lastIndexOf( separator );
return str.substring( 0, endIndex );
}
private String substringAfterLast( String str, String separator )
{
int beginIndex = str.lastIndexOf( separator ) + 1;
return str.substring( beginIndex );
}
}
private static class NodeGroup
{
final List<String> nodes;
NodeGroup( String... nodes )
{
this.nodes = asList( nodes );
}
}
}