Example usage for org.eclipse.jgit.api Git tag

List of usage examples for org.eclipse.jgit.api Git tag

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git tag.

Prototype

public TagCommand tag() 

Source Link

Document

Return a command object to execute a Tag command

Usage

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

License:Apache License

/**
 * creates a tag in a repository//from  w  w w. j a va 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.git.PushOneCommit.java

License:Apache License

public Result to(Git git, String ref) throws GitAPIException, IOException {
    add(git, fileName, content);// www .  ja  v  a2  s  .co m
    Commit c;
    if (changeId != null) {
        c = amendCommit(git, i, subject, changeId);
    } else {
        c = createCommit(git, i, subject);
        changeId = c.getChangeId();
    }
    if (tagName != null) {
        git.tag().setName(tagName).setAnnotated(false).call();
    }
    return new Result(db, ref, pushHead(git, ref, tagName != null), c, subject);
}

From source file:com.google.gerrit.server.change.IncludedInResolverTest.java

License:Apache License

@Override
@Before//from  w ww  . jav a  2  s.  co  m
public void setUp() throws Exception {
    super.setUp();

    /*- The following graph will be created.
            
      o   tag 2.5, 2.5_annotated, 2.5_annotated_twice
      |\
      | o tag 2.0.1
      | o tag 2.0
      o | tag 1.3
      |/
      o   c3
            
      | o tag 1.0.1
      |/
      o   tag 1.0
      o   c2
      o   c1
            
     */

    // TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
    @SuppressWarnings("resource")
    Git git = new Git(db);
    revWalk = new RevWalk(db);
    // Version 1.0
    commit_initial = git.commit().setMessage("c1").call();
    git.commit().setMessage("c2").call();
    RevCommit commit_v1_0 = git.commit().setMessage("version 1.0").call();
    git.tag().setName(TAG_1_0).setObjectId(commit_v1_0).call();
    RevCommit c3 = git.commit().setMessage("c3").call();
    // Version 1.01
    createAndCheckoutBranch(commit_v1_0, BRANCH_1_0);
    RevCommit commit_v1_0_1 = git.commit().setMessage("verREFS_HEADS_RELsion 1.0.1").call();
    git.tag().setName(TAG_1_0_1).setObjectId(commit_v1_0_1).call();
    // Version 1.3
    createAndCheckoutBranch(c3, BRANCH_1_3);
    commit_v1_3 = git.commit().setMessage("version 1.3").call();
    git.tag().setName(TAG_1_3).setObjectId(commit_v1_3).call();
    // Version 2.0
    createAndCheckoutBranch(c3, BRANCH_2_0);
    RevCommit commit_v2_0 = git.commit().setMessage("version 2.0").call();
    git.tag().setName(TAG_2_0).setObjectId(commit_v2_0).call();
    RevCommit commit_v2_0_1 = git.commit().setMessage("version 2.0.1").call();
    git.tag().setName(TAG_2_0_1).setObjectId(commit_v2_0_1).call();

    // Version 2.5
    createAndCheckoutBranch(commit_v1_3, BRANCH_2_5);
    git.merge().include(commit_v2_0_1).setCommit(false).setFastForward(FastForwardMode.NO_FF).call();
    commit_v2_5 = git.commit().setMessage("version 2.5").call();
    git.tag().setName(TAG_2_5).setObjectId(commit_v2_5).setAnnotated(false).call();
    Ref ref_tag_2_5_annotated = git.tag().setName(TAG_2_5_ANNOTATED).setObjectId(commit_v2_5).setAnnotated(true)
            .call();
    RevTag tag_2_5_annotated = revWalk.parseTag(ref_tag_2_5_annotated.getObjectId());
    git.tag().setName(TAG_2_5_ANNOTATED_TWICE).setObjectId(tag_2_5_annotated).setAnnotated(true).call();
}

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 {/*ww w  . java2  s .  c  om*/
        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.wadpam.gimple.GimpleMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {//w w w  .j a v  a2 s .  c om
        Repository repo = builder.setGitDir(new File(new File(gitDir), ".git")).readEnvironment().findGitDir()
                .build();
        final String branch = repo.getBranch();
        if (null != branch) {
            if (!currentVersion.endsWith(SUFFIX_SNAPSHOT)) {
                throw new MojoExecutionException("Maven project version not in SNAPSHOT: " + currentVersion);
            }

            getLog().info("gimple executing on " + gitDir);
            getLog().info("branch " + branch);

            if (null == releaseVersion) {
                releaseVersion = currentVersion.substring(0,
                        currentVersion.length() - SUFFIX_SNAPSHOT.length());
            }
            getLog().info(
                    "Transforming version from " + currentVersion + " to release version " + releaseVersion);

            Git git = new Git(repo);
            StatusCommand statusCommand = git.status();
            Status status = statusCommand.call();

            if (!status.isClean()) {
                throw new MojoExecutionException("Git project is not clean: " + status.getUncommittedChanges());
            }

            // versions:set releaseVersion
            transformPomVersions(git, releaseVersion);

            // tag release
            Ref tagRef = git.tag().setMessage(GIMPLE_MAVEN_PLUGIN + "tagging release " + releaseVersion)
                    .setName(releaseVersion).call();

            // next development version
            if (null == nextVersion) {
                nextVersion = getNextDevelopmentVersion(releaseVersion);
            }

            // versions:set nextVersion
            RevCommit nextRef = transformPomVersions(git, nextVersion);

            // push it all
            String developerConnection = mavenProject.getScm().getDeveloperConnection();
            if (developerConnection.startsWith(PREFIX_SCM_GIT)) {
                developerConnection = developerConnection.substring(PREFIX_SCM_GIT.length());
            }
            RefSpec spec = new RefSpec(branch + ":" + branch);
            git.push().setRemote(developerConnection).setRefSpecs(spec).add(tagRef).call();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("executing", e);
    } catch (GitAPIException e) {
        throw new MojoExecutionException("status", 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 ww  w. j  a  v  a  2 s  .c o  m*/
 * @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:info.debatty.jinu.Case.java

License:Open Source License

private void commitToGit(final String time_tag) {
    try {//  w  w w.j a v a  2 s .  c o  m
        Repository repo = new FileRepositoryBuilder().findGitDir().build();

        Git git = new Git(repo);
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage("Test case " + time_tag).call();
        git.tag().setName("T" + time_tag).call();
    } catch (Exception ex) {
        System.err.println("Could not commit GIT repo");
        System.err.println(ex.getMessage());
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitLabelingSupport.java

License:Apache License

@NotNull
public String label(@NotNull String label, @NotNull String version, @NotNull VcsRoot root,
        @NotNull CheckoutRules checkoutRules) throws VcsException {
    OperationContext context = myVcs.createContext(root, "labeling");
    GitVcsRoot gitRoot = context.getGitRoot();
    RevisionsInfo revisionsInfo = new RevisionsInfo();
    if (myConfig.useTagPackHeuristics()) {
        LOG.debug("Update repository before labeling " + gitRoot.debugInfo());
        RepositoryStateData currentState = myVcs.getCurrentState(gitRoot);
        if (!myConfig.analyzeTagsInPackHeuristics())
            currentState = excludeTags(currentState);
        try {/*from   w w  w.  j a  v  a2 s  . c o m*/
            myVcs.getCollectChangesPolicy().ensureRepositoryStateLoadedFor(context, context.getRepository(),
                    false, currentState);
        } catch (Exception e) {
            LOG.debug("Error while updating repository " + gitRoot.debugInfo(), e);
        }
        revisionsInfo = new RevisionsInfo(currentState);
    }
    ReadWriteLock rmLock = myRepositoryManager.getRmLock(gitRoot.getRepositoryDir());
    rmLock.readLock().lock();
    try {
        long start = System.currentTimeMillis();
        Repository r = context.getRepository();
        String commitSHA = GitUtils.versionRevision(version);
        RevCommit commit = myCommitLoader.loadCommit(context, gitRoot, commitSHA);
        Git git = new Git(r);
        Ref tagRef = git.tag().setTagger(gitRoot.getTagger(r)).setName(label).setObjectId(commit).call();
        if (tagRef.getObjectId() == null || resolve(r, tagRef) == null) {
            LOG.warn("Tag's " + tagRef.getName() + " objectId "
                    + (tagRef.getObjectId() != null ? tagRef.getObjectId().name() + " " : "")
                    + "cannot be resolved");
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("Tag created  " + label + "=" + version + " for " + gitRoot.debugInfo() + " in "
                    + (System.currentTimeMillis() - start) + "ms");
        }
        return push(label, version, gitRoot, r, tagRef, revisionsInfo);
    } catch (Exception e) {
        throw context.wrapException(e);
    } finally {
        rmLock.readLock().unlock();
        context.close();
    }
}

From source file:net.morimekta.idltool.cmd.RemotePublish.java

License:Apache License

@Override
public void execute(IdlTool idlTool) throws IOException, GitAPIException {
    String repository = idlTool.getIdl().getUpstreamRepository();
    File pwd = idlTool.getIdl().getWorkingGitDir();

    Git cacheRepository = idlTool.getRepositoryGitCache(repository);

    Path localIDL = pwd.toPath().resolve(Idl_Constants.IDL);
    Path localPath = localIDL.resolve(idlTool.getLocalRemoteName());

    if (!Files.exists(localPath)) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL dir in local remote location: .../" + relative);
        return;// ww w .  j  av  a2 s  .  c o  m
    }

    Map<String, String> localSha1sums = IdlUtils.buildSha1Sums(localPath);
    if (localSha1sums.isEmpty()) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL files in local remote location: .../" + relative);
        return;
    }

    Meta cacheMeta = IdlUtils.getMetaInRegistry(cacheRepository.getRepository());
    Remote cacheRemote = cacheMeta.hasRemotes()
            && cacheMeta.getRemotes().containsKey(idlTool.getLocalRemoteName())
                    ? cacheMeta.getRemotes().get(idlTool.getLocalRemoteName())
                    : Remote.builder().build();

    Map<String, String> publishedSha1sums = ImmutableMap.of();
    if (cacheRemote.hasShasums()) {
        publishedSha1sums = cacheMeta.getRemotes().get(idlTool.getLocalRemoteName()).getShasums();
    }

    if (localSha1sums.equals(publishedSha1sums)) {
        // No change.
        System.out.println("No change.");
        return;
    }

    Path remoteIDL = cacheRepository.getRepository().getWorkTree().toPath().resolve(Idl_Constants.IDL);
    Path remotePath = remoteIDL.resolve(idlTool.getLocalRemoteName());
    if (Files.isDirectory(remotePath)) {
        Files.list(remotePath).forEach(file -> {
            try {
                String name = file.getFileName().toString();
                if (Files.isHidden(file) || !Files.isRegularFile(file)) {
                    // Hidden and special files are ignored.
                    return;
                }
                if (!localSha1sums.containsKey(name)) {
                    Files.delete(file);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e.getMessage(), e);
            }
        });
    } else {
        Files.createDirectories(remotePath);
    }

    for (String file : localSha1sums.keySet()) {
        Path source = localPath.resolve(file);
        Path target = remotePath.resolve(file);

        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
    }

    ZonedDateTime now = ZonedDateTime.now(Clock.systemUTC());
    long timestamp = now.toInstant().toEpochMilli();
    String isoNow = DateTimeFormatter.ISO_DATE_TIME.format(now);

    Remote._Builder remoteBuilder = Remote.builder();
    remoteBuilder.setVersion(timestamp);
    remoteBuilder.setTime(timestamp);
    remoteBuilder.setShasums(localSha1sums);

    Meta._Builder metaBuilder = cacheMeta.mutate();
    metaBuilder.putInRemotes(idlTool.getLocalRemoteName(), remoteBuilder.build());
    metaBuilder.setVersion(timestamp);
    metaBuilder.setTime(isoNow);

    try (FileOutputStream out = new FileOutputStream(
            new File(cacheRepository.getRepository().getWorkTree(), Idl_Constants.META_JSON))) {
        new JsonSerializer().pretty().serialize(out, metaBuilder.build());
        out.write('\n');
    }

    Process add = Runtime.getRuntime().exec(new String[] { "git", "add", "." }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = add.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(add.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    cacheRepository.commit().setMessage("Updating " + idlTool.getLocalRemoteName() + " to latest version")
            .call();
    cacheRepository.tag().setName("v" + timestamp).setMessage(isoNow + " " + idlTool.getLocalRemoteName())
            .call();

    Process commit = Runtime.getRuntime().exec(new String[] { "git", "push" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    commit = Runtime.getRuntime().exec(new String[] { "git", "push", "--tags" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.tag.JGitTagCommand.java

License:Apache License

/**
 * {@inheritDoc}/*from   ww  w  . j a va  2  s .  co  m*/
 */
public ScmResult executeTagCommand(ScmProviderRepository repo, ScmFileSet fileSet, String tag,
        ScmTagParameters scmTagParameters) throws ScmException {
    if (tag == null || StringUtils.isEmpty(tag.trim())) {
        throw new ScmException("tag name must be specified");
    }

    if (!fileSet.getFileList().isEmpty()) {
        throw new ScmException("This provider doesn't support tagging subsets of a directory");
    }

    String escapedTagName = tag.trim().replace(' ', '_');

    Git git = null;
    try {
        git = Git.open(fileSet.getBasedir());

        // tag the revision
        String tagMessage = scmTagParameters.getMessage();
        Ref tagRef = git.tag().setName(escapedTagName).setMessage(tagMessage).setForceUpdate(false).call();

        if (repo.isPushChanges()) {
            getLogger().info("push tag [" + escapedTagName + "] to remote...");
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo,
                    new RefSpec(Constants.R_TAGS + escapedTagName));
        }

        // search for the tagged files
        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(tagRef.getObjectId());
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> taggedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            taggedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        return new TagScmResult("JGit tag", taggedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit tag failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}