Java Code Examples for org.eclipse.jgit.storage.file.FileRepositoryBuilder#create()

The following examples show how to use org.eclipse.jgit.storage.file.FileRepositoryBuilder#create() . 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: GitFileDecorator.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private Repository repositoryForPath(HttpServletRequest request, IPath targetPath) throws CoreException, IOException {
	IPath requestPath = targetPath;

	if (request.getContextPath().length() != 0) {
		IPath contextPath = new Path(request.getContextPath());
		if (contextPath.isPrefixOf(targetPath)) {
			requestPath = targetPath.removeFirstSegments(contextPath.segmentCount());
		}
	}

	File gitDir = GitUtils.getGitDir(requestPath);
	if (gitDir == null)
		return null;

	Repository db = FileRepositoryBuilder.create(gitDir);
	return db;
}
 
Example 2
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 3
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<GitCommit> getLog(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));

        Iterable<RevCommit> logs = new Git(repo).log().call();
        ImmutableList.Builder<GitCommit> versions = ImmutableList.builder();
        for (RevCommit rev : logs) {
            versions.add(new GitCommit(rev.getName(), rev.getAuthorIdent().getName(), new Date(rev.getCommitTime() * 1000L), rev.getShortMessage(), rev.getFullMessage()));
        }
        repo.close();
        return versions.build();

    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: Scenarios.java    From jgitver with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ScenarioBuilder object pointing to a temporary fresh new & empty git repository. 
 */
public ScenarioBuilder() {
    try {
        this.scenario = new Scenario(new File(Files.createTempDir(), ".git"));
        this.repository = FileRepositoryBuilder.create(scenario.getRepositoryLocation());
        repository.create();
        this.git = new Git(repository);
    } catch (Exception ex) {
        throw new IllegalStateException("failure building scenario", ex);
    }
}
 
Example 5
Source File: GitTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected void createRepository() throws IOException, GitAPIException, CoreException {
	IPath randomLocation = createTempDir();
	gitDir = randomLocation.toFile();
	randomLocation = randomLocation.addTrailingSeparator().append(Constants.DOT_GIT);
	File dotGitDir = randomLocation.toFile().getCanonicalFile();
	db = FileRepositoryBuilder.create(dotGitDir);
	toClose.add(db);
	assertFalse(dotGitDir.exists());
	db.create(false /* non bare */);

	testFile = new File(gitDir, "test.txt");
	testFile.createNewFile();
	createFile(testFile.toURI(), "test");
	File folder = new File(gitDir, "folder");
	folder.mkdir();
	File folderFile = new File(folder, "folder.txt");
	folderFile.createNewFile();
	createFile(folderFile.toURI(), "folder");

	Git git = Git.wrap(db);
	git.add().addFilepattern(".").call();
	git.commit().setMessage("Initial commit").call();

	// The system settings on eclipse.org was changed to receive.denyNonFastForward=true, see bug 343150.
	// Imitate the same setup when running tests locally, see bug 371881.
	StoredConfig cfg = db.getConfig();
	cfg.setBoolean("receive", null, "denyNonFastforwards", true);
	cfg.save();
}
 
Example 6
Source File: GitRemoteTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testRemoteProperties() throws IOException, SAXException, JSONException, CoreException, URISyntaxException {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	String workspaceId = workspaceIdFromLocation(workspaceLocation);
	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	IPath clonePath = getClonePath(workspaceId, project);
	JSONObject clone = clone(clonePath);
	String remotesLocation = clone.getString(GitConstants.KEY_REMOTE);
	project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

	// create remote
	final String remoteName = "remote1";
	final String remoteUri = "http://remote1.com";
	final String fetchRefSpec = "+refs/heads/*:refs/remotes/%s/*";
	final String pushUri = "http://remote2.com";
	final String pushRefSpec = "refs/heads/*:refs/heads/*";
	addRemote(remotesLocation, remoteName, remoteUri, fetchRefSpec, pushUri, pushRefSpec);

	Repository db2 = FileRepositoryBuilder.create(GitUtils.getGitDir(new Path(toRelativeURI(clonePath.toString()))));
	toClose.add(db2);
	StoredConfig config = db2.getConfig();
	RemoteConfig rc = new RemoteConfig(config, remoteName);

	assertNotNull(rc);
	// main uri
	assertEquals(1, rc.getURIs().size());
	assertEquals(new URIish(remoteUri).toString(), rc.getURIs().get(0).toString());
	// fetchRefSpec
	assertEquals(1, rc.getFetchRefSpecs().size());
	assertEquals(new RefSpec(fetchRefSpec), rc.getFetchRefSpecs().get(0));
	// pushUri
	assertEquals(1, rc.getPushURIs().size());
	assertEquals(new URIish(pushUri).toString(), rc.getPushURIs().get(0).toString());
	// pushRefSpec
	assertEquals(1, rc.getPushRefSpecs().size());
	assertEquals(new RefSpec(pushRefSpec), rc.getPushRefSpecs().get(0));
}
 
Example 7
Source File: FetchJob.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private Repository getRepository() throws IOException, CoreException {
	IPath p = null;
	if (path.segment(1).equals("file")) //$NON-NLS-1$
		p = path.removeFirstSegments(1);
	else
		p = path.removeFirstSegments(2);
	return FileRepositoryBuilder.create(GitUtils.getGitDir(p));
}
 
Example 8
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 9
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public static String getCloneUrl(File gitDir) {
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(resolveGitDir(gitDir));
		return getCloneUrl(db);
	} catch (IOException e) {
		// ignore and skip Git URL
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return null;
}
 
Example 10
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 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: LocalGitProvider.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void resetToParent(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).reset().setRef(repo.resolve("HEAD^").getName()).call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Source File: Helper.java    From tutorials with MIT License 5 votes vote down vote up
public static Repository createNewRepository() throws IOException {
    // prepare a new folder
    File localPath = File.createTempFile("TestGitRepository", "");
    if(!localPath.delete()) {
        throw new IOException("Could not delete temporary file " + localPath);
    }

    // create the directory
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();

    return repository;
}
 
Example 14
Source File: JGitSampleRepoManager.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
public static void gitPull(String localPathDynamic) {
	Repository localRepo;
	try {
		localRepo = FileRepositoryBuilder.create(new File(localPathDynamic + File.separator + ".git"));
		git = new Git(localRepo);
		PullCommand pullCmd = git.pull();
		pullCmd.call();
	} catch (IOException | GitAPIException e) {
		log.error("Error in pulling content from the git repository, hence proceeding with the previously cloned content ," + e);
	} 

}
 
Example 15
Source File: JGitHelper.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    Repository repository = null;
    try {
        Git.init().setDirectory(workingDir).call();

        repository = FileRepositoryBuilder.create(new File(workingDir.getAbsolutePath(), ".git"));
    } catch (Exception e) {
        throw new RuntimeException("init failed", e);
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
}
 
Example 16
Source File: SMAGitTest.java    From salesforce-migration-assistant with MIT License 4 votes vote down vote up
/**
 * Before to setup the test.
 *
 * @throws Exception
 */
@Before
public void setUp() throws Exception
{
    //Setup the fake repository
    localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();
    repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();

    File classesPath = new File(repository.getDirectory().getParent() + "/src/classes");
    classesPath.mkdirs();
    File pagesPath = new File(repository.getDirectory().getParent() + "/src/pages");
    pagesPath.mkdirs();
    File triggersPath = new File(repository.getDirectory().getParent() + "/src/triggers");
    triggersPath.mkdirs();


    //Add the first collection of files
    deletion = createFile("deleteThis.cls", classesPath);
    deleteMeta = createFile("deleteThis.cls-meta.xml", classesPath);
    modification = createFile("modifyThis.page", pagesPath);
    modifyMeta = createFile("modifyThis.page-meta.xml", pagesPath);
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page-meta.xml").call();

    //Create the first commit
    RevCommit firstCommit = new Git(repository).commit().setMessage("Add deleteThis and modifyThis").call();
    oldSha = firstCommit.getName();


    //Delete the deletion file, modify the modification file, and add the addition file
    new Git(repository).rm().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).rm().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();
    modification.setExecutable(true);
    addition = createFile("addThis.trigger", triggersPath);
    addMeta = createFile("addThis.trigger-meta.xml", triggersPath);
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page-meta.xml").call();
    new Git(repository).add().addFilepattern("src/triggers/addThis.trigger").call();
    new Git(repository).add().addFilepattern("src/triggers/addThis.trigger-meta.xml").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();

    //Create the second commit
    RevCommit secondCommit = new Git(repository).commit().setMessage("Remove deleteThis. Modify " +
            "modifyThis. Add addThis.").call();
    newSha = secondCommit.getName();

    gitDir = localPath.getPath();
}
 
Example 17
Source File: GitRemoteHandlerV1.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private boolean addRemote(HttpServletRequest request, HttpServletResponse response, String path, Boolean isGerrit) throws IOException, JSONException, ServletException,
		CoreException, URISyntaxException {
	// expected path: /git/remote/file/{path}
	Path p = new Path(path);
	JSONObject toPut = OrionServlet.readJSONRequest(request);
	String remoteName = toPut.optString(GitConstants.KEY_REMOTE_NAME, null);
	// remoteName is required
	if (remoteName == null || remoteName.isEmpty() || remoteName.contains(" ")) { //$NON-NLS-1$
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
				"Remote name must be provided", null));
	}
	String remoteURI = toPut.optString(GitConstants.KEY_REMOTE_URI, null);
	// remoteURI is required
	if (remoteURI == null || remoteURI.isEmpty()) {
		return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
				"Remote URI must be provided", null));
	}

	try {
		URIish uri = new URIish(remoteURI);
		if (GitUtils.isForbiddenGitUri(uri)) {
			statusHandler.handleRequest(
					request,
					response,
					new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind(
							"Remote URI {0} does not appear to be a git repository", remoteURI), null)); //$NON-NLS-1$
			return false;
		}
	} catch (URISyntaxException e) {
		statusHandler.handleRequest(request, response,
				new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, NLS.bind("Invalid remote URI: {0}", remoteURI), e)); //$NON-NLS-1$
		return false;
	}

	String fetchRefSpec = toPut.optString(GitConstants.KEY_REMOTE_FETCH_REF, null);
	String remotePushURI = toPut.optString(GitConstants.KEY_REMOTE_PUSH_URI, null);
	String pushRefSpec = toPut.optString(GitConstants.KEY_REMOTE_PUSH_REF, null);

	File gitDir = GitUtils.getGitDir(p);
	URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.REMOTE_LIST);
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(gitDir);
		StoredConfig config = db.getConfig();

		RemoteConfig rc = new RemoteConfig(config, remoteName);
		rc.addURI(new URIish(remoteURI));

		if(!isGerrit){
			// FetchRefSpec is required, but default version can be generated
			// if it isn't provided
			if (fetchRefSpec == null || fetchRefSpec.isEmpty()) {
				fetchRefSpec = String.format("+refs/heads/*:refs/remotes/%s/*", remoteName); //$NON-NLS-1$
			}
			rc.addFetchRefSpec(new RefSpec(fetchRefSpec));
		}else{
			rc.addFetchRefSpec(new RefSpec(String.format("+refs/heads/*:refs/remotes/%s/for/*", remoteName)));
			rc.addFetchRefSpec(new RefSpec(String.format("+refs/changes/*:refs/remotes/%s/changes/*", remoteName)));
		}
		// pushURI is optional
		if (remotePushURI != null && !remotePushURI.isEmpty())
			rc.addPushURI(new URIish(remotePushURI));
		// PushRefSpec is optional
		if (pushRefSpec != null && !pushRefSpec.isEmpty())
			rc.addPushRefSpec(new RefSpec(pushRefSpec));

		rc.update(config);
		config.save();

		Remote remote = new Remote(cloneLocation, db, remoteName);
		JSONObject result = new JSONObject();
		result.put(ProtocolConstants.KEY_LOCATION, remote.getLocation());
		OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
		response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
		response.setStatus(HttpServletResponse.SC_CREATED);
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return true;
}
 
Example 18
Source File: GitConfigHandlerV1.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path) throws CoreException, IOException, JSONException,
		ServletException, URISyntaxException, ConfigInvalidException {
	Path p = new Path(path);
	if (p.segment(0).equals(Clone.RESOURCE) && p.segment(1).equals("file")) { //$NON-NLS-1$
		// expected path /gitapi/config/clone/file/{path}
		File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
		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(1)),
							null));
		URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.CONFIG);
		JSONObject toPost = OrionServlet.readJSONRequest(request);
		String key = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_KEY, null);
		if (key == null || key.isEmpty())
			return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
					"Config entry key must be provided", null));
		String value = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_VALUE, null);
		if (value == null || value.isEmpty())
			return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
					"Config entry value must be provided", null));
		Repository db = null;
		try {
			db = FileRepositoryBuilder.create(gitDir);
			ConfigOption configOption = new ConfigOption(cloneLocation, db, key);
			boolean present = configOption.exists();
			ArrayList<String> valList = new ArrayList<String>();
			if (present) {
				String[] val = configOption.getValue();
				valList.addAll(Arrays.asList(val));
			}
			valList.add(value);
			save(configOption, valList);

			JSONObject result = configOption.toJSON();
			OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
			response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
			response.setStatus(HttpServletResponse.SC_CREATED);
			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 19
Source File: PushJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.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);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example 20
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;
}