List of usage examples for org.eclipse.jgit.api Git status
public StatusCommand status()
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @see gov.va.isaac.interfaces.sync.ProfileSyncI#addUntrackedFiles(java.io.File) *///from w w w. ja v a 2s. c om @Override public void addUntrackedFiles() throws IllegalArgumentException, IOException { log.info("Add Untracked files called"); try { Git git = getGit(); Status s = git.status().call(); addFiles(s.getUntracked().toArray(new String[s.getUntracked().size()])); } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure //from w w w . j a v a2 s. c o m * @throws AuthenticationException * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateCommitAndPush(java.io.File, java.lang.String, java.lang.String, java.lang.String, * java.lang.String[]) */ @Override public Set<String> updateCommitAndPush(String commitMessage, String username, String password, MergeFailOption mergeFailOption, String... files) throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException { try { log.info("Commit Files called {}", (files == null ? "-null-" : Arrays.toString(files))); Git git = getGit(); if (git.status().call().getConflicting().size() > 0) { log.info("Previous merge failure not yet resolved"); throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>()); } if (files == null) { files = git.status().call().getUncommittedChanges().toArray(new String[0]); log.info("Will commit the uncommitted files {}", Arrays.toString(files)); } if (StringUtils.isEmptyOrNull(commitMessage) && files.length > 0) { throw new IllegalArgumentException("The commit message is required when files are specified"); } if (files.length > 0) { CommitCommand commit = git.commit(); for (String file : files) { commit.setOnly(file); } commit.setAuthor(username, "42"); commit.setMessage(commitMessage); RevCommit rv = commit.call(); log.debug("Local commit completed: " + rv.getFullMessage()); } //need to merge origin/master into master now, prior to push Set<String> result = updateFromRemote(username, password, mergeFailOption); log.debug("Pushing"); CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, (password == null ? new char[] {} : password.toCharArray())); Iterable<PushResult> pr = git.push().setCredentialsProvider(cp).call(); pr.forEach(new Consumer<PushResult>() { @Override public void accept(PushResult t) { log.debug("Push Result Messages: " + t.getMessages()); } }); log.info("commit and push complete. Current status: " + statusToString(git.status().call())); return result; } catch (TransportException te) { if (te.getMessage().contains("Auth fail")) { log.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { log.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure/*from ww w.j a v a2 s .c o m*/ * @throws AuthenticationException * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateFromRemote(java.io.File, java.lang.String, java.lang.String, * gov.va.isaac.interfaces.sync.MergeFailOption) */ @Override public Set<String> updateFromRemote(String username, String password, MergeFailOption mergeFailOption) throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException { Set<String> filesChangedDuringPull; try { log.info("update from remote called "); Git git = getGit(); log.debug("Fetching from remote"); if (git.status().call().getConflicting().size() > 0) { log.info("Previous merge failure not yet resolved"); throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>()); } CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, (password == null ? new char[] {} : password.toCharArray())); log.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages()); ObjectId masterIdBeforeMerge = git.getRepository().getRef("master").getObjectId(); if (git.getRepository().getRef("refs/remotes/origin/master").getObjectId().getName() .equals(masterIdBeforeMerge.getName())) { log.info("No changes to merge"); return new HashSet<String>(); } RevCommit stash = null; if (git.status().call().getUncommittedChanges().size() > 0) { log.info("Stashing uncommitted changes"); stash = git.stashCreate().call(); } { log.debug("Merging from remotes/origin/master"); MergeResult mr = git.merge().include(git.getRepository().getRef("refs/remotes/origin/master")) .call(); AnyObjectId headAfterMergeID = mr.getNewHead(); if (!mr.getMergeStatus().isSuccessful()) { if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) { addNote(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE + (stash == null ? ":NO_STASH" : STASH_MARKER + stash.getName()), git); //We can use the status here - because we already stashed the stuff that they had uncommitted above. throw new MergeFailure(mr.getConflicts().keySet(), git.status().call().getUncommittedChanges()); } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption || MergeFailOption.KEEP_REMOTE == mergeFailOption) { HashMap<String, MergeFailOption> resolutions = new HashMap<>(); for (String s : mr.getConflicts().keySet()) { resolutions.put(s, mergeFailOption); } log.debug("Resolving merge failures with option {}", mergeFailOption); filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL, (stash == null ? null : stash.getName()), resolutions); } else { throw new IllegalArgumentException("Unexpected option"); } } else { //Conflict free merge - or perhaps, no merge at all. if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) { log.debug("Merge didn't result in a commit - no incoming changes"); filesChangedDuringPull = new HashSet<>(); } else { filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge, headAfterMergeID); } } } if (stash != null) { log.info("Replaying stash"); try { git.stashApply().setStashRef(stash.getName()).call(); log.debug("stash applied cleanly, dropping stash"); git.stashDrop().call(); } catch (StashApplyFailureException e) { log.debug("Stash failed to merge"); if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) { addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git); throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull); } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption || MergeFailOption.KEEP_REMOTE == mergeFailOption) { HashMap<String, MergeFailOption> resolutions = new HashMap<>(); for (String s : git.status().call().getConflicting()) { resolutions.put(s, mergeFailOption); } log.debug("Resolving stash apply merge failures with option {}", mergeFailOption); resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions); //When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above. for (Entry<String, MergeFailOption> r : resolutions.entrySet()) { if (MergeFailOption.KEEP_LOCAL == r.getValue()) { filesChangedDuringPull.remove(r.getKey()); } } } else { throw new IllegalArgumentException("Unexpected option"); } } } log.info("Files changed during updateFromRemote: {}", filesChangedDuringPull); return filesChangedDuringPull; } catch (CheckoutConflictException e) { log.error("Unexpected", e); throw new IOException( "A local file exists (but is not yet added to source control) which conflicts with a file from the server." + " Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.", e); } catch (TransportException te) { if (te.getMessage().contains("Auth fail")) { log.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { log.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
/** * @throws MergeFailure /*from w w w .j av a2 s . c o m*/ * @throws NoWorkTreeException * @see gov.va.isaac.interfaces.sync.ProfileSyncI#resolveMergeFailures(java.io.File, java.util.Map) */ @Override public Set<String> resolveMergeFailures(Map<String, MergeFailOption> resolutions) throws IllegalArgumentException, IOException, NoWorkTreeException, MergeFailure { log.info("resolve merge failures called - resolutions: {}", resolutions); try { Git git = getGit(); List<Note> notes = git.notesList().call(); Set<String> conflicting = git.status().call().getConflicting(); if (conflicting.size() == 0) { throw new IllegalArgumentException("You do not appear to have any conflicting files"); } if (conflicting.size() != resolutions.size()) { throw new IllegalArgumentException( "You must provide a resolution for each conflicting file. Files in conflict: " + conflicting); } for (String s : conflicting) { if (!resolutions.containsKey(s)) { throw new IllegalArgumentException("No conflit resolution specified for file " + s + ". Resolutions must be specified for all files"); } } if (notes == null || notes.size() == 0) { throw new IllegalArgumentException( "The 'note' that is required for tracking state is missing. This merge failure must be resolved on the command line"); } String noteValue = new String(git.getRepository().open(notes.get(0).getData()).getBytes()); MergeFailType mergeFailType; if (noteValue.startsWith(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE)) { mergeFailType = MergeFailType.REMOTE_TO_LOCAL; } else if (noteValue.startsWith(NOTE_FAILED_MERGE_HAPPENED_ON_STASH)) { mergeFailType = MergeFailType.STASH_TO_LOCAL; } else { throw new IllegalArgumentException( "The 'note' that is required for tracking state contains an unexpected value of '" + noteValue + "'"); } String stashIdToApply = null; if (noteValue.contains(STASH_MARKER)) { stashIdToApply = noteValue.substring(noteValue.indexOf(STASH_MARKER) + STASH_MARKER.length()); } return resolveMergeFailures(mergeFailType, stashIdToApply, resolutions); } catch (GitAPIException | LargeObjectException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:gov.va.isaac.sync.git.SyncServiceGIT.java
License:Apache License
private Set<String> resolveMergeFailures(MergeFailType mergeFailType, String stashIDToApply, Map<String, MergeFailOption> resolutions) throws IllegalArgumentException, IOException, MergeFailure { log.debug("resolve merge failures called - mergeFailType: {} stashIDToApply: {} resolutions: {}", mergeFailType, stashIDToApply, resolutions); try {//from w w w. ja v a2 s . co m Git git = getGit(); //We unfortunately, must know the mergeFailType option, because the resolution mechanism here uses OURS and THEIRS - but the //meaning of OURS and THEIRS reverse, depending on if you are recovering from a merge failure, or a stash apply failure. for (Entry<String, MergeFailOption> r : resolutions.entrySet()) { if (MergeFailOption.FAIL == r.getValue()) { throw new IllegalArgumentException("MergeFailOption.FAIL is not a valid option"); } else if (MergeFailOption.KEEP_LOCAL == r.getValue()) { log.debug("Keeping our local file for conflict {}", r.getKey()); git.checkout().addPath(r.getKey()) .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.OURS : Stage.THEIRS) .call(); } else if (MergeFailOption.KEEP_REMOTE == r.getValue()) { log.debug("Keeping remote file for conflict {}", r.getKey()); git.checkout().addPath(r.getKey()) .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.THEIRS : Stage.OURS) .call(); } else { throw new IllegalArgumentException("MergeFailOption is required"); } log.debug("calling add to mark merge resolved"); git.add().addFilepattern(r.getKey()).call(); } if (mergeFailType == MergeFailType.STASH_TO_LOCAL) { //clean up the stash log.debug("Dropping stash"); git.stashDrop().call(); } RevWalk walk = new RevWalk(git.getRepository()); Ref head = git.getRepository().getRef("refs/heads/master"); RevCommit commitWithPotentialNote = walk.parseCommit(head.getObjectId()); log.info("resolve merge failures Complete. Current status: " + statusToString(git.status().call())); RevCommit rc = git.commit().setMessage( "Merging with user specified merge failure resolution for files " + resolutions.keySet()) .call(); git.notesRemove().setObjectId(commitWithPotentialNote).call(); Set<String> filesChangedInCommit = listFilesChangedInCommit(git.getRepository(), commitWithPotentialNote.getId(), rc); //When we auto resolve to KEEP_REMOTE - these will have changed - make sure they are in the list. //seems like this shouldn't really be necessary - need to look into the listFilesChangedInCommit algorithm closer. //this might already be fixed by the rework on 11/12/14, but no time to validate at the moment. - doesn't do any harm. for (Entry<String, MergeFailOption> r : resolutions.entrySet()) { if (MergeFailOption.KEEP_REMOTE == r.getValue()) { filesChangedInCommit.add(r.getKey()); } if (MergeFailOption.KEEP_LOCAL == r.getValue()) { filesChangedInCommit.remove(r.getKey()); } } if (!StringUtils.isEmptyOrNull(stashIDToApply)) { log.info("Replaying stash identified in note"); try { git.stashApply().setStashRef(stashIDToApply).call(); log.debug("stash applied cleanly, dropping stash"); git.stashDrop().call(); } catch (StashApplyFailureException e) { log.debug("Stash failed to merge"); addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git); throw new MergeFailure(git.status().call().getConflicting(), filesChangedInCommit); } } return filesChangedInCommit; } catch (GitAPIException e) { log.error("Unexpected", e); throw new IOException("Internal error", e); } }
From source file:io.fabric8.forge.rest.git.RepositoryResource.java
License:Apache License
protected boolean hasGitChanges(Git git) throws GitAPIException { Status status = git.status().call(); return anySetsNotEmpty(status.getAdded(), status.getChanged(), status.getModified(), status.getRemoved(), status.getUntracked());//from ww w .ja va 2s . c o m }
From source file:io.fabric8.git.zkbridge.Bridge.java
License:Apache License
private static void update(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider) throws Exception { String remoteName = "origin"; boolean remoteAvailable = false; try {/*from w w w . j av a2 s . com*/ git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call(); remoteAvailable = true; } catch (Exception e) { // Ignore fetch exceptions if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to fetch master", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to fetch master: " + e.getClass().getName() + ": " + e.getMessage()); } } // Handle versions in git and not in zookeeper Map<String, Ref> localBranches = new HashMap<String, Ref>(); Map<String, Ref> remoteBranches = new HashMap<String, Ref>(); Set<String> gitVersions = new HashSet<String>(); for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) { if (ref.getName().startsWith("refs/remotes/" + remoteName + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length()); if (!"master".equals(name) && !name.endsWith("-tmp")) { remoteBranches.put(name, ref); gitVersions.add(name); } } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); if (!name.equals("master") && !name.endsWith("-tmp")) { localBranches.put(name, ref); gitVersions.add(name); } } } List<String> zkVersions = getChildren(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()); createDefault(zookeeper, "/fabric/configs/git", null); Properties versionsMetadata = loadProps(zookeeper, "/fabric/configs/git"); boolean allDone = true; // Check no modifs in zookeeper String lastModified = Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath())); if (!lastModified.equals(versionsMetadata.get("zk-lastmodified"))) { allDone = false; } // Check the versions in zk and git are the same if (zkVersions.size() != gitVersions.size() || !zkVersions.containsAll(gitVersions)) { allDone = false; } // Check all local and remote branches exists if (gitVersions.size() != localBranches.size() || !localBranches.keySet().containsAll(gitVersions)) { allDone = false; } // If remote is available, check that all remote branches exist if (remoteAvailable && !remoteBranches.keySet().containsAll(gitVersions)) { allDone = false; } // Check git commmits if (allDone) { for (String version : zkVersions) { String zkCommit = versionsMetadata.get(version); String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteAvailable ? remoteBranches.get(version).getObjectId().getName() : null; if (!localCommit.equals(zkCommit) || remoteCommit != null && !localCommit.equals(remoteCommit)) { allDone = false; break; } } } if (allDone) { return; } // ZooKeeper -> Git changes for (String version : zkVersions) { String zkNode = ZkPath.CONFIG_VERSION.getPath(version); // Checkout updated version List<Ref> allBranches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call(); Ref local = null; Ref remote = null; Ref tmp = null; for (Ref ref : allBranches) { if (ref.getName().equals("refs/remotes/" + remoteName + "/" + version)) { remote = ref; } else if (ref.getName().equals("refs/heads/" + version)) { local = ref; } else if (ref.getName().equals("refs/heads/" + version + "-tmp")) { tmp = ref; } } if (local == null) { git.branchCreate().setName(version).call(); } if (tmp == null) { git.branchCreate().setName(version + "-tmp").call(); } git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); if (remoteAvailable && remote != null) { MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS).include(remote.getObjectId()) .call(); // TODO: check merge conflicts } git.checkout().setName(version + "-tmp").setForce(true).call(); String gitCommit = versionsMetadata.get(version); if (gitCommit != null) { try { git.reset().setMode(ResetCommand.ResetType.HARD).setRef(gitCommit).call(); } catch (Exception e) { // Ignore, we did our best if (LOGGER.isTraceEnabled()) { LOGGER.trace("Unable to reset branch to commit", e); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unable to reset branch to commit " + gitCommit + ": " + e.getClass().getName() + ": " + e.getMessage()); } } } // Apply changes to git syncVersionFromZkToGit(git, zookeeper, zkNode); if (git.status().call().isClean()) { git.checkout().setName(version).setForce(true).call(); } else { ObjectId rev = git.commit().setMessage("Merge zookeeper updates in version " + version).call() .getId(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.OURS).include(rev).call(); // TODO: check merge conflicts } if (remoteAvailable) { git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(version)).call(); } // Apply changes to zookeeper syncVersionFromGitToZk(git, zookeeper, zkNode); versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // Iterate through known git versions for (String version : gitVersions) { String state = versionsMetadata.get(version); if (zkVersions.contains(version)) { continue; } // The version is not known to zookeeper, so create it if (state == null) { if (localBranches.containsKey(version)) { if (remoteAvailable) { git.push().setRefSpecs(new RefSpec(version)).call(); } } else { git.branchCreate().setName(version).call(); git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName()) .call(); } git.checkout().setName(version).setForce(true).call(); // Sync zookeeper String zkNode = ZkPath.CONFIG_VERSION.getPath(version); create(zookeeper, zkNode); create(zookeeper, ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version)); create(zookeeper, ZkPath.CONFIG_VERSIONS_CONTAINERS.getPath(version)); syncVersionFromGitToZk(git, zookeeper, zkNode); // Flag version as active versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName()); } // The version has been deleted from zookeeper so delete it in git else { git.checkout().setName("master").setForce(true).call(); git.branchDelete().setBranchNames(version, version + "-tmp").setForce(true).call(); git.push().setRefSpecs(new RefSpec(version + ":")).call(); versionsMetadata.remove(version); } } versionsMetadata.put("zk-lastmodified", Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()))); setPropertiesAsMap(zookeeper, "/fabric/configs/git", versionsMetadata); }
From source file:io.fabric8.vertx.maven.plugin.it.ExtraManifestInfoIT.java
License:Apache License
@Test public void testGITSCM() throws IOException, VerificationException, GitAPIException { File testDir = initProject(GIT_PROJECT_ROOT); assertThat(testDir).isDirectory();/*w ww . j a v a 2 s . co m*/ initVerifier(testDir); prepareProject(testDir, verifier); File gitFolder = GitUtil.findGitFolder(testDir); assertThat(testDir).isNotNull(); assertThat(testDir.getName()).endsWith("manifest-git-it"); assertThat(gitFolder).isNull(); Git git = prepareGitSCM(testDir, verifier); gitFolder = git.getRepository().getDirectory(); assertThat(gitFolder.getParentFile().getName()).isEqualTo(testDir.getName()); assertThat(git.status().call().getUntracked()).contains("pom.xml", "src/main/java/demo/SimpleVerticle.java"); //Now add and commit the file DirCache index = git.add().addFilepattern(".").call(); assertThat(index.getEntryCount()).isEqualTo(2); git.commit().setMessage("First Import").call(); runPackage(verifier); assertManifest(testDir, "git"); }
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();// www . jav a2s . co 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:net.tietema.versioning.GitJavaVersioning.java
License:Apache License
public String getRevision(File projectDir) throws MojoExecutionException { // XXX we use our own findGitDir because they JGit one doesn't find the git dir in a multi project build File gitDir = findGitDir(projectDir); String revision = "Unknown"; if (gitDir == null) return revision; FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = null;// w w w .ja v a2s.c o m try { repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables .findGitDir(projectDir) // scan up the file system tree .build(); log.info("Git dir: " + gitDir.toString()); RepositoryState state = repository.getRepositoryState(); log.info(state.getDescription()); String branch = repository.getBranch(); log.info("Branch is: " + branch); Git git = new Git(repository); String fullBranch = repository.getFullBranch(); log.info("Full branch is: " + fullBranch); ObjectId id = repository.resolve(fullBranch); log.info("Branch " + repository.getBranch() + " points to " + id.name()); Status status = git.status().call(); boolean strictClean = status.isClean(); // no untracked files boolean loseClean = status.getAdded().isEmpty() && status.getChanged().isEmpty() && status.getConflicting().isEmpty() && status.getMissing().isEmpty() && status.getModified().isEmpty() && status.getRemoved().isEmpty(); StringWriter buffer = new StringWriter(); JavaWriter writer = new JavaWriter(buffer); writer.emitPackage(packageName) .beginType(packageName + "." + className, "class", Modifier.PUBLIC | Modifier.FINAL) .emitField("String", "BRANCH", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC, String.format(Locale.US, "\"%s\"", branch)) .emitField("String", "REVISION", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC, String.format(Locale.US, "\"%s\"", id.name())) .emitField("String", "REVISION_SHORT", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC, String.format(Locale.US, "\"%s\"", id.name().substring(0, 8))) .emitJavadoc("Strict Clean means no changes, not even untracked files") .emitField("boolean", "STRICT_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC, (strictClean ? "true" : "false")) .emitJavadoc("Lose Clean means no changes except untracked files.") .emitField("boolean", "LOSE_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC, (loseClean ? "true" : "false")) .endType(); revision = buffer.toString(); return revision; } catch (IOException e) { log.error(e); throw new MojoExecutionException(e.getMessage()); } catch (GitAPIException e) { log.error(e); throw new MojoExecutionException(e.getMessage()); } finally { if (repository != null) repository.close(); } }