@Override public Boolean invoke(File file, VirtualChannel channel){ try{ Git git = Git.cloneRepository() .setURI(url) .setDirectory(localDir) .setTransportConfigCallback(getTransportConfigCallback()) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); // Default branch to checkout is master if(branch==null || branch.isEmpty()){ branch = "master"; } else if (cloneType.equals("branch")){ branch = "origin" + File.separator + branch; } git.checkout().setName(branch).call(); git.close(); }catch(GitAPIException e){ status = false; e.printStackTrace(listener.getLogger()); } return status; }
/** * Cloning the remote git repo to local directory * @param remoteUri remote git url e.g. git://gitli.example.com/project/repo.git * @param localDir local destination clone directory * @throws IOException * @throws GitAPIException */ public static void clone(String remoteUri, String localDir) throws IOException, GitAPIException { //create local git directory File localGitRepo = new File(localDir); if (localGitRepo.exists()) { if (localGitRepo.isDirectory()) { // clean up directory FileUtils.cleanDirectory(localGitRepo); } else { throw new IOException("File exists: " + localDir); } } else { localGitRepo.mkdirs(); } Git g = Git.cloneRepository().setURI(remoteUri).setDirectory(localGitRepo).call(); g.close(); }
@Override protected void run () throws GitException { Repository repository = getRepository(); org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame(); cmd.setFilePath(Utils.getRelativePath(getRepository().getWorkTree(), file)); if (revision != null) { cmd.setStartCommit(Utils.findCommit(repository, revision)); } else if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) { // work-around for autocrlf cmd.setTextComparator(new AutoCRLFComparator()); } cmd.setFollowFileRenames(true); try { BlameResult cmdResult = cmd.call(); if (cmdResult != null) { result = getClassFactory().createBlameResult(cmdResult, repository); } } catch (GitAPIException ex) { throw new GitException(ex); } }
public static void main(String[] args) throws IOException, GitAPIException { Repository repo = Commands.getRepo(Consts.META_REPO_PATH); Git git = new Git(repo); // Create a new branch git.branchCreate().setName("newBranch").call(); // Checkout the new branch git.checkout().setName("newBranch").call(); // List the existing branches List<Ref> listRefsBranches = git.branchList().setListMode(ListMode.ALL).call(); listRefsBranches.forEach((refBranch) -> { System.out.println("Branch : " + refBranch.getName()); }); // Go back on "master" branch and remove the created one git.checkout().setName("master"); git.branchDelete().setBranchNames("newBranch"); }
@Override protected void run () throws GitException { Repository repository = getRepository(); try { RevObject obj = Utils.findObject(repository, taggedObject); TagCommand cmd = new Git(repository).tag(); cmd.setName(tagName); cmd.setForceUpdate(forceUpdate); cmd.setObjectId(obj); cmd.setAnnotated(message != null && !message.isEmpty() || signed); if (cmd.isAnnotated()) { cmd.setMessage(message); cmd.setSigned(signed); } cmd.call(); ListTagCommand tagCmd = new ListTagCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor)); tagCmd.run(); Map<String, GitTag> tags = tagCmd.getTags(); tag = tags.get(tagName); } catch (JGitInternalException | GitAPIException ex) { throw new GitException(ex); } }
public static void main(String[] args) throws IOException, GitAPIException { Repository repo = new FileRepository(Consts.META_REPO_PATH + ".git"); // get a list of all known heads, tags, remotes, ... Collection<Ref> allRefs = repo.getAllRefs().values(); // a RevWalk allows to walk over commits based on some filtering that is defined try (RevWalk revWalk = new RevWalk(repo)) { for (Ref ref : allRefs) { revWalk.markStart(revWalk.parseCommit(ref.getObjectId())); } System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs); int count = 0; for (RevCommit commit : revWalk) { System.out.println("Commit: " + commit); count++; } System.out.println("Had " + count + " commits"); } }
private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException { Git git = this.gitFactory.open(projectDir); CheckoutCommand command = git.checkout().setName(branch); try { if (shouldTrack(git, branch)) { trackBranch(command, branch); } return command.call(); } catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; } finally { git.close(); } }
public static void main(String[] args) throws IOException, GitAPIException { Repository repo = Commands.getRepo(Consts.META_REPO_PATH); // Get the id of the tree associated to the two commits ObjectId head = repo.resolve("HEAD^{tree}"); ObjectId previousHead = repo.resolve("HEAD~^{tree}"); List<DiffEntry> list = listDiffs(repo, previousHead, head); if(list != null){ // Simply display the diff between the two commits list.forEach((diff) -> { System.out.println(diff); }); } }
public Repository cloneRepositoryToTempFolder(boolean checkoutAll) throws GitAPIException, IOException { this.targetFolder = createTempFolder(repositoryName); final Repository repository = Git.cloneRepository() .setURI(repositoryUrl) .setDirectory(targetFolder) .setCloneAllBranches(true) .setBranch("master") .call() .getRepository(); if (checkoutAll) { checkoutAllBranches(repository); } LOGGER.info("Cloned test repository to: " + targetFolder); return repository; }
private void applyStashChangesLocally(List<RevCommit> stashesToApply) throws GitAPIException { RevCommit tmpCommit = null; // We cannot just apply changes from stash one after the other // as git will complain about uncommitted changes when trying // to apply second consecutive stash. // So we create temporary commits to overcome this issue // and reset softly on the way to have it all as local changes for (final RevCommit stash : stashesToApply) { if (stash == null){ continue; } git.stashApply().setStashRef(stash.getName()).call(); if (tmpCommit != null) { git.reset().setRef(ONE_BACK).setMode(SOFT).call(); } tmpCommit = createTemporaryCommit(); } if (tmpCommit != null) { git.reset().setRef(ONE_BACK).setMode(SOFT).call(); } git.stashDrop().setAll(true).call(); }
@Test public void should_find_local_newly_staged_files_as_new() throws IOException, GitAPIException { //given Configuration configuration = createConfiguration("a4261d5", "1ee4abf"); final File testFile = gitFolder.newFile("core/src/test/java/org/arquillian/smart/testing/CalculatorTest.java"); Files.write(testFile.toPath(), getContentsOfClass().getBytes(), StandardOpenOption.APPEND); GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.getAbsolutePath()); final NewTestsDetector newTestsDetector = new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration); // when final Collection<TestSelection> newTests = newTestsDetector.getTests(); // then assertThat(newTests).extracting(TestSelection::getClassName) .containsOnly("org.arquillian.smart.testing.CalculatorTest", "org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest"); }
@Test public void should_find_modified_staged_tests_as_changed() throws IOException, GitAPIException { //given Configuration configuration = createConfiguration("7699c2c", "04d04fe"); final Path testFile = Paths.get(gitFolder.getRoot().getAbsolutePath(), "core/src/test/java/org/arquillian/smart/testing/FilesTest.java"); Files.write(testFile, "//This is a test".getBytes(), StandardOpenOption.APPEND); GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.toString()); final ChangedTestsDetector changedTestsDetector = new ChangedTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), className -> className.endsWith("Test"), configuration); // when final Collection<TestSelection> newTests = changedTestsDetector.getTests(); // then assertThat(newTests).extracting(TestSelection::getClassName) .containsOnly("org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest", "org.arquillian.smart.testing.FilesTest"); }
@Test public void should_fetch_all_untracked_files_for_first_commit() throws IOException, GitAPIException { // given final File parent = gitFolder.newFolder("parent"); final File newGitFolder = parent.getParentFile(); gitFolder.newFile("parent/foo.txt"); try (Git git = Git.init() .setDirectory(newGitFolder) .call()) { } this.gitChangeResolver = new GitChangeResolver(); // when final Set<Change> untrackedChanges = gitChangeResolver.diff(newGitFolder, "HEAD~0", "HEAD"); // then assertThat(untrackedChanges).hasSize(1).extracting(Change::getLocation, Change::getChangeType).containsOnly(tuple( relative("parent/foo.txt"), ChangeType.ADD)); }
@Test public void testPushOK() throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected { gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt")); gitAccess.commit("file test added"); gitAccess.push("", ""); assertEquals(db1.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"), db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}")); }
public void deleteTag(String tag) { String refName = GitUtils.tag2ref(tag); ObjectId commitId = getRevCommit(refName).getId(); try { git().tagDelete().setTags(tag).call(); } catch (GitAPIException e) { throw new RuntimeException(e); } Subject subject = SecurityUtils.getSubject(); GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() { @Override public void run() { ThreadContext.bind(subject); try { Project project = GitPlex.getInstance(ProjectManager.class).load(getId()); GitPlex.getInstance(ListenerRegistry.class).post( new RefUpdated(project, refName, commitId, ObjectId.zeroId())); } finally { ThreadContext.unbindSubject(); } } }); }
@Override public File clone(String branch, boolean noCheckout) throws GitException { checkGitUrl(); CloneCommand cloneCommand = Git.cloneRepository() .setURI(gitUrl) .setNoCheckout(noCheckout) .setBranch(branch) .setDirectory(targetDir.toFile()); try (Git git = buildCommand(cloneCommand).call()) { return git.getRepository().getDirectory(); } catch (GitAPIException e) { throw new GitException("Fail to clone git repo", e); } }
@Override public List<String> tags() throws GitException { try { Collection<Ref> refs = buildCommand(Git.lsRemoteRepository() .setTags(true) .setTimeout(GIT_TRANS_TIMEOUT) .setRemote(gitUrl)).call(); List<Ref> listRefs = Lists.newArrayList(refs); listRefs.sort(JGitUtil.REF_COMPARATOR); return JGitUtil.simpleRef(refs); } catch (GitAPIException e) { throw new GitException("Fail to list tags from remote repo", ExceptionUtil.findRootCause(e)); } }
@Test(expected = MissingObjectException.class) public void testRemoteRepositoryHasNoCommitst() throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected { gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt")); gitAccess.commit("file test added"); // throws missingObjectException db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"); }
/** * Creates a blank new Repository. * * @param path * - A string that specifies the git Repository folder */ public void createNewRepository(String path) { if (git != null) { // Stop intercepting authentication requests. AuthenticationInterceptor.unbind(getHostName()); git.close(); } try { git = Git.init().setBare(false).setDirectory(new File(path)).call(); } catch (IllegalStateException | GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } fireRepositoryChanged(); }
/** * Returns for the given submodule the SHA-1 commit id for the Index if the * given index boolean is <code>true</code> or the SHA-1 commit id for the * HEAD if the given index boolean is <code>false</code> * * @param submodulePath * - the path to get the submodule * @param index * - boolean to determine what commit id to return * @return the SHA-1 id */ public ObjectId submoduleCompare(String submodulePath, boolean index) { try { SubmoduleStatus submoduleStatus = git.submoduleStatus().addPath(submodulePath).call().get(submodulePath); if (submoduleStatus != null) { if (index) { return submoduleStatus.getIndexId(); } else { return submoduleStatus.getHeadId(); } } } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } return null; }
/** * Adds a single file to the staging area. Preparing it for commit * * @param file * - the name of the file to be added */ public void add(FileStatus file) { try { if (file.getChangeType().equals(GitChangeType.REMOVED)) { git.rm().addFilepattern(file.getFileLocation()).call(); } else { git.add().addFilepattern(file.getFileLocation()).call(); } fireFileStateChanged(new ChangeEvent(GitCommand.STAGE, getPaths(Arrays.asList(file)))); } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } }
/** * Gets the conflicting file from the git status * * @return the conflicting files list */ public List<FileStatus> getConflictingFiles() { if (git != null) { try { Status status = git.status().call(); List<FileStatus> stagedFiles = new ArrayList<FileStatus>(); for (String fileName : status.getConflicting()) { stagedFiles.add(new FileStatus(GitChangeType.CONFLICT, fileName)); } return stagedFiles; } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } } return new ArrayList<FileStatus>(); }
/** * Reset all the specified files from the staging area. * * @param fileNames * - the list of file to be removed */ public void resetAll(List<FileStatus> files) { try { if (!files.isEmpty()) { ResetCommand reset = git.reset(); for (FileStatus file : files) { reset.addPath(file.getFileLocation()); } reset.call(); } fireFileStateChanged(new ChangeEvent(GitCommand.UNSTAGE, getPaths(files))); } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } }
@Override protected void run () throws GitException { Repository repository = getRepository(); File workTree = repository.getWorkTree(); org.eclipse.jgit.api.SubmoduleInitCommand cmd = new Git(repository).submoduleInit(); for (String path : Utils.getRelativePaths(workTree, roots)) { cmd.addPath(path); } try { cmd.call(); statusCmd.run(); } catch (GitAPIException | JGitInternalException ex) { throw new GitException(ex); } }
@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); } }
private Path defaultRepository() throws java.io.IOException, GitAPIException { Path repositoryPath = uninitializedRepository(); Files.createFile(repositoryPath.resolve("file1")); Files.createFile(repositoryPath.resolve("file2")); org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.init().setDirectory(repositoryPath.toFile()).call(); git.add().addFilepattern("file1").call(); git.commit().setMessage( "Create file1" ).call(); git.tag().setName("phabricator/base/1").setAnnotated(false).call(); git.tag().setName("phabricator/diff/1").setAnnotated(false).call(); git.add().addFilepattern("file2").call(); git.commit().setMessage( "Create file2").call(); git.tag().setName("phabricator/base/2").setAnnotated(false).call(); git.tag().setName("phabricator/diff/2").setAnnotated(false).call(); git.branchCreate().setName("branch1").call(); git.branchCreate().setName("branch2").call(); git.checkout().setName("branch1").call(); Files.createFile(repositoryPath.resolve("file3")); git.add().addFilepattern("file3").call(); git.commit().setMessage( "Create file3" ).call(); git.checkout().setName("branch2").call(); Files.createFile(repositoryPath.resolve("file4")); git.add().addFilepattern("file4").call(); git.commit().setMessage( "Create file4" ).call(); return repositoryPath; }
@Override public void removeRemote() { RemoteRemoveCommand cmd = git.remoteRemove(); cmd.setName( Constants.DEFAULT_REMOTE_NAME ); try { cmd.call(); } catch ( GitAPIException e ) { showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() ); } }
public static void importNewGitProject(UserDetails userDetails, File basedir, String message, String gitUrl, String branch, String origin, Logger logger) throws GitAPIException { GitUtils.disableSslCertificateChecks(); InitCommand initCommand = Git.init(); initCommand.setDirectory(basedir); Git git = initCommand.call(); logger.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath()); gitAddCommitAndPush(git, gitUrl, userDetails, basedir, message, branch, origin, logger); }
private static void gitAddCommitAndPush(Git git, String gitUrl, UserDetails userDetails, File basedir, String message, String branch, String origin, Logger logger) throws GitAPIException { PersonIdent personIdent = userDetails.createPersonIdent(); GitUtils.configureBranch(git, branch, origin, gitUrl); GitUtils.addDummyFileToEmptyFolders(basedir); logger.info("About to git commit and push to: " + gitUrl + " and remote name " + origin); int retryCount = 5; for (int i = retryCount; i > 0; i--) { if (i < retryCount) { try { Thread.sleep(500); } catch (InterruptedException e1) { e1.printStackTrace(); } } try { GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true); return; } catch (TransportException e) { if (i <= 1) { throw e; } else { logger.info("Caught a transport exception: " + e + " so retrying"); } } } }
public Git cloneRepo(CloneRepoAttributes attributes) throws GitAPIException { CloneCommand command = Git.cloneRepository(); String gitUri = attributes.getUri(); UserDetails userDetails = attributes.getUserDetails(); CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider(); GitUtils.configureCommand(command, credentialsProvider, userDetails.getSshPrivateKey(), userDetails.getSshPublicKey()); command = command.setCredentialsProvider(credentialsProvider). setCloneAllBranches(attributes.isCloneAll()). setURI(gitUri). setDirectory(attributes.getDirectory()).setRemote(attributes.getRemote()); return command.call(); }
private void printLog(Git git) throws GitAPIException, IOException { int maxCount = 5; String currentBranch = git.getRepository().getBranch(); log.info("Printing [{}] last commits for branch [{}]", maxCount, currentBranch); Iterable<RevCommit> commits = git.log().setMaxCount(maxCount).call(); for (RevCommit commit : commits) { log.info("Name [{}], msg [{}]", commit.getId().name(), commit.getShortMessage()); } }
private Git cloneToBasedir(URI projectUrl, File destinationFolder) throws GitAPIException { CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository() .setURI(projectUrl.toString() + ".git").setDirectory(destinationFolder); try { return command.call(); } catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; } }
private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode) throws GitAPIException { ListBranchCommand command = git.branchList(); if (listMode != null) { command.setListMode(listMode); } List<Ref> branches = command.call(); for (Ref ref : branches) { if (ref.getName().endsWith("/" + label)) { return true; } } return false; }
public static void setOriginOnProjectToTmp(File origin, File project) throws GitAPIException, MalformedURLException { try(Git git = openGitProject(project)) { RemoteRemoveCommand remove = git.remoteRemove(); remove.setName("origin"); remove.call(); RemoteSetUrlCommand command = git.remoteSetUrl(); command.setUri(new URIish(origin.toURI().toURL())); command.setName("origin"); command.setPush(true); command.call(); } }
@Test public void testNoPushesAhead() throws RepositoryNotFoundException, IOException, URISyntaxException, NoRepositorySelected, InvalidRemoteException, TransportException, GitAPIException{ gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); int actual = gitAccess.getPushesAhead(); int expected = 0; assertEquals(expected, actual); }
/** * Return the submodule head commit to the previously one */ public void discardSubmodule() { try { git.submoduleSync().call(); git.submoduleUpdate().setStrategy(MergeStrategy.RECURSIVE).call(); } catch (GitAPIException e) { if (logger.isDebugEnabled()) { logger.debug(END_FETCH_DEBUG_MESSAGE); } } }
public void cloneRepo(final String gitUri, final Path repoDir) throws InvalidRemoteException, GitAPIException, IOException { if (Files.exists(repoDir)) { LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString()); com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir); } configureGitSslValidation(); if (shoudlUseToken(gitServiceUrlString, gitUri)) { cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token)); } if (refName != null && !refName.isEmpty()) { String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName; cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName })); cloneCommand.setBranch(fullRefName); } cloneCommand.setTimeout(290); cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile()); cloneCommand.setURI(gitUri); LOGGER.debug( MessageFormat.format("cloning repo with url {0} in repo dir {1} ref '{2}'", gitUri, repoDir.toAbsolutePath().toString())); try (Git callInstance = cloneCommand.call()) { Repository repo = callInstance.getRepository(); repo.close(); } catch (TransportException e) { Throwable cause1 = e.getCause(); if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) { throw new SLException(cause1.getCause(), "Failed to establish ssl connection"); // NOSONAR } throw e; } }
void cloneRepository() { try { if (!repository.isPresent()) { this.repository = Optional.of(gitCloner.cloneRepositoryToTempFolder(true)); } } catch (GitAPIException | IOException e) { throw new RuntimeException("Failed cloning repository [" + gitCloner.getRepositoryName() + ", " + gitCloner.getRepositoryUrl() + "].", e); } }
@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); } }
private void checkoutAllBranches(Repository repository) throws GitAPIException { final Git git = Git.wrap(repository); for (final Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call()) { final String refName = ref.getName(); final String branchName = refName.substring(refName.lastIndexOf('/') + 1); try { git.checkout().setCreateBranch(true).setName(branchName).setStartPoint("origin/" + branchName).call(); } catch (RefAlreadyExistsException e) { LOGGER.warning("Already exists, so ignoring " + e.getMessage()); } } }