Example usage for org.eclipse.jgit.lib Repository isValidRefName

List of usage examples for org.eclipse.jgit.lib Repository isValidRefName

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository isValidRefName.

Prototype

public static boolean isValidRefName(String refName) 

Source Link

Document

Check validity of a ref name.

Usage

From source file:com.google.gerrit.server.project.PerformCreateProject.java

License:Apache License

private void validateParameters() throws ProjectCreationFailedException {
    if (createProjectArgs.getProjectName() == null || createProjectArgs.getProjectName().isEmpty()) {
        throw new ProjectCreationFailedException("Project name is required");
    }// w w  w .j  a  v a2 s.c  o m

    String nameWithoutSuffix = ProjectUtil.stripGitSuffix(createProjectArgs.getProjectName());
    createProjectArgs.setProjectName(nameWithoutSuffix);

    if (!currentUser.getCapabilities().canCreateProject()) {
        throw new ProjectCreationFailedException(
                String.format("%s does not have \"Create Project\" capability.", currentUser.getUserName()));
    }

    if (createProjectArgs.ownerIds == null || createProjectArgs.ownerIds.isEmpty()) {
        createProjectArgs.ownerIds = new ArrayList<>(projectOwnerGroups);
    }

    List<String> transformedBranches = new ArrayList<>();
    if (createProjectArgs.branch == null || createProjectArgs.branch.isEmpty()) {
        createProjectArgs.branch = Collections.singletonList(Constants.MASTER);
    }
    for (String branch : createProjectArgs.branch) {
        while (branch.startsWith("/")) {
            branch = branch.substring(1);
        }
        if (!branch.startsWith(Constants.R_HEADS)) {
            branch = Constants.R_HEADS + branch;
        }
        if (!Repository.isValidRefName(branch)) {
            throw new ProjectCreationFailedException(
                    String.format("Branch \"%s\" is not a valid name.", branch));
        }
        if (!transformedBranches.contains(branch)) {
            transformedBranches.add(branch);
        }
    }
    createProjectArgs.branch = transformedBranches;
}

From source file:com.google.gerrit.server.project.RefControl.java

License:Apache License

public static void validateRefPattern(String refPattern) throws InvalidNameException {
    if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) {
        if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) {
            throw new InvalidNameException(refPattern);
        }//from  ww w  .  j  a  va  2s.  c om
    } else if (refPattern.equals(RefConfigSection.ALL)) {
        // This is a special case we have to allow, it fails below.
    } else if (refPattern.endsWith("/*")) {
        String prefix = refPattern.substring(0, refPattern.length() - 2);
        if (!Repository.isValidRefName(prefix)) {
            throw new InvalidNameException(refPattern);
        }
    } else if (!Repository.isValidRefName(refPattern)) {
        throw new InvalidNameException(refPattern);
    }
}

From source file:com.google.gerrit.server.project.RefPattern.java

License:Apache License

public static void validate(String refPattern) throws InvalidNameException {
    if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) {
        if (!Repository.isValidRefName(shortestExample(refPattern))) {
            throw new InvalidNameException(refPattern);
        }/*  w w w.j a va 2  s .  c  o  m*/
    } else if (refPattern.equals(RefConfigSection.ALL)) {
        // This is a special case we have to allow, it fails below.
    } else if (refPattern.endsWith("/*")) {
        String prefix = refPattern.substring(0, refPattern.length() - 2);
        if (!Repository.isValidRefName(prefix)) {
            throw new InvalidNameException(refPattern);
        }
    } else if (!Repository.isValidRefName(refPattern)) {
        throw new InvalidNameException(refPattern);
    }
    validateRegExp(refPattern);
}

From source file:com.google.gerrit.sshd.commands.CreateProject.java

License:Apache License

private void validateParameters() throws Failure {
    if (projectName.endsWith(Constants.DOT_GIT_EXT)) {
        projectName = projectName.substring(0, //
                projectName.length() - Constants.DOT_GIT_EXT.length());
    }/*from w w w.  j  a va  2 s  .  c o  m*/

    if (!CollectionsUtil.isAnyIncludedIn(currentUser.getEffectiveGroups(), projectCreatorGroups)) {
        throw new Failure(1, "fatal: Not permitted to create " + projectName);
    }

    if (ownerIds != null && !ownerIds.isEmpty()) {
        ownerIds = new ArrayList<AccountGroup.UUID>(new HashSet<AccountGroup.UUID>(ownerIds));
    } else {
        ownerIds = new ArrayList<AccountGroup.UUID>(projectOwnerGroups);
    }

    while (branch.startsWith("/")) {
        branch = branch.substring(1);
    }
    if (!branch.startsWith(Constants.R_HEADS)) {
        branch = Constants.R_HEADS + branch;
    }
    if (!Repository.isValidRefName(branch)) {
        throw new Failure(1, "--branch \"" + branch + "\" is not a valid name");
    }
}

From source file:com.google.gitiles.RefServletTest.java

License:Open Source License

@Test
public void evilRefName() throws Exception {
    setUpSimpleRefs();//from  w w  w.  ja  v a2 s  .  co  m
    String evilRefName = "refs/evil/<script>window.close();</script>/&foo";
    assertTrue(Repository.isValidRefName(evilRefName));
    repo.branch(evilRefName).commit().create();

    FakeHttpServletRequest req = FakeHttpServletRequest.newRequest();
    req.setPathInfo("/test/+refs/evil");
    req.setQueryString("format=TEXT");
    FakeHttpServletResponse res = new FakeHttpServletResponse();
    servlet.service(req, res);

    assertEquals(id(evilRefName) + " refs/evil/&lt;script&gt;window.close();&lt;/script&gt;/&amp;foo\n",
            res.getActualBodyString());
}

From source file:com.googlesource.gerrit.plugins.supermanifest.ConfigEntry.java

License:Apache License

ConfigEntry(Config cfg, String name) throws ConfigInvalidException {
    String[] parts = name.split(":");
    if (parts.length != 2) {
        throw new ConfigInvalidException(String.format("pluginName '%s' must have form REPO:BRANCH", name));
    }//from w  w w . ja  va 2 s  . c o m

    String destRepo = parts[0];
    String destRef = parts[1];

    if (!destRef.startsWith(REFS_HEADS)) {
        throw new ConfigInvalidException(
                String.format("invalid destination '%s'. Must specify refs/heads/", destRef));
    }

    if (destRef.contains("*") && !destRef.equals(REFS_HEADS + "*")) {
        throw new ConfigInvalidException(
                String.format("invalid destination '%s'. Use just '*' for all branches.", destRef));
    }

    String srcRepo = cfg.getString(SECTION_NAME, name, "srcRepo");
    if (srcRepo == null) {
        throw new ConfigInvalidException(String.format("entry %s did not specify srcRepo", name));
    }

    // TODO(hanwen): sanity check repo names.
    srcRepoKey = new Project.NameKey(srcRepo);

    String toolType = nullToEmpty(cfg.getString(SECTION_NAME, name, "toolType"));

    switch (toolType) {
    case "":
    case "repo":
        this.toolType = ToolType.Repo;
        break;
    case "jiri":
        this.toolType = ToolType.Jiri;
        break;
    default:
        throw new ConfigInvalidException(String.format("entry %s has invalid toolType: %s", name, toolType));
    }

    if (destRef.equals(REFS_HEADS + "*")) {
        srcRef = "";
    } else {
        if (!Repository.isValidRefName(destRef)) {
            throw new ConfigInvalidException(String.format("destination branch '%s' invalid", destRef));
        }

        srcRef = cfg.getString(SECTION_NAME, name, "srcRef");
        if (!Repository.isValidRefName(srcRef)) {
            throw new ConfigInvalidException(String.format("source ref '%s' invalid", srcRef));
        }

        if (srcRef == null) {
            throw new ConfigInvalidException(String.format("entry %s did not specify srcRef", name));
        }
    }

    xmlPath = cfg.getString(SECTION_NAME, name, "srcPath");
    if (xmlPath == null) {
        throw new ConfigInvalidException(String.format("entry %s did not specify srcPath", name));
    }

    destRepoKey = new Project.NameKey(destRepo);

    // The external format is chosen so we can support copying over tags as well.
    destBranch = destRef.substring(REFS_HEADS.length());

    repoGroups = nullToEmpty(cfg.getString(SECTION_NAME, name, "groups"));
    recordSubmoduleLabels = cfg.getBoolean(SECTION_NAME, name, "recordSubmoduleLabels", false);
    ignoreRemoteFailures = cfg.getBoolean(SECTION_NAME, name, "ignoreRemoteFailures", false);

    try {
        // http://foo/platform/manifest => http://foo/platform/
        baseUri = new URI(srcRepoKey.toString()).resolve("");
    } catch (URISyntaxException exception) {
        throw new ConfigInvalidException("could not build src URL", exception);
    }
}

From source file:com.microsoft.gittf.core.tasks.UnshelveTask.java

License:Open Source License

/**
 * Generates a valid tag name for the shelveset, Note that shelveset names
 * are not always valid ref names becuase of the unsupported characters that
 * can be in the shelveset name./*  w w  w  .j a va 2  s .c  om*/
 * 
 * @param shelveset
 * @return
 */
private String generateValidTagName(Shelveset shelveset) {
    String tagName = Messages.formatString("UnshelveTask.ShelvesetTagFormat", shelveset.getName()); //$NON-NLS-1$

    if (Repository.isValidRefName(Constants.R_TAGS + tagName)) {
        return tagName;
    }

    tagName = tagName.replace(' ', '_');

    if (Repository.isValidRefName(Constants.R_TAGS + tagName)) {
        return tagName;
    }

    return Messages.formatString("UnshelveTask.ShelvesetTagFormat", Long.toString(System.currentTimeMillis())); //$NON-NLS-1$
}

From source file:com.mooregreatsoftware.gitprocess.lib.Branch.java

License:Apache License

/**
 * Creates a representation of an existing branch.
 *
 * @param gitLib the GitLib to use for commands
 * @param name   the name of the existing branch; if not fully-qualified (e.g., "refs/heads/master") it will do
 *               the translation//from   w  w  w.ja  va  2  s  . c om
 * @throws IllegalArgumentException if it can't find the branch name
 */
public static Branch of(GitLib gitLib, String name) {
    final String refName = name.startsWith(R_REFS) ? name : computeRefName(gitLib, name);

    if (!Repository.isValidRefName(refName)) {
        throw new IllegalArgumentException("\"" + name + "\" is not a valid branch name");
    }

    final Ref ref = ExecUtils.<@Nullable Ref>e(() -> gitLib.repository().findRef(refName));

    if (ref == null)
        throw new IllegalArgumentException(
                name + " is not a known reference name in " + gitLib.repository().getAllRefs());

    return new Branch(gitLib, ref);
}

From source file:com.surevine.gateway.scm.git.jgit.BundleWriter.java

License:Eclipse Distribution License

/**
 * Include an object (and everything reachable from it) in the bundle.
 *
 * @param name//from w w  w  .j ava2s  .c  o  m
 *            name the recipient can discover this object as from the
 *            bundle's list of advertised refs . The name must be a valid
 *            ref format and must not have already been included in this
 *            bundle writer.
 * @param id
 *            object to pack. Multiple refs may point to the same object.
 */
public void include(final String name, final AnyObjectId id) {
    if (!"HEAD".equals(name) && !Repository.isValidRefName(name))
        throw new IllegalArgumentException(MessageFormat.format(JGitText.get().invalidRefName, name));
    if (include.containsKey(name))
        throw new IllegalStateException(JGitText.get().duplicateRef + name);
    include.put(name, id.toObjectId());
}

From source file:org.commonjava.gitwrap.BareGitRepository.java

License:Open Source License

public BareGitRepository createBranch(final String source, final String name) throws GitWrapException {
    final String refName = (name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)) ? name
            : Constants.R_HEADS + name;//w  ww .  j  av  a 2  s .  com

    try {
        String src;
        final Ref from = repository.getRef(source);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Creating branch: " + refName + " from: " + from);
        }

        final ObjectId startAt = repository.resolve(source + "^0");
        if (from != null) {
            src = from.getName();
        } else {
            src = startAt.name();
        }
        src = repository.shortenRefName(src);

        if (!Repository.isValidRefName(refName)) {
            throw new GitWrapException("Invalid branch name: " + refName);
        }

        if (repository.resolve(refName) != null) {
            throw new GitWrapException("Branch: " + refName + " already exists!");
        }

        final RefUpdate updateRef = repository.updateRef(refName);
        updateRef.setNewObjectId(startAt);
        updateRef.setRefLogMessage("branch: Created from " + source, false);
        final Result updateResult = updateRef.update();

        if (updateResult == Result.REJECTED) {
            throw new GitWrapException("Branch creation rejected for: %s", refName);
        }
    } catch (final IOException e) {
        throw new GitWrapException("Failed to create branch: %s from: %s.\nReason: %s", e, refName, source,
                e.getMessage());
    }

    return this;
}