/
FileMetadata.java
327 lines (279 loc) · 9.34 KB
/
FileMetadata.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
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.scan.filesystem;
import com.google.common.base.Charsets;
import com.google.common.primitives.Ints;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.BatchComponent;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.AnalysisMode;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
/**
* Computes hash of files. Ends of Lines are ignored, so files with
* same content but different EOL encoding have the same hash.
*/
public class FileMetadata implements BatchComponent {
private static final Logger LOG = LoggerFactory.getLogger(FileMetadata.class);
private static final char LINE_FEED = '\n';
private static final char CARRIAGE_RETURN = '\r';
private final AnalysisMode analysisMode;
public FileMetadata(AnalysisMode analysisMode) {
this.analysisMode = analysisMode;
}
private abstract static class CharHandler {
void handleAll(char c) {
}
void handleIgnoreEoL(char c) {
}
void newLine() {
}
void eof() {
}
}
private static class LineCounter extends CharHandler {
private boolean empty = true;
private int lines = 1;
private int nonBlankLines = 0;
private boolean blankLine = true;
boolean alreadyLoggedInvalidCharacter = false;
private final File file;
private final Charset encoding;
LineCounter(File file, Charset encoding) {
this.file = file;
this.encoding = encoding;
}
@Override
void handleAll(char c) {
this.empty = false;
if (!alreadyLoggedInvalidCharacter && c == '\ufffd') {
LOG.warn("Invalid character encountered in file " + file + " at line " + lines
+ " for encoding " + encoding + ". Please fix file content or configure the encoding to be used using property '" + CoreProperties.ENCODING_PROPERTY + "'.");
alreadyLoggedInvalidCharacter = true;
}
}
@Override
void newLine() {
lines++;
if (!blankLine) {
nonBlankLines++;
}
blankLine = true;
}
@Override
void handleIgnoreEoL(char c) {
if (!Character.isWhitespace(c)) {
blankLine = false;
}
}
@Override
void eof() {
if (!blankLine) {
nonBlankLines++;
}
}
public int lines() {
return lines;
}
public int nonBlankLines() {
return nonBlankLines;
}
public boolean isEmpty() {
return empty;
}
}
private static class FileHashComputer extends CharHandler {
private MessageDigest globalMd5Digest = DigestUtils.getMd5Digest();
private StringBuilder sb = new StringBuilder();
@Override
void handleIgnoreEoL(char c) {
sb.append(c);
}
@Override
void newLine() {
sb.append(LINE_FEED);
globalMd5Digest.update(sb.toString().getBytes(Charsets.UTF_8));
sb.setLength(0);
}
@Override
void eof() {
if (sb.length() > 0) {
globalMd5Digest.update(sb.toString().getBytes(Charsets.UTF_8));
}
}
@CheckForNull
public String getHash() {
return Hex.encodeHexString(globalMd5Digest.digest());
}
}
private static class LineHashComputer extends CharHandler {
private final MessageDigest lineMd5Digest = DigestUtils.getMd5Digest();
private final StringBuilder sb = new StringBuilder();
private final LineHashConsumer consumer;
private int line = 1;
public LineHashComputer(LineHashConsumer consumer) {
this.consumer = consumer;
}
@Override
void handleIgnoreEoL(char c) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
@Override
void newLine() {
consumer.consume(line, sb.length() > 0 ? lineMd5Digest.digest(sb.toString().getBytes(Charsets.UTF_8)) : null);
sb.setLength(0);
line++;
}
@Override
void eof() {
consumer.consume(line, sb.length() > 0 ? lineMd5Digest.digest(sb.toString().getBytes(Charsets.UTF_8)) : null);
}
}
private static class LineOffsetCounter extends CharHandler {
private int currentOriginalOffset = 0;
private List<Integer> originalLineOffsets = new ArrayList<Integer>();
private int lastValidOffset = 0;
public LineOffsetCounter() {
originalLineOffsets.add(0);
}
@Override
void handleAll(char c) {
currentOriginalOffset++;
}
@Override
void newLine() {
originalLineOffsets.add(currentOriginalOffset);
}
@Override
void eof() {
lastValidOffset = currentOriginalOffset;
}
public List<Integer> getOriginalLineOffsets() {
return originalLineOffsets;
}
public int getLastValidOffset() {
return lastValidOffset;
}
}
/**
* Compute hash of a file ignoring line ends differences.
* Maximum performance is needed.
*/
Metadata read(File file, Charset encoding) {
LineCounter lineCounter = new LineCounter(file, encoding);
FileHashComputer fileHashComputer = new FileHashComputer();
LineOffsetCounter lineOffsetCounter = new LineOffsetCounter();
if (!analysisMode.isPreview()) {
scanFile(file, encoding, lineCounter, fileHashComputer, lineOffsetCounter);
} else {
// No need to compute line offsets in preview mode since there is no syntax highlighting
scanFile(file, encoding, lineCounter, fileHashComputer);
}
return new Metadata(lineCounter.lines(), lineCounter.nonBlankLines(), fileHashComputer.getHash(), lineOffsetCounter.getOriginalLineOffsets(),
lineOffsetCounter.getLastValidOffset(),
lineCounter.isEmpty());
}
private static void scanFile(File file, Charset encoding, CharHandler... handlers) {
char c = (char) 0;
try (BOMInputStream bomIn = new BOMInputStream(new FileInputStream(file),
ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
Reader reader = new BufferedReader(new InputStreamReader(bomIn, encoding))) {
int i = reader.read();
boolean afterCR = false;
while (i != -1) {
c = (char) i;
if (afterCR) {
for (CharHandler handler : handlers) {
if (c != CARRIAGE_RETURN && c != LINE_FEED) {
handler.handleIgnoreEoL(c);
}
handler.handleAll(c);
handler.newLine();
}
afterCR = c == CARRIAGE_RETURN;
} else if (c == LINE_FEED) {
for (CharHandler handler : handlers) {
handler.handleAll(c);
handler.newLine();
}
} else if (c == CARRIAGE_RETURN) {
afterCR = true;
for (CharHandler handler : handlers) {
handler.handleAll(c);
}
} else {
for (CharHandler handler : handlers) {
handler.handleIgnoreEoL(c);
handler.handleAll(c);
}
}
i = reader.read();
}
for (CharHandler handler : handlers) {
handler.eof();
}
} catch (IOException e) {
throw new IllegalStateException(String.format("Fail to read file '%s' with encoding '%s'", file.getAbsolutePath(), encoding), e);
}
}
static class Metadata {
final int lines;
final int nonBlankLines;
final String hash;
final int[] originalLineOffsets;
final int lastValidOffset;
final boolean empty;
private Metadata(int lines, int nonBlankLines, String hash, List<Integer> originalLineOffsets, int lastValidOffset, boolean empty) {
this.lines = lines;
this.nonBlankLines = nonBlankLines;
this.hash = hash;
this.empty = empty;
this.originalLineOffsets = Ints.toArray(originalLineOffsets);
this.lastValidOffset = lastValidOffset;
}
}
public static interface LineHashConsumer {
void consume(int lineIdx, @Nullable byte[] hash);
}
/**
* Compute a MD5 hash of each line of the file after removing of all blank chars
*/
public static void computeLineHashesForIssueTracking(DefaultInputFile f, LineHashConsumer consumer) {
scanFile(f.file(), f.charset(), new LineHashComputer(consumer));
}
}