Example usage for org.eclipse.jgit.lib Constants MASTER

List of usage examples for org.eclipse.jgit.lib Constants MASTER

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants MASTER.

Prototype

String MASTER

To view the source code for org.eclipse.jgit.lib Constants MASTER.

Click Source Link

Document

Default main branch name

Usage

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

private List<Ref> getRefsToAdd(Repository repository) {
    List<Ref> result = new ArrayList<Ref>();
    Ref master = null;/*from ww w .  ja v a2  s  .com*/
    for (Entry<String, Ref> entry : repository.getAllRefs().entrySet()) {
        if (entry.getValue().getName().equals(Constants.R_HEADS + Constants.MASTER)) {
            master = entry.getValue();
        } else if (entry.getValue().getName().startsWith(Constants.R_HEADS)) {
            result.add(entry.getValue());
        }
    }
    if (master != null) {
        result.add(0, master);
    }
    return result;
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

public List<String> listBranches() throws IOException {
    ILockedRepository repo = null;//ww  w .j a v  a2  s .  c om
    try {
        repo = getCentralRepository();
        List<String> result = Lists.newArrayList(RepositoryUtils.getBranches(repo.r()));
        final int prefixLen = "refs/heads/".length(); //$NON-NLS-1$
        Function<String, String> function = new Function<String, String>() {
            @Override
            public String apply(String branch) {
                return branch.substring(prefixLen);
            }
        };
        result = Lists.newArrayList(Lists.transform(result, function));
        result.remove(Constants.MASTER);
        Collections.sort(result);
        return result;
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManagerTest.java

License:Open Source License

@Test
public void createCentralRepository() throws IOException, GitAPIException {
    File reposDir = tempDir.getRoot();
    ProjectRepositoryManager repoManager = new ProjectRepositoryManager("project", reposDir, lockManager, //$NON-NLS-1$
            eventBus);/*from   w  w w.  j  a va 2s . c om*/
    ILockedRepository lockedRepo = null;
    try {
        lockedRepo = repoManager.createCentralRepository(USER);
    } finally {
        Closeables.closeQuietly(lockedRepo);
        lockedRepo = null;
    }

    Repository repo = null;
    try {
        repo = new RepositoryBuilder().findGitDir(new File(reposDir, "_central")).build(); //$NON-NLS-1$
        assertEquals(new File(new File(reposDir, "_central"), ".git"), repo.getDirectory()); //$NON-NLS-1$ //$NON-NLS-2$
        assertNotNull(CommitUtils.getCommit(repo, Constants.MASTER));
    } finally {
        RepositoryUtil.closeQuietly(repo);
    }
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

License:Apache License

private void createMasterBranchIfNotExists() throws CitationDBException {
    try (Git git = new Git(repository)) {
        String master = Constants.MASTER;
        ObjectId head = repository.resolve(REF_MASTER);
        if (head == null) {
            git.commit().setMessage("Initial commit").call();
            String readmeFileName = "README.md";
            String[] text = new String[] { "DO NOT DELETE DIRECTORY. USED BY RECITABLE" };
            Files.write(Paths.get(getWorkingTreeDir(), readmeFileName), Arrays.asList(text),
                    StandardCharsets.UTF_8, StandardOpenOption.CREATE);
            git.add().addFilepattern(readmeFileName).call();
            PersonIdent personIdent = new PersonIdent("ReCitable", "recitable@fatlenny.net");
            git.commit().setMessage("Created README.md").setAuthor(personIdent).setCommitter(personIdent)
                    .call();/*w  ww.ja  v  a  2 s. c om*/
        }
    } catch (RevisionSyntaxException | IOException | GitAPIException e) {
        throw new CitationDBException("Error creating branch master", e);
    }
}

From source file:net.vexelon.jdevlog.vcs.git.GitSource.java

License:Open Source License

@Override
public Iterator<?> getLastHistory(long maxEntries) throws SCMException {

    Iterable<RevCommit> log = null;

    try {/*from  w w w. j ava  2  s.c o m*/
        Git git = new Git(repository);
        LogCommand cmd = git.log();

        cmd.setMaxCount((int) maxEntries);
        //         cmd.addPath(Constants.MASTER);

        try {
            cmd.add(repository.resolve(Constants.MASTER));
        } catch (Exception e) {
            throw new SCMException("Error getting log messages!", e);
        }

        log = cmd.call();
    } catch (NoHeadException e) {
        throw new SCMException("Error getting log messages!", e);
    }

    return log.iterator();
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java

License:Apache License

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>/* w w w. j a  v a 2s .  c  o m*/
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        ScmVersion version, boolean recursive) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;

    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol())
            && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }

    Git git = null;
    try {

        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());

        String branch = version != null ? version.getName() : null;

        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }

        getLogger().debug("try checkout of branch: " + branch);

        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }

            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();

            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }

        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);

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

        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists()
                && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);

            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }

        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true)
                    .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }

        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        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> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        getLogger().debug("current branch: " + git.getRepository().getBranch());

        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.chodavarapu.jgitaws.jgit.AmazonRepository.java

License:Eclipse Distribution License

@Override
public void create(boolean bare) throws IOException {
    if (exists())
        throw new IOException(MessageFormat.format(JGitText.get().repositoryAlreadyExists, ""));

    String master = Constants.R_HEADS + Constants.MASTER;
    RefUpdate.Result result = updateRef(Constants.HEAD, true).link(master);
    if (result != RefUpdate.Result.NEW)
        throw new IOException(result.name());
}

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

License:Open Source License

protected final void doClone(final String remoteUrl, final String remoteName, final String branch)
        throws GitWrapException {
    final FileRepository repository = getRepository();

    final String branchRef = Constants.R_HEADS + (branch == null ? Constants.MASTER : branch);

    try {/*from www . ja  v a  2  s  . c  om*/
        final RefUpdate head = repository.updateRef(Constants.HEAD);
        head.disableRefLog();
        head.link(branchRef);

        final RemoteConfig remoteConfig = new RemoteConfig(repository.getConfig(), remoteName);
        remoteConfig.addURI(new URIish(remoteUrl));

        final String remoteRef = Constants.R_REMOTES + remoteName;

        RefSpec spec = new RefSpec();
        spec = spec.setForceUpdate(true);
        spec = spec.setSourceDestination(Constants.R_HEADS + "*", remoteRef + "/*");

        remoteConfig.addFetchRefSpec(spec);

        remoteConfig.update(repository.getConfig());

        repository.getConfig().setString("branch", branch, "remote", remoteName);
        repository.getConfig().setString("branch", branch, "merge", branchRef);

        repository.getConfig().save();

        fetch(remoteName);
        postClone(remoteUrl, branchRef);
    } catch (final IOException e) {
        throw new GitWrapException("Failed to clone from: %s. Reason: %s", e, remoteUrl, e.getMessage());
    } catch (final URISyntaxException e) {
        throw new GitWrapException("Failed to clone from: %s. Reason: %s", e, remoteUrl, e.getMessage());
    }
}

From source file:org.eclipse.egit.core.internal.GitURI.java

License:Open Source License

/**
 * Construct the {@link GitURI} for the given URI.
 *
 * @param uri/*from w w w .  jav  a  2s. co m*/
 *            the URI in the SCM URL format
 */
public GitURI(URI uri) {
    try {
        if (SCHEME_SCM.equals(uri.getScheme())) {
            final String ssp = uri.getSchemeSpecificPart();
            if (ssp.startsWith(SCHEME_GIT)) {
                int indexOfSemicolon = ssp.indexOf(';');
                URIish r = new URIish(ssp.substring(SCHEME_GIT.length() + 1, indexOfSemicolon));
                IPath p = null;
                String t = Constants.MASTER; // default
                String pn = null;
                String[] params = ssp.substring(indexOfSemicolon).split(";"); //$NON-NLS-1$
                for (String param : params) {
                    if (param.startsWith(KEY_PATH + '=')) {
                        p = new Path(param.substring(param.indexOf('=') + 1));
                    } else if (param.startsWith(KEY_TAG + '=')) {
                        t = param.substring(param.indexOf('=') + 1);
                    } else if (param.startsWith(KEY_PROJECT + '=')) {
                        pn = param.substring(param.indexOf('=') + 1);
                    }
                }
                this.repository = r;
                this.path = p;
                this.tag = t;
                this.projectName = pn;
                return;
            }
        }
        throw new IllegalArgumentException(
                NLS.bind(CoreText.GitURI_InvalidSCMURL, new String[] { uri.toString() }));
    } catch (URISyntaxException e) {
        Activator.logError(e.getMessage(), e);
        throw new IllegalArgumentException(
                NLS.bind(CoreText.GitURI_InvalidURI, new String[] { uri.toString(), e.getMessage() }));
    }
}

From source file:org.eclipse.egit.core.internal.ProjectReferenceImporter.java

License:Open Source License

/**
 * @param gitUrl//from  w w  w.j a  va2 s  .  co m
 * @param branch
 *            the branch to check out
 * @param allBranches
 *            all branches which should be checked out for this gitUrl
 * @return the directory where the project should be checked out
 */
private static IPath getWorkingDir(URIish gitUrl, String branch, Set<String> allBranches) {
    final IPath workspaceLocation = ResourcesPlugin.getWorkspace().getRoot().getRawLocation();
    final String humanishName = gitUrl.getHumanishName();
    String extendedName;
    if (allBranches.size() == 1 || branch.equals(Constants.MASTER))
        extendedName = humanishName;
    else
        extendedName = humanishName + "_" + branch; //$NON-NLS-1$
    final IPath workDir = workspaceLocation.append(extendedName);
    return workDir;
}