Created
August 13, 2021 12:06
-
-
Save phdoerfler/eb89cc36a42bcb2c79ddc40dad52ea7f to your computer and use it in GitHub Desktop.
Scala Ammonite Script to move and symlink directories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env amm | |
import java.nio.file.Path | |
import java.nio.file.Paths | |
import $ivy.`org.jline:jline:3.19.0` | |
import org.jline.terminal._ | |
import org.jline.reader._ | |
import scala.sys.process._ | |
import $ivy.`com.github.pathikrit::better-files:3.9.1` | |
import better.files._ | |
import File._ | |
import java.io.{File => JFile} | |
import scala.language.postfixOps | |
@main | |
def main(toMoveF: JFile, targetDirF: JFile = new JFile("/data/ran-out-of-space")) { | |
val terminal = TerminalBuilder.terminal() | |
val lineReader = LineReaderBuilder.builder() | |
.terminal(terminal) | |
.build() | |
val reader = LineReaderBuilder.builder().build() | |
val toMove = toMoveF.toPath | |
val targetDir = targetDirF.toPath | |
val destF = new JFile(targetDirF, toMove.toString) | |
val dest = destF.toPath | |
var cmds = Seq[Seq[String]]() | |
cmds = cmds :+ Seq("set", "-e") | |
cmds = cmds :+ Seq("set", "-x") | |
cmds = cmds :+ Seq("mkdir", "-p", targetDir.toString) | |
cmds = cmds :+ Seq("cd", toMove.toAbsolutePath.getParent.toString) | |
cmds = cmds :+ Seq("cp", "-a", toMove.toString, dest.toString) | |
cmds = cmds :+ Seq("rm", "-rf", dest.toString) | |
cmds = cmds :+ Seq("mv", toMove.toString, dest.toString) | |
cmds = cmds :+ Seq("ln", "-s", dest.toString, toMove.toString) | |
def quote(s: String): String = s"'${s.replaceAll("'", "\\'")}'" | |
println("About to execute the following commands:") | |
val script = cmds.map(_.map(quote).mkString(" ")).mkString("\n") | |
println(script) | |
if (confirm("Proceed?")) { | |
File.usingTemporaryFile() { tempFile => | |
tempFile.overwrite(script) | |
Seq("sh") #< tempFile.toJava ! | |
} | |
} | |
def confirm(question: String): Boolean = { | |
ask(s"$question [Y/n]").toLowerCase match { | |
case "" | "y" | "yes" => true | |
case "n" | "no" => false | |
} | |
} | |
def ask(what: String): String = { | |
reader.readLine(s"$what ") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment