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

The following examples show how to use org.eclipse.jgit.lib.Repository#getConfig() . 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 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 2
Source File: GitCloneTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetCloneAndPull() throws Exception {
	// see bug 339254
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	String workspaceId = getWorkspaceId(workspaceLocation);

	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	String contentLocation = clone(workspaceId, project).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

	JSONArray clonesArray = listClones(workspaceId, null);
	assertEquals(1, clonesArray.length());

	Repository r = getRepositoryForContentLocation(contentLocation);

	// overwrite user settings, do not rebase when pulling, see bug 372489
	StoredConfig cfg = r.getConfig();
	cfg.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants.CONFIG_KEY_REBASE, false);
	cfg.save();

	// TODO: replace with RESTful API when ready, see bug 339114
	Git git = Git.wrap(r);
	PullResult pullResult = git.pull().call();
	assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE);
	assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState());
}
 
Example 3
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 4
Source File: UnignoreTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test199443_GlobalIgnoreFile () throws Exception {
    File f = new File(new File(workDir, "nbproject"), "file");
    f.getParentFile().mkdirs();
    f.createNewFile();
    File ignoreFile = new File(workDir.getParentFile(), "globalignore");
    write(ignoreFile, "nbproject");
    Repository repo = getRepository(getLocalGitRepository());
    StoredConfig cfg = repo.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EXCLUDESFILE, ignoreFile.getAbsolutePath());
    cfg.save();
    GitClient client = getClient(workDir);
    assertEquals(Status.STATUS_IGNORED, client.getStatus(new File[] { f }, NULL_PROGRESS_MONITOR).get(f).getStatusIndexWC());
    
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    
    write(new File(workDir, Constants.GITIGNORE_FILENAME), "/nbproject/file");
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    assertEquals("!/nbproject/file", read(new File(workDir, Constants.GITIGNORE_FILENAME)));
}
 
Example 5
Source File: IgnoreTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test199443_GlobalIgnoreFileOverwrite () throws Exception {
    File f = new File(new File(workDir, "nbproject"), "file");
    f.getParentFile().mkdirs();
    f.createNewFile();
    File ignoreFile = new File(workDir.getParentFile(), "globalignore");
    Repository repo = getRepository(getLocalGitRepository());
    StoredConfig cfg = repo.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EXCLUDESFILE, ignoreFile.getAbsolutePath());
    cfg.save();
    
    write(ignoreFile, "!nbproject");
    GitClient client = getClient(workDir);
    
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.ignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    assertEquals("/nbproject/file", read(new File(workDir, Constants.GITIGNORE_FILENAME)));
}
 
Example 6
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private Repository optimizeRepository(Repository repo) throws IOException {
    // Get git configuration
    StoredConfig config = repo.getConfig();
    // Set compression level (core.compression)
    config.setInt(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_COMPRESSION,
            CONFIG_PARAMETER_COMPRESSION_DEFAULT);
    // Set big file threshold (core.bigFileThreshold)
    config.setString(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_BIG_FILE_THRESHOLD,
            CONFIG_PARAMETER_BIG_FILE_THRESHOLD_DEFAULT);
    // Set fileMode
    config.setBoolean(CONFIG_SECTION_CORE, null, CONFIG_PARAMETER_FILE_MODE,
            CONFIG_PARAMETER_FILE_MODE_DEFAULT);
    // Save configuration changes
    config.save();

    return repo;
}
 
Example 7
Source File: RemoveRemoteCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    StoredConfig config = repository.getConfig();
    config.unsetSection(ConfigConstants.CONFIG_REMOTE_SECTION, remote);
    Set<String> subSections = config.getSubsections(ConfigConstants.CONFIG_BRANCH_SECTION);
    for (String subSection : subSections) {
        if (remote.equals(config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_REMOTE))) {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_REMOTE);
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, subSection, ConfigConstants.CONFIG_KEY_MERGE);
        }
    }
    try {
        config.save();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example 8
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 9
Source File: ResolveMerger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Constructor for ResolveMerger.
 *
 * @param local
 *            the {@link org.eclipse.jgit.lib.Repository}.
 * @param inCore
 *            a boolean.
 */
protected ResolveMerger(Repository local, boolean inCore) {
	super(local);
	Config config = local.getConfig();
	mergeAlgorithm = getMergeAlgorithm(config);
	inCoreLimit = getInCoreLimit(config);
	commitNames = defaultCommitNames();
	this.inCore = inCore;

	if (inCore) {
		implicitDirCache = false;
		dircache = DirCache.newInCore();
	} else {
		implicitDirCache = true;
		workingTreeOptions = local.getConfig().get(WorkingTreeOptions.KEY);
	}
}
 
Example 10
Source File: AbstractGitRepositoryTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected Repository createRepository() throws IOException {
    Repository repo = new FileRepositoryBuilder().setWorkTree(getJbossServerBaseDir().toFile())
            .setGitDir(getDotGitDir().toFile())
            .setup().build();
    StoredConfig config = repo.getConfig();
    config.setString("remote", "empty", "url", "file://" + emptyRemoteRoot.resolve(Constants.DOT_GIT).toAbsolutePath().toString());
    config.save();
    return repo;
}
 
Example 11
Source File: Utils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns git config remote.origin.url field of the repository located at gitConfigFolder
 */
public static String getGitRemoteUrl( String gitConfigFolder ) throws MojoExecutionException {
    try {
        Repository repo =
                new RepositoryBuilder().setGitDir( new File( gitConfigFolder ) ).readEnvironment().findGitDir()
                                       .build();
        Config config = repo.getConfig();
        return config.getString( "remote", "origin", "url" );
    }
    catch ( Exception e ) {
        throw new MojoExecutionException( "Error trying to get remote origin url of git repository", e );
    }
}
 
Example 12
Source File: ListBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    Map<String, Ref> refs;
    try {
        refs = repository.getAllRefs();
    } catch (IllegalArgumentException ex) {
        throw new GitException("Corrupted repository metadata at " + repository.getWorkTree().getAbsolutePath(), ex); //NOI18N
    }
    Ref head = refs.get(Constants.HEAD);
    branches = new LinkedHashMap<String, GitBranch>();
    Config cfg = repository.getConfig();
    if (head != null) {
        String current = head.getLeaf().getName();
        if (current.equals(Constants.HEAD)) {
            String name = GitBranch.NO_BRANCH;
            branches.put(name, getClassFactory().createBranch(name, false, true, head.getLeaf().getObjectId()));
        }
        branches.putAll(getRefs(refs.values(), Constants.R_HEADS, false, current, cfg));
    }
    Map<String, GitBranch> allBranches = getRefs(refs.values(), Constants.R_REMOTES, true, null, cfg);
    allBranches.putAll(branches);
    setupTracking(branches, allBranches, repository.getConfig());
    if (all) {
        branches.putAll(allBranches);
    }
}
 
Example 13
Source File: CreateBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void setupRebaseFlag (Repository repository) throws IOException {
    Ref baseRef = repository.findRef(revision);
    if (baseRef != null && baseRef.getName().startsWith(Constants.R_REMOTES)) {
        StoredConfig config = repository.getConfig();
        String autosetupRebase = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION,
                null, ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
        boolean rebase = ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
                || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase);
        if (rebase && !config.getNames(ConfigConstants.CONFIG_BRANCH_SECTION, branchName).isEmpty()) {
            config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REBASE, rebase);
            config.save();
        }
    }
}
 
Example 14
Source File: GitMirrorTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static void createGitRepo(Repository gitRepo) throws IOException {
    gitRepo.create();

    // Disable GPG signing.
    final StoredConfig config = gitRepo.getConfig();
    config.setBoolean(CONFIG_COMMIT_SECTION, null, CONFIG_KEY_GPGSIGN, false);
    config.save();
}
 
Example 15
Source File: Status.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(Wandora wandora, Context context) {

    try {
        Git git = getGit();
        if(git != null) {
            setDefaultLogger();
            setLogTitle("Git status");
            
            Repository repository = git.getRepository();
            StoredConfig config = repository.getConfig();
            
            log("Git conf:");
            log(config.toText());
            
            log("Git status:");
            org.eclipse.jgit.api.Status status = git.status().call();
            log("Added: " + status.getAdded());
            log("Changed: " + status.getChanged());
            log("Conflicting: " + status.getConflicting());
            log("ConflictingStageState: " + status.getConflictingStageState());
            log("IgnoredNotInIndex: " + status.getIgnoredNotInIndex());
            log("Missing: " + status.getMissing());
            log("Modified: " + status.getModified());
            log("Removed: " + status.getRemoved());
            log("Untracked: " + status.getUntracked());
            log("UntrackedFolders: " + status.getUntrackedFolders());
            log("Ready.");
        }
        else {
            logAboutMissingGitRepository();
        }
    }
    catch(Exception e) {
        log(e);
    }
    setState(WAIT);
}
 
Example 16
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 17
Source File: EmbeddedHttpGitServer.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
/**
 * To allow performing push operations from the cloned repository to remote (served by this server) let's
 * skip authorization for HTTP.
 */
private void enableInsecureReceiving(Repository repository) {
    final StoredConfig config = repository.getConfig();
    config.setBoolean("http", null, "receivepack", true);
    try {
        config.save();
    } catch (IOException e) {
        throw new RuntimeException("Unable to save http.receivepack=true config", e);
    }
}
 
Example 18
Source File: GitUtilities.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the remote repository at remoteUrl to the given local repository
 *
 * @param repository Repository instance representing local repo
 * @param remoteUrl remote repository url
 * @return true if remote successfully added, else false
 */
public static boolean addRemote (Repository repository, String remoteUrl) {

    boolean remoteAdded = false;

    StoredConfig config = repository.getConfig();
    config.setString(GitDeploymentSynchronizerConstants.REMOTE,
            GitDeploymentSynchronizerConstants.ORIGIN,
            GitDeploymentSynchronizerConstants.URL,
            remoteUrl);

    config.setString(GitDeploymentSynchronizerConstants.REMOTE,
            GitDeploymentSynchronizerConstants.ORIGIN,
            GitDeploymentSynchronizerConstants.FETCH,
            GitDeploymentSynchronizerConstants.FETCH_LOCATION);

    config.setString(GitDeploymentSynchronizerConstants.BRANCH,
            GitDeploymentSynchronizerConstants.MASTER,
            GitDeploymentSynchronizerConstants.REMOTE,
            GitDeploymentSynchronizerConstants.ORIGIN);

    config.setString(GitDeploymentSynchronizerConstants.BRANCH,
            GitDeploymentSynchronizerConstants.MASTER,
            GitDeploymentSynchronizerConstants.MERGE,
            GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER);

    try {
        config.save();
        remoteAdded = true;

    } catch (IOException e) {
        log.error("Error in adding remote origin " + remoteUrl + " for local repository " +
                repository.toString(), e);
    }

    return remoteAdded;
}
 
Example 19
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 20
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns the Git URL for a given git repository.
 * @param db
 * @return
 */
public static String getCloneUrl(Repository db) {
	StoredConfig config = db.getConfig();
	return config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, ConfigConstants.CONFIG_KEY_URL);
}