aboutsummaryrefslogtreecommitdiff
path: root/src/main/scala/Gpg.scala
blob: edd19352b95120859439adc3cb6d9ae29dc5a179 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package io.crashbox.gpg

import java.io.File

import scala.util.control.NonFatal
import sys.process._

class Gpg(command: String,
          options: Seq[String] = Seq.empty,
          keyId: Option[String] = None)(
    info: String => Unit = System.out.println,
    warn: String => Unit = System.err.println) {

  private val logger = ProcessLogger(info, info) // gpg uses stderr for everything; redirect to info

  def run(params: String*): Int =
    try {
      val idOption = keyId.toSeq.flatMap(id => Seq("--local-user", id))
      val process = Process(command, options ++ idOption ++ params).run(logger)
      process.exitValue()
    } catch {
      case NonFatal(ex) =>
        warn(ex.getMessage)
        127
    }

  def sign(file: File): Option[File] = {
    val out = new File(file.getAbsolutePath + ".asc")
    run("--armor",
        "--output",
        out.getAbsolutePath,
        "--detach-sign",
        file.getAbsolutePath) match {
      case 0 => Some(out)
      case _ => None
    }
  }

}