org.eclipse.jgit.lib.Config Java Examples

The following examples show how to use org.eclipse.jgit.lib.Config. 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: LegacyCompatibleGitAPIImplTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
@Deprecated
public void testCloneRemoteConfig() throws URISyntaxException, InterruptedException, IOException, ConfigInvalidException {
    if (gitImpl.equals("jgit")) {
        return;
    }
    Config config = new Config();
    /* Use local git-client-plugin repository as source for clone test */
    String remoteName = "localCopy";
    String localRepoPath = (new File(".")).getCanonicalPath().replace("\\", "/");
    String configText = "[remote \"" + remoteName + "\"]\n"
            + "url = " + localRepoPath + "\n"
            + "fetch = +refs/heads/*:refs/remotes/" + remoteName + "/*\n";
    config.fromText(configText);
    RemoteConfig remoteConfig = new RemoteConfig(config, remoteName);
    List<URIish> list = remoteConfig.getURIs();
    git.clone(remoteConfig);
    File[] files = git.workspace.listFiles();
    assertEquals(files.length + "files in " + Arrays.toString(files), 1, files.length);
    assertEquals("Wrong file name", ".git", files[0].getName());
}
 
Example #2
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 #3
Source File: AppNameResolver.java    From heroku-maven-plugin with MIT License 6 votes vote down vote up
private static Optional<String> resolveViaHerokuGitRemote(Path rootDirectory) throws IOException {
    try {
        Git gitRepo = Git.open(rootDirectory.toFile());
        Config config = gitRepo.getRepository().getConfig();

        for (String remoteName : config.getSubsections("remote")) {
            String remoteUrl = config.getString("remote", remoteName, "url");

            for (Pattern gitRemoteUrlAppNamePattern : GIT_REMOTE_URL_APP_NAME_PATTERNS) {
                Matcher matcher = gitRemoteUrlAppNamePattern.matcher(remoteUrl);
                if (matcher.matches()) {
                    return Optional.of(matcher.group(1));
                }
            }
        }
    } catch (RepositoryNotFoundException e) {
        return Optional.empty();
    }

    return Optional.empty();
}
 
Example #4
Source File: GitMigrator.java    From rtc2gitcli with MIT License 6 votes vote down vote up
private void fillConfigFromProperties(Config config) {
	for (Entry<Object, Object> entry : properties.entrySet()) {
		if (entry.getKey() instanceof String && (((String) entry.getKey()).startsWith(GIT_CONFIG_PREFIX))) {

			String key = ((String) entry.getKey()).substring(GIT_CONFIG_PREFIX.length());
			int dot = key.indexOf('.');
			int dot1 = key.lastIndexOf('.');
			// so far supporting section/key entries, no subsections
			if (dot < 1 || dot == key.length() - 1 || dot1 != dot) {
				// invalid config key entry
				continue;
			}
			String section = key.substring(0, dot);
			String name = key.substring(dot + 1);
			config.setString(section, null, name, entry.getValue().toString());
		}

	}
}
 
Example #5
Source File: SetUpstreamBranchTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testRemoteTrackingNoRemoteSet () throws GitException {
    GitClient client = getClient(workDir);
    File f = new File(workDir, "f");
    add(f);
    client.commit(new File[] { f }, "init commit", null, null, NULL_PROGRESS_MONITOR);
    
    // push to remote
    String remoteUri = getRemoteRepository().getWorkTree().toURI().toString();
    client.push(remoteUri,
            Arrays.asList("refs/heads/master:refs/heads/master"),
            Arrays.asList("+refs/heads/*:refs/remotes/origin/*"),
            NULL_PROGRESS_MONITOR);
    Map<String, GitBranch> branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    assertTrue(branches.containsKey("origin/master"));
    assertNull(branches.get("master").getTrackedBranch());
    
    // set tracking
    GitBranch b = client.setUpstreamBranch("master", "origin/master", NULL_PROGRESS_MONITOR);
    assertEquals("origin/master", b.getTrackedBranch().getName());
    
    Config cfg = repository.getConfig();
    assertEquals(".", cfg.getString(ConfigConstants.CONFIG_BRANCH_SECTION, "master", ConfigConstants.CONFIG_KEY_REMOTE));
    assertEquals("refs/remotes/origin/master", cfg.getString(ConfigConstants.CONFIG_BRANCH_SECTION, "master", ConfigConstants.CONFIG_KEY_MERGE));
}
 
Example #6
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static GitBranch getTrackedBranch (Config config, String branchName, Map<String, GitBranch> allBranches) {
    String remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE);
    String trackedBranchName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE);
    if (trackedBranchName != null) {
        if (trackedBranchName.startsWith(Constants.R_HEADS)) {
            trackedBranchName = trackedBranchName.substring(Constants.R_HEADS.length());
        } else if (trackedBranchName.startsWith(Constants.R_REMOTES)) {
            trackedBranchName = trackedBranchName.substring(Constants.R_REMOTES.length());
        }
    }
    if (trackedBranchName == null) {
        return null;
    } else {
        if (remoteName != null && ".".equals(remoteName)) { //NOI18N
            remoteName = ""; //NOI18N
        } else {
            remoteName = remoteName + "/"; //NOI18N
        }
        return allBranches.get(remoteName + trackedBranchName);
    }
}
 
Example #7
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public String getAuthorName( String commitId ) {
  if ( commitId.equals( IVCS.WORKINGTREE ) ) {
    Config config = git.getRepository().getConfig();
    return config.get( UserConfig.KEY ).getAuthorName()
        + " <" + config.get( UserConfig.KEY ).getAuthorEmail() + ">";
  } else {
    RevCommit commit = resolve( commitId );
    PersonIdent author = commit.getAuthorIdent();
    final StringBuilder r = new StringBuilder();
    r.append( author.getName() );
    r.append( " <" ); //$NON-NLS-1$
    r.append( author.getEmailAddress() );
    r.append( ">" ); //$NON-NLS-1$
    return r.toString();
  }
}
 
Example #8
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 #9
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_prune_without_remote() throws Exception {
    /* Create an empty working repo */
    testGitClient.init();
    /* Prune when a remote is not yet defined */
    String expectedMessage = testGitClient instanceof CliGitAPIImpl ? "returned status code 1" : "The uri was empty or null";
    GitException gitException = assertThrows(GitException.class, () -> {
        testGitClient.prune(new RemoteConfig(new Config(), "remote-is-not-defined"));
    });
    assertThat(gitException.getMessage(), containsString(expectedMessage));
}
 
Example #10
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_prune() throws Exception {
    // pretend that 'r' is a team repository and ws1 and ws2 are team members
    WorkingArea r = new WorkingArea();
    r.init(true);

    WorkingArea ws1 = new WorkingArea().init();
    WorkingArea ws2 = w.init();

    ws1.commitEmpty("c");
    ws1.launchCommand("git", "remote", "add", "origin", r.repoPath());

    ws1.launchCommand("git", "push", "origin", "master:b1");
    ws1.launchCommand("git", "push", "origin", "master:b2");
    ws1.launchCommand("git", "push", "origin", "master");

    ws2.launchCommand("git", "remote", "add", "origin", r.repoPath());
    ws2.launchCommand("git", "fetch", "origin");

    // at this point both ws1&ws2 have several remote tracking branches

    ws1.launchCommand("git", "push", "origin", ":b1");
    ws1.launchCommand("git", "push", "origin", "master:b3");

    ws2.git.prune(new RemoteConfig(new Config(),"origin"));

    assertFalse(ws2.exists(".git/refs/remotes/origin/b1"));
    assertTrue( ws2.exists(".git/refs/remotes/origin/b2"));
    assertFalse(ws2.exists(".git/refs/remotes/origin/b3"));
}
 
Example #11
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Deprecated
public void test_push_deprecated_signature() throws Exception {
    /* Make working repo a remote of the bare repo */
    w.init();
    w.commitEmpty("init");
    ObjectId workHead = w.head();

    /* Create a bare repo */
    WorkingArea bare = new WorkingArea();
    bare.init(true);

    /* Set working repo origin to point to bare */
    w.git.setRemoteUrl("origin", bare.repoPath());
    assertEquals("Wrong remote URL", w.git.getRemoteUrl("origin"), bare.repoPath());

    /* Push to bare repo */
    w.git.push("origin", "master");
    /* JGitAPIImpl revParse fails unexpectedly when used here */
    ObjectId bareHead = w.git instanceof CliGitAPIImpl ? bare.head() : ObjectId.fromString(bare.launchCommand("git", "rev-parse", "master").substring(0, 40));
    assertEquals("Heads don't match", workHead, bareHead);
    assertEquals("Heads don't match", w.git.getHeadRev(w.repoPath(), "master"), bare.git.getHeadRev(bare.repoPath(), "master"));

    /* Commit a new file */
    w.touch("file1");
    w.git.add("file1");
    w.git.commit("commit1");

    /* Push commit to the bare repo */
    Config config = new Config();
    config.fromText(w.contentOf(".git/config"));
    RemoteConfig origin = new RemoteConfig(config, "origin");
    w.igit().push(origin, "master");

    /* JGitAPIImpl revParse fails unexpectedly when used here */
    ObjectId workHead2 = w.git instanceof CliGitAPIImpl ? w.head() : ObjectId.fromString(w.launchCommand("git", "rev-parse", "master").substring(0, 40));
    ObjectId bareHead2 = w.git instanceof CliGitAPIImpl ? bare.head() : ObjectId.fromString(bare.launchCommand("git", "rev-parse", "master").substring(0, 40));
    assertEquals("Working SHA1 != bare SHA1", workHead2, bareHead2);
    assertEquals("Working SHA1 != bare SHA1", w.git.getHeadRev(w.repoPath(), "master"), bare.git.getHeadRev(bare.repoPath(), "master"));
}
 
Example #12
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 #13
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether the key gerrit.createchangeid is set to true in the git configuration
 * 
 * @param config
 *            the configuration of the git repository
 * @return true if the key gerrit.createchangeid is set to true
 */
public static boolean isGerrit(Config config, String remote) {
	String[] list = config.getStringList(ConfigConstants.CONFIG_REMOTE_SECTION, remote, GitConstants.KEY_IS_GERRIT.toLowerCase());
	for (int i = 0; i < list.length; i++) {
		if (list[i].equals("true")) {
			return true;
		}
	}
	return false;
}
 
Example #14
Source File: ListBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Map<String, GitBranch> getRefs (Collection<Ref> allRefs, String prefix, boolean isRemote, String activeBranch, Config config) {
    Map<String, GitBranch> branches = new LinkedHashMap<String, GitBranch>();
    for (final Ref ref : RefComparator.sort(allRefs)) {
        String refName = ref.getLeaf().getName();
        if (refName.startsWith(prefix)) {
            String name = refName.substring(refName.indexOf('/', 5) + 1);
            branches.put(name, getClassFactory().createBranch(name, isRemote, refName.equals(activeBranch), ref.getLeaf().getObjectId()));
        }
    }
    return branches;
}
 
Example #15
Source File: MergeConfig.java    From onedev with MIT License 5 votes vote down vote up
private static FastForwardMode getFastForwardMode(Config config,
		String[] mergeOptions) {
	for (String option : mergeOptions) {
		for (FastForwardMode mode : FastForwardMode.values())
			if (mode.matchConfigValue(option))
				return mode;
	}
	FastForwardMode ffmode = FastForwardMode.valueOf(config.getEnum(
			ConfigConstants.CONFIG_KEY_MERGE, null,
			ConfigConstants.CONFIG_KEY_FF, FastForwardMode.Merge.TRUE));
	return ffmode;
}
 
Example #16
Source File: MergeConfig.java    From onedev with MIT License 5 votes vote down vote up
private static String[] getMergeOptions(String branch, Config config) {
	String mergeOptions = config.getString(
			ConfigConstants.CONFIG_BRANCH_SECTION, branch,
			ConfigConstants.CONFIG_KEY_MERGEOPTIONS);
	if (mergeOptions != null) {
		return mergeOptions.split("\\s"); //$NON-NLS-1$
	}
	return new String[0];
}
 
Example #17
Source File: ConnectionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FileBasedConfig openUserConfig (Config config, FS fs) {
    return instance.openUserConfig(config, fs);
}
 
Example #18
Source File: ResolveMerger.java    From onedev with MIT License 4 votes vote down vote up
private static MergeAlgorithm getMergeAlgorithm(Config config) {
	SupportedAlgorithm diffAlg = config.getEnum(
			CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM,
			HISTOGRAM);
	return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
}
 
Example #19
Source File: ResolveMerger.java    From onedev with MIT License 4 votes vote down vote up
private static int getInCoreLimit(Config config) {
	return config.getInt(
			ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20);
}
 
Example #20
Source File: StrategyResolve.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new ResolveMerger(inserter, config);
}
 
Example #21
Source File: StrategySimpleTwoWayInCore.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new InCoreMerger(inserter);
}
 
Example #22
Source File: StrategyOneSided.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public Merger newMerger(ObjectInserter inserter, Config config) {
	return new OneSide(inserter, treeIndex);
}
 
Example #23
Source File: MergeConfig.java    From onedev with MIT License 4 votes vote down vote up
private MergeConfig(String branch, Config config) {
	String[] mergeOptions = getMergeOptions(branch, config);
	fastForwardMode = getFastForwardMode(config, mergeOptions);
	squash = isMergeConfigOptionSet("--squash", mergeOptions); //$NON-NLS-1$
	commit = !isMergeConfigOptionSet("--no-commit", mergeOptions); //$NON-NLS-1$
}
 
Example #24
Source File: ConnectionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FileBasedConfig openSystemConfig (Config config, FS fs) {
    return instance.openSystemConfig(config, fs);
}
 
Example #25
Source File: StrategyRecursive.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new RecursiveMerger(inserter, config);
}
 
Example #26
Source File: MergeConfig.java    From onedev with MIT License 4 votes vote down vote up
@Override
public MergeConfig parse(Config cfg) {
	return new MergeConfig(branch, cfg);
}
 
Example #27
Source File: TransportCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FileBasedConfig openSystemConfig (Config config, FS fs) {
    return instance.openSystemConfig(config, fs);
}
 
Example #28
Source File: TransportCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FileBasedConfig openUserConfig (Config config, FS fs) {
    return instance.openUserConfig(config, fs);
}
 
Example #29
Source File: ListBranchCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void setupTracking (Map<String, GitBranch> branches, Map<String, GitBranch> allBranches, Config cfg) {
    for (GitBranch b : branches.values()) {
        getClassFactory().setBranchTracking(b, Utils.getTrackedBranch(cfg, b.getName(), allBranches));
    }
}
 
Example #30
Source File: RepoRelativePath.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Tries to obtain repository name from the provided directory by reading git config in
 * {@code currendDir/.git/config}
 * <p>
 * Git clone folder name might be different from git repository name
 *
 * @return string with repo name or {@code null}
 */
private static String getRepoName(File currentDir) {
	if (currentDir == null) {
		return "NO_REPO";
	}
	File gitFolder = new File(currentDir, ".git");
	if (!gitFolder.isDirectory()) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug("No '.git' folder at " + currentDir.getAbsolutePath());
		return null;
	}

	File config = new File(gitFolder, "config");
	if (!config.isFile()) {
		if (LOGGER.isDebugEnabled())
			LOGGER.debug("No 'config' file at " + gitFolder.getAbsolutePath());
		return null;
	}
	try {
		String configStr = Files.asCharSource(config, Charset.defaultCharset()).read();
		Config cfg = new Config();

		cfg.fromText(configStr);
		String originURL = cfg.getString("remote", "origin", "url");
		if (originURL != null && !originURL.isEmpty()) {
			int lastSlash = originURL.lastIndexOf('/');
			String repoName = null;
			if (lastSlash >= 0) {
				repoName = originURL.substring(lastSlash + 1);
			} else {
				repoName = originURL;
			}
			if (repoName.endsWith(".git")) {
				repoName = repoName.substring(0, repoName.length() - 4);
			}
			return repoName;
		}
	} catch (ConfigInvalidException | IOException e) {
		LOGGER.warn("Cannot read git config at " + config.getAbsolutePath(), e);
	}

	return null;
}