Skip to content

Commit

Permalink
fix: escape illegal path characters in scope names (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
jGleitz committed Oct 12, 2020
1 parent 52a6e96 commit 043e99e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class DefaultTestFiles internal constructor(): LifecycleListener, TestFiles {

private fun enter(target: Scope) {
val currentScopeFiles = scopeFiles.peek()
val nextScopeDirectory = currentScopeFiles.targetDirectory.resolve("[${target.name}]")
val nextScopeDirectory = currentScopeFiles.targetDirectory.resolve("[${escapeScopeName(target.name)}]")
clear(nextScopeDirectory)
scopeFiles.push(ScopeFiles(nextScopeDirectory))
}
Expand All @@ -63,6 +63,8 @@ class DefaultTestFiles internal constructor(): LifecycleListener, TestFiles {
scopeFiles.pop().cleanup()
}

private fun escapeScopeName(name: String) = name.replace(invalidFileNameCharacters, "-")

private val Scope.name: String
get() = when (this) {
is ScopeImpl -> this.id.name
Expand Down Expand Up @@ -185,3 +187,11 @@ private inline fun tolerateDoesNotExist(path: Path, block: (Path) -> Unit) {
// swallow
}
}

private val unixInvalidCharacters get() = Regex("[/\u0000]")
private val windowsInvalidCharacters get() = Regex("[/\\\\<>:\"|?*\u0000]")
private val invalidFileNameCharacters by lazy {
val osName = System.getProperty("os.name").toLowerCase()
if (setOf("nix", "nux", "aix", "mac").any { osName.contains(it) }) unixInvalidCharacters
else windowsInvalidCharacters // default to windows because it is the most restrictive
}
17 changes: 11 additions & 6 deletions src/test/kotlin/DefaultTestFilesSpec.kt
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,17 @@ object DefaultTestFilesSpec: Spek({
}

listOf('/', '\\', '<', '>', ':', '\"', '|', '?', '*', '\u0000').forEach { badCharacter ->
it("escapes '$badCharacter' if necessary") {
testFiles.beforeExecuteTest(mockScope<TestScopeImpl>("test with -$badCharacter- in it"))

expect { testFiles.createFile("test") }.notToThrow {
// check that / \ is not messing up the directory structure
parent.fileName.matches(Regex(".test with -[^-]- in it."))
listOf(
"group" to { name: String -> testFiles.beforeExecuteGroup(mockScope<GroupScopeImpl>(name)) },
"test" to { name: String -> testFiles.beforeExecuteTest(mockScope<TestScopeImpl>(name)) }
).forEach { (scopeType, enterScope) ->
it("escapes '$badCharacter' in a $scopeType name if necessary") {
enterScope("test with -$badCharacter- in it")

expect { testFiles.createFile("test") }.notToThrow {
// check that / \ is not messing up the directory structure
parent.fileName.matches(Regex(".test with -.- in it."))
}
}
}
}
Expand Down

0 comments on commit 043e99e

Please sign in to comment.