Java Code Examples for org.eclipse.jgit.lib.Repository#findRef()

The following examples show how to use org.eclipse.jgit.lib.Repository#findRef() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitServiceImpl.java    From apidiff with MIT License 5 votes vote down vote up
@Override
public Integer countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 2
Source File: CreateBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void setupRebaseFlag (Repository repository) throws IOException {
    Ref baseRef = repository.findRef(revision);
    if (baseRef != null && baseRef.getName().startsWith(Constants.R_REMOTES)) {
        StoredConfig config = repository.getConfig();
        String autosetupRebase = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
                null, ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
        boolean rebase = ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
                || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase);
        if (rebase && !config.getNames(ConfigConstants.CONFIG_BRANCH_SECTION, branchName).isEmpty()) {
            config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REBASE, rebase);
            config.save();
        }
    }
}
 
Example 3
Source File: SetUpstreamBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    
    try {
        Ref ref = repository.findRef(trackedBranchName);
        if (ref == null) {
            throw new GitException(MessageFormat.format(Utils.getBundle(SetUpstreamBranchCommand.class)
                    .getString("MSG_Error_UpdateTracking_InvalidReference"), trackedBranchName)); //NOI18N)
        }
        String remote = null;
        String branchName = ref.getName();
        StoredConfig config = repository.getConfig();
        if (branchName.startsWith(Constants.R_REMOTES)) {
            String[] elements = branchName.split("/", 4);
            remote = elements[2];
            if (config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION).contains(remote)) {
                branchName = Constants.R_HEADS + elements[3];
                setupRebaseFlag(repository);
            } else {
                // remote not yet set
                remote = null;
            }
        }
        if (remote == null) {
            remote = "."; //NOI18N
        }
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_REMOTE, remote);
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_MERGE, branchName);
        config.save();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    ListBranchCommand branchCmd = new ListBranchCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor));
    branchCmd.run();
    Map<String, GitBranch> branches = branchCmd.getBranches();
    branch = branches.get(localBranchName);
}
 
Example 4
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public int countCommits(Repository repository, String branch) throws Exception {
	RevWalk walk = new RevWalk(repository);
	try {
		Ref ref = repository.findRef(REMOTE_REFS_PREFIX + branch);
		ObjectId objectId = ref.getObjectId();
		RevCommit start = walk.parseCommit(objectId);
		walk.setRevFilter(RevFilter.NO_MERGES);
		return RevWalkUtils.count(walk, start, null);
	} finally {
		walk.dispose();
	}
}
 
Example 5
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public Iterable<RevCommit> createRevsWalkBetweenTags(Repository repository, String startTag, String endTag)
		throws Exception {
	Ref refFrom = repository.findRef(startTag);
	Ref refTo = repository.findRef(endTag);
	try (Git git = new Git(repository)) {
		List<RevCommit> revCommits = StreamSupport.stream(git.log().addRange(getActualRefObjectId(refFrom), getActualRefObjectId(refTo)).call()
				.spliterator(), false)
		        .filter(r -> r.getParentCount() == 1)
		        .collect(Collectors.toList());
		Collections.reverse(revCommits);
		return revCommits;
	}
}
 
Example 6
Source File: NotesBuilder.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns actual SHA-1 object by commit reference.
 *
 * @param repo git repository.
 * @param ref string representation of commit reference.
 * @return actual SHA-1 object.
 * @throws IOException if an I/O error occurs.
 */
private static ObjectId getActualRefObjectId(Repository repo, String ref) throws IOException {
    final ObjectId actualObjectId;
    final Ref referenceObj = repo.findRef(ref);
    if (referenceObj == null) {
        actualObjectId = repo.resolve(ref);
    }
    else {
        final Ref repoPeeled = repo.peel(referenceObj);
        actualObjectId = Optional.ofNullable(repoPeeled.getPeeledObjectId())
            .orElse(referenceObj.getObjectId());
    }
    return actualObjectId;
}
 
Example 7
Source File: ThemeServiceImpl.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
private void pullFromGit(@NonNull ThemeProperty themeProperty) throws
    IOException, GitAPIException, URISyntaxException {
    Assert.notNull(themeProperty, "Theme property must not be null");

    // Get branch
    String branch = StringUtils.isBlank(themeProperty.getBranch()) ?
        DEFAULT_REMOTE_BRANCH : themeProperty.getBranch();

    Git git = null;

    try {
        git = GitUtils.openOrInit(Paths.get(themeProperty.getThemePath()));

        Repository repository = git.getRepository();

        RevWalk revWalk = new RevWalk(repository);

        Ref ref = repository.findRef(Constants.HEAD);

        Assert.notNull(ref, Constants.HEAD + " ref was not found!");

        RevCommit lastCommit = revWalk.parseCommit(ref.getObjectId());

        // Force to set remote name
        git.remoteRemove().setRemoteName(THEME_PROVIDER_REMOTE_NAME).call();
        RemoteConfig remoteConfig = git.remoteAdd()
            .setName(THEME_PROVIDER_REMOTE_NAME)
            .setUri(new URIish(themeProperty.getRepo()))
            .call();

        // Add all changes
        git.add()
            .addFilepattern(".")
            .call();
        // Commit the changes
        git.commit().setMessage("Commit by halo automatically").call();

        // Check out to specified branch
        if (!StringUtils.equalsIgnoreCase(branch, git.getRepository().getBranch())) {
            boolean present = git.branchList()
                .call()
                .stream()
                .map(Ref::getName)
                .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch));

            git.checkout()
                .setCreateBranch(true)
                .setForced(!present)
                .setName(branch)
                .call();
        }

        // Pull with rebasing
        PullResult pullResult = git.pull()
            .setRemote(remoteConfig.getName())
            .setRemoteBranchName(branch)
            .setRebase(true)
            .call();

        if (!pullResult.isSuccessful()) {
            log.debug("Rebase result: [{}]", pullResult.getRebaseResult());
            log.debug("Merge result: [{}]", pullResult.getMergeResult());

            throw new ThemeUpdateException("拉取失败!您与主题作者可能同时更改了同一个文件");
        }

        // updated successfully.
        ThemeProperty updatedThemeProperty = getProperty(Paths.get(themeProperty.getThemePath()));

        // Not support current halo version.
        if (StringUtils.isNotEmpty(updatedThemeProperty.getRequire()) && !VersionUtil.compareVersion(HaloConst.HALO_VERSION, updatedThemeProperty.getRequire())) {
            // reset theme version
            git.reset()
                .setMode(ResetCommand.ResetType.HARD)
                .setRef(lastCommit.getName())
                .call();
            throw new ThemeNotSupportException("新版本主题仅支持 Halo " + updatedThemeProperty.getRequire() + " 以上的版本");
        }
    } finally {
        GitUtils.closeQuietly(git);
    }

}