Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FileOps: read from files and URLs separately #2872

Merged
merged 2 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.scalafmt.sysops

import java.net.{URI, URL}
import java.nio.file.{AccessDeniedException, NoSuchFileException}
import java.nio.file.{Files, LinkOption, Path, Paths}
import scala.io.Codec
Expand Down Expand Up @@ -30,17 +31,27 @@ object FileOps {
finally iter.close()
}

// TODO(olafur) allow user to specify encoding through CLI.
/** Reads file from file system or from http url.
*/
/** Reads file from file system or from http url */
def readFile(filename: String)(implicit codec: Codec): String = {
if (filename matches "https?://.*") {
scala.io.Source.fromURL(filename)("UTF-8").getLines().mkString("\n")
} else {
readFile(getFile(filename))
Try(new URL(filename)) match {
case Success(url) => readFile(url)
case _ => readFile(getFile(filename))
}
}

def readFile(url: URL)(implicit codec: Codec): String = {
val isFile = Option(url.getProtocol).forall("file".equalsIgnoreCase)
if (isFile) readAsURI(url.toURI) else readAsURL(url)
}

@inline
private[sysops] def readAsURL(url: URL)(implicit codec: Codec): String =
scala.io.Source.fromURL(url).getLines().mkString("", "\n", "\n")

@inline
private[sysops] def readAsURI(uri: URI)(implicit codec: Codec): String =
readFile(Paths.get(uri))

def readFile(file: Path)(implicit codec: Codec): String = {
new String(Files.readAllBytes(file), codec.charSet)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ class FileOpsTest extends munit.FunSuite {
assertEquals(FileOps.listFiles(subsubfile), Seq(subsubfile))
}

test("readFile with URL") {
val url = getClass.getResource("/readme.md")
val contents = FileOps.readFile(url.toString)
val expectedFirstLine = "# scalafmt tests\n"
val firstLine = contents.substring(0, expectedFirstLine.length)
assertEquals(firstLine, expectedFirstLine)

assertEquals(FileOps.readFile(url), contents)
assertEquals(FileOps.readAsURL(url), contents)
}

}

object FileOpsTest {
Expand Down