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

The following examples show how to use org.eclipse.jgit.lib.Repository#close() . 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: JGitUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static void persistUser (File root, GitUser author) throws GitException {
    Repository repository = getRepository(root);
    if (repository != null) {
        try {
            StoredConfig config = repository.getConfig();
            config.setString("user", null, "name", author.getName()); //NOI18N
            config.setString("user", null, "email", author.getEmailAddress()); //NOI18N
            try {
                config.save();
                FileUtil.refreshFor(new File(GitUtils.getGitFolderForRoot(root), "config"));
            } catch (IOException ex) {
                throw new GitException(ex);
            }
        } finally {
            repository.close();
        }
    }
}
 
Example 2
Source File: GitFileDecorator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private void addGitLinks(HttpServletRequest request, URI location, JSONObject representation)
		throws URISyntaxException, JSONException, CoreException, IOException {
	Repository db = null;
	try {
		db = repositoryForPath(request, new Path(location.getPath()));
		if (db != null) {
			URI cloneLocation = BaseToCloneConverter.getCloneLocation(location, BaseToCloneConverter.FILE);
			String branch = db.getBranch();
			Remote defaultRemote = new Remote(cloneLocation, db, Constants.DEFAULT_REMOTE_NAME);
			RemoteBranch defaultRemoteBranch = new RemoteBranch(cloneLocation, db, defaultRemote, branch);
			addGitLinks(request, location, representation, cloneLocation, db, defaultRemoteBranch, branch);
		}
	} finally {
		if (db != null) {
			db.close();
		}
	}
}
 
Example 3
Source File: GitSubmoduleHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean handleDelete(RequestInfo requestInfo) throws ServletException {
	HttpServletRequest request = requestInfo.request;
	HttpServletResponse response = requestInfo.response;
	Repository db = requestInfo.db;
	Repository parentRepo = null;
	try {
		Map<IPath, File> parents = GitUtils.getGitDirs(requestInfo.filePath.removeLastSegments(1), Traverse.GO_UP);
		if (parents.size() < 1)
			return false;
		parentRepo = FileRepositoryBuilder.create(parents.entrySet().iterator().next().getValue());
		String pathToSubmodule = db.getWorkTree().toString().substring(parentRepo.getWorkTree().toString().length() + 1);
		removeSubmodule(db, parentRepo, pathToSubmodule);
		return true;
	} catch (Exception ex) {
		String msg = "An error occured for delete submodule command.";
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
	}finally{
		if (parentRepo != null) {
			parentRepo.close();
		}
	}
   
}
 
Example 4
Source File: GitRemoteHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, URISyntaxException,
		JSONException, ServletException {
	Path p = new Path(path);
	if (p.segment(1).equals("file")) { //$NON-NLS-1$
		// expected path: /gitapi/remote/{remote}/file/{path}
		String remoteName = p.segment(0);

		File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
		Repository db = null;
		try {
			db = FileRepositoryBuilder.create(gitDir);
			StoredConfig config = db.getConfig();
			config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName);
			config.save();
			// TODO: handle result
			return true;
		} finally {
			if (db != null) {
				db.close();
			}
		}
	}
	return false;
}
 
Example 5
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean fetch(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).fetch().setCheckFetchedObjects(true).call();

        RevWalk walk = new RevWalk(repo);
        RevCommit commit = walk.parseCommit(repo.getRef("master").getObjectId());

        walk.reset();
        RevCommit originCommit = walk.parseCommit(repo.getRef("origin/master").getObjectId());

        repo.close();
        return !commit.getName().equals(originCommit.getName());
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: JGitUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static boolean isUserSetup (File root) {
    Repository repository = getRepository(root);
    boolean userExists = true;
    if (repository != null) {
        try {
            StoredConfig config = repository.getConfig();
            String name = config.getString("user", null, "name"); //NOI18N
            String email = config.getString("user", null, "email"); //NOI18N
            if (name == null || name.isEmpty() || email == null || email.isEmpty()) {
                userExists = false;
            }
        } finally {
            repository.close();
        }
    }
    return userExists;
}
 
Example 7
Source File: GitManager.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Date getDateForRevision(VcsRepository repository, String revision) throws Exception {
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	walk.parseCommit(iterator.next());
	
	Date date = null;
	while (iterator.hasNext()) {
		RevCommit commit = iterator.next();
		if (commit.getId().getName().equals(revision)) {
			date = new Date(Long.valueOf(commit.getCommitTime())*1000); 
		}
	}
	
	repo.close();
	git.close();

	return date;
}
 
Example 8
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean rebase(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        RebaseResult result = new Git(repo).rebase().setUpstream("origin/master").call();

        if (result.getStatus() == RebaseResult.Status.STOPPED) {
            new Git(repo).rebase().setOperation(RebaseCommand.Operation.ABORT).call();
            repo.close();
            return false;
        }
        repo.close();
        return true;

    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: DefaultProjectManager.java    From onedev with MIT License 5 votes vote down vote up
@Listen
public void on(SystemStopping event) {
	taskScheduler.unschedule(taskId);
	synchronized(repositoryCache) {
		for (Repository repository: repositoryCache.values()) {
			repository.close();
		}
	}
}
 
Example 10
Source File: JGitUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static RepositoryInfo.PushMode getPushMode (File root) {
    Repository repository = getRepository(root);
    if (repository != null) {
        try {
            String val = repository.getConfig().getString("push", null, "default"); //NOI18N
            if ("upstream".equals(val)) { //NOI18N
                return PushMode.UPSTREAM;
            }
        } finally {
            repository.close();
        }
    }
    return PushMode.ASK;
}
 
Example 11
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void resetHard(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
public boolean deleteSiteGitRepo(String site) {
    boolean toReturn;

    // Get the Sandbox Path
    Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, site);
    // Get parent of that (since every site has two repos: Sandbox and Published)
    Path sitePath = siteSandboxPath.getParent();
    // Get a file handle to the parent and delete it
    File siteFolder = sitePath.toFile();

    try {
        Repository sboxRepo = sandboxes.get(site);
        if (sboxRepo != null) {
            sboxRepo.close();
            sandboxes.remove(site);
            RepositoryCache.close(sboxRepo);
            sboxRepo = null;
        }
        Repository pubRepo = published.get(site);
        if (pubRepo != null) {
            pubRepo.close();
            published.remove(site);
            RepositoryCache.close(pubRepo);
            pubRepo = null;
        }
        FileUtils.deleteDirectory(siteFolder);

        toReturn = true;

        logger.debug("Deleted site: " + site + " at path: " + sitePath);
    } catch (IOException e) {
        logger.error("Failed to delete site: " + site + " at path: " + sitePath + " exception " +
                e.toString());
        toReturn = false;
    }

    return toReturn;
}
 
Example 13
Source File: GitConfigHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private boolean handleDelete(HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, ServletException,
		ConfigInvalidException, URISyntaxException {
	Path p = new Path(path);
	if (p.segment(1).equals(Clone.RESOURCE) && p.segment(2).equals("file")) { //$NON-NLS-1$
		// expected path /gitapi/config/{key}/clone/file/{path}
		File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
		if (gitDir == null)
			return statusHandler.handleRequest(request, response,
					new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("No repository found under {0}", p.removeFirstSegments(2)),
							null));
		Repository db = null;
		URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.CONFIG_OPTION);
		try {
			db = FileRepositoryBuilder.create(gitDir);
			ConfigOption configOption = new ConfigOption(cloneLocation, db, GitUtils.decode(p.segment(0)));
			if (configOption.exists()) {
				String query = request.getParameter("index"); //$NON-NLS-1$
				if (query != null) {
					List<String> existing = new ArrayList<String>(Arrays.asList(configOption.getValue()));
					existing.remove(Integer.parseInt(query));
					save(configOption, existing);
				} else {
					delete(configOption);
				}
				response.setStatus(HttpServletResponse.SC_OK);
			} else {
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			}
			return true;
		} catch (IllegalArgumentException e) {
			return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), e));
		} finally {
			if (db != null) {
				db.close();
			}
		}
	}
	return false;
}
 
Example 14
Source File: GitManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
	public int compareVersions(VcsRepository repository, String versionOne, String versionTwo) throws Exception {
		Git git = getGit((GitRepository)repository);
		
		Repository repo = git.getRepository();
		RevWalk walk = new RevWalk(repo);
		
		Iterator<RevCommit> iterator = git.log().call().iterator();
		walk.parseCommit(iterator.next());
		
		List<String> revisions = new ArrayList<String>();
		
		// The commits are ordered latest first, so we want the last one.
		while(iterator.hasNext()) { 
			RevCommit commit = iterator.next();
			revisions.add(commit.getId().getName());
		}
		Integer oneIndex = revisions.indexOf(versionOne);
		Integer twoIndex = revisions.indexOf(versionTwo);
		
//		System.out.println(oneIndex);
//		System.out.println(twoIndex);
//		System.out.println(revisions);
		
		repo.close();
		git.close();
		
		// Because the revision list is reversed, we compare two to one instead of the other way around
		return twoIndex.compareTo(oneIndex);
	}
 
Example 15
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE",
                    justification = "JGit interaction with spotbugs")
@Deprecated
@Override
public boolean isBareRepository(String GIT_DIR) throws GitException, InterruptedException {
    Repository repo = null;
    boolean isBare = false;
    if (GIT_DIR == null) {
        throw new GitException("Not a git repository"); // Compatible with CliGitAPIImpl
    }
    try {
        if (isBlank(GIT_DIR) || !(new File(GIT_DIR)).isAbsolute()) {
            if ((new File(workspace, ".git")).exists()) {
                repo = getRepository();
            } else {
                repo = new RepositoryBuilder().setGitDir(workspace).build();
            }
        } else {
            repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build();
        }
        isBare = repo.isBare();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    } finally {
        if (repo != null) repo.close();
    }
    return isBare;
}
 
Example 16
Source File: GitIndexHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException {
	Repository db = null;
	try {
		IPath p = new Path(path);
		IPath filePath = p.hasTrailingSeparator() ? p : p.removeLastSegments(1);
		if (!AuthorizationService.checkRights(request.getRemoteUser(), "/" + filePath.toString(), request.getMethod())) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return true;
		}
		Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
		File gitDir = set.iterator().next().getValue();
		if (gitDir == null)
			return false; // TODO: or an error response code, 405?
		db = FileRepositoryBuilder.create(gitDir);
		switch (getMethod(request)) {
		case GET:
			return handleGet(request, response, db, GitUtils.getRelativePath(p, set.iterator().next().getKey()));
		case PUT:
			return handlePut(request, response, db, GitUtils.getRelativePath(p, set.iterator().next().getKey()));
		case POST:
			return handlePost(request, response, db, p);
		default:
			// fall through and return false below
		}
	} catch (Exception e) {
		String msg = NLS.bind("Failed to process an operation on index for {0}", path); //$NON-NLS-1$
		ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
		LogHelper.log(status);
		return statusHandler.handleRequest(request, response, status);
	} finally {
		if (db != null)
			db.close();
	}
	return false;
}
 
Example 17
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void commit(List<String> rootDirPath, String committerName, String committerEmail, String title, String description) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).commit().setAuthor(committerName, committerEmail).setMessage(title + "\n\n" + description).call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addAll(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));
    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).add().addFilepattern(".").call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 19
Source File: PullJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPull(IProgressMonitor monitor) throws IOException, GitAPIException, CoreException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(GitUtils.getGitDir(path));
		Git git = Git.wrap(db);
		PullCommand pc = git.pull();
		pc.setProgressMonitor(gitMonitor);
		pc.setCredentialsProvider(credentials);
		pc.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		PullResult pullResult = pc.call();

		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}

		// handle result
		if (pullResult.isSuccessful()) {
			return Status.OK_STATUS;
		}
		FetchResult fetchResult = pullResult.getFetchResult();

		IStatus fetchStatus = FetchJob.handleFetchResult(fetchResult);
		if (!fetchStatus.isOK()) {
			return fetchStatus;
		}

		MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
		if (!mergeStatus.isSuccessful())
			return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return Status.OK_STATUS;
}
 
Example 20
Source File: FetchJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doFetch(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = getRepository();
		Git git = Git.wrap(db);
		FetchCommand fc = git.fetch();
		fc.setProgressMonitor(gitMonitor);

		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		if (this.cookie != null) {
			fc.setTransportConfigCallback(new TransportConfigCallback() {
				@Override
				public void configure(Transport t) {
					if (t instanceof TransportHttp && cookie != null) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
						((TransportHttp) t).setAdditionalHeaders(map);
					}
				}
			});
		}
		fc.setCredentialsProvider(credentials);
		fc.setRemote(remote);
		if (branch != null) {
			// refs/heads/{branch}:refs/remotes/{remote}/{branch}
			String remoteBranch = branch;
			if (branch.startsWith("for/")) {
				remoteBranch = branch.substring(4);
			}

			RefSpec spec = new RefSpec(Constants.R_HEADS + remoteBranch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
			spec = spec.setForceUpdate(force);
			fc.setRefSpecs(spec);
		}
		FetchResult fetchResult = fc.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		GitJobUtils.packRefs(db, gitMonitor);
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		return handleFetchResult(fetchResult);
	} finally {
		if (db != null) {
			db.close();
		}
	}
}