Java Code Examples for org.eclipse.jgit.api.Git#open()
The following examples show how to use
org.eclipse.jgit.api.Git#open() .
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: GithubApi.java From karamel with Apache License 2.0 | 6 votes |
/** * Synchronizes your updates on your local repository with github. * * @param owner * @param repoName * @throws KaramelException */ public synchronized static void commitPush(String owner, String repoName) throws KaramelException { if (email == null || user == null) { throw new KaramelException("You forgot to call registerCredentials. You must call this method first."); } File repoDir = getRepoDirectory(repoName); Git git = null; try { git = Git.open(repoDir); git.commit().setAuthor(user, email).setMessage("Code generated by Karamel.") .setAll(true).call(); git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call(); } catch (IOException | GitAPIException ex) { logger.error("error during github push", ex); throw new KaramelException(ex.getMessage()); } finally { if (git != null) { git.close(); } } }
Example 2
Source File: MergeBaseCalculator.java From diff-check with GNU Lesser General Public License v2.1 | 6 votes |
/** * calculate the merge base between two refs * * @param repoDir the git directory * @param ref1 the ref * @param ref2 the other ref * @return the merge base * @throws Exception throw Exception when error happens */ public String calculateMergeBase(File repoDir, String ref1, String ref2) throws Exception { try (Git git = Git.open(repoDir); ObjectReader reader = git.getRepository().newObjectReader(); RevWalk rw = new RevWalk(git.getRepository())) { RevCommit commit1 = rw.parseCommit(git.getRepository().resolve(ref1)); RevCommit commit2 = rw.parseCommit(git.getRepository().resolve(ref2)); rw.setRevFilter(RevFilter.MERGE_BASE); rw.markStart(commit1); rw.markStart(commit2); RevCommit mergeBase = rw.next(); return mergeBase != null ? mergeBase.name() : ""; } }
Example 3
Source File: GitService.java From Refactoring-Bot with MIT License | 6 votes |
/** * This method fetches data from the 'upstrem' remote. * * @param gitConfig * @throws GitWorkflowException */ public void fetchRemote(GitConfiguration gitConfig) throws GitWorkflowException { try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) { // Fetch data if (gitConfig.getRepoService().equals(FileHoster.github)) { git.fetch().setRemote("upstream") .setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.getBotToken(), "")) .call(); } else { git.fetch().setRemote("upstream").setCredentialsProvider( new UsernamePasswordCredentialsProvider(gitConfig.getBotName(), gitConfig.getBotToken())) .call(); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new GitWorkflowException("Could not fetch data from 'upstream'!"); } }
Example 4
Source File: AbstractRepairStep.java From repairnator with MIT License | 5 votes |
protected Git createGitBranch4Push(String branchName) throws IOException{ Git git = Git.open(new File(this.getInspector().getRepoLocalPath())); int status = GitHelper.gitCreateNewBranchAndCheckoutIt(this.getInspector().getRepoLocalPath(), branchName); if (status != 0) { return null; } return git; }
Example 5
Source File: WalkCommitTreeAdapter.java From coderadar with MIT License | 5 votes |
@Override public void walkCommitTree( String projectRoot, String name, WalkTreeCommandInterface commandInterface) throws UnableToWalkCommitTreeException { try { Git git = Git.open(new File(projectRoot)); ObjectId commitId = git.getRepository().resolve(name); RevWalk walk = new RevWalk(git.getRepository()); RevCommit commit = walk.parseCommit(commitId); RevTree tree = commit.getTree(); TreeWalk treeWalk = new TreeWalk(git.getRepository()); treeWalk.addTree(tree); treeWalk.setRecursive(true); while (treeWalk.next()) { if (!treeWalk.getPathString().endsWith(".java") || treeWalk.getPathString().contains("build") || treeWalk.getPathString().contains("out") || treeWalk.getPathString().contains("classes") || treeWalk.getPathString().contains("node_modules") || treeWalk.getPathString().contains("test")) { continue; } commandInterface.walkMethod(treeWalk.getPathString()); } git.close(); } catch (IOException e) { throw new UnableToWalkCommitTreeException(e.getMessage()); } }
Example 6
Source File: WorldRepository.java From VoxelGamesLibv2 with MIT License | 5 votes |
public void commitRepo() { try { Git git = Git.open(worldsDir); new CustomAddCommand(git.getRepository()).addFilepattern(".").call(); git.commit().setAuthor("voxelgameslib", "[email protected]") .setMessage("Update " + LocalDateTime.now().toString()).call(); // don't push here, thats need to be done manually } catch (IOException | GitAPIException e) { e.printStackTrace(); } }
Example 7
Source File: CurioGenericCiPluginTest.java From curiostack with MIT License | 5 votes |
@BeforeAll void copyProject() throws Exception { Path projectDir = copyGitRepoFromResources("test-projects/gradle-curio-generic-ci-plugin/master-no-diffs"); try (Git git = Git.open(projectDir.toFile())) { changeBranch("prbuild", git); addDiffs(projectDir, git, "build.gradle.kts"); addTwoEmptyCommits(git); } this.projectDir = projectDir.toFile(); }
Example 8
Source File: GitPushWindow.java From XACML with MIT License | 5 votes |
protected void refreshStatus() { try { // // Grab our working repository // Path repoPath = ((XacmlAdminUI)getUI()).getUserGitPath(); final Git git = Git.open(repoPath.toFile()); // // Get our status // final String base; Status status; if (target == null) { base = "."; } else { Path relativePath = repoPath.relativize(Paths.get(target.getPath())); base = relativePath.toString(); } if (logger.isDebugEnabled()) { logger.debug("Status on base: " + base); } status = git.status().addPath(base).call(); // // Pass it to our container // this.container.refreshStatus(status); this.tableChanges.refreshRowCache(); } catch (NoWorkTreeException | IOException | GitAPIException e) { String error = "Failed to refresh status: " + e.getLocalizedMessage(); logger.error(error); } }
Example 9
Source File: GitConfigStore.java From vertx-config with Apache License 2.0 | 5 votes |
private Git initializeGit() throws IOException, GitAPIException { if (path.isDirectory()) { Git git = Git.open(path); String current = git.getRepository().getBranch(); if (branch.equalsIgnoreCase(current)) { PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider) .setTransportConfigCallback(transportConfigCallback).call(); if (!pull.isSuccessful()) { LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote + "'"); } return git; } else { git.checkout() .setName(branch) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint(remote + "/" + branch) .call(); return git; } } else { return Git.cloneRepository() .setURI(url) .setBranch(branch) .setRemote(remote) .setDirectory(path) .setCredentialsProvider(credentialProvider) .setTransportConfigCallback(transportConfigCallback) .call(); } }
Example 10
Source File: CurioGenericCiPluginTest.java From curiostack with MIT License | 5 votes |
@BeforeAll void copyProject() throws Exception { Path projectDir = copyGitRepoFromResources("test-projects/gradle-curio-generic-ci-plugin/master-no-diffs"); try (var git = Git.open(projectDir.toFile())) { changeBranch("prbuild", git); addDiffs(projectDir, git, "server2/src/main/java/Server2.java"); addTwoEmptyCommits(git); } this.projectDir = projectDir.toFile(); }
Example 11
Source File: CurioGenericCiPluginTest.java From curiostack with MIT License | 5 votes |
@BeforeAll void copyProject() throws Exception { Path projectDir = copyGitRepoFromResources("test-projects/gradle-curio-generic-ci-plugin/master-no-diffs"); try (var git = Git.open(projectDir.toFile())) { addDiffs(projectDir, git, "build.gradle.kts"); } this.projectDir = projectDir.toFile(); }
Example 12
Source File: CurioGenericCiPluginTest.java From curiostack with MIT License | 5 votes |
@BeforeAll void copyProject() throws Exception { Path projectDir = copyGitRepoFromResources("test-projects/gradle-curio-generic-ci-plugin/master-no-diffs"); try (var git = Git.open(projectDir.toFile())) { changeBranch("prbuild", git); addDiffs(projectDir, git, "staticsite1/build.gradle.kts"); addTwoEmptyCommits(git); } this.projectDir = projectDir.toFile(); }
Example 13
Source File: NoteBuildActionTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Before public void setup() throws Exception { Git.init().setDirectory(tmp.getRoot()).call(); tmp.newFile("test"); Git git = Git.open(tmp.getRoot()); git.add().addFilepattern("test"); RevCommit commit = git.commit().setMessage("test").call(); commitSha1 = commit.getId().getName(); gitRepoUrl = tmp.getRoot().toURI().toString(); }
Example 14
Source File: PipelineHookTriggerHandlerImplTest.java From gitlab-plugin with GNU General Public License v2.0 | 4 votes |
@Before public void setup() throws IOException, GitAPIException { List<String> allowedStates = new ArrayList<>(); allowedStates.add("success"); User user = new User(); user.setName("test"); user.setId(1); Git.init().setDirectory(tmp.getRoot()).call(); tmp.newFile("test"); Git git = Git.open(tmp.getRoot()); git.add().addFilepattern("test"); git.commit().setMessage("test").call(); ObjectId head = git.getRepository().resolve(Constants.HEAD); pipelineHookTriggerHandler = new PipelineHookTriggerHandlerImpl(allowedStates); pipelineHook = pipelineHook() .withUser(user) .withRepository(repository() .withName("test") .withHomepage("https://gitlab.org/test") .withUrl("[email protected]:test.git") .withGitSshUrl("[email protected]:test.git") .withGitHttpUrl("https://gitlab.org/test.git") .build()) .withProject(project() .withNamespace("test-namespace") .withWebUrl("https://gitlab.org/test") .withId(1) .build()) .withObjectAttributes(pipelineEventObjectAttributes() .withId(1) .withStatus("success") .withSha("bcbb5ec396a2c0f828686f14fac9b80b780504f2") .withStages(new ArrayList<String>()) .withRef("refs/heads/" + git.nameRev().add(head).call().get(head)) .build()) .build(); git.close(); }
Example 15
Source File: CommitPatch.java From repairnator with MIT License | 4 votes |
@Override protected StepStatus businessExecute() { if (this.getConfig().isPush()) { if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) { this.getLogger().info("Commit human patch..."); } else { this.getLogger().info("Commit info from repair tools..."); } super.setCommitType(this.commitType); try { Git git = Git.open(new File(this.getInspector().getRepoToPushLocalPath())); Ref oldHeadRef = git.getRepository().exactRef("HEAD"); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit headRev = revWalk.parseCommit(oldHeadRef.getObjectId()); revWalk.dispose(); StepStatus stepStatus = super.businessExecute(); if (stepStatus.isSuccess()) { RevCommit commit = super.getCommit(); this.getInspector().getGitHelper().computePatchStats(this.getInspector().getJobStatus(), git, headRev, commit); if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) { this.setPushState(PushState.PATCH_COMMITTED); } else { this.setPushState(PushState.REPAIR_INFO_COMMITTED); } } else { if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) { this.setPushState(PushState.PATCH_NOT_COMMITTED); } else { this.setPushState(PushState.REPAIR_INFO_NOT_COMMITTED); } } return stepStatus; } catch (IOException e) { this.addStepError("Error while opening the local git repository, maybe it has not been initialized.", e); } if (this.commitType == CommitType.COMMIT_HUMAN_PATCH) { this.setPushState(PushState.PATCH_NOT_COMMITTED); } else { this.setPushState(PushState.REPAIR_INFO_NOT_COMMITTED); } return StepStatus.buildSkipped(this,"Error while committing."); } else { this.getLogger().info("Repairnator is configured NOT to push. Step bypassed."); return StepStatus.buildSkipped(this); } }
Example 16
Source File: GitTestExtension.java From GitToolBox with Apache License 2.0 | 4 votes |
private void opsImpl(GitOps ops) throws IOException { Path rootPath = ops.getRootPath(); try (Git git = Git.open(rootPath.toFile())) { ops.invoke(git); } }
Example 17
Source File: NoteHookTriggerHandlerImplTest.java From gitlab-plugin with GNU General Public License v2.0 | 4 votes |
@Test public void note_build() throws IOException, InterruptedException, GitAPIException, ExecutionException { Git.init().setDirectory(tmp.getRoot()).call(); tmp.newFile("test"); Git git = Git.open(tmp.getRoot()); git.add().addFilepattern("test"); RevCommit commit = git.commit().setMessage("test").call(); ObjectId head = git.getRepository().resolve(Constants.HEAD); String repositoryUrl = tmp.getRoot().toURI().toString(); final OneShotEvent buildTriggered = new OneShotEvent(); FreeStyleProject project = jenkins.createFreeStyleProject(); project.setScm(new GitSCM(repositoryUrl)); project.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { buildTriggered.signal(); return true; } }); Date currentDate = new Date(); project.setQuietPeriod(0); noteHookTriggerHandler.handle(project, noteHook() .withObjectAttributes(noteObjectAttributes() .withId(1) .withNote("ci-run") .withAuthorId(1) .withProjectId(1) .withCreatedAt(currentDate) .withUpdatedAt(currentDate) .withUrl("https://gitlab.org/test/merge_requests/1#note_1") .build()) .withMergeRequest(mergeRequestObjectAttributes() .withTargetBranch("refs/heads/" + git.nameRev().add(head).call().get(head)) .withState(State.opened) .withIid(1) .withTitle("test") .withTargetProjectId(1) .withSourceProjectId(1) .withSourceBranch("feature") .withTargetBranch("master") .withLastCommit(commit().withAuthor(user().withName("test").build()).withId(commit.getName()).build()) .withSource(project() .withName("test") .withNamespace("test-namespace") .withHomepage("https://gitlab.org/test") .withUrl("[email protected]:test.git") .withSshUrl("[email protected]:test.git") .withHttpUrl("https://gitlab.org/test.git") .build()) .withTarget(project() .withName("test") .withNamespace("test-namespace") .withHomepage("https://gitlab.org/test") .withUrl("[email protected]:test.git") .withSshUrl("[email protected]:test.git") .withHttpUrl("https://gitlab.org/test.git") .withWebUrl("https://gitlab.org/test.git") .build()) .build()) .build(), true, BranchFilterFactory.newBranchFilter(branchFilterConfig().build(BranchFilterType.All)), newMergeRequestLabelFilter(null)); buildTriggered.block(10000); assertThat(buildTriggered.isSignaled(), is(true)); }
Example 18
Source File: JGitEnvironmentRepositoryIntegrationTests.java From spring-cloud-config with Apache License 2.0 | 4 votes |
/** * Tests a special use case where the remote repository has been updated with a forced * push conflicting with the local repo of the Config Server. The Config Server has to * reset hard on the new reference because a simple pull operation could result in a * conflicting local repository. * @throws Exception when git related exception happens */ @Test public void pullDirtyRepo() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); // Create a remote bare repository. Repository remote = ConfigServerTestUtils.prepareBareRemote(); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator() .next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class) .web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context .getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); assertThat(commitToRevertBeforePull).isEqualTo(locations.getVersion()); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. Path applicationFilePath = Paths .get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); String conflictingCommit = git.log().setMaxCount(1).call().iterator().next() .getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); assertThat(conflictingCommit).isEqualTo(locations.getVersion()); assertThat(git.status().call().isClean()) .as("Local repository is not cleaned after retrieving resources.") .isTrue(); }
Example 19
Source File: TestInitRepoToPush.java From repairnator with MIT License | 3 votes |
@Test public void testInitRepoToPushSimpleCase() throws IOException, GitAPIException { long buildId = 207924136; // surli/failingProject build RepairnatorConfig repairnatorConfig = RepairnatorConfig.getInstance(); repairnatorConfig.setClean(false); repairnatorConfig.setPush(true); Build build = this.checkBuildAndReturn(buildId, false); tmpDir = Files.createTempDirectory("test_initRepoToPush").toFile(); BuildToBeInspected toBeInspected = new BuildToBeInspected(build, null, ScannedBuildStatus.ONLY_FAIL, ""); JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath()+"/repo"); jobStatus.getProperties().getBuilds().setBuggyBuild(new fr.inria.spirals.repairnator.process.inspectors.properties.builds.Build(buildId, "", new Date())); ProjectInspector inspector = ProjectInspectorMocker.mockProjectInspector(jobStatus, tmpDir, toBeInspected); CloneRepository cloneStep = new CloneRepository(inspector); cloneStep.addNextStep(new CheckoutBuggyBuild(inspector, true)).addNextStep(new InitRepoToPush(inspector)); cloneStep.execute(); assertThat(jobStatus.getPushStates().contains(PushState.REPO_INITIALIZED), is(true)); Git gitDir = Git.open(new File(tmpDir, "repotopush")); Iterable<RevCommit> logs = gitDir.log().call(); Iterator<RevCommit> iterator = logs.iterator(); assertThat(iterator.hasNext(), is(true)); RevCommit commit = iterator.next(); assertThat(commit.getShortMessage(), containsString("Bug commit")); assertThat(iterator.hasNext(), is(false)); }
Example 20
Source File: TestCloneRepositoryStep.java From repairnator with MIT License | 3 votes |
@Test public void testCloneMasterBuild() throws IOException { long buildId = 207924136; // surli/failingProject build Build build = this.checkBuildAndReturn(buildId, false); tmpDir = Files.createTempDirectory("test_clone").toFile(); BuildToBeInspected toBeInspected = new BuildToBeInspected(build, null, ScannedBuildStatus.ONLY_FAIL, ""); JobStatus jobStatus = new JobStatus(tmpDir.getAbsolutePath()+"/repo"); ProjectInspector inspector = ProjectInspectorMocker.mockProjectInspector(jobStatus, tmpDir, toBeInspected); CloneRepository cloneStep = new CloneRepository(inspector); cloneStep.execute(); assertThat(cloneStep.isShouldStop(), is(false)); List<StepStatus> stepStatusList = jobStatus.getStepStatuses(); assertThat(stepStatusList.size(), is(1)); StepStatus cloneStatus = stepStatusList.get(0); assertThat(cloneStatus.getStep(), is(cloneStep)); assertThat(cloneStatus.isSuccess(), is(true)); Git gitDir = Git.open(new File(tmpDir, "repo")); Ref ref = gitDir.getRepository().exactRef("HEAD"); assertThat(ref.isSymbolic(), is(true)); ref = ref.getTarget(); assertThat(ref.getObjectId().getName(), not(build.getCommit().getSha())); // no check out yet }