Allow Underscores in Project Names (#1209)

This commit is contained in:
Marcin Kostrzewa 2020-10-09 15:23:44 +02:00 committed by GitHub
parent 2783d5e706
commit a2be12c3e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 3 deletions

View File

@ -302,6 +302,47 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) {
existing.getOrElse(create(root, generateName(root)))
}
/**
* Checks if a character is allowed in a project name.
*
* @param char the char to validate
* @return `true` if it's allowed, `false` otherwise
*/
private def isAllowedNameCharacter(char: Char): Boolean = {
char.isLetterOrDigit || char == '_'
}
/**
* Takes a name containing letters, digits, and `_` characters and makes it
* a proper `Upper_Snake_Case` name.
*
* @param string the input string
* @return the transformed string
*/
private def toUpperSnakeCase(string: String): String = {
val beginMarker = '#'
val chars = string.toList
val charPairs = (beginMarker :: chars).zip(chars)
charPairs
.map {
case (previous, current) =>
if (previous == beginMarker) {
current.toString
} else if (previous.isLower && current.isUpper) {
s"_$current"
} else if (previous.isLetter && current.isDigit) {
s"_$current"
} else if (previous == '_' && current == '_') {
""
} else if (previous.isDigit && current.isLetter) {
s"_${current.toUpper}"
} else {
current.toString
}
}
.mkString("")
}
/**
* Transforms the given string into a valid package name (i.e. a CamelCased identifier).
*
@ -310,10 +351,10 @@ class PackageManager[F](implicit val fileSystem: FileSystem[F]) {
*/
def normalizeName(name: String): String = {
val startingWithLetter =
if (name.length == 0 || !name(0).isLetter) "Project" ++ name else name
if (name.length == 0 || !name(0).isLetter) "Project_" ++ name else name
val startingWithUppercase = startingWithLetter.capitalize
val onlyAlphanumeric = startingWithUppercase.filter(_.isLetterOrDigit)
onlyAlphanumeric
val onlyAlphanumeric = startingWithUppercase.filter(isAllowedNameCharacter)
toUpperSnakeCase(onlyAlphanumeric)
}
/**

View File

@ -0,0 +1,23 @@
package org.enso.pkg
import java.io.File
import org.enso.filesystem.FileSystem
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
class NameSanitizationSpec extends AnyWordSpec with Matchers {
"Creating a new project" should {
"sanitize the name of the project" in {
implicit val fileSystem: FileSystem[File] = FileSystem.Default
val manager = new PackageManager()
manager.normalizeName("My_Project") shouldEqual "My_Project"
manager.normalizeName("My___Project") shouldEqual "My_Project"
manager.normalizeName("myProject") shouldEqual "My_Project"
manager.normalizeName("myPro??^ject123") shouldEqual "My_Project_123"
manager.normalizeName("???%$6543lib") shouldEqual "Project_6543_Lib"
}
}
}