package org.sonar.api.batch.fs;
import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
import java.nio.charset.Charset;
+import java.nio.file.Files;
import java.nio.file.Path;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
*/
Type type();
+ /**
+ * Creates a stream of the file's contents. Depending on the runtime context, the source might be a file in a physical or virtual filesystem.
+ * Typically, it won't be buffered. <b>The stream must be closed by the caller</b>.
+ * Note that there is a default implementation.
+ * @since 6.2
+ */
+ default InputStream inputStream() throws IOException {
+ return Files.newInputStream(path());
+ }
+
+ /**
+ * Fetches the entire contents of the file, decoding with the {@link #charset}.
+ * Note that there is a default implementation.
+ * @since 6.2
+ */
+ default String contents() throws IOException {
+ return new String(Files.readAllBytes(path()), charset());
+ }
+
/**
* Status regarding previous analysis
*/
*/
package org.sonar.api.batch.fs.internal;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.stream.Collectors;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
assertThat(inputFile.charset()).isEqualTo(StandardCharsets.ISO_8859_1);
}
+ @Test
+ public void test_content() throws IOException {
+ Path baseDir = temp.newFolder().toPath();
+ Path testFile = baseDir.resolve("src").resolve("Foo.php");
+ Files.createDirectories(testFile.getParent());
+ Files.write(testFile, "test string".getBytes(StandardCharsets.UTF_8));
+ DefaultInputFile inputFile = new DefaultInputFile("ABCDE", "src/Foo.php")
+ .setModuleBaseDir(baseDir)
+ .setLines(42)
+ .setLanguage("php")
+ .setStatus(InputFile.Status.ADDED)
+ .setType(InputFile.Type.TEST)
+ .setCharset(StandardCharsets.ISO_8859_1);
+
+ assertThat(inputFile.contents()).isEqualTo("test string");
+ try (InputStream inputStream = inputFile.inputStream()) {
+ String result = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining());
+ assertThat(result).isEqualTo("test string");
+ }
+
+ }
+
@Test
public void test_equals_and_hashcode() throws Exception {
DefaultInputFile f1 = new DefaultInputFile("ABCDE", "src/Foo.php");