Skip to content

Commit

Permalink
FileOps: read from files and URLs separately
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Nov 8, 2021
1 parent 42bb572 commit 713cbfa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
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 @@ -49,10 +49,13 @@ class FileOpsTest extends munit.FunSuite {

test("readFile with URL") {
val url = getClass.getResource("/readme.md")
val contents = FileOps.readFile(url.getPath)
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)
}

}
Expand Down

0 comments on commit 713cbfa

Please sign in to comment.