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);
}
}
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);
}
}
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);
}
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);
}
}
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;
}
Aggregations