ギャラリーアンモナイト#1
昨日の記事ではできないことばかり並べてしまったので、今日は作ってみたものをご紹介。 Ammoniteですぐに使えるスクリプトを書きとめておくコーナーです。
カレントディレクトリを変更する
/** bashのcdコマンドのように、現在地を移動する */ object cd extends ammonite.ops.ImplicitOp[Unit] { import ammonite.repl.Ref import ammonite.ops._ // JVMプロセスを起動したディレクトリを初期値とする val focus = Ref(cwd) // Ref[Path]型 def apply(arg: Path): Unit = { if (exists! arg) { if (arg == root || arg.isDir) { focus() = arg println(focus()) } else { println(s"$arg is not a directory.") } } else println(s"$arg does not exist.") } def ~ = apply(home) }
手軽に参照したい場合は下のようなメソッドを用意します。
/** 暗黙的にカレントディレクトリへの参照を取得する */ implicit def wd: Path = cd.focus()
cd! path
やcd(path)
でカレントディレクトリを移動します。
wd
を定義しておけば、ls!
の引数を省略して、よりbashのように動かすことができます。
ImplicitOp[Path]
型にして直接パスを返させるのもよさそうですね。