List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath) { Repository r = git.getRepository(); String blobPath = trimLeadingSlash(pathOrBlobPath); /*// ww w. j a va2s . co m RevCommit commit = JGitUtils.getCommit(r, objectId); ObjectId current; if (isNotBlank(objectId)) { current = BlobUtils.getId(r, objectId, blobPath); } else { current = CommitUtils.getHead(r).getId(); } ObjectId previous; if (isNotBlank(baseObjectId)) { previous = BlobUtils.getId(r, baseObjectId, blobPath); } else { RevCommit revCommit = CommitUtils.getCommit(r, current); RevCommit[] parents = revCommit.getParents(); if (parents.length == 0) { throw new IllegalArgumentException("No parent commits!"); } else { previous = parents[0]; } } Collection<Edit> changes = BlobUtils.diff(r, previous, current); // no idea how to format Collection<Edit> :) */ RevCommit commit; if (Strings.isNotBlank(objectId)) { commit = CommitUtils.getCommit(r, objectId); } else { commit = CommitUtils.getHead(r); } RevCommit baseCommit = null; if (Strings.isNotBlank(baseObjectId)) { baseCommit = CommitUtils.getCommit(r, baseObjectId); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); RawTextComparator cmp = RawTextComparator.DEFAULT; DiffFormatter formatter = new DiffFormatter(buffer); formatter.setRepository(r); formatter.setDiffComparator(cmp); formatter.setDetectRenames(true); RevTree commitTree = commit.getTree(); RevTree baseTree; try { if (baseCommit == null) { if (commit.getParentCount() > 0) { final RevWalk rw = new RevWalk(r); RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); rw.dispose(); baseTree = parent.getTree(); } else { // FIXME initial commit. no parent?! baseTree = commitTree; } } else { baseTree = baseCommit.getTree(); } List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree); if (blobPath != null && blobPath.length() > 0) { for (DiffEntry diffEntry : diffEntries) { if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) { formatter.format(diffEntry); break; } } } else { formatter.format(diffEntries); } formatter.flush(); return buffer.toString(); } catch (IOException e) { throw new RuntimeIOException(e); } }
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
/** * Returns the file changes in a commit/*w ww . j av a 2s .co m*/ */ protected List<CommitTreeInfo> doGetCommitTree(Git git, String commitId) { Repository repository = git.getRepository(); List<CommitTreeInfo> list = new ArrayList<CommitTreeInfo>(); RevCommit commit = CommitUtils.getCommit(repository, commitId); if (commit != null) { RevWalk rw = new RevWalk(repository); try { if (commit.getParentCount() == 0) { TreeWalk treeWalk = new TreeWalk(repository); treeWalk.reset(); treeWalk.setRecursive(true); treeWalk.addTree(commit.getTree()); while (treeWalk.next()) { String pathString = treeWalk.getPathString(); ObjectId objectId = treeWalk.getObjectId(0); int rawMode = treeWalk.getRawMode(0); list.add(new CommitTreeInfo(pathString, pathString, 0, rawMode, objectId.getName(), commit.getId().getName(), ChangeType.ADD)); } treeWalk.close(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); if (diff.getChangeType().equals(ChangeType.DELETE)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getOldPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { list.add(new CommitTreeInfo(diff.getOldPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } else { list.add(new CommitTreeInfo(diff.getNewPath(), diff.getNewPath(), 0, diff.getNewMode().getBits(), objectId, commit.getId().getName(), diff.getChangeType())); } } } } catch (Throwable e) { LOG.warn("Failed to walk tree for commit " + commitId + ". " + e, e); } finally { rw.dispose(); } } return list; }
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
protected CommitInfo doGetCommitInfo(Git git, String commitId) { Repository repository = git.getRepository(); RevCommit commit = CommitUtils.getCommit(repository, commitId); if (commit == null) { return null; } else {//w w w . jav a2 s . c om return createCommitInfo(commit); } }
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
protected String doGetHead(Git git) { RevCommit commit = CommitUtils.getHead(git.getRepository()); return commit.getName(); }
From source file:io.hawt.git.GitFacadeSupport.java
License:Apache License
protected List<CommitInfo> doHistory(Git git, String branch, String objectId, String pathOrBlobPath, int limit) { List<CommitInfo> results = new ArrayList<CommitInfo>(); Repository r = git.getRepository(); try {/*from ww w .java 2 s. com*/ String head = getHEAD(); } catch (Exception e) { LOG.error("Cannot find HEAD of this git repository! " + e, e); return results; } String path = trimLeadingSlash(pathOrBlobPath); CommitFinder finder = new CommitFinder(r); CommitListFilter filter = new CommitListFilter(); if (Strings.isNotBlank(path)) { finder.setFilter(PathFilterUtils.and(path)); } finder.setFilter(filter); if (limit > 0) { finder.setFilter(new CommitLimitFilter(limit).setStop(true)); } if (Strings.isNotBlank(objectId)) { finder.findFrom(objectId); } else { if (Strings.isNotBlank(branch)) { ObjectId branchObjectId = getBranchObjectId(git, branch); if (branchObjectId != null) { finder = finder.findFrom(branchObjectId); } else { finder = finder.findInBranches(); } } else { finder.find(); } } List<RevCommit> commits = filter.getCommits(); for (RevCommit entry : commits) { CommitInfo commitInfo = createCommitInfo(entry); results.add(commitInfo); } return results; }
From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java
License:Open Source License
@Override byte[] read() throws IOException { return invokeOnScm(new GitSCMFileSystem.FSFunction<byte[]>() { @Override// www .j a v a 2 s . c o m public byte[] invoke(Repository repository) throws IOException, InterruptedException { Git activeRepo = getActiveRepository(repository); Repository repo = activeRepo.getRepository(); File repoDir = repo.getDirectory().getParentFile(); try { File f = new File(repoDir, filePath); if (f.canRead()) { return IOUtils.toByteArray(new FileInputStream(f)); } return null; } finally { FileUtils.deleteDirectory(repoDir); } } }); }
From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java
License:Open Source License
@Override void save() throws IOException { invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() { @Override//from w w w.java 2 s.c o m public Void invoke(Repository repository) throws IOException, InterruptedException { Git activeRepo = getActiveRepository(repository); Repository repo = activeRepo.getRepository(); File repoDir = repo.getDirectory().getParentFile(); log.fine("Repo cloned to: " + repoDir.getCanonicalPath()); try { File f = new File(repoDir, filePath); if (!f.exists() || f.canWrite()) { try (Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8")) { w.write(new String(contents, "utf-8")); } try { AddCommand add = activeRepo.add(); add.addFilepattern(filePath); add.call(); CommitCommand commit = activeRepo.commit(); commit.setMessage(commitMessage); commit.call(); // Push the changes GitUtils.push(gitSource.getRemote(), repo, getCredential(), LOCAL_REF_BASE + sourceBranch, REMOTE_REF_BASE + branch); } catch (GitAPIException ex) { throw new ServiceException.UnexpectedErrorException(ex.getMessage(), ex); } return null; } throw new ServiceException.UnexpectedErrorException("Unable to write " + filePath); } finally { FileUtils.deleteDirectory(repoDir); } } }); }
From source file:io.liveoak.git.HTTPGitResourceTest.java
License:Open Source License
@Test public void rootResource() throws Exception { // Test #1 - Git Repo present after install File appDir = new File(testApplication.directory().getParentFile(), "newApp"); File appGitDir = new File(appDir, ".git"); // Verify app and git dir do not exist assertThat(appDir.exists()).isFalse(); assertThat(appGitDir.exists()).isFalse(); // Create new app assertThat(execPost(ADMIN_ROOT, "{ \"id\": \"newApp\" }")).hasStatus(201); awaitStability();/*from w ww .j a v a 2s.c o m*/ // Verify app and git dirs exist assertThat(appDir.exists()).isTrue(); assertThat(appGitDir.exists()).isTrue(); assertThat(new File(appGitDir, ".git").exists()).isFalse(); // Verify REST endpoints assertThat(execGet(GIT_ADMIN_ROOT)).hasStatus(200); assertThat(execGet(GIT_PUBLIC_ROOT)).hasStatus(404).hasNoSuchResource(); // Test #2 - Post a commit, with auto add files to index // Create a file in the application directory File testFile = new File(appDir, "test.txt"); assertThat(testFile.createNewFile()).isTrue(); Files.write(testFile.toPath(), "content".getBytes()); Git gitRepo = Git.open(appDir); // Execute a commit assertThat( execPost("/admin/applications/newApp/resources/git/commits", "{ \"msg\": \"my commit message\" }")) .hasStatus(201); assertThat(gitRepo.status().call().hasUncommittedChanges()).isFalse(); Iterator<RevCommit> iterator = gitRepo.log().all().call().iterator(); int commitSize = 0; RevCommit latestCommit = null; while (iterator.hasNext()) { RevCommit commit = iterator.next(); if (commitSize == 0) { latestCommit = commit; } commitSize++; } assertThat(commitSize).isEqualTo(2); assertThat(latestCommit.getFullMessage()).isEqualTo("my commit message"); TreeWalk treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("test.txt")); assertThat(treeWalk.next()).isTrue(); String fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes()); treeWalk.release(); assertThat(fileContent).isEqualTo("content"); // Test #3 - Post a commit, with auto add files to index off File anotherFile = new File(appDir, "another.txt"); assertThat(anotherFile.createNewFile()).isTrue(); Files.write(anotherFile.toPath(), "another content".getBytes()); Files.write(testFile.toPath(), "updated content".getBytes()); // Execute a commit assertThat(execPost("/admin/applications/newApp/resources/git/commits", "{ \"msg\": \"another commit\", \"include-untracked\": \"false\" }")).hasStatus(201); assertThat(gitRepo.status().call().isClean()).isFalse(); iterator = gitRepo.log().all().call().iterator(); commitSize = 0; while (iterator.hasNext()) { RevCommit commit = iterator.next(); if (commitSize == 0) { latestCommit = commit; } commitSize++; } assertThat(commitSize).isEqualTo(3); assertThat(latestCommit.getFullMessage()).isEqualTo("another commit"); treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("another.txt")); assertThat(treeWalk.next()).isFalse(); treeWalk.release(); treeWalk = new TreeWalk(gitRepo.getRepository()); treeWalk.addTree(latestCommit.getTree()); treeWalk.setFilter(PathFilter.create("test.txt")); assertThat(treeWalk.next()).isTrue(); fileContent = new String(treeWalk.getObjectReader().open(treeWalk.getObjectId(0)).getBytes()); treeWalk.release(); assertThat(fileContent).isEqualTo("updated content"); // Test #4 - Verify PUT on commit is not supported assertThat(execPut("/admin/applications/newApp/resources/git/commits/" + latestCommit.getName(), "{ \"bad\": \"request\" }")).hasStatus(500).isInternalError(); }
From source file:io.vertx.config.git.GitConfigStore.java
License:Apache License
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 + "'"); }//from ww w . j a va2 s. c om 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(); } }
From source file:io.vertx.config.git.GitConfigStoreTest.java
License:Apache License
private GitConfigStoreTest add(Git git, File root, File file, String directory) throws IOException, GitAPIException { if (!file.isFile()) { throw new RuntimeException("File not found " + file.getAbsolutePath()); }//from w w w.j a v a 2 s .co m if (!"master".equalsIgnoreCase(git.getRepository().getBranch())) { git.checkout().setCreateBranch(true).setName("master").call(); } if (!branch.equalsIgnoreCase(git.getRepository().getBranch())) { boolean create = true; for (Ref ref : git.branchList().call()) { if (ref.getName().equals("refs/heads/" + branch)) { create = false; } } git.checkout().setCreateBranch(create).setName(branch).call(); } String relative; if (directory != null) { relative = directory + File.separator + file.getName(); } else { relative = file.getName(); } File output = new File(root, relative); if (output.exists()) { output.delete(); } if (!output.getParentFile().isDirectory()) { output.getParentFile().mkdirs(); } FileUtils.copyFile(file, output); git.add().addFilepattern(relative).call(); git.commit().setAuthor("clement", "clement@apache.org").setCommitter("clement", "clement@apache.org") .setMessage("Add " + relative).call(); return this; }