Skip to content

Commit af1e3ab

Browse files
committed
Conf: add {remove,replace}If with partial function
1 parent 80220fd commit af1e3ab

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

  • metaconfig-core/shared/src/main/scala/metaconfig

metaconfig-core/shared/src/main/scala/metaconfig/Conf.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import metaconfig.internal.{CliParser, ConfGet, ConfPatch, HoconPrinter}
77
import java.io.File
88

99
import scala.annotation.tailrec
10+
import scala.collection.mutable.ListBuffer
1011
import scala.language.implicitConversions
1112
import scala.util.Try
1213

@@ -99,6 +100,7 @@ object Conf {
99100
def apply(values: Conf*): Lst = Lst(values.toList)
100101
}
101102
case class Obj(values: Obj.Elems) extends Conf {
103+
def isEmpty: Boolean = values.isEmpty
102104
override final def equals(obj: scala.Any): Boolean = this
103105
.eq(obj.asInstanceOf[AnyRef]) || {
104106
obj match {
@@ -116,6 +118,10 @@ object Conf {
116118
ev: ConfDecoder[T],
117119
): Configured[Option[T]] = ConfGet
118120
.getOrOK(this, path +: extraNames, ev.read(_).map(Some.apply), None)
121+
def replace(f: PartialFunction[Obj.Elem, Obj.Elems]): Obj = replaceIf(f)
122+
.getOrElse(this)
123+
def replaceIf(f: PartialFunction[Obj.Elem, Obj.Elems]): Option[Obj] = Obj
124+
.replaceIf(values)(f)
119125
def replaceKeyIfVal(key: String)(
120126
f: PartialFunction[Conf, Conf],
121127
): Option[Obj] = Obj.replaceKeyIfVal(values)(key)(f)
@@ -143,6 +149,12 @@ object Conf {
143149
def apply(values: Elem*): Obj =
144150
if (values.isEmpty) empty else Obj(values.toList)
145151

152+
def replaceIf(values: Elems)(f: PartialFunction[Elem, Elems]): Option[Obj] = {
153+
val add = new ListBuffer[Elems]
154+
val old = values.filterNot(f.runWith(add += _))
155+
if (old eq values) None
156+
else Some(Obj(if (add.isEmpty) old else ConfOps.merge(add += old)))
157+
}
146158
def replaceKeyIfVal(values: Elems)(key: String)(
147159
fv: PartialFunction[Conf, Conf],
148160
): Option[Obj] = removeKeyIfVal(values)(key)(fv).map { case (v, rest) =>

0 commit comments

Comments
 (0)