Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/c7491b5cef1491d9c0d59b2bab20482b to your computer and use it in GitHub Desktop.
Save dacr/c7491b5cef1491d9c0d59b2bab20482b to your computer and use it in GitHub Desktop.
Various file and path helper functions / published by https://github.com/dacr/code-examples-manager #0c93e52d-b966-44cd-8cec-51c26893bb73/34bd5a58781ba51e5478a8a85c8c29a59219b61e
// summary : Various file and path helper functions
// keywords : scala, functions, file, path, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 0c93e52d-b966-44cd-8cec-51c26893bb73
// created-on : 2021-03-05T17:40:29Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
//> using dep "org.scalatest::scalatest:3.2.16"
//> using objectWrapper
// ---------------------
import org.scalatest.*, flatspec.*, matchers.*
import java.nio.file.*
def basename(filename:String):String = {
filename
.split("[/](?=[^/]*$)", 2)
.last
.split("[.]",2)
.head
}
// -----------------------------------------------------------------------------------------
class FilePathToolsTest extends AnyFlatSpec with should.Matchers {
override def suiteName = "FilePathToolsTest"
"basename" should "only provide the filename" in {
basename("toto.tmp") shouldBe "toto"
basename("http://truc:80/muche/image.png") shouldBe "image"
basename("/var/tmp/Abc.file") shouldBe "Abc"
basename("/var/tmp/Abc") shouldBe "Abc"
basename("/var/tmp/Abc.") shouldBe "Abc"
basename("toto") shouldBe "toto"
basename(".tmp") shouldBe ""
basename("") shouldBe ""
}
"nio.path" should "provide easy API to deal with files" in {
Path.of("/tmp/truc/toto.truc").toString shouldBe "/tmp/truc/toto.truc"
Path.of("/tmp/truc/toto.truc").getFileName.toString shouldBe "toto.truc"
Path.of("/tmp/truc/toto.truc").getParent.toString shouldBe "/tmp/truc"
Path.of("/tmp/truc/toto.truc").isAbsolute shouldBe true
Path.of("/tmp/truc/toto.truc").endsWith("toto.truc") shouldBe true
Path.of("/tmp/truc/toto.truc").endsWith(".truc") shouldBe false
Path.of("/tmp/truc/").endsWith("truc") shouldBe true
}
}
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[FilePathToolsTest].getName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment