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.google.gerrit.acceptance.api.change.ChangeIT.java

License:Apache License

@Test
public void createEmptyChange() throws Exception {
    ChangeInfo in = new ChangeInfo();
    in.branch = Constants.MASTER;
    in.subject = "Create a change from the API";
    in.project = project.get();//from   w ww . j av a  2s  . c o m
    ChangeInfo info = gApi.changes().create(in).get();
    assertThat(info.project).isEqualTo(in.project);
    assertThat(info.branch).isEqualTo(in.branch);
    assertThat(info.subject).isEqualTo(in.subject);
    assertThat(Iterables.getOnlyElement(info.messages).message).isEqualTo("Uploaded patch set 1.");
}

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

License:Apache License

private List<String> normalizeBranchNames(List<String> branches) throws BadRequestException {
    if (branches == null || branches.isEmpty()) {
        return Collections.singletonList(Constants.R_HEADS + Constants.MASTER);
    }//from   w  ww  .  j  a v  a2  s  .c om

    List<String> normalizedBranches = new ArrayList<>();
    for (String branch : branches) {
        while (branch.startsWith("/")) {
            branch = branch.substring(1);
        }
        branch = RefNames.fullName(branch);
        if (!Repository.isValidRefName(branch)) {
            throw new BadRequestException(String.format("Branch \"%s\" is not a valid name.", branch));
        }
        if (!normalizedBranches.contains(branch)) {
            normalizedBranches.add(branch);
        }
    }
    return normalizedBranches;
}

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");
    }//from   w  w w . j  av  a2  s.c  om

    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.googlecode.ounit.GitQuestion.java

License:Open Source License

@Override
public String findHeadRevision() {
    if (cloneDir == null)
        findRepo();// ww  w .ja v a2s.  c om

    try {
        Repository repo = Git.open(cloneDir).getRepository();
        Ref ref = repo.getRef(version);
        if (ref == null)
            ref = repo.getRef(Constants.MASTER);

        return ref.getObjectId().name();
    } catch (IOException e) {
        throw new RuntimeException("Unable to find HEAD revision", e);
    }
}

From source file:com.microsoft.gittf.client.clc.commands.framework.Command.java

License:Open Source License

protected void verifyMasterBranch() throws Exception {
    final Repository repository = getRepository();

    if (!RepositoryUtil.isEmptyRepository(repository)) {
        Ref master = repository.getRef(Constants.R_HEADS + Constants.MASTER);
        Ref head = repository.getRef(Constants.HEAD);
        Ref masterHeadRef = master != null ? master.getLeaf() : null;
        Ref currentHeadRef = head != null ? head.getLeaf() : null;

        if (masterHeadRef == null || !masterHeadRef.getName().equals(currentHeadRef.getName())) {
            throw new Exception(Messages.getString("Command.MasterNotCurrentBranch")); //$NON-NLS-1$
        }/*from   w ww.j av  a  2 s. c om*/
    }
}

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

License:Open Source License

@Override
public TaskStatus run(final TaskProgressMonitor progressMonitor) throws Exception {
    final String taskName = Messages.formatString("CloneTask.CloningFormat", //$NON-NLS-1$
            tfsPath,/*from   ww  w .  ja  va  2  s  .  com*/
            bare ? repository.getDirectory().getAbsolutePath() : repository.getWorkTree().getAbsolutePath());

    progressMonitor.beginTask(taskName, 1,
            TaskProgressDisplay.DISPLAY_PROGRESS.combine(TaskProgressDisplay.DISPLAY_SUBTASK_DETAIL));

    /*
     * Query the changesets.
     */

    /* See if this is an actual server path. */
    final Item item = vcClient.getItem(tfsPath, versionSpec, DeletedState.NON_DELETED, GetItemsOptions.NONE);
    Check.notNull(item, "item"); //$NON-NLS-1$

    if (item.getItemType() != ItemType.FOLDER) {
        return new TaskStatus(TaskStatus.ERROR,
                Messages.formatString("CloneTask.CannotCloneFileFormat", tfsPath)); //$NON-NLS-1$
    }

    /* Determine the latest changeset on the server. */
    final Changeset[] changesets = vcClient.queryHistory(tfsPath, versionSpec, 0, RecursionType.FULL, null,
            new ChangesetVersionSpec(0), versionSpec, depth, false, false, false, false);

    /*
     * Create and configure the repository.
     */

    repository.create(bare);

    final ConfigureRepositoryTask configureTask = new ConfigureRepositoryTask(repository, serverURI, tfsPath);
    configureTask.setTag(tag);

    final TaskStatus configureStatus = new TaskExecutor(new NullTaskProgressMonitor()).execute(configureTask);

    if (!configureStatus.isOK()) {
        return configureStatus;
    }

    if (changesets.length > 0) {
        ObjectId lastCommitID = null;
        ObjectId lastTreeID = null;
        Item[] previousChangesetItems = null;

        /*
         * Download changesets.
         */
        final int numberOfChangesetToDownload = changesets.length;

        progressMonitor.setWork(numberOfChangesetToDownload);

        for (int i = numberOfChangesetToDownload; i > 0; i--) {
            CreateCommitForChangesetVersionSpecTask commitTask = new CreateCommitForChangesetVersionSpecTask(
                    repository, vcClient, changesets[i - 1], previousChangesetItems, lastCommitID, witClient);

            TaskStatus commitStatus = new TaskExecutor(progressMonitor.newSubTask(1)).execute(commitTask);

            if (!commitStatus.isOK()) {
                return commitStatus;
            }

            lastCommitID = commitTask.getCommitID();
            lastTreeID = commitTask.getCommitTreeID();
            previousChangesetItems = commitTask.getCommittedItems();

            Check.notNull(lastCommitID, "lastCommitID"); //$NON-NLS-1$
            Check.notNull(lastTreeID, "lastTreeID"); //$NON-NLS-1$

            new ChangesetCommitMap(repository).setChangesetCommit(changesets[i - 1].getChangesetID(),
                    commitTask.getCommitID());

            progressMonitor.displayVerbose(Messages.formatString("CloneTask.ClonedFormat", //$NON-NLS-1$
                    Integer.toString(changesets[i - 1].getChangesetID()),
                    ObjectIdUtil.abbreviate(repository, lastCommitID)));
        }

        progressMonitor.setDetail(Messages.getString("CloneTask.Finalizing")); //$NON-NLS-1$

        /* Update master head reference */
        RefUpdate ref = repository.updateRef(Constants.R_HEADS + Constants.MASTER);
        ref.setNewObjectId(lastCommitID);
        ref.update();

        /* Create tfs branch */
        TfsBranchUtil.create(repository, Constants.R_HEADS + Constants.MASTER);

        /*
         * Check out the cloned commit.
         */
        if (!bare) {
            DirCache dirCache = repository.lockDirCache();
            DirCacheCheckout checkout = new DirCacheCheckout(repository, dirCache, lastTreeID);
            checkout.checkout();
            dirCache.unlock();

            RepositoryUtil.fixFileAttributes(repository);
        }

        progressMonitor.endTask();

        final int finalChangesetID = changesets[0].getChangesetID();

        if (numberOfChangesetToDownload == 1) {
            progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedFormat", //$NON-NLS-1$
                    Integer.toString(finalChangesetID), ObjectIdUtil.abbreviate(repository, lastCommitID)));
        } else {
            progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedMultipleFormat", //$NON-NLS-1$
                    changesets.length, Integer.toString(finalChangesetID),
                    ObjectIdUtil.abbreviate(repository, lastCommitID)));
        }
    } else {
        // the folder exists on the server but is empty

        progressMonitor.displayMessage(Messages.getString("CloneTask.NothingToDownload")); //$NON-NLS-1$

        progressMonitor.displayMessage(Messages.formatString("CloneTask.ClonedFolderEmptyFormat", //$NON-NLS-1$
                tfsPath));
    }

    log.info("Clone task completed."); //$NON-NLS-1$

    return TaskStatus.OK_STATUS;
}

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

License:Open Source License

/**
 * Returns the commit id referenced by refs/heads/master
 * /*from www  . j a va  2s  .  c  o m*/
 * @param repository
 *        the git repository
 * @return
 * @throws Exception
 */
public static ObjectId getMasterHeadCommitID(final Repository repository) throws Exception {
    return getCommitId(repository, Constants.R_HEADS + Constants.MASTER);
}

From source file:com.puppetlabs.geppetto.forge.jenkins.RepositoryInfo.java

License:Open Source License

public static RepositoryInfo getRepositoryInfo(AbstractBuild<?, ?> build, BuildListener listener) {
    SCM scm = build.getProject().getScm();
    if (!(scm instanceof GitSCM))
        return null;

    GitSCM git = (GitSCM) scm;//w  ww.  j av a 2 s .  c  o  m
    FilePath gitRoot = git.getModuleRoot(build.getWorkspace(), build);
    List<UserRemoteConfig> repos = git.getUserRemoteConfigs();
    if (repos.size() == 0) {
        listener.error("Unable to find the Git repository URL");
        return null;
    }
    if (repos.size() > 1) {
        listener.error("Sorry, but publishing from multiple repositories is currently not supported");
        return null;
    }
    String repository = repos.get(0).getUrl();
    List<BranchSpec> branches = git.getBranches();
    String branchName = null;
    if (branches.size() == 0)
        branchName = Constants.MASTER;
    else if (branches.size() == 1) {
        BranchSpec branchSpec = branches.get(0);
        branchName = branchSpec.getName();
        if ("**".equals(branchName))
            branchName = Constants.MASTER;
        else if (branchName.startsWith("*/"))
            branchName = branchName.substring(2);
    } else {
        listener.error("Sorry, but publishing from multiple branches is not supported");
        return null;
    }
    return new RepositoryInfo(repository, branchName, gitRoot);
}

From source file:com.rimerosolutions.ant.git.tasks.FetchTask.java

License:Apache License

@Override
public void doExecute() {
    try {/*from w  ww .j av a  2s.  c o m*/
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES
                    + Constants.DEFAULT_REMOTE_NAME + "/*"));

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_REMOTE, Constants.DEFAULT_REMOTE_NAME);
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + Constants.MASTER);

            remoteConfig.update(config);
            config.save();
        }

        List<RefSpec> specs = new ArrayList<RefSpec>(3);

        specs.add(new RefSpec(
                "+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*"));
        specs.add(new RefSpec("+" + Constants.R_NOTES + "*:" + Constants.R_NOTES + "*"));
        specs.add(new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*"));

        FetchCommand fetchCommand = git.fetch().setDryRun(dryRun).setThin(thinPack).setRemote(getUri())
                .setRefSpecs(specs).setRemoveDeletedRefs(removeDeletedRefs);

        setupCredentials(fetchCommand);

        if (getProgressMonitor() != null) {
            fetchCommand.setProgressMonitor(getProgressMonitor());
        }

        FetchResult fetchResult = fetchCommand.call();

        GitTaskUtils.validateTrackingRefUpdates(FETCH_FAILED_MESSAGE, fetchResult.getTrackingRefUpdates());

        log(fetchResult.getMessages());

    } catch (URISyntaxException e) {
        throw new GitBuildException("Invalid URI syntax: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new GitBuildException("Could not save or get repository configuration: " + e.getMessage(), e);
    } catch (InvalidRemoteException e) {
        throw new GitBuildException("Invalid remote URI: " + e.getMessage(), e);
    } catch (TransportException e) {
        throw new GitBuildException("Communication error: " + e.getMessage(), e);
    } catch (GitAPIException e) {
        throw new GitBuildException("Unexpected exception: " + e.getMessage(), e);
    }
}

From source file:com.tasktop.c2c.server.internal.profile.service.template.GitServiceCloner.java

License:Open Source License

private void copyRepo(ScmRepository scmRepo, CloneContext context)
        throws IOException, JGitInternalException, GitAPIException {

    File workDirectory = null;//from  ww w. j  a v  a2s . c  om
    try {
        Project templateProject = context.getTemplateService().getProjectServiceProfile().getProject();
        String cloneUrl = jgitProvider.computeRepositoryUrl(templateProject.getIdentifier(), scmRepo.getName());

        AuthUtils.assumeSystemIdentity(templateProject.getIdentifier());
        tenancyManager.establishTenancyContext(context.getTemplateService());

        workDirectory = createTempDirectory();
        Git git = Git.cloneRepository().setDirectory(workDirectory)
                .setBranch(Constants.R_HEADS + Constants.MASTER).setURI(cloneUrl).call();

        AuthUtils.assumeSystemIdentity(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier());
        tenancyManager.establishTenancyContext(context.getTargetService());

        FileUtils.deleteDirectory(git.getRepository().getDirectory());

        git = Git.init().setDirectory(git.getRepository().getDirectory().getParentFile()).call();

        maybeRewriteRepo(workDirectory, context);

        String pushUrl = jgitProvider.computeRepositoryUrl(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier(),
                scmRepo.getName());

        // FIXME: User's locale is not defined here
        String commitMessage = messageSource.getMessage("project.template.git.commitMessage",
                new Object[] { templateProject.getName() }, null);

        git.add().addFilepattern(".").call();
        git.commit().setCommitter(committerName, committerEmail).setMessage(commitMessage).call();
        git.getRepository().getConfig().setString("remote", "target", "url", pushUrl);
        git.push().setRemote("target").setPushAll().call();
    } finally {
        if (workDirectory != null) {
            FileUtils.deleteDirectory(workDirectory);
        }
    }
}