List of usage examples for org.eclipse.jgit.api Git clean
public CleanCommand clean()
From source file:com.barchart.jenkins.cascade.PluginScmGit.java
License:BSD License
/** * Remove untracked files.// w w w.j a v a2 s. co m */ public static Set<String> doClean(final File workspace) { try { final Git git = Git.open(workspace); return git.clean().call(); } catch (final Throwable e) { throw new RuntimeException(e); } }
From source file:com.github.checkstyle.regression.extract.CheckstyleInjector.java
License:Open Source License
/** * Clears the injected files and the generated info file in checkstyle repository. * @throws InjectException failure of clearing */// www . jav a 2 s.c om public void clearInjections() throws InjectException { final Git git = new Git(repository); try { git.clean().setCleanDirectories(true).call(); } catch (GitAPIException ex) { throw new InjectException("unable to clear injections", ex); } finally { git.close(); } }
From source file:com.searchcode.app.jobs.IndexGitRepoJob.java
private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName); try {// w ww .j a v a 2s. c o m Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git")); Ref head = localRepository.getRef("HEAD"); Git git = new Git(localRepository); git.reset(); git.clean(); PullCommand pullCmd = git.pull(); if (useCredentials) { pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword)); } pullCmd.call(); Ref newHEAD = localRepository.getRef("HEAD"); if (!head.toString().equals(newHEAD.toString())) { changed = true; // Get the differences between the the heads which we updated at // and use these to just update the differences between them ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}"); ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}"); ObjectReader reader = localRepository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, newHead); List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); for (DiffEntry entry : entries) { if ("DELETE".equals(entry.getChangeType().name())) { deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath())); } else { changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath())); } } } } catch (IOException | GitAPIException | InvalidPathException ex) { changed = false; Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } return new RepositoryChanged(changed, changedFiles, deletedFiles); }
From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java
License:Open Source License
/** * Update a git repository and return if it has changed and the differences */// ww w. java 2 s.c o m public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName); Repository localRepository = null; Git git = null; try { localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git")); Ref head = localRepository.getRef("HEAD"); git = new Git(localRepository); git.reset(); git.clean(); PullCommand pullCmd = git.pull(); if (useCredentials) { pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword)); } pullCmd.call(); Ref newHEAD = localRepository.getRef("HEAD"); if (!head.toString().equals(newHEAD.toString())) { changed = true; // Get the differences between the the heads which we updated at // and use these to just update the differences between them ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}"); ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}"); ObjectReader reader = localRepository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, newHead); List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); for (DiffEntry entry : entries) { if ("DELETE".equals(entry.getChangeType().name())) { deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath())); } else { changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath())); } } } } catch (IOException | GitAPIException | InvalidPathException ex) { changed = false; Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Singleton.getHelpers().closeQuietly(localRepository); Singleton.getHelpers().closeQuietly(git); } return new RepositoryChanged(changed, changedFiles, deletedFiles); }
From source file:fi.otavanopisto.changelogger.Changelogger.java
private static void prependLine(String line, String message) throws IOException, GitAPIException { FileRepositoryBuilder frBuilder = new FileRepositoryBuilder(); Repository repository = frBuilder.setGitDir(new File("./.git")).readEnvironment().build(); Git git = new Git(repository); git.reset().setMode(ResetCommand.ResetType.HARD).call(); git.clean().call(); git.fetch().call();// w ww .j a v a 2s. c o m git.pull().call(); File file = new File(CHANGELOG_FILE); List<String> lines = FileUtils.readLines(file, Charsets.UTF_8); lines.add(0, line); FileUtils.writeLines(file, lines); git.commit().setMessage(message).setAuthor("Changelogger", "changelogger@otavanopisto.fi").call(); git.push().call(); }
From source file:fi.otavanopisto.santra.Santra.java
License:Open Source License
private void reload(String botName) throws IOException, GitAPIException { log.info("Starting bot reload"); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(new File(arguments.getBasePath() + "/.git")).readEnvironment() .build();/* w ww .j a v a 2 s .c o m*/ log.info("Starting repository update"); Git git = new Git(repository); git.reset().setMode(ResetCommand.ResetType.HARD).call(); log.info("Reset complete"); git.clean().call(); log.info("Clean compete"); git.fetch().call(); log.info("Fetch complete"); git.pull().call(); log.info("Repository update finished"); initBot(botName); log.info("Bot reloaded"); }
From source file:io.fabric8.git.internal.GitDataStore.java
License:Apache License
/** * Performs a pull so the git repo is pretty much up to date before we start performing operations on it. * * @param git The {@link Git} instance to use. * @param credentialsProvider The {@link CredentialsProvider} to use. * @param doDeleteBranches Flag that determines if local branches that don't exist in remote should get deleted. *///from ww w .java 2 s . c o m protected void doPull(Git git, CredentialsProvider credentialsProvider, boolean doDeleteBranches) { assertValid(); try { Repository repository = git.getRepository(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", remoteRef.get(), "url"); if (Strings.isNullOrBlank(url)) { if (LOG.isDebugEnabled()) { LOG.debug("No remote repository defined for the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } /* String branch = repository.getBranch(); String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { if (LOG.isDebugEnabled()) { LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at " + GitHelpers.getRootGitDirectory(git) + " so not doing a pull"); } return; } */ if (LOG.isDebugEnabled()) { LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git) + " on remote URL: " + url); } boolean hasChanged = false; try { FetchResult result = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider) .setRemote(remoteRef.get()).call(); if (LOG.isDebugEnabled()) { LOG.debug("Git fetch result: {}", result.getMessages()); } lastFetchWarning = null; } catch (Exception ex) { String fetchWarning = ex.getMessage(); if (!fetchWarning.equals(lastFetchWarning)) { LOG.warn("Fetch failed because of: " + fetchWarning); LOG.debug("Fetch failed - the error will be ignored", ex); lastFetchWarning = fetchWarning; } return; } // Get local and remote branches 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/" + remoteRef.get() + "/")) { String name = ref.getName().substring(("refs/remotes/" + remoteRef.get() + "/").length()); remoteBranches.put(name, ref); gitVersions.add(name); } else if (ref.getName().startsWith("refs/heads/")) { String name = ref.getName().substring(("refs/heads/").length()); localBranches.put(name, ref); gitVersions.add(name); } } // Check git commits for (String version : gitVersions) { // Delete unneeded local branches. //Check if any remote branches was found as a guard for unwanted deletions. if (remoteBranches.isEmpty()) { //Do nothing } else if (!remoteBranches.containsKey(version)) { //We never want to delete the master branch. if (doDeleteBranches && !version.equals(MASTER_BRANCH)) { try { git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } catch (CannotDeleteCurrentBranchException ex) { git.checkout().setName(MASTER_BRANCH).setForce(true).call(); git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true) .call(); } removeVersion(version); hasChanged = true; } } // Create new local branches else if (!localBranches.containsKey(version)) { addVersion(version); git.checkout().setCreateBranch(true).setName(version) .setStartPoint(remoteRef.get() + "/" + version) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call(); hasChanged = true; } else { String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteBranches.get(version).getObjectId().getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS) .include(remoteBranches.get(version).getObjectId()).call(); if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE && hasChanged(git, localCommit, remoteCommit)) { hasChanged = true; } // TODO: handle conflicts } } } if (hasChanged) { LOG.debug("Changed after pull!"); if (credentialsProvider != null) { // TODO lets test if the profiles directory is present after checking out version 1.0? getProfilesDirectory(git); } fireChangeNotifications(); } } catch (Throwable ex) { LOG.debug("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git), ex); LOG.warn("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due " + ex.getMessage() + ". This exception is ignored."); } }
From source file:io.fabric8.git.zkbridge.Bridge.java
License:Apache License
private void updateLocal(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider) throws Exception { String remoteName = "origin"; try {/* w ww . j a v a 2s. c o m*/ git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call(); } catch (Exception e) { // Ignore fetch exceptions return; } // Get local and remote branches 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); } } } // Check git commmits for (String version : gitVersions) { // Delete unneeded local branches if (!remoteBranches.containsKey(version)) { git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true).call(); } // Create new local branches else if (!localBranches.containsKey(version)) { git.branchCreate().setName(version).call(); git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName()) .call(); } else { String localCommit = localBranches.get(version).getObjectId().getName(); String remoteCommit = remoteBranches.get(version).getObjectId().getName(); if (!localCommit.equals(remoteCommit)) { git.clean().setCleanDirectories(true).call(); git.checkout().setName("HEAD").setForce(true).call(); git.checkout().setName(version).setForce(true).call(); MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS) .include(remoteBranches.get(version).getObjectId()).call(); // TODO: handle conflicts } } } }
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 ww w .j a va2s . c om 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:org.eclipse.egit.ui.internal.clean.CleanRepositoryPage.java
License:Open Source License
private void updateCleanItems() { try {//from ww w . j a va 2 s . c o m getContainer().run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(UIText.CleanRepositoryPage_findingItems, IProgressMonitor.UNKNOWN); Git git = Git.wrap(repository); CleanCommand command = git.clean().setDryRun(true); command.setCleanDirectories(cleanDirectories); command.setIgnore(!includeIgnored); try { final Set<String> paths = command.call(); getShell().getDisplay().syncExec(new Runnable() { public void run() { cleanTable.setInput(paths); } }); } catch (GitAPIException ex) { Activator.logError("cannot call clean command!", ex); //$NON-NLS-1$ } monitor.done(); } }); } catch (InvocationTargetException e) { Activator.logError("Unexpected exception while finding items to clean", e); //$NON-NLS-1$ clearPage(); } catch (InterruptedException e) { clearPage(); } }