Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TEXT-217: Add SnakeCase Parsing #552

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions src/main/java/org/apache/commons/text/CasedString.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.text;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

/**
* Handles converting from one string case to another (e.g. camel case to snake case).
* @since 1.13.0
*/
public class CasedString {
/** the string the the cased format. */
private final String string;
/** the case of the string. */
private final StringCase stringCase;

/**
* A method to join camel string fragments together.
*/
private static final Function<String[], String> CAMEL_JOINER = a -> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems to me a JOINER should be kept in it's specifc case enum.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know how to do this. Every attempt I made resulted in the enum not being able to locate the method.

StringBuilder sb = new StringBuilder(a[0]);

for (int i = 1; i < a.length; i++) {
sb.append(WordUtils.capitalize(a[i]));
}
return sb.toString();
};

/**
* An enumeration of supported string cases.
*/
public enum StringCase {
/**
* Camel case identifies strings like 'CamelCase'.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each string case should have a precise definition (a RegEx for example) or a link to a precise definition.

*/
Camel(Character::isUpperCase, true, CAMEL_JOINER),
/**
* Snake case identifies strings like 'Snake_Case'.
*/
Snake(c -> c == '_', false, a -> String.join("_", a)),
/**
* Kebab case identifies strings like 'kebab-case'.
*/
Kebab(c -> c == '-', false, a -> String.join("-", a)),

/**
* Phrase case identifies phrases of words like 'phrase case'.
*/
Phrase(c -> c == ' ', false, a -> String.join(" ", a)),

/**
* Dot case identifies strings of words like 'dot.case'.
*/
Dot(c -> c == '.', false, a -> String.join(".", a));

/** test for split position character. */
private final Predicate<Character> splitter;
/** if {@code true} split position character will be preserved in following segment. */
private final boolean preserveSplit;
/** a function to joing the segments into this case type. */
private final Function<String[], String> joiner;

/**
* Defines a String Case.
* @param splitter The predicate that determines when a new word in the cased string begins.
* @param preserveSplit if {@code true} the character that the splitter detected is preserved as the first character of the new word.
* @param joiner The function to merge a list of strings into the cased String.
*/
StringCase(final Predicate<Character> splitter, final boolean preserveSplit, final Function<String[], String> joiner) {
this.splitter = splitter;
this.preserveSplit = preserveSplit;
this.joiner = joiner;
}
}

/**
* A representation of a cased string and the identified case of that string.
* @param stringCase The {@code StringCase} that the {@code string} argument is in.
* @param string The string.
*/
public CasedString(StringCase stringCase, String string) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This constructor should not let me construct illegal instances, for example " a b c " should not be an allowed camel case string (or a kebab, or a snake string). Otherwise, it's just GIGO.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is just GIGO. I expect that you know what the string looks like that you are starting with. So I guess it is not really "parsing" but converting. Perhaps it does not belong with TEXT-217 but should have its own ticket.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not acceptable IMO, when I create a BigInteger or a Duration, I get an exception when I feed the methods garbage. It should be the same here, fail-fast is always better in this case, otherwise, I could get all sorts of junk down the line.

I expect that you know what the string looks like that you are starting with.

This will not only be for user input, where typos could still happen of course.

When you start with an Open API or XML Schema, you hope the input is well-formed and valid, but even if so, the contents may be junky.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no way that I can think of that will not produce errors down the line for somebody. The commitment here is that the string will be parsed into segments based upon the splitter rule, and it does that. Other than the SnakeCase the conversions do not change the case of the characters. If you want to validate the result then the external code should do that before or after the conversion.

I ended up developing this code because I needed to convert commons-cli based long kebab keys into Java class and variable names to convert the CLI interface into Ant and Maven build tools for the Rat project.

Perhaps it does not belong here, but I went looking for a lightweight conversion utility and found none.

I think that the "parser" moniker does not fit and that conversion is probably the correct term. So this is really not a fix for TEXT-217 as it does not "parse".

this.string = string;
this.stringCase = stringCase;
}

private String[] split() {
List<String> lst = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (char c : string.toCharArray()) {
if (stringCase.splitter.test(c)) {
if (sb.length() > 0) {
lst.add(sb.toString());
sb.setLength(0);
}
if (stringCase.preserveSplit) {
sb.append(c);
}
} else {
sb.append(c);
}
}
if (sb.length() > 0) {
lst.add(sb.toString());
}
return lst.toArray(new String[0]);
}

/**
* Converts this cased string into a {@code String} of another format.
* The upper/lower case of the characters within the string are not modified.
* @param stringCase THe fomrat to convert to.
* @return the String current string represented in the new format.
*/
public String toCase(StringCase stringCase) {
if (stringCase == this.stringCase) {
return string;
}
return stringCase.joiner.apply(split());
}

/**
* Returns the string representation provided in the constructor.
* @return the string representation.
*/
@Override
public String toString() {
return string;
}
}
65 changes: 65 additions & 0 deletions src/test/java/org/apache/commons/text/CasedStringTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.text;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

public class CasedStringTest {

private static String expectedValue(CasedString.StringCase stringCase) {
switch (stringCase) {
case Camel:
return "HelloWorld";
case Kebab:
return "Hello-World";
case Phrase:
return "Hello World";
case Snake:
return "Hello_World";
case Dot:
return "Hello.World";
default:
throw new RuntimeException("Unsupported StringCase: " + stringCase);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use JUnit's fail() API.

}
}

@ParameterizedTest
@MethodSource("conversionProvider")
public void testConversions(CasedString underTest) {
for (CasedString.StringCase stringCase : CasedString.StringCase.values()) {
assertEquals(expectedValue(stringCase), underTest.toCase(stringCase), () -> "failed converting to " + stringCase);
}
}

private static Stream<Arguments> conversionProvider() {
List<Arguments> lst = new ArrayList<>();
for (CasedString.StringCase stringCase : CasedString.StringCase.values()) {
lst.add(Arguments.of(new CasedString(stringCase, expectedValue(stringCase))));
}
return lst.stream();
}
}
Loading