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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
|
/*
* SonarQube
* Copyright (C) 2009-2025 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.api.batch.fs.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.TextRange;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
/**
* @since 4.2
* To create {@link InputFile} in tests, use TestInputFileBuilder.
*/
public class DefaultInputFile extends DefaultInputComponent implements InputFile {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private final DefaultIndexedFile indexedFile;
private final String contents;
private final Consumer<DefaultInputFile> metadataGenerator;
private final Consumer<DefaultInputFile> scmStatusGenerator;
private boolean published;
private boolean excludedForCoverage;
private boolean excludedForDuplication;
private boolean ignoreAllIssues;
// Lazy init to save memory
private BitSet noSonarLines;
private Status status;
private Charset charset;
private Metadata metadata;
private Collection<int[]> ignoreIssuesOnlineRanges;
private BitSet executableLines;
private boolean markedAsUnchanged;
public DefaultInputFile(DefaultIndexedFile indexedFile, Consumer<DefaultInputFile> metadataGenerator, Consumer<DefaultInputFile> scmStatusGenerator) {
this(indexedFile, metadataGenerator, null, scmStatusGenerator);
}
// For testing
public DefaultInputFile(DefaultIndexedFile indexedFile, Consumer<DefaultInputFile> metadataGenerator, @Nullable String contents,
Consumer<DefaultInputFile> scmStatusGenerator) {
super(indexedFile.scannerId());
this.indexedFile = indexedFile;
this.metadataGenerator = metadataGenerator;
this.scmStatusGenerator = scmStatusGenerator;
this.metadata = null;
this.markedAsUnchanged = false;
this.published = false;
this.excludedForCoverage = false;
this.contents = contents;
}
public void checkMetadata() {
if (metadata == null) {
metadataGenerator.accept(this);
}
}
private void checkScmStatus() {
if (status == null) {
scmStatusGenerator.accept(this);
}
}
@Override
public InputStream inputStream() throws IOException {
return contents != null ? new ByteArrayInputStream(contents.getBytes(charset()))
: new BOMInputStream(Files.newInputStream(path()),
ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
}
public boolean isMarkedAsUnchanged() {
return markedAsUnchanged;
}
public DefaultInputComponent setMarkedAsUnchanged(boolean markedAsUnchanged) {
this.markedAsUnchanged = markedAsUnchanged;
return this;
}
@Override
public String contents() throws IOException {
if (contents != null) {
return contents;
} else {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try (InputStream inputStream = inputStream()) {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
}
return result.toString(charset().name());
}
}
public DefaultInputFile setPublished(boolean published) {
this.published = published;
return this;
}
public boolean isPublished() {
return published;
}
public DefaultInputFile setExcludedForCoverage(boolean excludedForCoverage) {
this.excludedForCoverage = excludedForCoverage;
return this;
}
public boolean isExcludedForCoverage() {
return excludedForCoverage;
}
public DefaultInputFile setExcludedForDuplication(boolean excludedForDuplication) {
this.excludedForDuplication = excludedForDuplication;
return this;
}
public boolean isExcludedForDuplication() {
return excludedForDuplication;
}
/**
* @deprecated since 6.6
*/
@Deprecated
@Override
public String relativePath() {
return indexedFile.relativePath();
}
public String getModuleRelativePath() {
return indexedFile.getModuleRelativePath();
}
public String getProjectRelativePath() {
return indexedFile.getProjectRelativePath();
}
@Override
public String absolutePath() {
return indexedFile.absolutePath();
}
@CheckForNull
public String oldRelativePath() {
return indexedFile.oldRelativePath();
}
@Override
public File file() {
return indexedFile.file();
}
@Override
public Path path() {
return indexedFile.path();
}
@CheckForNull
@Override
public String language() {
return indexedFile.language();
}
@Override
public Type type() {
return indexedFile.type();
}
@Override
public boolean isHidden() {
return indexedFile.isHidden();
}
/**
* Component key (without branch).
*/
@Override
public String key() {
return indexedFile.key();
}
@Override
public int hashCode() {
return indexedFile.hashCode();
}
@Override
public String toString() {
return indexedFile.toString();
}
/**
* {@link #setStatus(Status)}
*/
@Override
public Status status() {
checkScmStatus();
if (status == null) {
// scm might not be available, fallback to using hashes in the metadata
checkMetadata();
}
return status;
}
public boolean isStatusSet() {
return status != null;
}
@Override
public int lines() {
checkMetadata();
return metadata.lines();
}
@Override
public boolean isEmpty() {
checkMetadata();
return metadata.isEmpty();
}
@Override
public Charset charset() {
checkMetadata();
return charset;
}
public int lastValidOffset() {
checkMetadata();
return metadata.lastValidOffset();
}
/**
* Digest hash of the file.
*/
@Override
public String md5Hash() {
checkMetadata();
return metadata.hash();
}
public int nonBlankLines() {
checkMetadata();
return metadata.nonBlankLines();
}
public int[] originalLineStartOffsets() {
checkMetadata();
checkState(metadata.originalLineStartOffsets() != null, "InputFile is not properly initialized.");
checkState(metadata.originalLineStartOffsets().length == metadata.lines(),
"InputFile is not properly initialized. 'originalLineStartOffsets' property length should be equal to 'lines'");
return metadata.originalLineStartOffsets();
}
public int[] originalLineEndOffsets() {
checkMetadata();
checkState(metadata.originalLineEndOffsets() != null, "InputFile is not properly initialized.");
checkState(metadata.originalLineEndOffsets().length == metadata.lines(),
"InputFile is not properly initialized. 'originalLineEndOffsets' property length should be equal to 'lines'");
return metadata.originalLineEndOffsets();
}
@Override
public TextPointer newPointer(int line, int lineOffset) {
checkMetadata();
DefaultTextPointer textPointer = new DefaultTextPointer(line, lineOffset);
checkValid(textPointer, "pointer");
return textPointer;
}
@Override
public TextRange newRange(TextPointer start, TextPointer end) {
checkMetadata();
checkValid(start, "start pointer");
checkValid(end, "end pointer");
return newRangeValidPointers(start, end, false);
}
@Override
public TextRange newRange(int startLine, int startLineOffset, int endLine, int endLineOffset) {
checkMetadata();
TextPointer start = newPointer(startLine, startLineOffset);
TextPointer end = newPointer(endLine, endLineOffset);
return newRangeValidPointers(start, end, false);
}
@Override
public TextRange selectLine(int line) {
checkMetadata();
TextPointer startPointer = newPointer(line, 0);
TextPointer endPointer = newPointer(line, lineLength(line));
return newRangeValidPointers(startPointer, endPointer, true);
}
public void validate(TextRange range) {
checkMetadata();
checkValid(range.start(), "start pointer");
checkValid(range.end(), "end pointer");
}
/**
* Create Range from global offsets. Used for backward compatibility with older API.
*/
public TextRange newRange(int startOffset, int endOffset) {
checkMetadata();
return newRangeValidPointers(newPointer(startOffset), newPointer(endOffset), false);
}
public TextPointer newPointer(int globalOffset) {
checkMetadata();
checkArgument(globalOffset >= 0, "%s is not a valid offset for a file", globalOffset);
checkArgument(globalOffset <= lastValidOffset(), "%s is not a valid offset for file %s. Max offset is %s", globalOffset, this, lastValidOffset());
int line = findLine(globalOffset);
int startLineOffset = originalLineStartOffsets()[line - 1];
// In case the global offset is between \r and \n, move the pointer to a valid location
return new DefaultTextPointer(line, Math.min(globalOffset, originalLineEndOffsets()[line - 1]) - startLineOffset);
}
public DefaultInputFile setStatus(Status status) {
this.status = status;
return this;
}
public DefaultInputFile setCharset(Charset charset) {
this.charset = charset;
return this;
}
private void checkValid(TextPointer pointer, String owner) {
checkArgument(pointer.line() >= 1, "%s is not a valid line for a file", pointer.line());
checkArgument(pointer.line() <= this.metadata.lines(), "%s is not a valid line for %s. File %s has %s line(s)", pointer.line(), owner, this, metadata.lines());
checkArgument(pointer.lineOffset() >= 0, "%s is not a valid line offset for a file", pointer.lineOffset());
int lineLength = lineLength(pointer.line());
checkArgument(pointer.lineOffset() <= lineLength,
"%s is not a valid line offset for %s. File %s has %s character(s) at line %s", pointer.lineOffset(), owner, this, lineLength, pointer.line());
}
public int lineLength(int line) {
return originalLineEndOffsets()[line - 1] - originalLineStartOffsets()[line - 1];
}
private static TextRange newRangeValidPointers(TextPointer start, TextPointer end, boolean acceptEmptyRange) {
checkArgument(acceptEmptyRange ? (start.compareTo(end) <= 0) : (start.compareTo(end) < 0),
"Start pointer %s should be before end pointer %s", start, end);
return new DefaultTextRange(start, end);
}
private int findLine(int globalOffset) {
return Math.abs(Arrays.binarySearch(originalLineStartOffsets(), globalOffset) + 1);
}
public DefaultInputFile setMetadata(Metadata metadata) {
this.metadata = metadata;
return this;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
DefaultInputFile that = (DefaultInputFile) obj;
return this.getProjectRelativePath().equals(that.getProjectRelativePath());
}
@Override
public boolean isFile() {
return true;
}
@Override
public String filename() {
return indexedFile.filename();
}
@Override
public URI uri() {
return indexedFile.uri();
}
public void noSonarAt(Set<Integer> noSonarLines) {
if (this.noSonarLines == null) {
this.noSonarLines = new BitSet(lines());
}
noSonarLines.forEach(l -> this.noSonarLines.set(l - 1));
}
public boolean hasNoSonarAt(int line) {
if (this.noSonarLines == null) {
return false;
}
return this.noSonarLines.get(line - 1);
}
public boolean isIgnoreAllIssues() {
checkMetadata();
return ignoreAllIssues;
}
public void setIgnoreAllIssues(boolean ignoreAllIssues) {
this.ignoreAllIssues = ignoreAllIssues;
}
public void addIgnoreIssuesOnLineRanges(Collection<int[]> lineRanges) {
if (this.ignoreIssuesOnlineRanges == null) {
this.ignoreIssuesOnlineRanges = new ArrayList<>();
}
this.ignoreIssuesOnlineRanges.addAll(lineRanges);
}
public boolean isIgnoreAllIssuesOnLine(@Nullable Integer line) {
checkMetadata();
if (line == null || ignoreIssuesOnlineRanges == null) {
return false;
}
return ignoreIssuesOnlineRanges.stream().anyMatch(r -> r[0] <= line && line <= r[1]);
}
public void setExecutableLines(Set<Integer> executableLines) {
checkState(this.executableLines == null, "Executable lines have already been saved for file: {}", this.toString());
this.executableLines = new BitSet(lines());
executableLines.forEach(l -> this.executableLines.set(l - 1));
}
public Optional<Set<Integer>> getExecutableLines() {
if (this.executableLines == null) {
return Optional.empty();
}
return Optional.of(this.executableLines.stream().map(i -> i + 1).boxed().collect(Collectors.toSet()));
}
}
|