mirror of
https://gitflic.ru/project/openide/openide.git
synced 2025-12-15 02:59:33 +07:00
[util] NameUtilCore.uniqName
GitOrigin-RevId: 9ff6d21d5e1efc735239d79a80c8993f476d7a5d
This commit is contained in:
committed by
intellij-monorepo-bot
parent
eadfa417ab
commit
832b80f75b
@@ -6,6 +6,7 @@ import com.intellij.util.text.NameUtilCore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
@@ -72,4 +73,14 @@ public class NameUtilTest {
|
||||
final String[] result = NameUtil.splitNameIntoWords(name);
|
||||
assertEquals(Arrays.asList(expected).toString(), Arrays.asList(result).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUniqName() {
|
||||
assertEquals("best", NameUtilCore.uniqName("best", Set.of("test", "test1")::contains));
|
||||
assertEquals("test1", NameUtilCore.uniqName("test", Set.of("test")::contains));
|
||||
assertEquals("test2", NameUtilCore.uniqName("test", Set.of("test", "test1")::contains));
|
||||
assertEquals("test3", NameUtilCore.uniqName("test", Set.of("test", "test1", "test2")::contains));
|
||||
assertEquals("test3", NameUtilCore.uniqName("test1", Set.of("test", "test1", "test2")::contains));
|
||||
assertEquals("test3", NameUtilCore.uniqName("test2", Set.of("test", "test1", "test2")::contains));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class NameUtilCore {
|
||||
|
||||
@@ -168,4 +170,29 @@ public final class NameUtilCore {
|
||||
}
|
||||
return ArrayUtilRt.toStringArray(array);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a unique name
|
||||
*
|
||||
* @param origName original symbol name
|
||||
* @param alreadyUsed a predicate that returns true if a supplied name is already used and we cannot use it
|
||||
* @return the name based on the origName, which is definitely not used (typically by adding a numeric suffix)
|
||||
*/
|
||||
public static @NotNull String uniqName(@NotNull String origName, @NotNull Predicate<@NotNull String> alreadyUsed) {
|
||||
if (!alreadyUsed.test(origName)) return origName;
|
||||
String baseName = origName;
|
||||
int index = 0;
|
||||
Pattern pattern = Pattern.compile("(.+?)(\\d+)");
|
||||
java.util.regex.Matcher matcher = pattern.matcher(baseName);
|
||||
if (matcher.matches()) {
|
||||
baseName = matcher.group(1);
|
||||
index = Integer.parseInt(matcher.group(2));
|
||||
}
|
||||
while (true) {
|
||||
String name = baseName + (++index);
|
||||
if (!alreadyUsed.test(name)) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user