-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
RequiredFileArgument.kt
79 lines (70 loc) · 2.83 KB
/
RequiredFileArgument.kt
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package nl.hannahsten.texifyidea.lang.commands
import nl.hannahsten.texifyidea.file.FileExtensionMatcher
import nl.hannahsten.texifyidea.file.FileNameMatcher
import java.util.*
import java.util.regex.Pattern
/**
* A required file argument with a given name and a pattern that matches
* corresponding file names.
* Ignores case: everything will be converted to lower case.
* Type will be [nl.hannahsten.texifyidea.lang.commands.Argument.Type.NORMAL].
*
* @param name
* The name of the required argument.
* @param commaSeparatesArguments True if arguments are separated by commas, for example \command{arg1,arg2}. If false, "arg1,arg2" will be seen as one argument.
* @param extensions
* All supported extensions, of which the first extension is the default extension.
* @author Hannah Schellekens
*/
open class RequiredFileArgument(name: String?, open val isAbsolutePathSupported: Boolean = true, open val commaSeparatesArguments: Boolean, vararg extensions: String) : RequiredArgument(name!!, Type.FILE), FileNameMatcher, FileExtensionMatcher {
lateinit var supportedExtensions: Set<String>
lateinit var defaultExtension: String
private set
private var pattern: Pattern? = null
init {
setExtensions(*extensions)
}
/**
* Registers all extensions and compiles them to a regex file matcher.
*
* @param extensions
* All the file extensions (lower case) that should result in match for this required
* argument. The file extensions should *not* have a dot. When given no
* extensions, all files will match.
*/
private fun setExtensions(vararg extensions: String) {
val supportedExtensions = mutableSetOf<String>()
val regex = StringBuilder(".*")
if (extensions.isEmpty()) {
setRegex(regex.toString())
this.supportedExtensions = supportedExtensions
this.defaultExtension = ""
return
}
else {
defaultExtension = extensions[0]
}
regex.append("(")
for (extension in extensions) {
regex.append("\\.")
val extensionLower = extension.lowercase(Locale.getDefault())
regex.append(extensionLower)
supportedExtensions.add(extensionLower)
if (extension != extensions[extensions.size - 1]) {
regex.append("|")
}
}
regex.append(")$")
setRegex(regex.toString())
this.supportedExtensions = supportedExtensions
}
private fun setRegex(regex: String) {
pattern = Pattern.compile(regex)
}
override fun matchesName(fileName: String): Boolean {
return pattern!!.matcher(fileName.lowercase(Locale.getDefault())).matches()
}
override fun matchesExtension(extension: String): Boolean {
return supportedExtensions.contains(extension)
}
}