List of usage examples for org.eclipse.jgit.api Git Git
public Git(Repository repo)
From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java
License:Open Source License
public void performConfiguration(Map<String, Object> options, SubMonitor monitor) throws CoreException { monitor.beginTask("", repo2branch.size() * 2); for (Entry<String, RepoSetup> entry : repo2branch.entrySet()) { if (monitor.isCanceled()) return; RepoSetup repo = entry.getValue(); String repositoryName = repo.name; String repositoryBranch = repo.branch; boolean localBranch = repositoryBranch.startsWith("refs/heads/"); //$NON-NLS-1$ String branchName = null; if (localBranch) { branchName = repositoryBranch.substring(11); }//from w w w . j a va 2 s . c o m switch (repo.state) { case LOCATED: org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(new File(repo.location, ".git")); //$NON-NLS-1$ break; case CLONE: monitor.setTaskName("Cloning repository " + repositoryName); monitor.subTask(""); try { URIish uri = new URIish(repo.url); if (repo.userName != null) { uri = uri.setUser(repo.userName); } else { uri = uri.setUser(null); } CloneOperation co = new CloneOperation(uri, true, null, repo.location, repositoryBranch, "origin", 5000); //$NON-NLS-1$ co.setCredentialsProvider(new EGitCredentialsProvider()); co.setCloneSubmodules(true); co.run(new SubProgressMonitor(monitor, 0, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil() .addConfiguredRepository(co.getGitDir()); break; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = e.getCause(); } throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, (e instanceof InterruptedException) ? "Operation cancelled" : e.getMessage(), e)); } default: } monitor.setTaskName("Preparing repository " + repositoryName); Repository repository = RepositoryUtils.getRepositoryForName(repositoryName); if (repository == null) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format( "Cannot continue. A required git repository named {0} is not configured.", repositoryName))); } monitor.subTask(MessageFormat.format("Checking out branch \"{0}\" of git repository \"{1}\"", repositoryBranch, repositoryName)); if (repositoryBranch != null && repositoryBranch.length() > 0) { //checkout the branch boolean newBranch = false; try { Ref ref = repository.getRef(repositoryBranch); if (localBranch && ref == null) { String originBranch = "refs/remotes/origin/" + branchName; //$NON-NLS-1$ ref = repository.getRef(originBranch); if (ref == null) { try { new Git(repository).fetch().setRemote("origin").call(); //$NON-NLS-1$ } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format( "Cannot fetch from remote 'origin' of repository \"{0}\":\n{1}", repositoryName, e.getMessage(), e))); } } ref = repository.getRef(originBranch); if (ref == null) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format("Cannot find branch \"{1}\" in repository \"{0}\".", repositoryName, originBranch))); } //we need to create the local branch based on remote branch new Git(repository).branchCreate().setName(branchName).setStartPoint(originBranch) .setUpstreamMode(SetupUpstreamMode.TRACK).call(); newBranch = true; } if (monitor.isCanceled()) return; try { new Git(repository).checkout().setName(repositoryBranch).call(); } catch (Exception e) { if (options.containsKey(PROP_FORCE_CHECKOUT) && (Boolean) options.get(PROP_FORCE_CHECKOUT)) { //try to reset new Git(repository).reset().setMode(ResetType.HARD).call(); //and then checkout again new Git(repository).checkout().setName(repositoryBranch).call(); } else { throw e; } } int fileCount = repository.getDirectory().getParentFile().list().length; if (fileCount == 1) { //we need to hard reset the repository - there are no files in it new Git(repository).reset().setMode(ResetType.HARD).call(); } } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format("Cannot checkout branch \"{1}\" of repository \"{0}\":\n{2}", repositoryName, repositoryBranch, e.getMessage(), e))); } if (monitor.isCanceled()) return; if (localBranch) { monitor.subTask(MessageFormat.format("Configuring branch \"{0}\" of git repository \"{1}\"", repositoryBranch, repositoryName)); try { StoredConfig config = repository.getConfig(); if (options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM) != null && (Boolean) options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM)) { //configure push to upstream config.setString("remote", "origin", "push", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ repositoryBranch + ":refs/for/" + branchName); //$NON-NLS-1$ } if (newBranch || (options.get(PROP_RECONFIGURE_BRANCH) != null && (Boolean) options.get(PROP_RECONFIGURE_BRANCH))) { config.setString("branch", branchName, "remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ config.setString("branch", branchName, "merge", repositoryBranch); //$NON-NLS-1$ //$NON-NLS-2$ config.setString("branch", branchName, "rebase", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } config.save(); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format("Cannot configure branch \"{1}\" of repository \"{0}\":\n{2}", repositoryName, repositoryBranch, e.getMessage(), e))); } } if (monitor.isCanceled()) return; if (options.containsKey(PROP_AUTO_PULL) && (Boolean) options.get(PROP_AUTO_PULL)) { monitor.subTask(MessageFormat.format("Pulling branch \"{0}\" from git repository \"{1}\"", repositoryBranch, repositoryName)); try { new Git(repository).pull().call(); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, MessageFormat.format("Cannot pull branch \"{1}\" of repository \"{0}\":\n{2}", repositoryName, repositoryBranch, e.getMessage(), e))); } } } monitor.worked(1); } }
From source file:com.gitblit.GCExecutor.java
License:Apache License
@Override public void run() { if (!isReady()) { return;//ww w.j a v a2s .com } running.set(true); Date now = new Date(); for (String repositoryName : GitBlit.self().getRepositoryList()) { if (forceClose.get()) { break; } if (isCollectingGarbage(repositoryName)) { logger.warn(MessageFormat.format("Already collecting garbage from {0}?!?", repositoryName)); continue; } boolean garbageCollected = false; RepositoryModel model = null; Repository repository = null; try { model = GitBlit.self().getRepositoryModel(repositoryName); repository = GitBlit.self().getRepository(repositoryName); if (repository == null) { logger.warn(MessageFormat.format("GCExecutor is missing repository {0}?!?", repositoryName)); continue; } if (!isRepositoryIdle(repository)) { logger.debug(MessageFormat.format("GCExecutor is skipping {0} because it is not idle", repositoryName)); continue; } // By setting the GCStatus to COLLECTING we are // disabling *all* access to this repository from Gitblit. // Think of this as a clutch in a manual transmission vehicle. if (!setGCStatus(repositoryName, GCStatus.COLLECTING)) { logger.warn(MessageFormat.format("Can not acquire GC lock for {0}, skipping", repositoryName)); continue; } logger.debug(MessageFormat.format("GCExecutor locked idle repository {0}", repositoryName)); Git git = new Git(repository); GarbageCollectCommand gc = git.gc(); Properties stats = gc.getStatistics(); // determine if this is a scheduled GC Calendar cal = Calendar.getInstance(); cal.setTime(model.lastGC); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.DATE, model.gcPeriod); Date gcDate = cal.getTime(); boolean shouldCollectGarbage = now.after(gcDate); // determine if filesize triggered GC long gcThreshold = FileUtils.convertSizeToLong(model.gcThreshold, 500 * 1024L); long sizeOfLooseObjects = (Long) stats.get("sizeOfLooseObjects"); boolean hasEnoughGarbage = sizeOfLooseObjects >= gcThreshold; // if we satisfy one of the requirements, GC boolean hasGarbage = sizeOfLooseObjects > 0; if (hasGarbage && (hasEnoughGarbage || shouldCollectGarbage)) { long looseKB = sizeOfLooseObjects / 1024L; logger.info(MessageFormat.format("Collecting {1} KB of loose objects from {0}", repositoryName, looseKB)); // do the deed gc.call(); garbageCollected = true; } } catch (Exception e) { logger.error("Error collecting garbage in " + repositoryName, e); } finally { // cleanup if (repository != null) { if (garbageCollected) { // update the last GC date model.lastGC = new Date(); GitBlit.self().updateConfiguration(repository, model); } repository.close(); } // reset the GC lock releaseLock(repositoryName); logger.debug(MessageFormat.format("GCExecutor released GC lock for {0}", repositoryName)); } } running.set(false); }
From source file:com.gitblit.service.GarbageCollectorService.java
License:Apache License
@Override public void run() { if (!isReady()) { return;/* www . j av a 2 s . c om*/ } running.set(true); Date now = new Date(); for (String repositoryName : repositoryManager.getRepositoryList()) { if (forceClose.get()) { break; } if (isCollectingGarbage(repositoryName)) { logger.warn(MessageFormat.format("Already collecting garbage from {0}?!?", repositoryName)); continue; } boolean garbageCollected = false; RepositoryModel model = null; Repository repository = null; try { model = repositoryManager.getRepositoryModel(repositoryName); repository = repositoryManager.getRepository(repositoryName); if (repository == null) { logger.warn(MessageFormat.format("GCExecutor is missing repository {0}?!?", repositoryName)); continue; } if (!repositoryManager.isIdle(repository)) { logger.debug(MessageFormat.format("GCExecutor is skipping {0} because it is not idle", repositoryName)); continue; } // By setting the GCStatus to COLLECTING we are // disabling *all* access to this repository from Gitblit. // Think of this as a clutch in a manual transmission vehicle. if (!setGCStatus(repositoryName, GCStatus.COLLECTING)) { logger.warn(MessageFormat.format("Can not acquire GC lock for {0}, skipping", repositoryName)); continue; } logger.debug(MessageFormat.format("GCExecutor locked idle repository {0}", repositoryName)); Git git = new Git(repository); GarbageCollectCommand gc = git.gc(); Properties stats = gc.getStatistics(); // determine if this is a scheduled GC Calendar cal = Calendar.getInstance(); cal.setTime(model.lastGC); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.add(Calendar.DATE, model.gcPeriod); Date gcDate = cal.getTime(); boolean shouldCollectGarbage = now.after(gcDate); // determine if filesize triggered GC long gcThreshold = FileUtils.convertSizeToLong(model.gcThreshold, 500 * 1024L); long sizeOfLooseObjects = (Long) stats.get("sizeOfLooseObjects"); boolean hasEnoughGarbage = sizeOfLooseObjects >= gcThreshold; // if we satisfy one of the requirements, GC boolean hasGarbage = sizeOfLooseObjects > 0; if (hasGarbage && (hasEnoughGarbage || shouldCollectGarbage)) { long looseKB = sizeOfLooseObjects / 1024L; logger.info(MessageFormat.format("Collecting {1} KB of loose objects from {0}", repositoryName, looseKB)); // do the deed gc.call(); garbageCollected = true; } } catch (Exception e) { logger.error("Error collecting garbage in " + repositoryName, e); } finally { // cleanup if (repository != null) { if (garbageCollected) { // update the last GC date model.lastGC = new Date(); repositoryManager.updateConfiguration(repository, model); } repository.close(); } // reset the GC lock releaseLock(repositoryName); logger.debug(MessageFormat.format("GCExecutor released GC lock for {0}", repositoryName)); } } running.set(false); }
From source file:com.gitblit.service.MirrorService.java
License:Apache License
@Override public void run() { if (!isReady()) { return;//w ww .j ava2 s. co m } running.set(true); for (String repositoryName : repositoryManager.getRepositoryList()) { if (forceClose.get()) { break; } if (repositoryManager.isCollectingGarbage(repositoryName)) { logger.debug("mirror is skipping {} garbagecollection", repositoryName); continue; } RepositoryModel model = null; Repository repository = null; try { model = repositoryManager.getRepositoryModel(repositoryName); if (!model.isMirror && !model.isBare) { // repository must be a valid bare git mirror logger.debug("mirror is skipping {} !mirror !bare", repositoryName); continue; } repository = repositoryManager.getRepository(repositoryName); if (repository == null) { logger.warn( MessageFormat.format("MirrorExecutor is missing repository {0}?!?", repositoryName)); continue; } // automatically repair (some) invalid fetch ref specs if (!repairAttempted.contains(repositoryName)) { repairAttempted.add(repositoryName); JGitUtils.repairFetchSpecs(repository); } // find the first mirror remote - there should only be one StoredConfig rc = repository.getConfig(); RemoteConfig mirror = null; List<RemoteConfig> configs = RemoteConfig.getAllRemoteConfigs(rc); for (RemoteConfig config : configs) { if (config.isMirror()) { mirror = config; break; } } if (mirror == null) { // repository does not have a mirror remote logger.debug("mirror is skipping {} no mirror remote found", repositoryName); continue; } logger.debug("checking {} remote {} for ref updates", repositoryName, mirror.getName()); final boolean testing = false; Git git = new Git(repository); FetchResult result = git.fetch().setRemote(mirror.getName()).setDryRun(testing).call(); Collection<TrackingRefUpdate> refUpdates = result.getTrackingRefUpdates(); if (refUpdates.size() > 0) { ReceiveCommand ticketBranchCmd = null; for (TrackingRefUpdate ru : refUpdates) { StringBuilder sb = new StringBuilder(); sb.append("updated mirror "); sb.append(repositoryName); sb.append(" "); sb.append(ru.getRemoteName()); sb.append(" -> "); sb.append(ru.getLocalName()); if (ru.getResult() == Result.FORCED) { sb.append(" (forced)"); } sb.append(" "); sb.append(ru.getOldObjectId() == null ? "" : ru.getOldObjectId().abbreviate(7).name()); sb.append(".."); sb.append(ru.getNewObjectId() == null ? "" : ru.getNewObjectId().abbreviate(7).name()); logger.info(sb.toString()); if (BranchTicketService.BRANCH.equals(ru.getLocalName())) { ReceiveCommand.Type type = null; switch (ru.getResult()) { case NEW: type = Type.CREATE; break; case FAST_FORWARD: type = Type.UPDATE; break; case FORCED: type = Type.UPDATE_NONFASTFORWARD; break; default: type = null; break; } if (type != null) { ticketBranchCmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(), ru.getLocalName(), type); } } } if (ticketBranchCmd != null) { repository.fireEvent(new ReceiveCommandEvent(model, ticketBranchCmd)); } } } catch (Exception e) { logger.error("Error updating mirror " + repositoryName, e); } finally { // cleanup if (repository != null) { repository.close(); } } } running.set(false); }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Fetch updates from the remote repository. If refSpecs is unspecifed, * remote heads, tags, and notes are retrieved. * * @param credentialsProvider/*from ww w .jav a 2 s .c o m*/ * @param repository * @param refSpecs * @return FetchResult * @throws Exception */ public static FetchResult fetchRepository(CredentialsProvider credentialsProvider, Repository repository, RefSpec... refSpecs) throws Exception { Git git = new Git(repository); FetchCommand fetch = git.fetch(); List<RefSpec> specs = new ArrayList<RefSpec>(); if (refSpecs == null || refSpecs.length == 0) { specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); specs.add(new RefSpec("+refs/tags/*:refs/tags/*")); specs.add(new RefSpec("+refs/notes/*:refs/notes/*")); } else { specs.addAll(Arrays.asList(refSpecs)); } if (credentialsProvider != null) { fetch.setCredentialsProvider(credentialsProvider); } fetch.setRefSpecs(specs); FetchResult fetchRes = fetch.call(); return fetchRes; }
From source file:com.github.checkstyle.github.NotesBuilder.java
License:Open Source License
/** * Returns a list of commits between two references. * @param repoPath path to local git repository. * @param startRef start reference.//from www.j a va 2s. co m * @param endRef end reference. * @return a list of commits. * @throws IOException if I/O error occurs. * @throws GitAPIException if an error occurs when accessing Git API. */ private static Set<RevCommit> getCommitsBetweenReferences(String repoPath, String startRef, String endRef) throws IOException, GitAPIException { final FileRepositoryBuilder builder = new FileRepositoryBuilder(); final Path path = Paths.get(repoPath); final Repository repo = builder.findGitDir(path.toFile()).readEnvironment().build(); final ObjectId startCommit = getActualRefObjectId(repo, startRef); Verify.verifyNotNull(startCommit, "Start reference \"" + startRef + "\" is invalid!"); final ObjectId endCommit = getActualRefObjectId(repo, endRef); final Iterable<RevCommit> commits = new Git(repo).log().addRange(startCommit, endCommit).call(); return Sets.newLinkedHashSet(commits); }
From source file:com.github.checkstyle.publishers.XdocPublisher.java
License:Open Source License
/** * Publish release notes./*from w w w .j a va2 s.c o m*/ * @throws IOException if problem with access to files appears. * @throws GitAPIException for problems with jgit. */ public void publish() throws IOException, GitAPIException { changeLocalRepoXdoc(); final FileRepositoryBuilder builder = new FileRepositoryBuilder(); final File localRepo = new File(localRepoPath); final Repository repo = builder.findGitDir(localRepo).readEnvironment().build(); final Git git = new Git(repo); git.add().addFilepattern(PATH_TO_XDOC_IN_REPO).call(); git.commit().setMessage(String.format(Locale.ENGLISH, COMMIT_MESSAGE_TEMPLATE, releaseNumber)).call(); if (doPush) { final CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(authToken, ""); git.push().setCredentialsProvider(credentialsProvider).call(); } }
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 *///from ww w.j a v a 2s. c o m 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.github.checkstyle.regression.extract.CheckstyleInjector.java
License:Open Source License
/** * Checkouts to the PR branch in the given repository. * @throws GitAPIException JGit library exception *//*from w w w. jav a 2 s . co m*/ private void checkoutToPrBranch() throws GitAPIException { final Git git = new Git(repository); try { git.checkout().setName(branch).call(); } finally { git.close(); } }
From source file:com.github.checkstyle.regression.git.DiffParser.java
License:Open Source License
/** * Parses the diff between a given branch and the master in the give repository path. * @param repositoryPath the path of checkstyle repository * @param branchName the name of the branch to be compared with master * @return a list of {@link GitChange} to represent the changes * @throws IOException JGit library exception * @throws GitAPIException JGit library exception *///from w w w .j a v a 2 s. c om public static List<GitChange> parse(String repositoryPath, String branchName) throws IOException, GitAPIException { final List<GitChange> returnValue = new LinkedList<>(); final File gitDir = new File(repositoryPath, ".git"); final Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).readEnvironment().findGitDir() .build(); try { final TreeParserPair pair = getTreeParserPair(repository, branchName); final Git git = new Git(repository); final DiffFormatter formatter = new DiffFormatter(DisabledOutputStream.INSTANCE); formatter.setRepository(repository); try { final List<DiffEntry> diffs = git.diff().setOldTree(pair.commonAncestorTreeParser) .setNewTree(pair.prTreeParser).call().stream() .filter(entry -> entry.getChangeType() != DiffEntry.ChangeType.DELETE) .collect(Collectors.toList()); for (DiffEntry diff : diffs) { returnValue.add(convertDiffEntryToGitChange(diff, formatter)); } } finally { git.close(); } } finally { repository.close(); } return returnValue; }