org.eclipse.jgit.api.Git Java Examples
The following examples show how to use
org.eclipse.jgit.api.Git.
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: GitUtils.java From gitPic with MIT License | 8 votes |
public static void pull(Repository repository) { Git git = new Git(repository); try { PullResult result = git.pull().call(); FetchResult fetchResult = result.getFetchResult(); MergeResult mergeResult = result.getMergeResult(); if (fetchResult.getMessages() != null && !fetchResult.getMessages().isEmpty()) { logger.info(fetchResult.getMessages()); } logger.info(mergeResult.getMergeStatus().toString()); if (!mergeResult.getMergeStatus().isSuccessful()) { throw new TipException(mergeResult.getMergeStatus().toString()); } } catch (GitAPIException e) { logger.error(e.getMessage(), e); throw new TipException("git commit 异常"); } }
Example #2
Source File: GitUtils.java From singleton with Eclipse Public License 2.0 | 6 votes |
public static File cloneRepository(String remoteUri, String tempFolder, String branch, CredentialsProvider credentialsProvider) { File file = new File(tempFolder); try { if (file.exists()) { deleteFolder(file); } file.mkdirs(); Git.cloneRepository().setURI(remoteUri).setDirectory(file).setBranch(branch) .setCredentialsProvider(credentialsProvider).call(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error(e.getMessage(), e); } return file; }
Example #3
Source File: GitManagerTest.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testForCreateAnotationTag() throws GitAPIException, IOException { Git git = Git.wrap(repository); gitMgr.createTag(ws, "test", null, "test message", false); List<Ref> refs = git.tagList().call(); assertEquals(1, refs.size()); assertEquals("refs/tags/test", refs.get(0).getName()); assertNotEquals(repository.resolve("HEAD"), refs.get(0).getObjectId()); RevWalk walk = new RevWalk(repository); RevTag tag = walk.parseTag(refs.get(0).getObjectId()); assertEquals("test message", tag.getFullMessage()); }
Example #4
Source File: CurioGenericCiPluginTest.java From curiostack with MIT License | 6 votes |
private static void addDiffs(Path projectDir, Git git, String... paths) throws Exception { for (String path : paths) { var filePath = projectDir.resolve(path); try { Files.writeString(filePath, Files.readString(filePath).replace("|DIFF-ME|", "-DIFFED-")); } catch (IOException e) { throw new UncheckedIOException("Could not add diff to file.", e); } } git.commit() .setAll(true) .setMessage("Automated commit in test") .setAuthor("Unit Test", "[email protected]") .call(); }
Example #5
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 6 votes |
protected void checkoutBranch(Git git, GitContext context) throws GitAPIException { String current = currentBranch(git); if (Objects.equals(current, branch)) { return; } System.out.println("Checking out branch: " + branch); // lets check if the branch exists CheckoutCommand command = git.checkout().setName(branch); boolean exists = localBranchExists(git, branch); if (!exists) { command = command.setCreateBranch(true).setForce(true). setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). setStartPoint(getRemote() + "/" + branch); } Ref ref = command.call(); if (LOG.isDebugEnabled()) { LOG.debug("Checked out branch " + branch + " with results " + ref.getName()); } configureBranch(git, branch); }
Example #6
Source File: BlameCalculator.java From diff-check with GNU Lesser General Public License v2.1 | 6 votes |
public List<BlameResult> calculate( File repoDir, List<String> filePathList, String startRev) throws Exception { try (Git git = Git.open(repoDir); ObjectReader reader = git.getRepository().newObjectReader(); RevWalk rw = new RevWalk(git.getRepository())) { RevCommit startCommit = rw.parseCommit(git.getRepository().resolve(startRev)); List<BlameResult> resultList = new ArrayList<>(); for (String filePath : filePathList) { BlameResult result = calculateBlame(filePath, startCommit, git); resultList.add(result); } return resultList; } }
Example #7
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 #8
Source File: RepositoryManagementServiceInternalImpl.java From studio with GNU General Public License v3.0 | 6 votes |
@Override public RepositoryStatus getRepositoryStatus(String siteId) throws CryptoException, ServiceLayerException { GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration); Repository repo = helper.getRepository(siteId, SANDBOX); RepositoryStatus repositoryStatus = new RepositoryStatus(); logger.debug("Execute git status and return conflicting paths and uncommitted changes"); try (Git git = new Git(repo)) { Status status = git.status().call(); repositoryStatus.setClean(status.isClean()); repositoryStatus.setConflicting(status.getConflicting()); repositoryStatus.setUncommittedChanges(status.getUncommittedChanges()); } catch (GitAPIException e) { logger.error("Error while getting repository status for site " + siteId, e); throw new ServiceLayerException("Error getting repository status for site " + siteId, e); } return repositoryStatus; }
Example #9
Source File: AbstractUpgradeOperation.java From studio with GNU General Public License v3.0 | 6 votes |
protected void commitAllChanges(String site) throws UpgradeException { try { Path repositoryPath = getRepositoryPath(site); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder .setGitDir(repositoryPath.toFile()) .readEnvironment() .findGitDir() .build(); try (Git git = new Git(repo)) { git.add().addFilepattern(".").call(); Status status = git.status().call(); if (status.hasUncommittedChanges() || !status.isClean()) { git.commit() .setAll(true) .setMessage(getCommitMessage()) .call(); } } } catch (IOException | GitAPIException e) { throw new UpgradeException("Error committing changes for site " + site, e); } }
Example #10
Source File: GitManagerTest.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void initRepo(Repository repository) throws IOException, GitAPIException { Git git = new Git(repository); ws.write("README.md", "This is readme", false, true, false); ws.write("README2.md", "this is readme2", false, true, false); git.add().addFilepattern("README.md").call(); git.add().addFilepattern("README2.md").call(); git.commit().setMessage("create readme").call(); // create test branch createTestBranch(repository, "branch1", (g, branch) -> { ws.write("README.md", "branch1", false, true, false); g.add().addFilepattern("README.md").call(); g.commit().setMessage(branch).call(); }); createTestBranch(repository, "branch2", (g, branch) -> { ws.write("README.md", "branch2", false, true, false); g.add().addFilepattern("README.md").call(); g.commit().setMessage(branch).call(); }); }
Example #11
Source File: GitClient.java From cf-butler with Apache License 2.0 | 6 votes |
public RevCommit getLatestCommit(Repository repo) throws IOException, GitAPIException { RevCommit latestCommit = null; int inc = 0; try( Git git = new Git(repo); RevWalk walk = new RevWalk(repo); ) { List<Ref> branches = git.branchList().call(); for(Ref branch : branches) { RevCommit commit = walk.parseCommit(branch.getObjectId()); if (inc == 0) latestCommit = commit; if(commit.getAuthorIdent().getWhen().compareTo(latestCommit.getAuthorIdent().getWhen()) > 0) latestCommit = commit; inc++; } } return latestCommit; }
Example #12
Source File: AppRepo.java From app-runner with MIT License | 6 votes |
public static AppRepo create(String name, String sampleAppName) { try { File originDir = copySampleAppToTempDir(sampleAppName); InitCommand initCommand = Git.init(); initCommand.setDirectory(originDir); Git origin = initCommand.call(); origin.add().addFilepattern(".").call(); origin.commit().setMessage("Initial commit") .setAuthor(new PersonIdent("Author Test", "[email protected]")) .call(); return new AppRepo(name, originDir, origin); } catch (Exception e) { throw new RuntimeException("Error while creating git repo", e); } }
Example #13
Source File: UpdaterGenerator.java From neembuu-uploader with GNU General Public License v3.0 | 6 votes |
/** * Clone GIT repository from sourceforge. * * @param gitDirectory The directory of Git. */ private void gitClone(File gitDirectory) { try { git = Git.cloneRepository() .setDirectory(gitDirectory) .setURI(env.gitURI()) //.setURI("http://git.code.sf.net/p/neembuuuploader/gitcode") .setProgressMonitor(new TextProgressMonitor()).call(); for (Ref f : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { git.checkout().setName(f.getName()).call(); System.out.println("checked out branch " + f.getName() + ". HEAD: " + git.getRepository().getRef("HEAD")); } // try to checkout branches by specifying abbreviated names git.checkout().setName("master").call(); } catch (GitAPIException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
Example #14
Source File: JGitEnvironmentRepository.java From spring-cloud-config with Apache License 2.0 | 6 votes |
private Ref resetHard(Git git, String label, String ref) { ResetCommand reset = git.reset(); reset.setRef(ref); reset.setMode(ResetType.HARD); try { Ref resetRef = reset.call(); if (resetRef != null) { this.logger.info( "Reset label " + label + " to version " + resetRef.getObjectId()); } return resetRef; } catch (Exception ex) { String message = "Could not reset to remote for " + label + " (current ref=" + ref + "), remote: " + git.getRepository().getConfig() .getString("remote", "origin", "url"); warn(message, ex); return null; } }
Example #15
Source File: SvnTestServer.java From git-as-svn with GNU General Public License v2.0 | 6 votes |
private void cleanupBranches(@NotNull Repository repository) throws IOException { final List<String> branches = new ArrayList<>(); for (Ref ref : repository.getRefDatabase().getRefsByPrefix(Constants.R_HEADS + TEST_BRANCH_PREFIX)) { branches.add(ref.getName().substring(Constants.R_HEADS.length())); } if (!branches.isEmpty()) { for (String branch : branches) { log.info("Cleanup branch: {}", branch); try { new Git(repository) .branchDelete() .setBranchNames(branch) .setForce(true) .call(); } catch (GitAPIException e) { log.error("Cleanup branch: " + branch, e); } } } }
Example #16
Source File: JenkinsCloneRepository.java From repairnator with MIT License | 6 votes |
@Override protected StepStatus businessExecute() { String repoSlug = this.gitSlug; String repoRemotePath = this.gitUrl; String repoLocalPath = this.getInspector().getRepoLocalPath(); String repoBranch = this.gitBranch; String gitCommitHash = this.gitCommitHash; try { Git git = Git.cloneRepository().setCloneSubmodules(true).setURI(repoRemotePath).setBranch(repoBranch).setDirectory(new File(repoLocalPath)).call(); /* Also check out if provided gitCommitHash if provided */ if (gitCommitHash != null){ git.checkout().setName(gitCommitHash).call(); } return StepStatus.buildSuccess(this); } catch (Exception e) { this.addStepError("Repository " + repoSlug + " cannot be cloned.", e); return StepStatus.buildError(this, PipelineState.NOTCLONABLE); } }
Example #17
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 5 votes |
@GET @Path("diff/{objectId1}/{objectId2}/{path:.*}") public String diff(final @PathParam("objectId1") String objectId, final @PathParam("objectId2") String baseObjectId, final @PathParam("path") String pathOrBlobPath) throws Exception { return gitReadOperation(new GitOperation<String>() { @Override public String call(Git git, GitContext context) throws Exception { return doDiff(git, objectId, baseObjectId, pathOrBlobPath); } }); }
Example #18
Source File: GitMigratorTest.java From rtc2gitcli with MIT License | 5 votes |
@Test public void testInit_GitConfig() throws Exception { git = Git.init().setDirectory(basedir).call(); StoredConfig config = git.getRepository().getConfig(); migrator.init(basedir); config.load(); assertFalse(config.getBoolean("core", null, "ignorecase", true)); assertEquals(File.separatorChar == '/' ? "input" : "true", config.getString("core", null, "autocrlf")); assertEquals("simple", config.getString("push", null, "default")); assertFalse(config.getBoolean("http", null, "sslverify", true)); }
Example #19
Source File: CommitTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testSingleTreeCommit () throws Exception { File folder = new File(workDir, "folder"); File subfolder1 = new File(folder, "subfolder"); File subfolder11 = new File(subfolder1, "subfolder1"); File subfolder12 = new File(subfolder1, "subfolder2"); subfolder11.mkdirs(); subfolder12.mkdirs(); File file1 = new File(subfolder11, "file1"); File file2 = new File(subfolder12, "file2"); write(file1, "file1 content"); write(file2, "file2 content"); File[] files = new File[] { folder }; GitClient client = getClient(workDir); client.add(files, NULL_PROGRESS_MONITOR); GitRevisionInfo info = client.commit(files, "initial commit", null, null, NULL_PROGRESS_MONITOR); Map<File, GitFileInfo> modifiedFiles = info.getModifiedFiles(); assertEquals(2, modifiedFiles.size()); assertTrue(modifiedFiles.get(file1).getStatus().equals(Status.ADDED)); assertTrue(modifiedFiles.get(file2).getStatus().equals(Status.ADDED)); Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR); assertStatus(statuses, workDir, file1, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false); assertStatus(statuses, workDir, file2, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false); Git git = new Git(repository); LogCommand log = git.log(); RevCommit com = log.call().iterator().next(); assertEquals("initial commit", com.getFullMessage()); }
Example #20
Source File: CreateAndDeleteTag.java From tutorials with MIT License | 5 votes |
public static void main(String[] args) throws IOException, GitAPIException { // prepare test-repository try (Repository repository = Helper.openJGitRepository()) { try (Git git = new Git(repository)) { // remove the tag before creating it git.tagDelete().setTags("tag_for_testing").call(); // set it on the current HEAD Ref tag = git.tag().setName("tag_for_testing").call(); System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); // remove the tag again git.tagDelete().setTags("tag_for_testing").call(); // read some other commit and set the tag on it ObjectId id = repository.resolve("HEAD^"); try (RevWalk walk = new RevWalk(repository)) { RevCommit commit = walk.parseCommit(id); tag = git.tag().setObjectId(commit).setName("tag_for_testing").call(); System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); // remove the tag again git.tagDelete().setTags("tag_for_testing").call(); // create an annotated tag tag = git.tag().setName("tag_for_testing").setAnnotated(true).call(); System.out.println("Created/moved tag " + tag + " to repository at " + repository.getDirectory()); // remove the tag again git.tagDelete().setTags("tag_for_testing").call(); walk.dispose(); } } } }
Example #21
Source File: StashSaveCommand.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void run () throws GitException { Repository repository = getRepository(); try { StashCreateCommand cmd = new Git(repository).stashCreate() .setIncludeUntracked(includeUntracked) .setWorkingDirectoryMessage(message); RevCommit commit = cmd.call(); this.stash = getClassFactory().createRevisionInfo(commit, repository); } catch (GitAPIException ex) { throw new GitException(ex); } }
Example #22
Source File: AfterReceivePackResetFilter.java From smart-testing with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); try { for (final LazilyLoadedRepository repository : repositories) { Git.wrap(repository.get()).reset().setMode(HARD).call(); } } catch (GitAPIException e) { throw new ServletException(e); } }
Example #23
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 #24
Source File: RepositoryResource.java From fabric8-forge with Apache License 2.0 | 5 votes |
protected CommitInfo doRemove(Git git, String path) throws Exception { File file = getRelativeFile(path); if (file.exists()) { Files.recursiveDelete(file); String filePattern = getFilePattern(path); git.rm().addFilepattern(filePattern).call(); CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message); return createCommitInfo(commitThenPush(git, commit)); } else { return null; } }
Example #25
Source File: GitContentRepository.java From studio with GNU General Public License v3.0 | 5 votes |
@Override public String copyContent(String site, String fromPath, String toPath) { String commitId = null; synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) { Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX); String gitFromPath = helper.getGitPath(fromPath); String gitToPath = helper.getGitPath(toPath); try (Git git = new Git(repo)) { Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath); File sourceFile = sourcePath.toFile(); Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath); File targetFile = targetPath.toFile(); // Check if we're copying a single file or whole subtree FileUtils.copyDirectory(sourceFile, targetFile); // The operation is done on disk, now it's time to commit git.add().addFilepattern(gitToPath).call(); RevCommit commit = git.commit() .setOnly(gitFromPath) .setOnly(gitToPath) .setAuthor(helper.getCurrentUserIdent()) .setCommitter(helper.getCurrentUserIdent()) .setMessage(helper.getCommitMessage(REPO_COPY_CONTENT_COMMIT_MESSAGE) .replaceAll(PATTERN_FROM_PATH, fromPath).replaceAll(PATTERN_TO_PATH, toPath)) .call(); commitId = commit.getName(); } catch (IOException | GitAPIException | ServiceLayerException | UserNotFoundException e) { logger.error("Error while copying content for site: " + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: "); } } return commitId; }
Example #26
Source File: MicroGitSync.java From nh-micro with Apache License 2.0 | 5 votes |
public void reset() throws Exception{ logger.debug("begin git sync loop"); File file = new File(localPath); if(!file.exists()){ logger.debug("rep not exist"); } String localRepo=localPath+"/.git"; Git git = new Git(new FileRepository(localRepo)); git.reset().setMode(ResetType.HARD).call(); logger.debug("end git sync loop"); }
Example #27
Source File: GitUtils.java From n4js with Eclipse Public License 1.0 | 5 votes |
private static void pull(final Git git, IProgressMonitor monitor) throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException, InvalidRemoteException, CanceledException, RefNotFoundException, RefNotAdvertisedException, NoHeadException, TransportException { @SuppressWarnings("restriction") ProgressMonitor gitMonitor = (null == monitor) ? createMonitor() : new org.eclipse.egit.core.EclipseGitProgressTransformer(monitor); pull(git, gitMonitor); }
Example #28
Source File: GitContentRepository.java From studio with GNU General Public License v3.0 | 5 votes |
private boolean isRemoteValid(Git git, String remote, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey) throws CryptoException, IOException, ServiceLayerException, GitAPIException { LsRemoteCommand lsRemoteCommand = git.lsRemote(); lsRemoteCommand.setRemote(remote); switch (authenticationType) { case NONE: logger.debug("No authentication"); break; case BASIC: logger.debug("Basic authentication"); lsRemoteCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword)); break; case TOKEN: logger.debug("Token based authentication"); lsRemoteCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider(remoteToken, EMPTY)); break; case PRIVATE_KEY: logger.debug("Private key authentication"); final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp"); tempKey.toFile().deleteOnExit(); lsRemoteCommand.setTransportConfigCallback( new TransportConfigCallback() { @Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey)); } }); Files.delete(tempKey); break; default: throw new ServiceLayerException("Unsupported authentication type " + authenticationType); } lsRemoteCommand.call(); return true; }
Example #29
Source File: GitConfigurationPersistenceResource.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
protected void gitCommit(String msg) { try (Git git = repository.getGit()) { if(!git.status().call().isClean()) { git.commit().setMessage(msg).setAll(true).setNoVerify(true).call(); } } catch (GitAPIException e) { MGMT_OP_LOGGER.failedToStoreConfiguration(e, file.getName()); } }
Example #30
Source File: GitClonePull.java From data7 with Apache License 2.0 | 5 votes |
/** * Function that clone or pull the remote repository * * @throws GitAPIException * @throws IOException */ public Git updateRepo() throws GitAPIException, IOException { File git = new File(destinationFolder, ".git"); Git result; if (!git.exists()) { result = Git.cloneRepository() .setURI(GitURL) .setDirectory(destinationFolder) .call(); } else { result = Git.open(git); result.pull().call(); } return result; }