@Test public void logAllCommits() throws Exception { List<RevCommit> commits = new ArrayList<RevCommit>(); Git git = Git.wrap(db); writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); commits.add(git.commit().setMessage("initial commit").call()); git.branchCreate().setName("branch1").call(); Ref checkedOut = git.checkout().setName("branch1").call(); assertEquals("refs/heads/branch1", checkedOut.getName()); writeTrashFile("Test1.txt", "Hello world!"); git.add().addFilepattern("Test1.txt").call(); commits.add(git.commit().setMessage("branch1 commit").call()); checkedOut = git.checkout().setName("master").call(); assertEquals("refs/heads/master", checkedOut.getName()); writeTrashFile("Test2.txt", "Hello world!!"); git.add().addFilepattern("Test2.txt").call(); commits.add(git.commit().setMessage("branch1 commit").call()); Iterator<RevCommit> log = git.log().all().call().iterator(); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertTrue(log.hasNext()); assertTrue(commits.contains(log.next())); assertFalse(log.hasNext()); }
@Test public void testSomeCommits() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { // do 4 commits Git git = new Git(db); git.commit().setMessage("initial commit").call(); git.commit().setMessage("second commit").setCommitter(committer).call(); git.commit().setMessage("third commit").setAuthor(author).call(); git.commit().setMessage("fourth commit").setAuthor(author).setCommitter(committer).call(); Iterable<RevCommit> commits = git.log().call(); // check that all commits came in correctly PersonIdent defaultCommitter = new PersonIdent(db); PersonIdent expectedAuthors[] = new PersonIdent[] {defaultCommitter, committer, author, author}; PersonIdent expectedCommitters[] = new PersonIdent[] {defaultCommitter, committer, defaultCommitter, committer}; String expectedMessages[] = new String[] {"initial commit", "second commit", "third commit", "fourth commit"}; int l = expectedAuthors.length - 1; for (RevCommit c : commits) { assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent().getName()); assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent().getName()); assertEquals(c.getFullMessage(), expectedMessages[l]); l--; } assertEquals(l, -1); }
@Test public void testPullConflict() throws Exception { PullResult res = target.pull().call(); // nothing to update since we don't have different data yet assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty()); assertTrue(res.getMergeResult().getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)); assertFileContentsEqual(targetFile, "Hello world"); // change the source file writeToFile(sourceFile, "Source change"); source.add().addFilepattern("SomeFile.txt").call(); source.commit().setMessage("Source change in remote").call(); // change the target file writeToFile(targetFile, "Target change"); target.add().addFilepattern("SomeFile.txt").call(); target.commit().setMessage("Target change in local").call(); res = target.pull().call(); String sourceChangeString = "Source change\n>>>>>>> branch 'refs/heads/master' of " + target.getRepository().getConfig().getString("remote", "origin", "url"); assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty()); assertEquals(res.getMergeResult().getMergeStatus(), MergeStatus.CONFLICTING); String result = "<<<<<<< HEAD\nTarget change\n=======\n" + sourceChangeString + "\n"; assertFileContentsEqual(targetFile, result); assertEquals(RepositoryState.MERGING, target.getRepository().getRepositoryState()); }
@Test public void testCommitRange() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException, IncorrectObjectTypeException, MissingObjectException { // do 4 commits and set the range to the second and fourth one Git git = new Git(db); git.commit().setMessage("first commit").call(); RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call(); git.commit().setMessage("third commit").setAuthor(author).call(); RevCommit last = git.commit().setMessage("fourth commit").setAuthor(author).setCommitter(committer).call(); Iterable<RevCommit> commits = git.log().addRange(second.getId(), last.getId()).call(); // check that we have the third and fourth commit PersonIdent defaultCommitter = new PersonIdent(db); PersonIdent expectedAuthors[] = new PersonIdent[] {author, author}; PersonIdent expectedCommitters[] = new PersonIdent[] {defaultCommitter, committer}; String expectedMessages[] = new String[] {"third commit", "fourth commit"}; int l = expectedAuthors.length - 1; for (RevCommit c : commits) { assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent().getName()); assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent().getName()); assertEquals(c.getFullMessage(), expectedMessages[l]); l--; } assertEquals(l, -1); }
@Test public void testHardResetAfterSquashMerge() throws Exception { Git g = new Git(db); writeTrashFile("file1", "file1"); g.add().addFilepattern("file1").call(); RevCommit first = g.commit().setMessage("initial commit").call(); assertTrue(resolve(db.getWorkTree(), "file1").exists()); createBranch(first, "refs/heads/branch1"); checkoutBranch("refs/heads/branch1"); writeTrashFile("file2", "file2"); g.add().addFilepattern("file2").call(); g.commit().setMessage("second commit").call(); assertTrue(resolve(db.getWorkTree(), "file2").exists()); checkoutBranch("refs/heads/master"); MergeResult result = g.merge().include(db.getRef("branch1")).setSquash(true).call(); assertEquals(MergeResult.MergeStatus.FAST_FORWARD_SQUASHED, result.getMergeStatus()); assertNotNull(db.readSquashCommitMsg()); g.reset().setMode(ResetType.HARD).setRef(first.getName()).call(); assertNull(db.readSquashCommitMsg()); }
@Test public void testAddUnstagedChanges() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException, NoFilepatternException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); Git git = new Git(db); git.add().addFilepattern("a.txt").call(); RevCommit commit = git.commit().setMessage("initial commit").call(); TreeWalk tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.getObjectId(0).getName()); writer = new PrintWriter(file); writer.print("content2"); writer.close(); commit = git.commit().setMessage("second commit").call(); tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.getObjectId(0).getName()); commit = git.commit().setAll(true).setMessage("third commit").setAll(true).call(); tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("db00fd65b218578127ea51f3dffac701f12f486a", tw.getObjectId(0).getName()); }
private List<RevCommit> createCommits(Git git) throws Exception { List<RevCommit> commits = new ArrayList<RevCommit>(); writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); commits.add(git.commit().setMessage("commit#1").call()); writeTrashFile("Test1.txt", "Hello world!"); git.add().addFilepattern("Test1.txt").call(); commits.add(git.commit().setMessage("commit#2").call()); writeTrashFile("Test2.txt", "Hello world!!"); git.add().addFilepattern("Test2.txt").call(); commits.add(git.commit().setMessage("commit#3").call()); return commits; }
@Test public void testPathsResetWithUnmerged() throws Exception { setupRepository(); String file = "a.txt"; writeTrashFile(file, "data"); git.add().addFilepattern(file).call(); git.commit().setMessage("commit").call(); DirCache index = db.lockDirCache(); DirCacheBuilder builder = index.builder(); builder.add(createEntry(file, FileMode.REGULAR_FILE, 1, "")); builder.add(createEntry(file, FileMode.REGULAR_FILE, 2, "")); builder.add(createEntry(file, FileMode.REGULAR_FILE, 3, "")); builder.add(createEntry("b.txt", FileMode.REGULAR_FILE)); assertTrue(builder.commit()); assertEquals( "[a.txt, mode:100644, stage:1]" + "[a.txt, mode:100644, stage:2]" + "[a.txt, mode:100644, stage:3]" + "[b.txt, mode:100644]", indexState(0)); git.reset().addPath(file).call(); assertEquals("[a.txt, mode:100644]" + "[b.txt, mode:100644]", indexState(0)); }
@Override @Before public void setUp() throws Exception { super.setUp(); dbTarget = createWorkRepository(); source = new Git(db); target = new Git(dbTarget); // put some file in the source repo sourceFile = new File(db.getWorkTree(), "SomeFile.txt"); writeToFile(sourceFile, "Hello world"); // and commit it source.add().addFilepattern("SomeFile.txt").call(); source.commit().setMessage("Initial commit for source").call(); // configure the target repo to connect to the source via "origin" StoredConfig targetConfig = dbTarget.getConfig(); targetConfig.setString("branch", "master", "remote", "origin"); targetConfig.setString("branch", "master", "merge", "refs/heads/master"); RemoteConfig config = new RemoteConfig(targetConfig, "origin"); config.addURI(new URIish(source.getRepository().getWorkTree().getPath())); config.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); config.update(targetConfig); targetConfig.save(); targetFile = new File(dbTarget.getWorkTree(), "SomeFile.txt"); // make sure we have the same content target.pull().call(); assertFileContentsEqual(targetFile, "Hello world"); }
public void setUp() throws Exception { super.setUp(); git = new Git(db); // commit something writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); git.commit().setMessage("Initial commit").call(); // create a master branch and switch to it git.branchCreate().setName("test").call(); RefUpdate rup = db.updateRef(Constants.HEAD); rup.link("refs/heads/test"); // commit something on the test branch writeTrashFile("Test.txt", "Some change"); git.add().addFilepattern("Test.txt").call(); git.commit().setMessage("Second commit").call(); }
public void setupRepository() throws IOException, JGitInternalException, GitAPIException { // create initial commit git = new Git(db); initialCommit = git.commit().setMessage("initial commit").call(); // create nested file File dir = resolve(db.getWorkTree(), "dir"); FileUtils.mkdir(dir); File nestedFile = resolve(dir, "b.txt"); FileUtils.createNewFile(nestedFile); PrintWriter nesterFileWriter = getPrintWriter(nestedFile); nesterFileWriter.print("content"); nesterFileWriter.flush(); // create file indexFile = resolve(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(indexFile); PrintWriter writer = getPrintWriter(indexFile); writer.print("content"); writer.flush(); // add file and commit it git.add().addFilepattern("dir").addFilepattern("a.txt").call(); secondCommit = git.commit().setMessage("adding a.txt and dir/b.txt").call(); prestage = DirCache.read(db.getIndexFile(), db.getFS()).getEntry(indexFile.getName()); // modify file and add to index writer.print("new content"); writer.close(); nesterFileWriter.print("new content"); nesterFileWriter.close(); git.add().addFilepattern("a.txt").addFilepattern("dir").call(); // create a file not added to the index untrackedFile = resolve(db.getWorkTree(), "notAddedToIndex.txt"); FileUtils.createNewFile(untrackedFile); PrintWriter writer2 = getPrintWriter(untrackedFile); writer2.print("content"); writer2.close(); }
// try to do a commit without specifying a message. Should fail! @Test public void testWrongParams() throws UnmergedPathException, NoHeadException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); try { git.commit().setAuthor(author).call(); fail("Didn't get the expected exception"); } catch (NoMessageException e) { // expected } }
@Test public void testPullLocalConflict() throws Exception { target .branchCreate() .setName("basedOnMaster") .setStartPoint("refs/heads/master") .setUpstreamMode(SetupUpstreamMode.TRACK) .call(); target.getRepository().updateRef(Constants.HEAD).link("refs/heads/basedOnMaster"); PullResult res = target.pull().call(); // nothing to update since we don't have different data yet assertNull(res.getFetchResult()); assertTrue(res.getMergeResult().getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)); assertFileContentsEqual(targetFile, "Hello world"); // change the file in master target.getRepository().updateRef(Constants.HEAD).link("refs/heads/master"); writeToFile(targetFile, "Master change"); target.add().addFilepattern("SomeFile.txt").call(); target.commit().setMessage("Source change in master").call(); // change the file in slave target.getRepository().updateRef(Constants.HEAD).link("refs/heads/basedOnMaster"); writeToFile(targetFile, "Slave change"); target.add().addFilepattern("SomeFile.txt").call(); target.commit().setMessage("Source change in based on master").call(); res = target.pull().call(); String sourceChangeString = "Master change\n>>>>>>> branch 'refs/heads/master' of local repository"; assertNull(res.getFetchResult()); assertEquals(res.getMergeResult().getMergeStatus(), MergeStatus.CONFLICTING); String result = "<<<<<<< HEAD\nSlave change\n=======\n" + sourceChangeString + "\n"; assertFileContentsEqual(targetFile, result); assertEquals(RepositoryState.MERGING, target.getRepository().getRepositoryState()); }
@Test public void testMixedResetRetainsSizeAndModifiedTime() throws Exception { git = new Git(db); writeTrashFile("a.txt", "a").setLastModified(System.currentTimeMillis() - 60 * 1000); assertNotNull(git.add().addFilepattern("a.txt").call()); assertNotNull(git.commit().setMessage("a commit").call()); writeTrashFile("b.txt", "b").setLastModified(System.currentTimeMillis() - 60 * 1000); assertNotNull(git.add().addFilepattern("b.txt").call()); RevCommit commit2 = git.commit().setMessage("b commit").call(); assertNotNull(commit2); DirCache cache = db.readDirCache(); DirCacheEntry aEntry = cache.getEntry("a.txt"); assertNotNull(aEntry); assertTrue(aEntry.getLength() > 0); assertTrue(aEntry.getLastModified() > 0); DirCacheEntry bEntry = cache.getEntry("b.txt"); assertNotNull(bEntry); assertTrue(bEntry.getLength() > 0); assertTrue(bEntry.getLastModified() > 0); git.reset().setMode(ResetType.MIXED).setRef(commit2.getName()).call(); cache = db.readDirCache(); DirCacheEntry mixedAEntry = cache.getEntry("a.txt"); assertNotNull(mixedAEntry); assertEquals(aEntry.getLastModified(), mixedAEntry.getLastModified()); assertEquals(aEntry.getLastModified(), mixedAEntry.getLastModified()); DirCacheEntry mixedBEntry = cache.getEntry("b.txt"); assertNotNull(mixedBEntry); assertEquals(bEntry.getLastModified(), mixedBEntry.getLastModified()); assertEquals(bEntry.getLastModified(), mixedBEntry.getLastModified()); }
@Test public void testMergeEmptyBranches() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("initial commit").call(); RefUpdate r = db.updateRef("refs/heads/side"); r.setNewObjectId(db.resolve(Constants.HEAD)); assertEquals(r.forceUpdate(), RefUpdate.Result.NEW); RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call(); db.updateRef(Constants.HEAD).link("refs/heads/side"); RevCommit firstSide = git.commit().setMessage("first side commit").setAuthor(author).call(); write( new File(db.getDirectory(), Constants.MERGE_HEAD), ObjectId.toString(db.resolve("refs/heads/master"))); write(new File(db.getDirectory(), Constants.MERGE_MSG), "merging"); RevCommit commit = git.commit().call(); RevCommit[] parents = commit.getParents(); assertEquals(parents[0], firstSide); assertEquals(parents[1], second); assertTrue(parents.length == 2); }
@Test public void testCommitAmend() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("first comit").call(); // typo git.commit().setAmend(true).setMessage("first commit").call(); Iterable<RevCommit> commits = git.log().call(); int c = 0; for (RevCommit commit : commits) { assertEquals("first commit", commit.getFullMessage()); c++; } assertEquals(1, c); }
@Before public void setUp() throws Exception { super.setUp(); git = new Git(db); // create test files writeTrashFile("File1.txt", "Hello world"); writeTrashFile("File2.txt", "Delete Me"); writeTrashFile("File3.txt", "Delete Me"); // create files in sub-directories. writeTrashFile("sub-noclean/File1.txt", "Hello world"); writeTrashFile("sub-noclean/File2.txt", "Delete Me"); writeTrashFile("sub-clean/File4.txt", "Delete Me"); writeTrashFile("sub-noclean/Ignored.txt", "Ignored"); writeTrashFile(".gitignore", "/ignored-dir\n/sub-noclean/Ignored.txt"); writeTrashFile("ignored-dir/Ignored2.txt", "Ignored"); // add and commit first file git.add().addFilepattern("File1.txt").call(); git.add().addFilepattern("sub-noclean/File1.txt").call(); git.add().addFilepattern(".gitignore").call(); git.commit().setMessage("Initial commit").call(); }
// try to work with Commands after command has been invoked. Should throw // exceptions @Test public void testMultipleInvocations() throws NoHeadException, ConcurrentRefUpdateException, NoMessageException, UnmergedPathException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); CommitCommand commitCmd = git.commit(); commitCmd.setMessage("initial commit").call(); try { // check that setters can't be called after invocation commitCmd.setAuthor(author); fail("didn't catch the expected exception"); } catch (IllegalStateException e) { // expected } LogCommand logCmd = git.log(); logCmd.call(); try { // check that call can't be called twice logCmd.call(); fail("didn't catch the expected exception"); } catch (IllegalStateException e) { // expected } }
@Test public void testPullFastForward() throws Exception { PullResult res = target.pull().call(); // nothing to update since we don't have different data yet assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty()); assertTrue(res.getMergeResult().getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)); assertFileContentsEqual(targetFile, "Hello world"); // change the source file writeToFile(sourceFile, "Another change"); source.add().addFilepattern("SomeFile.txt").call(); source.commit().setMessage("Some change in remote").call(); res = target.pull().call(); assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty()); assertEquals(res.getMergeResult().getMergeStatus(), MergeStatus.FAST_FORWARD); assertFileContentsEqual(targetFile, "Another change"); assertEquals(RepositoryState.SAFE, target.getRepository().getRepositoryState()); res = target.pull().call(); assertEquals(res.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE); }
@Override protected boolean handlePost(RequestInfo requestInfo) throws ServletException { String gitSegment = requestInfo.gitSegment; HttpServletRequest request = requestInfo.request; HttpServletResponse response = requestInfo.response; Repository db = requestInfo.db; String pattern = requestInfo.relativePath; JSONObject requestObject = requestInfo.getJSONRequest(); try { String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null); if (commitToMerge != null) { boolean squash = requestObject.optBoolean(GitConstants.KEY_SQUASH, false); return merge(request, response, db, commitToMerge, squash); } String commitToRebase = requestObject.optString(GitConstants.KEY_REBASE, null); String rebaseOperation = requestObject.optString(GitConstants.KEY_OPERATION, null); if (commitToRebase != null) { return rebase(request, response, db, commitToRebase, rebaseOperation); } String commitToCherryPick = requestObject.optString(GitConstants.KEY_CHERRY_PICK, null); if (commitToCherryPick != null) { return cherryPick(request, response, db, commitToCherryPick); } String commitToRevert = requestObject.optString(GitConstants.KEY_REVERT, null); if (commitToRevert != null) { return revert(request, response, db, commitToRevert); } String newCommit = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null); if (newCommit != null) return identifyNewCommitResource(request, response, db, newCommit); String reviewReqLogin = requestObject.optString(GitConstants.KEY_REVIEW_REQ_NOTIFY_LOGIN); if (reviewReqLogin != null && reviewReqLogin.length() != 0) { String reviewReqUrl = requestObject.optString(GitConstants.KEY_REVIEW_REQ_URL); String ReviewReqCommit = requestObject.optString(GitConstants.KEY_REVIEW_REQ_COMMIT); String ReviewReqAuthorName = requestObject.optString(GitConstants.KEY_REVIEW_REQ_AUTHOR_NAME); String ReviewMessage = requestObject.optString(GitConstants.KEY_REVIEW_REQ_MESSAGE); return sendNotification( request, response, db, reviewReqLogin, ReviewReqCommit, reviewReqUrl, ReviewReqAuthorName, ReviewMessage); } ObjectId refId = db.resolve(gitSegment); if (refId == null || !Constants.HEAD.equals(gitSegment)) { String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", gitSegment); return statusHandler.handleRequest( request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null); if (message == null || message.isEmpty()) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit message.", null)); } Git git = new Git(db); CommitCommand cc = git.commit(); Config config = git.getRepository().getConfig(); boolean amend = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null)); boolean insertChangeId = GitUtils.isGerrit(config) || Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_CHANGE_ID, null)); String committerName = requestObject.optString(GitConstants.KEY_COMMITTER_NAME, null); String committerEmail = requestObject.optString(GitConstants.KEY_COMMITTER_EMAIL, null); String authorName = requestObject.optString(GitConstants.KEY_AUTHOR_NAME, null); String authorEmail = requestObject.optString(GitConstants.KEY_AUTHOR_EMAIL, null); // workaround of a bug in JGit which causes invalid // support of null values of author/committer name/email, see bug 352984 PersonIdent defPersonIdent = new PersonIdent(db); if (committerName == null) committerName = defPersonIdent.getName(); if (committerEmail == null) committerEmail = defPersonIdent.getEmailAddress(); if (authorName == null) authorName = committerName; if (authorEmail == null) authorEmail = committerEmail; cc.setCommitter(committerName, committerEmail); cc.setAuthor(authorName, authorEmail); if (insertChangeId) cc.setInsertChangeId(true); // support for committing by path: "git commit -o path" if (!pattern.isEmpty()) { cc.setOnly(pattern); } try { // "git commit [--amend] -m '{message}' [-a|{path}]" RevCommit lastCommit = cc.setAmend(amend).setMessage(message).call(); URI cloneLocation = BaseToCloneConverter.getCloneLocation( getURI(request), BaseToCloneConverter.COMMIT_REFRANGE); Commit commit = new Commit(cloneLocation, db, lastCommit, pattern); JSONObject result = commit.toJSON(); OrionServlet.writeJSONResponse( request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT); return true; } catch (GitAPIException e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "An error occured when commiting.", e)); } catch (UnmergedPathException e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An internal error occured when commiting.", e)); } } catch (Exception e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when requesting a commit info.", e)); } }
// 2. Get branch/commit hash for the source repo - the actual source code @Test public void existsIn2() throws IOException { final String repo = "binrepo-devex"; // final String repo = "search_raptor_binary"; // String githubUrl = "https://github.scm.corp.ebay.com/api/v3"; // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc"; final String path = "D:\\dev\\devex\\.binrepo-devex\\.git"; File gitDir = new File(path); org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(gitDir); String branch = repository.getBranch(); System.out.println("Branch=" + branch); final Map<String, Ref> allRefs = repository.getAllRefs(); for (String s : allRefs.keySet()) { System.out.println("Here" + s); } RevWalk revWalk = new RevWalk(repository); ObjectId resolve = repository.resolve(Constants.HEAD); RevCommit commitRev = revWalk.parseCommit(resolve); String commitHash = commitRev.getName(); System.out.println(commitHash + "\t" + commitRev.getFullMessage()); Git binaryRepo = Git.open(gitDir); final ListBranchCommand listBranchCommand = binaryRepo.branchList(); System.out.println(listBranchCommand.getRepository().getFullBranch()); // get "status" final StatusCommand statusCommand = binaryRepo.status(); Collection<String> toadd = GitUtils.getFilesToStage(statusCommand); for (String s : toadd) { System.out.println("To be added:" + s); } // add files to "staging" if (toadd.size() > 0) { AddCommand addCmd = binaryRepo.add(); for (String file : toadd) { addCmd.addFilepattern(file); } try { addCmd.call(); } catch (Exception e) { e.printStackTrace(); } } final StoredConfig config = repository.getConfig(); String url = config.getString("remote", "origin", "url"); if (url != null) { System.out.println("Origin comes from " + url); } // commit final CommitCommand commit = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repo, branch, commitHash, new Date().toString()); commit.setMessage(formattedMsg); try { commit.call(); } catch (Exception e) { e.printStackTrace(); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
public void updateBinaryRepository() throws IOException, GitException, MapServiceException { // 1. Check if repository exists remotely [email protected]/Binary/Repo_Binary.git // find the name of the "source repository" final String repoUrl = getSourceRemoteUrl(); // find where ".git" folder is found // SourceRepository = D:\dev\devex\binrepo-devex // BinaryRepository = D:\dev\devex\.binrepo-devex final File srcRepoDir = sourceRepository.getDirectory(); final File sourceDir = srcRepoDir.getParentFile(); final String sourceRepoFolder = srcRepoDir.getParentFile().getCanonicalPath(); final File parent = srcRepoDir.getParentFile().getParentFile(); final File binaryRepoDir = new File(parent, "." + srcRepoDir.getParentFile().getName()); System.out.println( "SourceRepository = " + sourceRepoFolder + "\nBinaryRepository = " + binaryRepoDir.getCanonicalPath()); // 2. Get branch/commit hash for the source repo - the actual source code final org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(srcRepoDir); final String branch = repository.getBranch(); final RevWalk revWalk = new RevWalk(repository); final ObjectId resolve = repository.resolve(Constants.HEAD); final RevCommit commit = revWalk.parseCommit(resolve); String commitHash = commit.getName(); System.out.println("CommitHash:" + commitHash + "\tMessage:" + commit.getFullMessage()); // 3. Call the BinRepo service and check if a corresponding BinRepo entry exists final String url = getUrlForFindByRepoBranchCommit() + "repourl=" + URLEncoder.encode(repoUrl, UTF_8) + "&branch=" + URLEncoder.encode(branch, UTF_8) + "&commitid=" + URLEncoder.encode(commitHash, UTF_8); System.out.println("svc url : " + url); WebResource webResource = client.resource(url); boolean noContent = false; BinRepoBranchCommitDO binRepoBranchCommitDO1 = null; try { binRepoBranchCommitDO1 = webResource.accept(MediaType.APPLICATION_JSON).get(BinRepoBranchCommitDO.class); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("Service Status Code : " + statusCode); noContent = (statusCode == 204 || statusCode == 404); // HTTP 204 is NO CONTENT which is ok for us } catch (Exception e) { // Catch-all to deal with network problems etc. e.printStackTrace(); } System.out.println( binRepoBranchCommitDO1 != null ? binRepoBranchCommitDO1.toString() : "Resource not found on server"); // 4. If not copy all the target folders from the source repo to the binary repo - root to root // copy of artifacts if (noContent) { System.out.println( "Source Directory:'" + sourceDir.getCanonicalPath() + "' Destination Directory:'" + binaryRepoDir.getCanonicalPath() + "'"); FileUtil.copyBinaries(sourceDir, binaryRepoDir); } // 5. Call git status to get the delta (Use StatusCommand and refine it) Git binaryRepo; try { binaryRepo = Git.open(binaryRepoDir); } catch (IOException e) { throw new GitException("Unable to open repository" + binaryRepoDir, e); } // get "status" final StatusCommand statusCommand = binaryRepo.status(); // TODO: RGIROTI Ask Nambi if we should actually filter this to only add .class files and // nothing else Collection<String> filesToStage = GitUtils.getFilesToStage(statusCommand); /*for (String file : filesToStage) { System.out.println("File to be added:" + file); }*/ // add files to "staging" - if there is nothing to stage none of the other operations make any // sense at all if (filesToStage.size() > 0) { final AddCommand addCmd = binaryRepo.add(); for (String file : filesToStage) { addCmd.addFilepattern(file); } final String[] filesArr = filesToStage.toArray(new String[filesToStage.size()]); final String files = StringUtils.join(filesArr, ","); try { addCmd.call(); } catch (Exception e) { throw new GitException("Unable to add files to repository" + files, e); } // 6. Commit the changes to local and call push after that (use JGit API for this) // 6a. COmmit message should use format "Saving url:branch:commit:UTC time" // commit final CommitCommand commitCommand = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repoUrl, branch, commitHash, new Date().toString()); commitCommand.setMessage(formattedMsg); String commitHashBinRepo; try { final RevCommit call = commitCommand.call(); commitHashBinRepo = call.getName(); } catch (Exception e) { throw new GitException("Unable to read commit hash from commit command", e); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); final String remoteBranch = push.getRepository().getBranch(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { throw new GitException("Unable to push to remote", e); } // Calculate the remote url for binary repository String binRepoUrl = calculateBinaryRepositoryUrl(); // 7. Call the BinRepo service and create a new entity for this change - repoUrl, branch, and // commit System.out.println( "Update Bin Repo Service with the new changes - POST new object to service"); final BinRepoBranchCommitDO binRepoBranchCommitDO = newInstance(repoUrl, branch, commitHash, binRepoUrl, remoteBranch, commitHashBinRepo); webResource = client.resource(getUrlForPost()); BinRepoBranchCommitDO postedDO = null; try { postedDO = webResource .accept(MediaType.APPLICATION_XML) .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("status code: " + statusCode); throw new MapServiceException("Unable to register the commit details in update binrepo", e); } System.out.println(postedDO != null ? postedDO.toString() : "Post failed"); } }
public void createBinaryRepository() throws IOException, GitException, MapServiceException { // check whether "binary repository" exists if (isBinaryRepositoryAvailable()) throw new GitException("Repository already exists"); // find the name of the "source repository" // String sourceRepoName = getRepositoryName(); // find where ".git" folder is found File f = sourceRepository.getDirectory(); File sourceRepoFolder = f.getParentFile(); String sourceRepoFolderName = f.getParentFile().getName(); // calculate binary repository folder File parent = f.getParentFile().getParentFile(); File binaryRepoFolder = new File(parent, ("." + sourceRepoFolderName)); // create binary repository folder FileUtils.mkdir(binaryRepoFolder, true); // initialize "git" repository InitCommand initCmd = Git.init(); initCmd.setDirectory(binaryRepoFolder); Git binaryRepo = null; try { System.out.println("initializing bare repository"); binaryRepo = initCmd.call(); } catch (GitAPIException e) { throw new GitException("unable to initialize repository", e); } System.out.println("adding readme.md file"); createReadMeFile(binaryRepoFolder); // get "status" StatusCommand statusC = binaryRepo.status(); Collection<String> toadd = GitUtils.getFilesToStage(statusC); // add "readme" file to staging if (toadd.size() > 0) { AddCommand add = binaryRepo.add(); for (String file : toadd) { add.addFilepattern(file); } try { add.call(); CommitCommand commit = binaryRepo.commit(); commit.setMessage("initial commit"); System.out.println("performing first commit"); commit.call(); } catch (NoFilepatternException e) { throw new GitException("unable to add file(s)", e); } catch (GitAPIException e) { throw new GitException("Unable to add or commit", e); } } // Calculate the remote url for binary repository String remoteUrl = calculateBinaryRepositoryUrl(); // TODO: check whether the remote exists, if not create it, else fail GitHub github = new GitHubClient().getGithub(); GHOrganization githubOrg = github.getOrganization("Binary"); GHRepository repository = githubOrg.getRepository(GitUtils.getRepositoryName(remoteUrl)); if (repository == null) { System.out.println("creating remote repository : " + remoteUrl); GHRepository repo = githubOrg.createRepository( GitUtils.getRepositoryName(remoteUrl), "Binary repository", "https://github.scm.corp.ebay.com", "Owners", true); System.out.println(repo.getUrl() + " created successfully "); } else { // fail, it shouldn't come here } // add "remote" repository StoredConfig config = binaryRepo.getRepository().getConfig(); config.setString("remote", "origin", "url", remoteUrl); System.out.println("adding remote origin " + remoteUrl); config.save(); // get "status" StatusCommand stat = binaryRepo.status(); Collection<String> filesToAdd = GitUtils.getFilesToStage(stat); // add files to "staging" if (filesToAdd.size() > 0) { AddCommand addCmd = binaryRepo.add(); for (String file : filesToAdd) { addCmd.addFilepattern(file); } try { addCmd.call(); } catch (NoFilepatternException e) { throw new GitException("unable to add files", e); } catch (GitAPIException e) { throw new GitException("unable to add files", e); } } // commit System.out.println("commiting the files"); CommitCommand commit = binaryRepo.commit(); // add the 'source' repository git-url, commit-id and branch commit.setMessage("adding readme.md file"); try { commit.call(); } catch (NoHeadException e) { throw new GitException("unable to commit", e); } catch (NoMessageException e) { throw new GitException("unable to commit", e); } catch (UnmergedPathsException e) { throw new GitException("unable to commit", e); } catch (ConcurrentRefUpdateException e) { throw new GitException("unable to commit", e); } catch (WrongRepositoryStateException e) { throw new GitException("unable to commit", e); } catch (GitAPIException e) { throw new GitException("unable to commit", e); } // push System.out.println("pushing to remote"); PushCommand push = binaryRepo.push(); try { push.call(); } catch (InvalidRemoteException e) { throw new GitException("unable to push", e); } catch (TransportException e) { throw new GitException("unable to push", e); } catch (GitAPIException e) { throw new GitException("unable to push", e); } // read the branch from "source" repository String branchname = sourceRepository.getBranch(); // create a "branch" if (!branchname.toLowerCase().equals("master")) { CreateBranchCommand branchCmd = binaryRepo.branchCreate(); branchCmd.setName(branchname); try { // create branch branchCmd.call(); // checkout the branch CheckoutCommand checkout = binaryRepo.checkout(); checkout.setName(branchname); checkout.call(); } catch (RefAlreadyExistsException e) { throw new GitException("unable to create a branch", e); } catch (RefNotFoundException e) { throw new GitException("unable to create a branch", e); } catch (InvalidRefNameException e) { throw new GitException("unable to create a branch", e); } catch (GitAPIException e) { throw new GitException("unable to create a branch", e); } } // find the "localobr" folders and exclude them during copy List<String> excludes = new ArrayList<String>(); Collection<File> excludeFiles = FileUtil.findDirectoriesThatEndWith(sourceRepoFolder, "localobr"); for (File file : excludeFiles) { excludes.add(file.getCanonicalPath()); } // copy the classes System.out.println("copying binary files"); copyBinaryFolders("target", excludes, binaryRepoFolder); // get "status" StatusCommand statusCmd = binaryRepo.status(); Collection<String> tobeAdded = GitUtils.getFilesToStage(statusCmd); // add files to "staging" if (tobeAdded.size() > 0) { AddCommand addCmd = binaryRepo.add(); for (String file : tobeAdded) { addCmd.addFilepattern(file); } try { addCmd.call(); } catch (NoFilepatternException e) { throw new GitException("unable to add files", e); } catch (GitAPIException e) { throw new GitException("unable to add files", e); } } // commit System.out.println("commiting the files"); CommitCommand commit1 = binaryRepo.commit(); commit1.setMessage("saving the files"); try { commit1.call(); } catch (NoHeadException e) { throw new GitException("unable to commit", e); } catch (NoMessageException e) { throw new GitException("unable to commit", e); } catch (UnmergedPathsException e) { throw new GitException("unable to commit", e); } catch (ConcurrentRefUpdateException e) { throw new GitException("unable to commit", e); } catch (WrongRepositoryStateException e) { throw new GitException("unable to commit", e); } catch (GitAPIException e) { throw new GitException("unable to commit", e); } // push System.out.println("pushing to remote"); PushCommand pushCmd = binaryRepo.push(); try { pushCmd.call(); } catch (InvalidRemoteException e) { throw new GitException("unable to push", e); } catch (TransportException e) { throw new GitException("unable to push", e); } catch (GitAPIException e) { throw new GitException("unable to push", e); } final String repoUrl = getSourceRemoteUrl(); // branchName was computed above final org.eclipse.jgit.lib.Repository repo = new org.eclipse.jgit.storage.file.FileRepository(f); final RevWalk revWalk = new RevWalk(repo); final ObjectId resolve = repo.resolve(Constants.HEAD); final RevCommit commitRev = revWalk.parseCommit(resolve); final String commitHash = commitRev.getName(); Git git = Git.open(binaryRepoFolder); final RevCommit binRepoResolveCommitRev; try { binRepoResolveCommitRev = git.log().call().iterator().next(); } catch (NoHeadException e) { throw new GitException("No head found for repo", e); } catch (GitAPIException e) { throw new GitException("No head found for repo", e); } final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName(); final String binRepoBranchName = git.getRepository().getBranch(); System.out.println("Update Bin Repo Service with the new changes - POST new object to service"); final BinRepoBranchCommitDO binRepoBranchCommitDO = newInstance( repoUrl, branchname, commitHash, remoteUrl, binRepoBranchName, binRepoResolveCommitHash); final WebResource resource = client.resource(getUrlForPost()); BinRepoBranchCommitDO postedDO = null; try { postedDO = resource .accept(MediaType.APPLICATION_XML) .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO); System.out.println("Posted Object = " + postedDO.toString()); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("status code: " + statusCode); throw new MapServiceException("Unable to register the commit details", e); } // System.out.println(postedDO != null ? postedDO.toString() : "postedDO was null"); System.out.println("updated the map service"); }