org.eclipse.jgit.lib.StoredConfig Java Examples

The following examples show how to use org.eclipse.jgit.lib.StoredConfig. 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: 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 #2
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addRemoteUrl(String name, String url) throws GitException, InterruptedException {
    try (Repository repo = getRepository()) {
        StoredConfig config = repo.getConfig();

        List<String> urls = new ArrayList<>();
        urls.addAll(Arrays.asList(config.getStringList("remote", name, "url")));
        urls.add(url);

        config.setStringList("remote", name, "url", urls);
        config.save();
    } catch (IOException e) {
        throw new GitException(e);
    }
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: AbstractGitTest.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
void setOriginOnProjectToTmp(File origin, File project, boolean push)
		throws GitAPIException, IOException, URISyntaxException {
	try (Git git = openGitProject(project)) {
		RemoteRemoveCommand remove = git.remoteRemove();
		remove.setName("origin");
		remove.call();
		RemoteSetUrlCommand command = git.remoteSetUrl();
		command.setUri(new URIish(origin.toURI().toURL()));
		command.setName("origin");
		command.setPush(push);
		command.call();
		StoredConfig config = git.getRepository().getConfig();
		RemoteConfig originConfig = new RemoteConfig(config, "origin");
		originConfig
				.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
		originConfig.update(config);
		config.save();
	}
}
 
Example #8
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected void configureBranch(Git git, String branch) {
    // lets update the merge config
    if (Strings.isNotBlank(branch)) {
        StoredConfig config = git.getRepository().getConfig();
        if (Strings.isNullOrBlank(config.getString("branch", branch, "remote")) || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
            config.setString("branch", branch, "remote", getRemote());
            config.setString("branch", branch, "merge", "refs/heads/" + branch);
            try {
                config.save();
            } catch (IOException e) {
                LOG.error("Failed to save the git configuration to " + basedir
                        + " with branch " + branch + " on remote repo: " + remoteRepository + " due: " + e.getMessage() + ". This exception is ignored.", e);
            }
        }
    }
}
 
Example #9
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPullForcepullNotClean() throws Exception {
	Git git = mock(Git.class);
	StatusCommand statusCommand = mock(StatusCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class);
	StoredConfig storedConfig = mock(StoredConfig.class);

	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(status.isClean()).thenReturn(false);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());
	repo.setForcePull(true);

	boolean shouldPull = repo.shouldPull(git);

	assertThat(shouldPull).as("shouldPull was false").isTrue();
}
 
Example #10
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPullNotClean() throws Exception {
	Git git = mock(Git.class);
	StatusCommand statusCommand = mock(StatusCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class);
	StoredConfig storedConfig = mock(StoredConfig.class);

	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(status.isClean()).thenReturn(false);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());

	boolean shouldPull = repo.shouldPull(git);

	assertThat(shouldPull).as("shouldPull was true").isFalse();
}
 
Example #11
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPullClean() throws Exception {
	Git git = mock(Git.class);
	StatusCommand statusCommand = mock(StatusCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class);
	StoredConfig storedConfig = mock(StoredConfig.class);

	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(status.isClean()).thenReturn(true);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());

	boolean shouldPull = repo.shouldPull(git);

	assertThat(shouldPull).as("shouldPull was false").isTrue();
}
 
Example #12
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 #13
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 #14
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 #15
Source File: GitSubmoduleHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static void removeSubmodule(Repository db, Repository parentRepo, String pathToSubmodule) throws Exception {
	pathToSubmodule = pathToSubmodule.replace("\\", "/");
	StoredConfig gitSubmodulesConfig = getGitSubmodulesConfig(parentRepo);
	gitSubmodulesConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
	gitSubmodulesConfig.save();
	StoredConfig repositoryConfig = parentRepo.getConfig();
	repositoryConfig.unsetSection(CONFIG_SUBMODULE_SECTION, pathToSubmodule);
	repositoryConfig.save();
	Git git = Git.wrap(parentRepo);
	git.add().addFilepattern(DOT_GIT_MODULES).call();
	RmCommand rm = git.rm().addFilepattern(pathToSubmodule);
	if (gitSubmodulesConfig.getSections().size() == 0) {
		rm.addFilepattern(DOT_GIT_MODULES);
	}
	rm.call();
	FileUtils.delete(db.getWorkTree(), FileUtils.RECURSIVE);
	FileUtils.delete(db.getDirectory(), FileUtils.RECURSIVE);
}
 
Example #16
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 #17
Source File: GitProctorCoreWithRepositoryTest.java    From proctor with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloneRepository() throws Exception {
    final File workingDir = temporaryFolder.newFolder("testCloneRepository");

    // Run cloneRepository
    final GitProctorCore gitProctorCore = new GitProctorCore(
            gitUrl,
            GIT_USERNAME,
            GIT_PASSWORD,
            TEST_DEFINITION_DIRECTORY,
            workingDir
    );

    final Git git = gitProctorCore.getGit();

    assertNotNull(git);
    assertThat(git.getRepository().getBranch()).isEqualTo("master");

    final StoredConfig config = git.getRepository().getConfig();
    assertThat(config.getBoolean("pack", "singlePack", false)).isTrue();

    final String localCommitMessage = git.log().call().iterator().next().getFullMessage();
    assertThat(localCommitMessage).isEqualTo(COMMIT_MESSAGE);
}
 
Example #18
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 #19
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 #20
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 #21
Source File: GitTestExtension.java    From GitToolBox with Apache License 2.0 6 votes vote down vote up
private void prepareImpl(GitTestSetup setup) throws Exception {
  Path rootPath = setup.getRootPath();
  File rootDir = rootPath.toFile();
  if (FileUtil.isExistingFolder(rootDir)) {
    log.info("Deleting existing git root dir {}", rootPath);
    FileUtil.deleteDir(rootDir);
  }
  log.info("Initializing git [bare={}] repository in {}", setup.isBare(), rootPath);
  try (Git git = Git.init().setDirectory(rootDir).setBare(setup.isBare()).call()) {
    if (!setup.isBare()) {
      StoredConfig config = git.getRepository().getConfig();
      config.load();
      config.setString("user", null, "name", "Jon Snow");
      config.setString("user", null, "email", "[email protected]");
      config.save();
    }
    log.info("Setup initial git repository state in {}", rootPath);
    setup.setup(git);
    git.close();
    log.info("Git repository ready in {}", rootPath);
  }
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
Source File: GitRelatedTest.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
@Test
public void ifThereIsNoScmInfoAndNoRemoteBranchThenAnErrorIsThrown() throws GitAPIException, IOException, InterruptedException {
    TestProject testProject = TestProject.singleModuleProject();

    StoredConfig config = testProject.local.getRepository().getConfig();
    config.unsetSection("remote", "origin");
    config.save();

    try {
        testProject.mvnRelease("1");
        Assert.fail("Should have failed");
    } catch (MavenExecutionException e) {
        assertThat(e.output, oneOf(containsString("[ERROR] origin: not found.")));
    }
}
 
Example #27
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 #28
Source File: GitBasedArtifactRepository.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
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 #29
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 #30
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateLastRefresh() throws Exception {
	Git git = mock(Git.class);
	StatusCommand statusCommand = mock(StatusCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class);
	StoredConfig storedConfig = mock(StoredConfig.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	FetchResult fetchResult = mock(FetchResult.class);

	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(fetchCommand.call()).thenReturn(fetchResult);
	when(git.fetch()).thenReturn(fetchCommand);
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(status.isClean()).thenReturn(true);

	JGitEnvironmentProperties properties = new JGitEnvironmentProperties();
	properties.setRefreshRate(1000);
	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			properties);

	repo.setLastRefresh(0);
	repo.fetch(git, "master");

	long timeDiff = System.currentTimeMillis() - repo.getLastRefresh();

	assertThat(timeDiff < 1000L)
			.as("time difference (" + timeDiff + ") was longer than 1 second")
			.isTrue();
}