Example usage for org.eclipse.jgit.api TagCommand call

List of usage examples for org.eclipse.jgit.api TagCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api TagCommand call.

Prototype

@Override
public Ref call()
        throws GitAPIException, ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException 

Source Link

Document

Executes the tag command with all the options and parameters collected by the setter methods of this class.

Usage

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * creates a tag in a repository//  w w w  .  j  a  v  a 2 s. c  o  m
 *
 * @param repository
 * @param objectId, the ref the tag points towards
 * @param tagger, the person tagging the object
 * @param tag, the string label
 * @param message, the string message
 * @return boolean, true if operation was successful, otherwise false
 */
public static boolean createTag(Repository repository, String objectId, PersonIdent tagger, String tag,
        String message) {
    try {
        Git gitClient = Git.open(repository.getDirectory());
        TagCommand tagCommand = gitClient.tag();
        tagCommand.setTagger(tagger);
        tagCommand.setMessage(message);
        if (objectId != null) {
            RevObject revObj = getCommit(repository, objectId);
            tagCommand.setObjectId(revObj);
        }
        tagCommand.setName(tag);
        Ref call = tagCommand.call();
        return call != null ? true : false;
    } catch (Exception e) {
        error(e, repository, "Failed to create tag {1} in repository {0}", objectId, tag);
    }
    return false;
}

From source file:com.google.gerrit.acceptance.PushOneCommit.java

License:Apache License

private Result execute(String ref) throws Exception {
    RevCommit c = commitBuilder.create();
    if (changeId == null) {
        changeId = GitUtil.getChangeId(testRepo, c).get();
    }//  w w w  . ja  v  a2s . co m
    if (tag != null) {
        TagCommand tagCommand = testRepo.git().tag().setName(tag.name);
        if (tag instanceof AnnotatedTag) {
            AnnotatedTag annotatedTag = (AnnotatedTag) tag;
            tagCommand.setAnnotated(true).setMessage(annotatedTag.message).setTagger(annotatedTag.tagger);
        } else {
            tagCommand.setAnnotated(false);
        }
        tagCommand.call();
    }
    return new Result(ref, pushHead(testRepo, ref, tag != null, force), c, subject);
}

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

License:Apache License

@Override
public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException {
    if (input == null) {
        input = new TagInput();
    }/*w w  w  . ja va  2  s.  c om*/
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    if (ref.startsWith(R_REFS) && !ref.startsWith(R_TAGS)) {
        throw new BadRequestException("invalid tag name \"" + ref + "\"");
    }
    if (!ref.startsWith(R_TAGS)) {
        ref = R_TAGS + ref;
    }
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid tag name \"" + ref + "\"");
    }

    RefControl refControl = resource.getControl().controlForRef(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated && !refControl.canPerform(Permission.PUSH_TAG)) {
            throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
        } else if (!refControl.canPerform(Permission.CREATE)) {
            throw new AuthException("Cannot create tag \"" + ref + "\"");
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }

        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length()))
                    .setAnnotated(isAnnotated).setSigned(isSigned);

            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(
                        identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
            }

            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(),
                    identifiedUser.get().getAccount());
            try (RevWalk w = new RevWalk(repo)) {
                return ListTags.createTagInfo(result, w);
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision");
    } catch (GitAPIException e) {
        log.error("Cannot create tag \"" + ref + "\"", e);
        throw new IOException(e);
    }
}

From source file:com.microsoft.gittf.core.util.TagUtil.java

License:Open Source License

/**
 * Creates a tag//from  w  w w .j  a  va2s  .c o  m
 * 
 * @param repository
 *        the git repository
 * @param commitID
 *        the commit id to tag
 * @param tagName
 *        the tag name
 * @param tagOwner
 *        the tag owner
 * @return
 */
public static boolean createTag(final Repository repository, ObjectId commitID, String tagName,
        PersonIdent tagOwner) {
    final RevWalk walker = new RevWalk(repository);
    try {
        /* Look up the object to tag */
        RevObject objectToTag = walker.lookupCommit(commitID);

        /* Create a tag command */
        TagCommand tagCommand = new Git(repository).tag();
        tagCommand.setName(tagName);
        tagCommand.setObjectId(objectToTag);
        tagCommand.setForceUpdate(true);
        tagCommand.setTagger(tagOwner);

        /* Call the tag command */
        Ref tagRef = tagCommand.call();

        if (tagRef == null || tagRef == ObjectId.zeroId()) {
            log.warn("Failed to tag commit."); //$NON-NLS-1$

            return false;
        }

        return true;
    } catch (Exception e) {
        // this is not a critical failure so we can still continue with the
        // operation even if tagging failed.

        log.error(e);

        return false;
    } finally {
        if (walker != null) {
            walker.release();
        }
    }
}

From source file:com.peergreen.configuration.git.GitWrite.java

License:Apache License

@Override
public void tag(Version version) throws RepositoryException {

    if (currentWriteId == null) {
        throw new RepositoryException("Cannot tag a version, there were no changes");
    }// w ww . j  ava 2  s  . co  m

    // Check that the version doesn't exist
    if (getGitManager().existRef(Constants.R_TAGS + version.getName())) {
        throw new RepositoryException("Tag version '" + version.getName() + "' already exists.");
    }

    // Get commit of the current ObjectId
    RevWalk revWalk = new RevWalk(getGitManager().repository());
    RevCommit revCommit = null;
    try {
        revCommit = revWalk.parseCommit(currentWriteId);
    } catch (IOException e) {
        throw new RepositoryException("Unable to get commit from ID '" + currentWriteId
                + "' for production version '" + version.getName() + "'", e);
    } finally {
        revWalk.dispose();
    }

    TagCommand tagCommand = getGitManager().git().tag().setObjectId(revCommit).setName(version.getName());
    try {
        tagCommand.call();
    } catch (GitAPIException e) {
        throw new RepositoryException(
                "Unable to set the production version with name '" + version.getName() + "'", e);
    }

}

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

License:Open Source License

@Override
public void tag(final LocalRepoBean repoBean, final String tag) throws GitException {
    try {/*  w ww. j  a v a  2  s.com*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        TagCommand tagCommand = git.tag();
        tagCommand.setName(tag);
        tagCommand.call();
        repository.close();
    } catch (GitAPIException | IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Create a new tag in the local git repository
 * (git checkout tagname) and finally pushes new branch on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication/*from   w w w  .  j  a v  a2  s. c om*/
 * @param message   the commit message to be used    
 */
public static void createTag(@NonNull File directory, String tagName, String username, String password,
        String message) {

    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);

        TagCommand tagCommand = git.tag();
        tagCommand.setName(tagName);
        tagCommand.setMessage(message);
        tagCommand.call();
        log.info("Tag created");

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException | IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitTag.java

License:Apache License

/**
 * Tags the HEAD.//ww w .  j ava2  s  . c  om
 */
@TaskAction
public void tag() {
    TagCommand cmd = getGit().tag();
    cmd.setName(getTagName());
    cmd.setMessage(getMessage());
    cmd.setSigned(getSign());
    cmd.setForceUpdate(getForce());
    if (tagger != null) {
        cmd.setTagger(getTagger());
    }

    try {
        cmd.call();
    } catch (ConcurrentRefUpdateException e) {
        throw new GradleException("Another process is accessing or updating the ref.", e);
    } catch (InvalidTagNameException e) {
        throw new GradleException("Invalid tag name: " + getTagName(), e);
    } catch (NoHeadException e) {
        throw new GradleException("Cannot tag without a HEAD revision.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with tag.", e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String createVersion(String site, String path, String comment, boolean majorVersion) {
    // SJ: Will ignore minor revisions since git handles that via write/commit
    // SJ: Major revisions become git tags
    // TODO: SJ: Redesign/refactor the whole approach in 3.1+
    String toReturn = StringUtils.EMPTY;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : PUBLISHED)) {
        if (majorVersion) {
            Repository repo = helper.getRepository(site,
                    StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.PUBLISHED);
            // Tag the repository with a date-time based version label
            String gitPath = helper.getGitPath(path);

            try (Git git = new Git(repo)) {
                PersonIdent currentUserIdent = helper.getCurrentUserIdent();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                String versionLabel = dateFormat.format(cal);

                TagCommand tagCommand = git.tag().setName(versionLabel).setMessage(comment)
                        .setTagger(currentUserIdent);

                tagCommand.call();

                toReturn = versionLabel;

                git.close();/*from  w  ww. j a  v  a2  s.c  o  m*/
            } catch (GitAPIException err) {
                logger.error("error creating new version for site:  " + site + " path: " + path, err);
            }
        } else {
            logger.info("request to create minor revision ignored for site: " + site + " path: " + path);
        }
    }

    return toReturn;
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public Tag tagCreate(TagCreateRequest request) throws GitException {
    String commit = request.getCommit();
    if (commit == null) {
        commit = Constants.HEAD;//ww  w .jav  a2  s . co  m
    }

    try {
        RevWalk revWalk = new RevWalk(repository);
        RevObject revObject;
        try {
            revObject = revWalk.parseAny(repository.resolve(commit));
        } finally {
            revWalk.close();
        }

        TagCommand tagCommand = getGit().tag().setName(request.getName()).setObjectId(revObject)
                .setMessage(request.getMessage()).setForceUpdate(request.isForce());

        GitUser tagger = getUser();
        if (tagger != null) {
            tagCommand.setTagger(new PersonIdent(tagger.getName(), tagger.getEmail()));
        }

        Ref revTagRef = tagCommand.call();
        RevTag revTag = revWalk.parseTag(revTagRef.getLeaf().getObjectId());
        return newDto(Tag.class).withName(revTag.getTagName());
    } catch (IOException | GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}