Skip to content

Commit

Permalink
Refactor zipper
Browse files Browse the repository at this point in the history
  • Loading branch information
yuchesc committed Jul 30, 2018
1 parent 33fd75e commit 33dfa91
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 14 deletions.
22 changes: 8 additions & 14 deletions src/main/scala/com/yuchesc/sczip/ScZip.scala
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,10 @@ object ScZip {
* @return entry name list
*/
def zipTree(targetPath: Path, out: OutputStream, exclude: Option[Condition] = None): Seq[String] = {
var zip: Option[Zipper] = None
try {
zip = Option(new Zipper(out))
zip.get.addTree(targetPath, exclude)
} finally {
zip.foreach(_.close())
}
Zipper.withResource(out, {
zip =>
zip.addTree(targetPath, exclude)
})
}


Expand Down Expand Up @@ -92,13 +89,10 @@ object ScZip {
* @return entry name list
*/
def zipFiles(files: Seq[Path], out: OutputStream): Seq[String] = {
var zip: Option[Zipper] = None
try {
zip = Option(new Zipper(out))
files.map(zip.get.add)
} finally {
zip.foreach(_.close())
}
Zipper.withResource(out, {
zip =>
files.map(zip.add)
})
}

def main(args: Array[String]): Unit = {
Expand Down
20 changes: 20 additions & 0 deletions src/main/scala/com/yuchesc/sczip/Zipper.scala
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,23 @@ class Zipper(out: OutputStream,
*/
def close(): Unit = zip.close()
}

object Zipper {
/**
* Use zipper object with auto close.
*
* @param out the output stream
* @param f implement
* @tparam A return type
* @return
*/
def withResource[A](out: OutputStream, f: Zipper => A): A = {
var zip: Option[Zipper] = None
try {
zip = Option(new Zipper(out))
f(zip.get)
} finally {
zip.foreach(_.close())
}
}
}

0 comments on commit 33dfa91

Please sign in to comment.