Mercurial > cgi-bin > hgweb.cgi > JpegWasher
diff src/name/blackcap/exifwasher/Whitelist.kt @ 2:efd9fe2d70d7
Rationalize exceptions, code whitelist, add command-line tool.
author | David Barts <n5jrn@me.com> |
---|---|
date | Wed, 01 Apr 2020 14:23:54 -0700 |
parents | |
children | 19c381c536ec |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/name/blackcap/exifwasher/Whitelist.kt Wed Apr 01 14:23:54 2020 -0700 @@ -0,0 +1,48 @@ +/* + * An exif key whitelist. Supports both prefixes and entire strings. + */ +package name.blackcap.exifwasher + +import java.util.regex.Pattern +import kotlin.collections.mutableSetOf +import kotlin.collections.mutableListOf + +class Whitelist { + private val entire = mutableSetOf<String>() + private val prefixes = mutableListOf<String>() + + fun addEntire(s: String) = entire.add(s) + + fun addPrefix(s: String) = prefixes.add(s) + + private fun autoOp(s: String, pfx: (String) -> Boolean, ent: (String) -> Boolean): Boolean { + return if (s.endsWith('*')) { pfx(s.dropLast(1)) } else { ent(s) } + } + + fun add(s: String) = autoOp(s, ::addPrefix, ::addEntire) + + fun removeEntire(s: String) = entire.remove(s) + + fun removePrefix(s: String) = prefixes.remove(s) + + fun remove(s: String) = autoOp(s, ::removePrefix, ::removeEntire) + + fun contains(s: String) = entire.contains(s) || prefixes.find { s.startsWith(it) } != null + + fun toList(): List<String> = mutableListOf<String>().also { + it.addAll(entire) + it.addAll(prefixes) + it.sort() + } + + override fun toString(): String = toList().joinToString(",") + + companion object { + private val SPLITTER = Pattern.compile(",\\s*") + fun parse(raw: String) = Whitelist().also { + for (s in raw.split(SPLITTER)) { + it.add(s) + } + } + } +}