org.eclipse.jgit.api.errors.GitAPIException Java Examples
The following examples show how to use
org.eclipse.jgit.api.errors.GitAPIException.
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: SubmoduleStatusCommand.java From netbeans with Apache License 2.0 | 6 votes |
@Override protected void run () throws GitException { Repository repository = getRepository(); File workTree = repository.getWorkTree(); org.eclipse.jgit.api.SubmoduleStatusCommand cmd = new Git(repository).submoduleStatus(); for (String path : Utils.getRelativePaths(workTree, roots)) { cmd.addPath(path); } try { Map<String, SubmoduleStatus> result = cmd.call(); GitClassFactory fac = getClassFactory(); for (Map.Entry<String, SubmoduleStatus> e : result.entrySet()) { File root = new File(workTree, e.getKey()); statuses.put(root, fac.createSubmoduleStatus(e.getValue(), root)); } } catch (GitAPIException | JGitInternalException ex) { throw new GitException(ex); } }
Example #2
Source File: LocalRepoMock.java From gitflow-incremental-builder with MIT License | 6 votes |
public LocalRepoMock(File baseFolder, TestServerType remoteRepoServerType) throws IOException, URISyntaxException, GitAPIException { this.baseFolder = new File(baseFolder.getAbsolutePath(), "tmp/repo/"); new UnZipper().act(templateProjectZip, this.baseFolder); remoteRepo = remoteRepoServerType != null ? new RemoteRepoMock(baseFolder, remoteRepoServerType) : null; git = new Git(new FileRepository(new File(this.baseFolder, ".git"))); if (remoteRepoServerType != null) { try { configureRemote(git, remoteRepo.repoUri.toString()); } catch (IOException | URISyntaxException | GitAPIException | RuntimeException e) { close(); throw e; } } }
Example #3
Source File: GitPull.java From nano-framework with Apache License 2.0 | 6 votes |
public GitPull quickPull(String... args) { if (!ArrayUtils.isEmpty(args)) { for (final String arg : args) { if (StringUtils.equals("stop", StringUtils.lowerCase(arg))) { return this; } } } if (enabled) { try { return dir().pull().copy().clean(); } catch (final IOException | GitAPIException e) { throw new org.nanoframework.server.exception.GitAPIException(e.getMessage(), e); } } return this; }
Example #4
Source File: WLGitBridgeIntegrationTest.java From writelatex-git-bridge with MIT License | 6 votes |
@Test public void pushFailsOnInvalidProject() throws IOException, GitAPIException, InterruptedException { MockSnapshotServer server = new MockSnapshotServer(3870, getResource("/pushFailsOnInvalidProject").toFile()); server.start(); server.setState(states.get("pushFailsOnInvalidProject").get("state")); GitBridgeApp wlgb = new GitBridgeApp(new String[] { makeConfigFile(33870, 3870) }); wlgb.run(); File testprojDir = gitClone("testproj", 33870, dir); assertTrue(FileUtil.gitDirectoriesAreEqual(getResource("/pushFailsOnInvalidProject/state/testproj"), testprojDir.toPath())); runtime.exec("touch push.tex", null, testprojDir).waitFor(); gitAdd(testprojDir); gitCommit(testprojDir, "push"); Process push = gitPush(testprojDir, 1); wlgb.stop(); List<String> actual = Util.linesFromStream(push.getErrorStream(), 2, "[K"); assertEquals(EXPECTED_OUT_PUSH_INVALID_PROJECT, actual); }
Example #5
Source File: JGitUtil.java From mcg-helper with Apache License 2.0 | 6 votes |
public static boolean cloneRepository(String remoteUrl, String branch, String projectPath, String user, String pwd) throws InvalidRemoteException, TransportException, GitAPIException { File projectDir = new File(projectPath); UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd); try (Git git = Git.cloneRepository() .setURI(remoteUrl) .setBranch(branch) .setDirectory(projectDir) .setCredentialsProvider(provider) .setProgressMonitor(new CloneProgressMonitor()) .call()) { } return true; }
Example #6
Source File: GitProctorCore.java From proctor with Apache License 2.0 | 6 votes |
@Nullable private Set<String> parseStagedTestNames() { try { final Status status = git.status().call(); return Stream.of( status.getAdded(), status.getChanged(), status.getRemoved()) .flatMap(Set::stream) .distinct() .map(s -> parseTestName(testDefinitionsDirectory, s)) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch (final GitAPIException | NoWorkTreeException e) { LOGGER.warn("Failed to call git status", e); return null; } }
Example #7
Source File: SquashActionHandler.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public RebaseResponse process(Repository repository, String message) throws GitAPIException, IOException { try (Git git = Git.wrap(repository)) { git.commit() .setMessage(stripCommentLines(message)) .setAmend(true).setNoVerify(true).call(); getRebaseFile(repository, MESSAGE_SQUASH).delete(); getRebaseFile(repository, MESSAGE_FIXUP).delete(); createFile(repository, MESSAGE, message); RebaseResult result = git.rebase() .setOperation(RebaseCommand.Operation.SKIP) .runInteractively(handler) .call(); return new RebaseResponse(result); } }
Example #8
Source File: WrapGit.java From jphp with Apache License 2.0 | 6 votes |
@Signature public Memory resolveCommit(String revstr) throws IOException, GitAPIException { ObjectId objectId = getWrappedObject().getRepository().resolve(revstr); if (objectId == null) { return Memory.NULL; } LogCommand command = getWrappedObject() .log() .add(objectId) .setMaxCount(1); Iterable<RevCommit> call = command.call(); for (RevCommit revCommit : call) { return GitUtils.valueOf(revCommit); } return Memory.NULL; }
Example #9
Source File: GitHubNotebookRepo.java From zeppelin with Apache License 2.0 | 6 votes |
private void pullFromRemoteStream() { try { LOG.debug("Pulling latest changes from remote stream"); PullCommand pullCommand = git.pull(); pullCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider( zeppelinConfiguration.getZeppelinNotebookGitUsername(), zeppelinConfiguration.getZeppelinNotebookGitAccessToken() ) ); pullCommand.call(); } catch (GitAPIException e) { LOG.error("Error when pulling latest changes from remote repository", e); } }
Example #10
Source File: GitContentRepository.java From studio with GNU General Public License v3.0 | 6 votes |
@Override public void resetStagingRepository(String siteId) throws ServiceLayerException { Repository repo = helper.getRepository(siteId, PUBLISHED); String stagingName = servicesConfig.getStagingEnvironment(siteId); String liveName = servicesConfig.getLiveEnvironment(siteId); synchronized (repo) { try (Git git = new Git(repo)) { logger.debug("Checkout live first becuase it is not allowed to delete checkedout branch"); git.checkout().setName(liveName).call(); logger.debug("Delete staging branch in order to reset it for site: " + siteId); git.branchDelete().setBranchNames(stagingName).setForce(true).call(); logger.debug("Create new branch for staging with live HEAD as starting point"); git.branchCreate() .setName(stagingName) .setStartPoint(liveName) .call(); } catch (GitAPIException e) { logger.error("Error while reseting staging environment for site: " + siteId); throw new ServiceLayerException(e); } } }
Example #11
Source File: UploadUtilTests.java From super-cloudops with Apache License 2.0 | 6 votes |
@Test public void uploadTest() throws GitAPIException { Netty4ClientHttpRequestFactory factory = new Netty4ClientHttpRequestFactory(); //factory.setConnectTimeout(10_000); //factory.setReadTimeout(60_000); //factory.setMaxResponseSize(1024 * 1024 * 10); RestTemplate restTemplate = new RestTemplate(factory); FileSystemResource resource = new FileSystemResource(new File("/Users/vjay/Downloads/logo.png")); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("deviceId", "123424"); param.add("file", resource); String recv = restTemplate.postForObject(uploadUrl, param, String.class); System.out.println(recv); /*MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("id",id); HttpHeaders header = new HttpHeaders(); // 需求需要传参为form-data格式 header.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, header);*/ }
Example #12
Source File: ConfigRepository.java From gocd with Apache License 2.0 | 6 votes |
String getMergedConfig(String branchName, RevCommit newCommit) throws GitAPIException, IOException { MergeResult result = null; try { checkout(branchName); result = git.merge().include(newCommit).call(); } catch (GitAPIException e) { LOGGER.info("[CONFIG_MERGE] Merging commit {} by user {} to branch {} at revision {} failed", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName()); throw e; } if (!result.getMergeStatus().isSuccessful()) { LOGGER.info("[CONFIG_MERGE] Merging commit {} by user {} to branch {} at revision {} failed as config file has changed", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName()); throw new ConfigFileHasChangedException(); } LOGGER.info("[CONFIG_MERGE] Successfully merged commit {} by user {} to branch {}. Merge commit revision is {}", newCommit.getId().getName(), newCommit.getAuthorIdent().getName(), branchName, getCurrentRevCommit().getId().getName()); return FileUtils.readFileToString(new File(workingDir, CRUISE_CONFIG_XML), UTF_8); }
Example #13
Source File: GitConfigStoreTest.java From vertx-config with Apache License 2.0 | 6 votes |
@Test public void testWith2FileSetsAndNoIntersection(TestContext tc) throws GitAPIException, IOException { Async async = tc.async(); add(git, root, new File("src/test/resources/files/regular.json"), "file"); add(git, root, new File("src/test/resources/files/a.json"), "dir"); push(git); retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(new ConfigStoreOptions().setType("git").setConfig(new JsonObject() .put("url", bareRoot.getAbsolutePath()) .put("path", "target/junk/work") .put("filesets", new JsonArray() .add(new JsonObject().put("pattern", "file/reg*.json")) .add(new JsonObject().put("pattern", "dir/a.*son")) )))); retriever.getConfig(ar -> { assertThat(ar.result().getString("key")).isEqualTo("value"); assertThat(ar.result().getString("a.name")).isEqualTo("A"); async.complete(); }); }
Example #14
Source File: UnchangedProjectsRemoverTest.java From gitflow-incremental-builder with MIT License | 6 votes |
@Test public void singleChanged_buildUpstream_modeChanged() throws GitAPIException, IOException { MavenProject changedModuleMock = addModuleMock(AID_MODULE_B, true); MavenProject unchangedModuleMock = addModuleMock("unchanged-module", false); MavenProject dependsOnBothModuleMock = addModuleMock("changed-and-unchanged-dependent", false); when(mavenExecutionRequestMock.getMakeBehavior()).thenReturn(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM); setUpAndDownstreamsForBuildUpstreamModeTests(changedModuleMock, unchangedModuleMock, dependsOnBothModuleMock); addGibProperty(Property.buildUpstreamMode, "changed"); underTest.act(); verify(mavenSessionMock).setProjects(Arrays.asList(moduleA, changedModuleMock, dependsOnBothModuleMock)); assertProjectPropertiesEqual(moduleA, Collections.emptyMap()); assertProjectPropertiesEqual(changedModuleMock, Collections.emptyMap()); assertProjectPropertiesEqual(unchangedModuleMock, Collections.emptyMap()); assertProjectPropertiesEqual(dependsOnBothModuleMock, Collections.emptyMap()); }
Example #15
Source File: WLGitBridgeIntegrationTest.java From writelatex-git-bridge with MIT License | 6 votes |
@Test public void pushFailsOnInvalidFiles() throws IOException, GitAPIException, InterruptedException { MockSnapshotServer server = new MockSnapshotServer(3869, getResource("/pushFailsOnInvalidFiles").toFile()); server.start(); server.setState(states.get("pushFailsOnInvalidFiles").get("state")); GitBridgeApp wlgb = new GitBridgeApp(new String[] { makeConfigFile(33869, 3869) }); wlgb.run(); File testprojDir = gitClone("testproj", 33869, dir); assertTrue(FileUtil.gitDirectoriesAreEqual(getResource("/pushFailsOnInvalidFiles/state/testproj"), testprojDir.toPath())); runtime.exec("touch push.tex", null, testprojDir).waitFor(); gitAdd(testprojDir); gitCommit(testprojDir, "push"); Process push = gitPush(testprojDir, 1); wlgb.stop(); List<String> actual = Util.linesFromStream(push.getErrorStream(), 2, "[K"); assertEquals(EXPECTED_OUT_PUSH_INVALID_FILES, actual); }
Example #16
Source File: SubmoduleInitializeCommand.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void run () throws GitException { Repository repository = getRepository(); File workTree = repository.getWorkTree(); org.eclipse.jgit.api.SubmoduleInitCommand cmd = new Git(repository).submoduleInit(); for (String path : Utils.getRelativePaths(workTree, roots)) { cmd.addPath(path); } try { cmd.call(); statusCmd.run(); } catch (GitAPIException | JGitInternalException ex) { throw new GitException(ex); } }
Example #17
Source File: TestGitFlowPersistenceProvider.java From nifi-registry with Apache License 2.0 | 5 votes |
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 #18
Source File: JGitAPIImpl.java From git-client-plugin with MIT License | 5 votes |
private void doInit(String workspace, boolean bare) throws GitException { try { Git.init().setBare(bare).setDirectory(new File(workspace)).call(); } catch (GitAPIException e) { throw new GitException(e); } }
Example #19
Source File: GitRepo.java From spring-cloud-release-tools with Apache License 2.0 | 5 votes |
private FetchResult fetch(File projectDir) throws GitAPIException { Git git = this.gitFactory.open(projectDir); FetchCommand command = git.fetch(); try { return command.call(); } catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; } finally { git.close(); } }
Example #20
Source File: GitTestUtils.java From spring-cloud-release-tools with Apache License 2.0 | 5 votes |
public static void setOriginOnProjectToTmp(File origin, File project) throws GitAPIException, MalformedURLException { 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(true); command.call(); } }
Example #21
Source File: GitClonerTest.java From fasten with Apache License 2.0 | 5 votes |
@Test public void cloneRepoWithoutExtensionWithSlashTest() throws GitAPIException, IOException { var repo = Path.of(baseDir, "f/fasten-project/fasten").toFile(); var path = gitCloner.cloneRepo("https://github.com/fasten-project/fasten/"); Assertions.assertEquals(repo.getAbsolutePath(), path); Assertions.assertTrue(repo.exists()); Assertions.assertTrue(repo.isDirectory()); }
Example #22
Source File: GitWorkflowRepositoryTest.java From copper-engine with Apache License 2.0 | 5 votes |
@Test public void change2BranchesTest() throws CopperException, InterruptedException, IOException, GitAPIException { wfRepo.setBranch("1.0"); LockSupport.parkNanos(1000000000 + CHECK_INTERVAL_M_SEC * 1000000); // wait for workflow refresh engine.run("Workflow1", "foo"); String result1 = (String) channel.wait("correlationId", 1000, TimeUnit.MILLISECONDS); assertEquals("V1.0", result1); wfRepo.setBranch("2.0"); LockSupport.parkNanos(1000000000 + CHECK_INTERVAL_M_SEC * 1000000); // wait for workflow refresh engine.run("Workflow1", "foo"); String result2 = (String) channel.wait("correlationId", 1000, TimeUnit.MILLISECONDS); assertEquals("V2.0", result2); }
Example #23
Source File: GitManagerImpl.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void sync(Workspace ws) throws GitAPIException { Repository repository = getRepository(ws.getSpaceKey()); try (Git git = Git.wrap(repository)) { git.submoduleSync().call(); } }
Example #24
Source File: ChangeApplier.java From smart-testing with Apache License 2.0 | 5 votes |
private Collection<TestResult> applyLocallyFromTags(Collection<RevTag> tags) throws GitAPIException { final Set<TestResult> combinedTestResults = new HashSet<>(); final List<RevCommit> stashesToApply = new ArrayList<>(); stashesToApply.add(git.stashCreate().setIncludeUntracked(true).call()); for (final RevTag tag : tags) { final ObjectId tagId = tag.getObject().getId(); git.cherryPick().setNoCommit(true).include(tagId).call(); stashesToApply.add(git.stashCreate().setIncludeUntracked(true).call()); combinedTestResults.addAll(testResultsExtractor.expectedTestResults(tagId)); } applyStashChangesLocally(stashesToApply); return combinedTestResults; }
Example #25
Source File: GitExceptionTest.java From git-client-plugin with MIT License | 5 votes |
@Test public void initJGitImplThrowsGitException() throws GitAPIException, IOException, InterruptedException { String fileName = isWindows() ? "\\\\badserver\\badshare\\bad\\dir" : "/this/is/a/bad/dir"; final File badDirectory = new File(fileName); assumeFalse("running as root?", new File("/").canWrite()); GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(badDirectory).using("jgit").getClient(); assertNotNull(defaultClient); JGitInternalException e = assertThrows(JGitInternalException.class, () -> { defaultClient.init_().workspace(badDirectory.getAbsolutePath()).execute(); }); assertThat(e.getCause(), isA(IOException.class)); }
Example #26
Source File: WLGitBridgeIntegrationTest.java From writelatex-git-bridge with MIT License | 5 votes |
@Test public void canCloneARepository() throws IOException, GitAPIException, InterruptedException { MockSnapshotServer server = new MockSnapshotServer(3857, getResource("/canCloneARepository").toFile()); server.start(); server.setState(states.get("canCloneARepository").get("state")); GitBridgeApp wlgb = new GitBridgeApp(new String[] { makeConfigFile(33857, 3857) }); wlgb.run(); File testprojDir = gitClone("testproj", 33857, dir); wlgb.stop(); assertTrue(FileUtil.gitDirectoriesAreEqual(getResource("/canCloneARepository/state/testproj"), testprojDir.toPath())); }
Example #27
Source File: ProjectWebsiteTest.java From jbake with MIT License | 5 votes |
private void cloneJbakeWebsite() throws GitAPIException { CloneCommand cmd = Git.cloneRepository(); cmd.setBare(false); cmd.setBranch("master"); cmd.setRemote("origin"); cmd.setURI(WEBSITE_REPO_URL); cmd.setDirectory(projectFolder); cmd.call(); assertThat(new File(projectFolder,"README.md").exists()).isTrue(); }
Example #28
Source File: UnchangedProjectsRemoverTest.java From gitflow-incremental-builder with MIT License | 5 votes |
@Test public void singleChanged() throws GitAPIException, IOException { MavenProject changedModuleMock = addModuleMock(AID_MODULE_B, true); underTest.act(); verify(mavenSessionMock).setProjects(Collections.singletonList(changedModuleMock)); }
Example #29
Source File: PipelineConfigServiceIntegrationTest.java From gocd with Apache License 2.0 | 5 votes |
@Test public void shouldNotUpdatePipelineConfigInCaseOfValidationErrors() throws GitAPIException { GoConfigHolder goConfigHolder = goConfigDao.loadConfigHolder(); String digest = entityHashingService.hashForEntity(pipelineConfig, groupName); pipelineConfig.setLabelTemplate("LABEL"); pipelineConfigService.updatePipelineConfig(user, pipelineConfig, groupName, digest, result); assertThat(result.toString(), result.isSuccessful(), is(false)); assertThat(result.httpCode(), is(422)); assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), contains("Invalid label")); assertThat(configRepository.getCurrentRevCommit().name(), is(headCommitBeforeUpdate)); assertThat(goConfigDao.loadConfigHolder().configForEdit, is(goConfigHolder.configForEdit)); assertThat(goConfigDao.loadConfigHolder().config, is(goConfigHolder.config)); }
Example #30
Source File: RepoMerger.java From git-merge-repos with Apache License 2.0 | 5 votes |
public List<MergedRef> run() throws IOException, GitAPIException { fetch(); List<MergedRef> mergedBranches = mergeBranches(); List<MergedRef> mergedTags = mergeTags(); List<MergedRef> mergedRefs = new ArrayList<>(); mergedRefs.addAll(mergedBranches); mergedRefs.addAll(mergedTags); deleteOriginalRefs(); resetToBranch(); return mergedRefs; }