blob: 27dadb5a05aefc75f3bc0f00c6151681724fec8b [file] [log] [blame]
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed 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.zmlx.hg4idea.util;
import com.intellij.openapi.ui.InputValidatorEx;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.repo.HgRepository;
import java.util.Collection;
import java.util.regex.Pattern;
import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE;
public class HgReferenceValidator implements InputValidatorEx {
private final HgRepository myRepository;
private String myErrorText;
private static final Pattern ILLEGAL = Pattern.compile(
".*:.*|" + // colon character is not allowed
"[0-9]*" // reference name couldn't contain only digits
);
private HgReferenceValidator(@NotNull HgRepository repository) {
myRepository = repository;
}
public static HgReferenceValidator newInstance(@NotNull HgRepository repository) {
return new HgReferenceValidator(repository);
}
@Override
public boolean checkInput(@Nullable String name) {
if (StringUtil.isEmptyOrSpaces(name)) {
return false;
}
if (ILLEGAL.matcher(name).matches()) {
myErrorText = "Invalid name for branch/tag";
return false;
}
return !isReservedWord(name) && !hasConflictsWithAnotherBranch(name);
}
@Override
public boolean canClose(@Nullable String name) {
return checkInput(name);
}
boolean isReservedWord(@Nullable String name) {
myErrorText = TIP_REFERENCE.equals(name) ? String.format("The name \'%s\' is reserved.", name) : null;
return myErrorText != null;
}
boolean hasConflictsWithAnotherBranch(@Nullable String name) {
Collection<String> branches = myRepository.getBranches().keySet();
String currentBranch = myRepository.getCurrentBranch(); // branches set doesn't contain uncommitted branch -> need an addition check
myErrorText = currentBranch.equals(name) || branches.contains(name)
? String.format("A branch with the \'%s\' name already exists", name) : null;
return myErrorText != null;
}
@Nullable
@Override
public String getErrorText(@Nullable String inputString) {
return myErrorText;
}
}