Search in sources :

Example 36 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.

the class JGitConnection method clone.

public void clone(CloneParams params) throws GitException, UnauthorizedException {
    String remoteUri = params.getRemoteUrl();
    boolean removeIfFailed = false;
    try {
        if (params.getRemoteName() == null) {
            params.setRemoteName(Constants.DEFAULT_REMOTE_NAME);
        }
        if (params.getWorkingDir() == null) {
            params.setWorkingDir(repository.getWorkTree().getCanonicalPath());
        }
        // If clone fails and the .git folder didn't exist we want to remove it.
        // We have to do this here because the clone command doesn't revert its own changes in case of failure.
        removeIfFailed = !repository.getDirectory().exists();
        CloneCommand cloneCommand = Git.cloneRepository().setDirectory(new File(params.getWorkingDir())).setRemote(params.getRemoteName()).setCloneSubmodules(params.isRecursive()).setURI(remoteUri);
        if (params.getBranchesToFetch().isEmpty()) {
            cloneCommand.setCloneAllBranches(true);
        } else {
            cloneCommand.setBranchesToClone(params.getBranchesToFetch());
        }
        LineConsumer lineConsumer = lineConsumerFactory.newLineConsumer();
        cloneCommand.setProgressMonitor(new BatchingProgressMonitor() {

            @Override
            protected void onUpdate(String taskName, int workCurr) {
                try {
                    lineConsumer.writeLine(taskName + ": " + workCurr + " completed");
                } catch (IOException exception) {
                    LOG.error(exception.getMessage(), exception);
                }
            }

            @Override
            protected void onEndTask(String taskName, int workCurr) {
            }

            @Override
            protected void onUpdate(String taskName, int workCurr, int workTotal, int percentDone) {
                try {
                    lineConsumer.writeLine(taskName + ": " + workCurr + " of " + workTotal + " completed, " + percentDone + "% done");
                } catch (IOException exception) {
                    LOG.error(exception.getMessage(), exception);
                }
            }

            @Override
            protected void onEndTask(String taskName, int workCurr, int workTotal, int percentDone) {
            }
        });
        ((Git) executeRemoteCommand(remoteUri, cloneCommand, params.getUsername(), params.getPassword())).close();
        StoredConfig repositoryConfig = getRepository().getConfig();
        GitUser gitUser = getUser();
        if (gitUser != null) {
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, gitUser.getName());
            repositoryConfig.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, gitUser.getEmail());
        }
        repositoryConfig.save();
    } catch (IOException | GitAPIException exception) {
        // Delete .git directory in case it was created
        if (removeIfFailed) {
            deleteRepositoryFolder();
        }
        //try to clone repository by replacing http to https in the url if HTTP 301 redirect happened
        if (exception.getMessage().contains(": 301 Moved Permanently")) {
            remoteUri = "https" + remoteUri.substring(4);
            try {
                clone(params.withRemoteUrl(remoteUri));
            } catch (UnauthorizedException | GitException e) {
                throw new GitException("Failed to clone the repository", e);
            }
            return;
        }
        String message = generateExceptionMessage(exception);
        throw new GitException(message, exception);
    }
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) GitUser(org.eclipse.che.api.git.shared.GitUser) StoredConfig(org.eclipse.jgit.lib.StoredConfig) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) Git(org.eclipse.jgit.api.Git) BatchingProgressMonitor(org.eclipse.jgit.lib.BatchingProgressMonitor) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Example 37 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.

the class JGitConnection method mv.

@Override
public void mv(String source, String target) throws GitException {
    try {
        getGit().add().addFilepattern(target).call();
        getGit().rm().addFilepattern(source).call();
    } catch (GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) GitException(org.eclipse.che.api.git.exception.GitException)

Example 38 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gitblit by gitblit.

the class GitServletTest method testCreateOnPush.

private void testCreateOnPush(boolean canCreate, boolean canAdmin) throws Exception {
    UserModel user = new UserModel("sampleuser");
    user.password = user.username;
    delete(user);
    user.canCreate = canCreate;
    user.canAdmin = canAdmin;
    gitblit().addUser(user);
    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);
    // fork from original to a temporary bare repo
    File tmpFolder = File.createTempFile("gitblit", "").getParentFile();
    File createCheck = new File(tmpFolder, "ticgit.git");
    if (createCheck.exists()) {
        FileUtils.delete(createCheck, FileUtils.RECURSIVE);
    }
    File personalRepo = new File(GitBlitSuite.REPOSITORIES, MessageFormat.format("~{0}/ticgit.git", user.username));
    GitBlitSuite.close(personalRepo);
    if (personalRepo.exists()) {
        FileUtils.delete(personalRepo, FileUtils.RECURSIVE);
    }
    File projectRepo = new File(GitBlitSuite.REPOSITORIES, "project/ticgit.git");
    GitBlitSuite.close(projectRepo);
    if (projectRepo.exists()) {
        FileUtils.delete(projectRepo, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/ticgit.git", url));
    clone.setDirectory(createCheck);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    Git git = clone.call();
    GitBlitSuite.close(personalRepo);
    // add a personal repository remote and a project remote
    git.getRepository().getConfig().setString("remote", "user", "url", MessageFormat.format("{0}/~{1}/ticgit.git", url, user.username));
    git.getRepository().getConfig().setString("remote", "project", "url", MessageFormat.format("{0}/project/ticgit.git", url));
    git.getRepository().getConfig().save();
    // push to non-existent user repository
    try {
        Iterable<PushResult> results = git.push().setRemote("user").setPushAll().setCredentialsProvider(cp).call();
        for (PushResult result : results) {
            RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
            Status status = ref.getStatus();
            assertTrue("User failed to create repository?! " + status.name(), Status.OK.equals(status));
        }
        assertTrue("User canAdmin:" + user.canAdmin + " canCreate:" + user.canCreate, user.canAdmin || user.canCreate);
        // confirm default personal repository permissions
        RepositoryModel model = repositories().getRepositoryModel(MessageFormat.format("~{0}/ticgit.git", user.username));
        assertEquals("Unexpected owner", user.username, ArrayUtils.toString(model.owners));
        assertEquals("Unexpected authorization control", AuthorizationControl.NAMED, model.authorizationControl);
        assertEquals("Unexpected access restriction", AccessRestrictionType.VIEW, model.accessRestriction);
    } catch (GitAPIException e) {
        assertTrue(e.getMessage(), e.getMessage().contains("git-receive-pack not found"));
        assertFalse("User canAdmin:" + user.canAdmin + " canCreate:" + user.canCreate, user.canAdmin || user.canCreate);
    }
    // push to non-existent project repository
    try {
        Iterable<PushResult> results = git.push().setRemote("project").setPushAll().setCredentialsProvider(cp).call();
        GitBlitSuite.close(git);
        for (PushResult result : results) {
            RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
            Status status = ref.getStatus();
            assertTrue("User failed to create repository?! " + status.name(), Status.OK.equals(status));
        }
        assertTrue("User canAdmin:" + user.canAdmin, user.canAdmin);
        // confirm default project repository permissions
        RepositoryModel model = repositories().getRepositoryModel("project/ticgit.git");
        assertEquals("Unexpected owner", user.username, ArrayUtils.toString(model.owners));
        assertEquals("Unexpected authorization control", AuthorizationControl.fromName(settings().getString(Keys.git.defaultAuthorizationControl, "NAMED")), model.authorizationControl);
        assertEquals("Unexpected access restriction", AccessRestrictionType.fromName(settings().getString(Keys.git.defaultAccessRestriction, "NONE")), model.accessRestriction);
    } catch (GitAPIException e) {
        assertTrue(e.getMessage(), e.getMessage().contains("git-receive-pack not found"));
        assertFalse("User canAdmin:" + user.canAdmin, user.canAdmin);
    }
    GitBlitSuite.close(git);
    delete(user);
}
Also used : UserModel(com.gitblit.models.UserModel) CloneCommand(org.eclipse.jgit.api.CloneCommand) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) Status(org.eclipse.jgit.transport.RemoteRefUpdate.Status) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) PushResult(org.eclipse.jgit.transport.PushResult) RepositoryModel(com.gitblit.models.RepositoryModel) File(java.io.File)

Example 39 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project gitblit by gitblit.

the class JGitUtils method createRepository.

/**
	 * Creates a bare, shared repository.
	 *
	 * @param repositoriesFolder
	 * @param name
	 * @param shared
	 *          the setting for the --shared option of "git init".
	 * @return Repository
	 */
public static Repository createRepository(File repositoriesFolder, String name, String shared) {
    try {
        Repository repo = null;
        try {
            Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(true).call();
            repo = git.getRepository();
        } catch (GitAPIException e) {
            throw new RuntimeException(e);
        }
        GitConfigSharedRepository sharedRepository = new GitConfigSharedRepository(shared);
        if (sharedRepository.isShared()) {
            StoredConfig config = repo.getConfig();
            config.setString("core", null, "sharedRepository", sharedRepository.getValue());
            config.setBoolean("receive", null, "denyNonFastforwards", true);
            config.save();
            if (!JnaUtils.isWindows()) {
                Iterator<File> iter = org.apache.commons.io.FileUtils.iterateFilesAndDirs(repo.getDirectory(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
                // Adjust permissions on file/directory
                while (iter.hasNext()) {
                    adjustSharedPerm(iter.next(), sharedRepository);
                }
            }
        }
        return repo;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) IOException(java.io.IOException) File(java.io.File)

Example 40 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project zeppelin by apache.

the class GitNotebookRepo method checkpoint.

/* implemented as git add+commit
   * @param pattern is the noteId
   * @param commitMessage is a commit message (checkpoint message)
   * (non-Javadoc)
   * @see org.apache.zeppelin.notebook.repo.VFSNotebookRepo#checkpoint(String, String)
   */
@Override
public Revision checkpoint(String pattern, String commitMessage, AuthenticationInfo subject) {
    Revision revision = Revision.EMPTY;
    try {
        List<DiffEntry> gitDiff = git.diff().call();
        if (!gitDiff.isEmpty()) {
            LOG.debug("Changes found for pattern '{}': {}", pattern, gitDiff);
            DirCache added = git.add().addFilepattern(pattern).call();
            LOG.debug("{} changes are about to be commited", added.getEntryCount());
            RevCommit commit = git.commit().setMessage(commitMessage).call();
            revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
        } else {
            LOG.debug("No changes found {}", pattern);
        }
    } catch (GitAPIException e) {
        LOG.error("Failed to add+comit {} to Git", pattern, e);
    }
    return revision;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) DirCache(org.eclipse.jgit.dircache.DirCache) DiffEntry(org.eclipse.jgit.diff.DiffEntry) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)60 IOException (java.io.IOException)25 Git (org.eclipse.jgit.api.Git)22 GitException (org.eclipse.che.api.git.exception.GitException)18 File (java.io.File)16 Ref (org.eclipse.jgit.lib.Ref)13 RevCommit (org.eclipse.jgit.revwalk.RevCommit)12 ArrayList (java.util.ArrayList)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 RefSpec (org.eclipse.jgit.transport.RefSpec)11 Repository (org.eclipse.jgit.lib.Repository)9 URISyntaxException (java.net.URISyntaxException)8 PushResult (org.eclipse.jgit.transport.PushResult)8 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)8 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)8 PushCommand (org.eclipse.jgit.api.PushCommand)7 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)6 FetchCommand (org.eclipse.jgit.api.FetchCommand)6 HashMap (java.util.HashMap)5 DiffCommitFile (org.eclipse.che.api.git.shared.DiffCommitFile)5