Java Code Examples for org.eclipse.jgit.lib.StoredConfig#setString()

The following examples show how to use org.eclipse.jgit.lib.StoredConfig#setString() . 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: IgnoreTest.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, ".DS_Store\n.svn\nnbproject\nnbproject/private\n");
    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());
    
    // now since the file is already ignored, no ignore file should be modified
    assertEquals(0, client.ignore(new File[] { f }, NULL_PROGRESS_MONITOR).length);
            
    // on the other hand, if .git/info/exclude reverts the effect of global excludes file, ignored file should be modified
    File dotGitIgnoreFile = new File(new File(repo.getDirectory(), "info"), "exclude");
    dotGitIgnoreFile.getParentFile().mkdirs();
    write(dotGitIgnoreFile, "!/nbproject/");
    assertEquals(Status.STATUS_ADDED, client.getStatus(new File[] { f }, NULL_PROGRESS_MONITOR).get(f).getStatusIndexWC());
    assertEquals(dotGitIgnoreFile, client.ignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    assertEquals(Status.STATUS_IGNORED, client.getStatus(new File[] { f }, NULL_PROGRESS_MONITOR).get(f).getStatusIndexWC());
}
 
Example 2
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 3
Source File: RestGitBackupService.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@Override
public Response gitInit(String botId) {
    try {
        deleteFileIfExists(Paths.get(tmpPath + botId));
        Path gitPath = Files.createDirectories(Paths.get(tmpPath + botId));
        Git git = Git.cloneRepository()
                .setBranch(gitBranch)
                .setURI(gitUrl)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitUsername, gitPassword))
                .setDirectory(gitPath.toFile())
                .call();
        StoredConfig config = git.getRepository().getConfig();
        config.setString( CONFIG_BRANCH_SECTION, "local-branch", "remote", gitBranch);
        config.setString( CONFIG_BRANCH_SECTION, "local-branch", "merge", "refs/heads/" + gitBranch );
        config.save();

    } catch (IOException | GitAPIException e) {
        log.error(e.getLocalizedMessage(), e);
        throw new InternalServerErrorException();
    }
    return Response.accepted().build();
}
 
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: GitBasedArtifactRepository.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the Invalid configuration issues
 *
 * @param gitRepoCtx RepositoryContext instance of the tenant
 */
private void handleInvalidConfigurationError(RepositoryContext gitRepoCtx) {

    StoredConfig storedConfig = gitRepoCtx.getLocalRepo().getConfig();
    boolean modifiedConfig = false;
    if (storedConfig != null) {

        if (storedConfig.getString("branch", "master", "remote") == null ||
                storedConfig.getString("branch", "master", "remote").isEmpty()) {

            storedConfig.setString("branch", "master", "remote", "origin");
            modifiedConfig = true;
        }

        if (storedConfig.getString("branch", "master", "merge") == null ||
                storedConfig.getString("branch", "master", "merge").isEmpty()) {

            storedConfig.setString("branch", "master", "merge", "refs/heads/master");
            modifiedConfig = true;
        }

        if (modifiedConfig) {
            try {
                storedConfig.save();
                // storedConfig.load();

            } catch (IOException e) {
                String message = "Error saving git configuration file in local repo at " + gitRepoCtx.getGitLocalRepoPath();
                System.out.println(message);
                log.error(message, e);
            }
        }
    }
}
 
Example 6
Source File: GitLabIT.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String initGitLabProject(String url, boolean addFeatureBranch) throws GitAPIException, IOException {
    // Setup git repository
    Git.init().setDirectory(tmp.getRoot()).call();
    Git git = Git.open(tmp.getRoot());
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", url);
    config.save();

    // Setup remote master branch
    tmp.newFile("test");
    git.add().addFilepattern("test");
    RevCommit commit = git.commit().setMessage("test").call();
    git.push()
        .setRemote("origin").add("master")
        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitlab.getUsername(), gitlab.getPassword()))
        .call();

    if (addFeatureBranch) {
        // Setup remote feature branch
        git.checkout().setName("feature").setCreateBranch(true).call();
        tmp.newFile("feature");
        commit = git.commit().setMessage("feature").call();
        git.push().setRemote("origin").add("feature").setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitlab.getUsername(), gitlab.getPassword()))
            .call();
    }

    return commit.getName();
}
 
Example 7
Source File: TestGitFlowPersistenceProvider.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
private void assertProvider(final Map<String, String> properties, final GitConsumer gitConsumer, final Consumer<GitFlowPersistenceProvider> assertion, boolean deleteDir)
        throws IOException, GitAPIException {

    final File gitDir = new File(properties.get(GitFlowPersistenceProvider.FLOW_STORAGE_DIR_PROP));
    try {
        FileUtils.ensureDirectoryExistAndCanReadAndWrite(gitDir);

        try (final Git git = Git.init().setDirectory(gitDir).call()) {
            logger.debug("Initiated a git repository {}", git);
            final StoredConfig config = git.getRepository().getConfig();
            config.setString("user", null, "name", "git-user");
            config.setString("user", null, "email", "[email protected]");
            config.save();
            gitConsumer.accept(git);
        }

        final GitFlowPersistenceProvider persistenceProvider = new GitFlowPersistenceProvider();

        final ProviderConfigurationContext configurationContext = new StandardProviderConfigurationContext(properties);
        persistenceProvider.onConfigured(configurationContext);
        assertion.accept(persistenceProvider);

    } finally {
        if (deleteDir) {
            FileUtils.deleteFile(gitDir, true);
        }
    }
}
 
Example 8
Source File: GitMigrator.java    From rtc2gitcli with MIT License 5 votes vote down vote up
private void initConfig() throws IOException {
	StoredConfig config = git.getRepository().getConfig();
	config.setBoolean("core", null, "ignoreCase", false);
	config.setString("core", null, "autocrlf", File.separatorChar == '/' ? "input" : "true");
	config.setBoolean("http", null, "sslverify", false);
	config.setString("push", null, "default", "simple");
	fillConfigFromProperties(config);
	config.save();
}
 
Example 9
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
private void configRemote(String name, String url, String branchName) {
    try {
        StoredConfig config = gitRepo.getRepository().getConfig();
        config.setString("remote", name, "url", url);
        config.setString("remote", name, "fetch",
                "+refs/heads/" + branchName + ":refs/remotes/origin/" + branchName);
        config.save();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: BlameTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testBlameMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);

    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();

    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    GitRevisionInfo info = client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);

    content = content.replaceFirst("0", "01");
    write(f, content);

    // it should be up to date again
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath("f");
    BlameResult blameResult = cmd.call();
    assertEquals(info.getRevision(), blameResult.getSourceCommit(1).getName());
    
    GitBlameResult res = client.blame(f, null, NULL_PROGRESS_MONITOR);
    assertNull(res.getLineDetails(0));
    assertLineDetails(f, 1, info.getRevision(), info.getAuthor(), info.getCommitter(), res.getLineDetails(1));
    
    // without autocrlf it should all be modified
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "false");
    cfg.save();
    res = client.blame(f, null, NULL_PROGRESS_MONITOR);
    assertNull(res.getLineDetails(1));
}
 
Example 11
Source File: BranchTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testBranchTracking () throws Exception {
    final File otherWT = new File(workDir.getParentFile(), "repo2");
    GitClient client = getClient(otherWT);
    client.init(NULL_PROGRESS_MONITOR);
    File f = new File(otherWT, "f");
    write(f, "init");
    client.add(new File[] { f }, NULL_PROGRESS_MONITOR);
    client.commit(new File[] { f }, "init commit", null, null, NULL_PROGRESS_MONITOR);
    
    client = getClient(workDir);
    client.setRemote(new GitRemoteConfig("origin", 
            Arrays.asList(otherWT.getAbsolutePath()),
            Arrays.asList(otherWT.getAbsolutePath()),
            Arrays.asList("+refs/heads/*:refs/remotes/origin/*"), Collections.<String>emptyList()), NULL_PROGRESS_MONITOR);
    client.fetch("origin", NULL_PROGRESS_MONITOR);
    GitBranch b = client.createBranch(Constants.MASTER, "origin/master", NULL_PROGRESS_MONITOR);
    assertEquals("origin/master", b.getTrackedBranch().getName());
    assertTrue(b.getTrackedBranch().isRemote());
    client.checkoutRevision(Constants.MASTER, true, NULL_PROGRESS_MONITOR);
    
    b = client.createBranch("nova1", Constants.MASTER, NULL_PROGRESS_MONITOR);
    assertNull(b.getTrackedBranch());
    
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_BRANCH_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE, "always");
    cfg.save();
    b = client.createBranch("nova2", Constants.MASTER, NULL_PROGRESS_MONITOR);
    assertEquals("master", b.getTrackedBranch().getName());
    assertFalse(b.getTrackedBranch().isRemote());
    
    // list branches
    Map<String, GitBranch> branches = client.getBranches(true, NULL_PROGRESS_MONITOR);
    b = branches.get(Constants.MASTER);
    assertEquals("origin/master", b.getTrackedBranch().getName());
    assertTrue(b.getTrackedBranch().isRemote());
    b = branches.get("origin/master");
    assertNull(b.getTrackedBranch());
}
 
Example 12
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public void setSubmoduleUrl(String name, String url) throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();
        config.setString("submodule", name, "url", url);
        config.save();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example 13
Source File: SetUpstreamBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    
    try {
        Ref ref = repository.findRef(trackedBranchName);
        if (ref == null) {
            throw new GitException(MessageFormat.format(Utils.getBundle(SetUpstreamBranchCommand.class)
                    .getString("MSG_Error_UpdateTracking_InvalidReference"), trackedBranchName)); //NOI18N)
        }
        String remote = null;
        String branchName = ref.getName();
        StoredConfig config = repository.getConfig();
        if (branchName.startsWith(Constants.R_REMOTES)) {
            String[] elements = branchName.split("/", 4);
            remote = elements[2];
            if (config.getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION).contains(remote)) {
                branchName = Constants.R_HEADS + elements[3];
                setupRebaseFlag(repository);
            } else {
                // remote not yet set
                remote = null;
            }
        }
        if (remote == null) {
            remote = "."; //NOI18N
        }
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_REMOTE, remote);
        config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_MERGE, branchName);
        config.save();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
    ListBranchCommand branchCmd = new ListBranchCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor));
    branchCmd.run();
    Map<String, GitBranch> branches = branchCmd.getBranches();
    branch = branches.get(localBranchName);
}
 
Example 14
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
@SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
                              "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE" },
                    justification = "Java 11 spotbugs error and JGit interaction with spotbugs")
public void setRemoteUrl(String name, String url, String GIT_DIR) throws GitException, InterruptedException {
    try (Repository repo = new RepositoryBuilder().setGitDir(new File(GIT_DIR)).build()) {
        StoredConfig config = repo.getConfig();
        config.setString("remote", name, "url", url);
        config.save();
    } catch (IOException ioe) {
        throw new GitException(ioe);
    }
}
 
Example 15
Source File: CheckoutTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLineEndingsWindows () throws Exception {
    if (!isWindows()) {
        return;
    }
    // lets turn autocrlf on
    Thread.sleep(1100);
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    File f = new File(workDir, "f");
    write(f, "a\r\nb\r\n");
    File[] roots = new File[] { f };
    
    GitClient client = getClient(workDir);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    List<String> res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("A  f"), res);
    DirCacheEntry e1 = repository.readDirCache().getEntry("f");
    runExternally(workDir, Arrays.asList("git.cmd", "commit", "-m", "hello"));
    
    write(f, "a\r\nb\r\nc\r\n");
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList(" M f"), res);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("M  f"), res);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_MODIFIED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_MODIFIED, false);
    
    client.checkout(roots, "HEAD", true, NULL_PROGRESS_MONITOR);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
    assertEquals(e1.getObjectId(), repository.readDirCache().getEntry("f").getObjectId());
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(0, res.size());

    write(f, "a\r\nb\r\nc\r\n");
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList(" M f"), res);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_MODIFIED, GitStatus.Status.STATUS_MODIFIED, false);
    
    client.checkout(roots, null, true, NULL_PROGRESS_MONITOR);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
    assertEquals(e1.getObjectId(), repository.readDirCache().getEntry("f").getObjectId());
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(0, res.size());
}
 
Example 16
Source File: DifferentFilesHttpFetchBasicAuthTest.java    From gitflow-incremental-builder with MIT License 4 votes vote down vote up
@BeforeEach
void configureCredentialHelper() throws IOException {
    StoredConfig config = localRepoMock.getGit().getRepository().getConfig();
    config.setString("credential", null, "helper", "store");
    config.save();
}
 
Example 17
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);
    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);
    
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    // when this starts failing, remove the work around
    ObjectInserter inserter = repository.newObjectInserter();
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setFilter(PathFilterGroup.createFromStrings("f"));
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new FileTreeIterator(repository));
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertEquals("f", path);
        WorkingTreeIterator fit = treeWalk.getTree(0, WorkingTreeIterator.class);
        try (InputStream in = fit.openEntryStream()) {
            inserter.insert(Constants.OBJ_BLOB, fit.getEntryLength(), in);
            fail("this should fail, remove the work around");
        } catch (EOFException ex) {
            assertEquals("Input did not match supplied length. 10.000 bytes are missing.", ex.getMessage());
        } finally {
            inserter.close();
        }
        break;
    }
    
    // no err should occur
    write(f, content + "hello");
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    client.add(files, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    client.commit(files, "message", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example 18
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLineEndingsWindows () throws Exception {
    if (!isWindows()) {
        return;
    }
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    File f = new File(workDir, "f");
    write(f, "a\r\nb\r\n");
    File[] roots = new File[] { f };
    
    GitClient client = getClient(workDir);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    DirCacheEntry e1 = repository.readDirCache().getEntry("f");
    client.add(roots, NULL_PROGRESS_MONITOR);
    DirCacheEntry e2 = repository.readDirCache().getEntry("f");
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    List<String> res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("A  f"), res);
    assertEquals(e1.getFileMode(), e2.getFileMode());
    assertEquals(e1.getPathString(), e2.getPathString());
    assertEquals(e1.getRawMode(), e2.getRawMode());
    assertEquals(e1.getStage(), e2.getStage());
    assertEquals(e1.getLength(), e2.getLength());
    assertEquals(e1.getObjectId(), e2.getObjectId());

    write(f, "a\nb\n");
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("AM f"), res);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_ADDED, Status.STATUS_MODIFIED, Status.STATUS_ADDED, false);
    
    res = runExternally(workDir, Arrays.asList("git.cmd", "commit", "-m", "gugu"));
    res = runExternally(workDir, Arrays.asList("git.cmd", "checkout", "--", "f"));
    
    RevCommit commit = Utils.findCommit(repository, "HEAD");
    TreeWalk walk = new TreeWalk(repository);
    walk.reset();
    walk.addTree(commit.getTree());
    walk.setFilter(PathFilter.create("f"));
    walk.setRecursive(true);
    walk.next();
    assertEquals("f", walk.getPathString());
    ObjectLoader loader = repository.getObjectDatabase().open(walk.getObjectId(0));
    assertEquals(4, loader.getSize());
    assertEquals("a\nb\n", new String(loader.getBytes()));
    assertEquals(e1.getObjectId(), walk.getObjectId(0));
    
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(0, res.size());
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example 19
Source File: CatTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLineEndingsWindows () throws Exception {
    if (!isWindows()) {
        return;
    }
    // lets turn autocrlf on
    Thread.sleep(1100);
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    File f = new File(workDir, "f");
    write(f, "a\r\nb\r\n");
    File[] roots = new File[] { f };
    
    GitClient client = getClient(workDir);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    List<String> res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("A  f"), res);
    DirCacheEntry e1 = repository.readDirCache().getEntry("f");
    runExternally(workDir, Arrays.asList("git.cmd", "commit", "-m", "hello"));
    
    write(f, "a\r\nb\r\nc\r\n");
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList(" M f"), res);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("M  f"), res);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_MODIFIED, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_MODIFIED, false);
    
    FileOutputStream fo = new FileOutputStream(f);
    client.catFile(f, "HEAD", fo, NULL_PROGRESS_MONITOR);
    fo.close();
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_MODIFIED, GitStatus.Status.STATUS_MODIFIED, GitStatus.Status.STATUS_NORMAL, false);
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("MM f"), res);

    client.reset("HEAD", GitClient.ResetType.MIXED, NULL_PROGRESS_MONITOR);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR), workDir, f, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
    assertEquals(e1.getObjectId(), repository.readDirCache().getEntry("f").getObjectId());
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(0, res.size());
}
 
Example 20
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new Git-backed repository.
 *
 * @param repoDir the location of this repository
 * @param format the repository format
 * @param repositoryWorker the {@link Executor} which will perform the blocking repository operations
 * @param creationTimeMillis the creation time
 * @param author the user who initiated the creation of this repository
 *
 * @throws StorageException if failed to create a new repository
 */
GitRepository(Project parent, File repoDir, GitRepositoryFormat format, Executor repositoryWorker,
              long creationTimeMillis, Author author, @Nullable RepositoryCache cache) {

    this.parent = requireNonNull(parent, "parent");
    name = requireNonNull(repoDir, "repoDir").getName();
    this.repositoryWorker = requireNonNull(repositoryWorker, "repositoryWorker");
    this.format = requireNonNull(format, "format");
    this.cache = cache;

    requireNonNull(author, "author");

    final RepositoryBuilder repositoryBuilder = new RepositoryBuilder().setGitDir(repoDir).setBare();
    boolean success = false;
    try {
        // Create an empty repository with format version 0 first.
        try (org.eclipse.jgit.lib.Repository initRepo = repositoryBuilder.build()) {
            if (exist(repoDir)) {
                throw new StorageException(
                        "failed to create a repository at: " + repoDir + " (exists already)");
            }

            initRepo.create(true);

            final StoredConfig config = initRepo.getConfig();
            if (format == GitRepositoryFormat.V1) {
                // Update the repository settings to upgrade to format version 1 and reftree.
                config.setInt(CONFIG_CORE_SECTION, null, CONFIG_KEY_REPO_FORMAT_VERSION, 1);
            }

            // Disable hidden files, symlinks and file modes we do not use.
            config.setEnum(CONFIG_CORE_SECTION, null, CONFIG_KEY_HIDEDOTFILES, HideDotFiles.FALSE);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_SYMLINKS, false);
            config.setBoolean(CONFIG_CORE_SECTION, null, CONFIG_KEY_FILEMODE, false);

            // Disable GPG signing.
            config.setBoolean(CONFIG_COMMIT_SECTION, null, CONFIG_KEY_GPGSIGN, false);

            // Set the diff algorithm.
            config.setString(CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, "histogram");

            // Disable rename detection which we do not use.
            config.setBoolean(CONFIG_DIFF_SECTION, null, CONFIG_KEY_RENAMES, false);

            config.save();
        }

        // Re-open the repository with the updated settings and format version.
        jGitRepository = new RepositoryBuilder().setGitDir(repoDir).build();

        // Initialize the master branch.
        final RefUpdate head = jGitRepository.updateRef(Constants.HEAD);
        head.disableRefLog();
        head.link(Constants.R_HEADS + Constants.MASTER);

        // Initialize the commit ID database.
        commitIdDatabase = new CommitIdDatabase(jGitRepository);

        // Insert the initial commit into the master branch.
        commit0(null, Revision.INIT, creationTimeMillis, author,
                "Create a new repository", "", Markup.PLAINTEXT,
                Collections.emptyList(), true);

        headRevision = Revision.INIT;
        success = true;
    } catch (IOException e) {
        throw new StorageException("failed to create a repository at: " + repoDir, e);
    } finally {
        if (!success) {
            internalClose();
            // Failed to create a repository. Remove any cruft so that it is not loaded on the next run.
            deleteCruft(repoDir);
        }
    }
}