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

The following examples show how to use org.eclipse.jgit.lib.StoredConfig#setBoolean() . 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: 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 2
Source File: LocalRepoMock.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private void configureRemote(Git git, String repoUrl) throws URISyntaxException, IOException, GitAPIException {
    StoredConfig config = git.getRepository().getConfig();
    config.clear();
    config.setString("remote", "origin" ,"fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("remote", "origin" ,"push", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("branch", "master", "remote", "origin");
    config.setString("baseBranch", "master", "merge", "refs/heads/master");
    config.setString("push", null, "default", "current");

    // disable all gc
    // http://download.eclipse.org/jgit/site/5.2.1.201812262042-r/apidocs/org/eclipse/jgit/internal/storage/file/GC.html#setAuto-boolean-
    config.setString("gc", null, "auto", "0");
    config.setString("gc", null, "autoPackLimit", "0");
    config.setBoolean("receive", null, "autogc", false);

    RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
    URIish uri = new URIish(repoUrl);
    remoteConfig.addURI(uri);
    remoteConfig.addFetchRefSpec(new RefSpec("refs/heads/master:refs/heads/master"));
    remoteConfig.addPushRefSpec(new RefSpec("refs/heads/master:refs/heads/master"));
    remoteConfig.update(config);

    config.save();
}
 
Example 3
Source File: MergeTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMergeBranchNoHeadYet_196837 () throws Exception {
    StoredConfig cfg = getRemoteRepository().getConfig();
    cfg.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, false);
    cfg.save();
    File otherRepo = getRemoteRepository().getWorkTree();
    File original = new File(otherRepo, "f");
    GitClient clientOtherRepo = getClient(otherRepo);
    write(original, "initial content");
    clientOtherRepo.add(new File[] { original }, NULL_PROGRESS_MONITOR);
    clientOtherRepo.commit(new File[] { original }, "initial commit", null, null, NULL_PROGRESS_MONITOR);
    
    GitClient client = getClient(workDir);
    Map<String, GitTransportUpdate> updates = client.fetch(otherRepo.toURI().toString(), Arrays.asList(new String[] { "+refs/heads/master:refs/remotes/origin/master" }), NULL_PROGRESS_MONITOR);
    GitMergeResult result = client.merge("origin/master", NULL_PROGRESS_MONITOR);
    assertEquals(MergeStatus.FAST_FORWARD, result.getMergeStatus());
    assertEquals(Arrays.asList(new String[] { ObjectId.zeroId().getName(), updates.get("origin/master").getNewObjectId() }), Arrays.asList(result.getMergedCommits()));
}
 
Example 4
Source File: AddTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddIgnoreExecutable () throws Exception {
    if (isWindows()) {
        // no reason to test on windows
        return;
    }
    File f = new File(workDir, "f");
    write(f, "hi, i am executable");
    f.setExecutable(true);
    File[] roots = { f };
    GitClient client = getClient(workDir);
    StoredConfig config = repository.getConfig();
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();
    // add should not set executable bit in index
    add(roots);
    Map<File, GitStatus> statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    
    // index should differ from wt
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
    config.save();
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_ADDED, Status.STATUS_MODIFIED, Status.STATUS_ADDED, false);
}
 
Example 5
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 6
Source File: GitCloneHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static void doConfigureClone(Git git, String user, String gitUserName, String gitUserMail) throws IOException, CoreException, JSONException {
	StoredConfig config = git.getRepository().getConfig();
	if (gitUserName == null && gitUserMail == null) {
		JSONObject gitUserConfig = getUserGitConfig(user);
		if (gitUserConfig != null) {
			gitUserName = gitUserConfig.getString("GitName"); //$NON-NLS-1$
			gitUserMail = gitUserConfig.getString("GitMail"); //$NON-NLS-1$
		}
	}
	if (gitUserName != null)
		config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, gitUserName);
	if (gitUserMail != null)
		config.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL, gitUserMail);

	config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
	config.save();
}
 
Example 7
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 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: 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 10
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 11
Source File: AddTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testUpdateIndexIgnoreExecutable () throws Exception {
    if (isWindows()) {
        // no reason to test on windows
        return;
    }
    File f = new File(workDir, "f");
    write(f, "hi, i am not executable");
    File[] roots = { f };
    add(roots);
    commit(roots);
    f.setExecutable(true);
    GitClient client = getClient(workDir);
    StoredConfig config = repository.getConfig();
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();
    write(f, "hi, i am executable");
    // add should not set executable bit in index
    add(roots);
    Map<File, GitStatus> statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    
    // index should differ from wt
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
    config.save();
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
}
 
Example 12
Source File: AddTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddKeepExecutableInIndex () throws Exception {
    if (isWindows()) {
        // no reason to test on windows
        return;
    }
    File f = new File(workDir, "f");
    write(f, "hi, i am executable");
    f.setExecutable(true);
    File[] roots = { f };
    GitClient client = getClient(workDir);
    add(roots);
    Map<File, GitStatus> statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    
    StoredConfig config = repository.getConfig();
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();
    // add should not overwrite executable bit in index
    f.setExecutable(false);
    add(roots);
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    
    // index should differ from wt
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
    config.save();
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_ADDED, Status.STATUS_MODIFIED, Status.STATUS_ADDED, false);
}
 
Example 13
Source File: StatusTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIgnoreExecutable () throws Exception {
    if (isWindows()) {
        // no reason to test on win
        return;
    }
    File f = new File(workDir, "f");
    write(f, "hi, i am executable");
    f.setExecutable(true);
    File[] roots = { f };
    add(roots);
    commit(roots);
    GitClient client = getClient(workDir);
    Map<File, GitStatus> statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    f.setExecutable(false);
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    
    StoredConfig config = repository.getConfig();
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
    config.save();
    add(roots);
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    
    config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, false);
    config.save();
    add(roots);
    statuses = client.getStatus(roots, NULL_PROGRESS_MONITOR);
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example 14
Source File: SetUpstreamBranchCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void setupRebaseFlag (Repository repository) throws IOException {
    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.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, localBranchName,
                ConfigConstants.CONFIG_KEY_REBASE, rebase);
    }
}
 
Example 15
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 16
Source File: GitService.java    From Refactoring-Bot with MIT License 4 votes vote down vote up
/**
 * This method performs 'git push' programmically
 * 
 * @throws GitWorkflowException
 */
public void commitAndPushChanges(GitConfiguration gitConfig, String commitMessage) throws GitWorkflowException {
	try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) {
		StoredConfig storedRepoConfig = git.getRepository().getConfig();
		// set autocrlf to true to handle line endings of different operating systems
		// correctly. Otherwise the bot will most likely change the line endings of all
		// files to the default of its operating system.
		// Corresponds to 'git config --global core.autocrlf true'
		storedRepoConfig.setEnum(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF,
				AutoCRLF.TRUE);
		// set filemode explicitly to false
		storedRepoConfig.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE,
				false);
		storedRepoConfig.save();

		// We only add those files to the staging area that have actually been changed.
		// 'git add .' in this JGit config would sometimes cause files to be added
		// without content changes (e.g. due to unpredictable whitespace changes).
		List<DiffEntry> diffEntries = git.diff().call();
		for (DiffEntry diffEntry : diffEntries) {
			git.add().addFilepattern(diffEntry.getOldPath()).call();
		}

		// 'git commit -m'
		git.commit().setMessage(commitMessage).setCommitter(gitConfig.getBotName(), gitConfig.getBotEmail()).call();

		// push with bot credentials
		if (gitConfig.getRepoService().equals(FileHoster.github)) {
			git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.getBotToken(), ""))
					.call();
		} else {
			git.push().setCredentialsProvider(
					new UsernamePasswordCredentialsProvider(gitConfig.getBotName(), gitConfig.getBotToken()))
					.call();
		}
	} catch (TransportException t) {
		logger.error(t.getMessage(), t);
		throw new GitWorkflowException("Wrong bot token!");
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new GitWorkflowException("Could not successfully perform 'git push'!");
	}
}
 
Example 17
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);
        }
    }
}
 
Example 18
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Ignore("see bug 339397")
public void testResetAutocrlfTrue() throws Exception {

	// "git config core.autocrlf true"
	Git git = Git.wrap(db);
	StoredConfig config = git.getRepository().getConfig();
	config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, Boolean.TRUE);
	config.save();

	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);

	String projectName = getMethodName().concat("Project");
	JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());
	String projectId = project.getString(ProtocolConstants.KEY_ID);

	JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
	String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
	String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
	String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

	// CRLF
	JSONObject testTxt = getChild(project, "test.txt");
	modifyFile(testTxt, "f" + "\r\n" + "older");
	addFile(testTxt);

	// commit
	WebRequest request = GitCommitTest.getPostGitCommitRequest(gitCommitUri, "added new line - crlf", false);
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// assert there is nothing to commit
	assertStatus(StatusResult.CLEAN, gitStatusUri);

	// create new file
	String fileName = "new.txt";
	// TODO: don't create URIs out of thin air
	request = getPostFilesRequest(projectId + "/", getNewFileJSON(fileName).toString(), fileName);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
	JSONObject file = new JSONObject(response.getText());
	String location = file.optString(ProtocolConstants.KEY_LOCATION, null);
	assertNotNull(location);

	// LF
	JSONObject newTxt = getChild(project, "new.txt");
	modifyFile(newTxt, "i'm" + "\n" + "new");

	// "git add ."
	request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* stage all */);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// reset
	request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	assertStatus(new StatusResult().setUntracked(1), gitStatusUri);
}
 
Example 19
Source File: GitBranchTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testCreateTrackingBranch() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
		String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

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

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject project = new JSONObject(response.getText());

		JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
		String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
		String gitRemoteUri = gitSection.optString(GitConstants.KEY_REMOTE);

		// create local branch tracking origin/master
		final String BRANCH_NAME = "a";
		final String REMOTE_BRANCH = Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER;

		branch(branchesLocation, BRANCH_NAME, REMOTE_BRANCH);

		// modify, add, commit
		JSONObject testTxt = getChild(project, "test.txt");
		modifyFile(testTxt, "some change");
		addFile(testTxt);
		request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// push
		ServerStatus pushStatus = push(gitRemoteUri, 1, 0, Constants.MASTER, Constants.HEAD, false);
		assertEquals(true, pushStatus.isOK());

		// TODO: replace with RESTful API for git pull when available
		// try to pull - up to date status is expected
		Git git = Git.wrap(getRepositoryForContentLocation(cloneContentLocation));
		PullResult pullResults = git.pull().call();
		assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
		assertEquals(MergeStatus.ALREADY_UP_TO_DATE, pullResults.getMergeResult().getMergeStatus());
		assertNull(pullResults.getRebaseResult());

		// checkout branch which was created a moment ago
		response = checkoutBranch(cloneLocation, BRANCH_NAME);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// TODO: replace with RESTful API for git pull when available
		// try to pull again - now fast forward update is expected
		pullResults = git.pull().call();
		assertEquals(Constants.DEFAULT_REMOTE_NAME, pullResults.getFetchedFrom());
		assertEquals(MergeStatus.FAST_FORWARD, pullResults.getMergeResult().getMergeStatus());
		assertNull(pullResults.getRebaseResult());
	}
}