private Iterable<RevCommit> getCommitsFromTag(String treeName) { try { List<Ref> call = git.tagList().call(); Iterable<RevCommit> logs = null; for (Ref ref : call) { if (ref.getName().equals(treeName)) { LogCommand log = git.log(); Ref peeledRef = repository.peel(ref); if (peeledRef.getPeeledObjectId() != null) { log.add(peeledRef.getPeeledObjectId()); } else { log.add(ref.getObjectId()); } logs = log.call(); return logs; } } return null; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (MissingObjectException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IncorrectObjectTypeException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
@Override public List<CommitDB> getCommits() { try { Iterable<RevCommit> revCommits; revCommits = git.log().all().call(); List<CommitDB> commits = new ArrayList<CommitDB>(); for (RevCommit revCommit : revCommits) { PersonIdent author = revCommit.getAuthorIdent(); CommitDB commit = new CommitDB(0, author.getWhen(), revCommit.getFullMessage(), revCommit.getName()); CommitterDB committerDb = new CommitterDB(0, author.getEmailAddress(), author.getName()); commit.setCommitter(committerDb); commits.add(commit); } return commits; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IOException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
/** * {@inheritDoc} * * <p>Warnings are suppressed for false positive with Sonar and multiple exceptions on public API. * {@inheritDoc} */ @Override @SuppressWarnings("all") public List<String> getFileList(final String directory) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { final File dir; try { dir = getFileForResource(directory); } catch (final GitAPIException e) { throw new AuthorizationException(e.getMessage(), e); } catch (final IOException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final URISyntaxException e) { throw new ResourceDoesNotExistException(e.getMessage(), e); } final File[] files = dir.listFiles(); if (files == null) { throw new ResourceDoesNotExistException( format(R.getString("dirnotfound"), dir)); // $NON-NLS-1$ } final List<String> list = new LinkedList<String>(); for (final File file : files) { String name = file.getName(); if (file.isDirectory() && !name.endsWith("/")) { // $NON-NLS-1$ name += "/"; // NOPMD this is easier to read. //$NON-NLS-1$ } list.add(name); } return list; }
@Override public void checkoutToTree(String treeName) { try { git.checkout().setName(treeName).call(); } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
@Override protected Control createContents(Composite parent) { Table table = new Table(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); String[] titles = { UIText.RepositoryStatistics_Description, UIText.RepositoryStatistics_LooseObjects, UIText.RepositoryStatistics_PackedObjects }; for (int i = 0; i < titles.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(titles[i]); } Repository repo = AdapterUtils.adapt(getElement(), Repository.class); if (repo == null) { return table; } try (Git git = new Git(repo)) { GarbageCollectCommand gc = git.gc(); Properties stats = gc.getStatistics(); table.setLinesVisible(true); table.setHeaderVisible(true); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.heightHint = 200; table.setLayoutData(data); TableItem item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfObjects); item.setText(1, getStatsAsString(stats, "numberOfLooseObjects")); // $NON-NLS-1$ item.setText(2, getStatsAsString(stats, "numberOfPackedObjects")); // $NON-NLS-1$ item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfPackfiles); item.setText(2, getStatsAsString(stats, "numberOfPackFiles")); // $NON-NLS-1$ item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfRefs); item.setText(1, getStatsAsString(stats, "numberOfLooseRefs")); // $NON-NLS-1$ item.setText(2, getStatsAsString(stats, "numberOfPackedRefs")); // $NON-NLS-1$ item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_SpaceNeededOnFilesystem); item.setText(1, describeSize(getStatsAsLong(stats, "sizeOfLooseObjects"))); // $NON-NLS-1$ item.setText(2, describeSize(getStatsAsLong(stats, "sizeOfPackedObjects"))); // $NON-NLS-1$ for (int i = 0; i < titles.length; i++) { table.getColumn(i).pack(); } parent.pack(); } catch (GitAPIException e) { Activator.handleError(e.getMessage(), e, false); } return table; }
public static Ref switchBranch(final Git repo, final String branchName) { Ref switchedBranch = null; try { switchedBranch = repo.checkout().setName(branchName).call(); if (switchedBranch == null) throw new RuntimeException("Couldn't switch to branch " + branchName); } catch (GitAPIException e) { e.printStackTrace(); } return switchedBranch; }
private Iterable<RevCommit> getCommitsFromBranch(String treeName) { try { Iterable<RevCommit> revCommits = git.log().add(repository.resolve(treeName)).call(); return revCommits; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IOException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
public ArrayList<RevCommit> getAllRevisions() { ArrayList<RevCommit> revisions = new ArrayList<>(); Iterable<RevCommit> allRevisions = null; try { allRevisions = git.log().call(); } catch (GitAPIException e) { e.printStackTrace(); } for (RevCommit rev : allRevisions) { revisions.add(rev); } return revisions; }
/** * Adds the all. * * @param g the g */ public void addAll(Git g) { try { g.add().addFilepattern(".").call(); System.out.println("Added all to repository at " + g.getRepository().getDirectory()); } catch (NoFilepatternException e) { e.printStackTrace(); } catch (GitAPIException e) { e.printStackTrace(); } }
private void commitAll() throws CoreException { Git git = new Git(repo); try { CommitCommand commitCommand = git.commit(); setAuthorAndCommitter(commitCommand); commit = commitCommand.setAll(true).setMessage(message).setInsertChangeId(createChangeId).call(); } catch (JGitInternalException e) { throw new CoreException("An internal error occurred", e); } catch (GitAPIException e) { throw new CoreException(e.getLocalizedMessage(), e); } }
private void core(AnyObjectId upstream) { Git git = new Git(CurrentRepository.getInstance().getRepository()); try { rebaseUpstream(git, upstream); } catch (NoHeadException e) { WriteToPane.getInstance().writeErr(e.getMessage()); e.printStackTrace(); } catch (WrongRepositoryStateException e) { WriteToPane.getInstance().writeErr(e.getMessage()); e.printStackTrace(); } catch (GitAPIException e) { WriteToPane.getInstance().writeErr(e.getMessage()); e.printStackTrace(); } }
/** * This will commit the local changes and push them to the repository. If the method is unable to * push to the repository without force, it will throw an exception. {@inheritDoc} */ @Override public void closeConnection() throws ConnectionException { try { for (final String gitRemoteUri : gitCache.keySet()) { final Git git = gitCache.get(gitRemoteUri); git.add().addFilepattern(".").call(); // $NON-NLS-1$ git.commit().setMessage(R.getString("commitmessage")).call(); // $NON-NLS-1$ git.push().setRemote(gitRemoteUri).setCredentialsProvider(credentialsProvider).call(); git.close(); FileUtils.deleteDirectory(git.getRepository().getDirectory()); } } catch (final GitAPIException e) { throw new ConnectionException(e.getMessage(), e); } catch (final IOException e) { throw new ConnectionException(e.getMessage(), e); } }
/** {@inheritDoc} */ @Override public boolean resourceExists(final String resourceName) throws TransferFailedException { final File file; try { file = getFileForResource(resourceName); } catch (final GitAPIException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final IOException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final URISyntaxException e) { throw new TransferFailedException(e.getMessage(), e); } if (resourceName.endsWith("/")) { // $NON-NLS-1$ return file.isDirectory(); } return file.exists(); }
/** * If the destination directory is not inside the source directory (denoted by starting with * "../"), then another git repository is registered. Warnings are suppressed for false positive * with Sonar and multiple exceptions on public API. {@inheritDoc} */ @Override @SuppressWarnings("all") public void putDirectory(final File sourceDirectory, final String destinationDirectory) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { try { if (!sourceDirectory.isDirectory()) { throw new ResourceDoesNotExistException( format(R.getString("dirnotfound"), sourceDirectory)); // $NON-NLS-1$ } final File fileForResource = getFileForResource(destinationDirectory); FileUtils.copyDirectoryStructure(sourceDirectory, fileForResource); } catch (final IOException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final GitAPIException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final URISyntaxException e) { throw new TransferFailedException(e.getMessage(), e); } }
/** This will write to the working copy. {@inheritDoc} */ @Override public void fillOutputData(final OutputData outputData) throws TransferFailedException { try { final File file = getFileForResource(outputData.getResource().getName()); if (!file.getParentFile().mkdirs() && !file.getParentFile().exists()) { throw new TransferFailedException( format( R.getString("unabletocreatedirs"), // $NON-NLS-1$ file.getParentFile())); } outputData.setOutputStream(new FileOutputStream(file)); } catch (final IOException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final GitAPIException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final URISyntaxException e) { throw new TransferFailedException(e.getMessage(), e); } }
@Override public List<TreeDB> getTrees() { try { List<TreeDB> trees = new ArrayList<TreeDB>(); Iterable<Ref> refs = git.branchList().call(); for (Ref ref : refs) { if (ref.getName().equals(HEAD)) continue; TreeDB tree = new TreeDB( 0, ref.getName(), getLastCommitDate(ref.getName()), ref.getName().split("/")[2], TreeType.BRANCH); trees.add(tree); } refs = git.tagList().call(); for (Ref ref : refs) { TreeDB tree = new TreeDB( 0, ref.getName(), getLastCommitDate(ref.getName()), ref.getName().split("/")[2], TreeType.TAG); trees.add(tree); } return trees; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
// This will probs end up being static public static void addFile(Git g, String fileName) { File myFile = new File(g.getRepository().getDirectory().getParent(), fileName); try { myFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); return; } try { g.add().addFilepattern(fileName).call(); System.out.println( "Added file " + myFile + " to repository at " + g.getRepository().getDirectory()); } catch (NoFilepatternException e) { e.printStackTrace(); } catch (GitAPIException e) { e.printStackTrace(); } }
public void branchesCheckout() { String branchName = ""; Set<Entry<String, Ref>> refs = repository.getAllRefs().entrySet(); for (Entry<String, Ref> ref : refs) { if (ref.getKey().startsWith(Constants.R_REMOTES) && !ref.getKey().contains(Constants.HEAD)) { branchName = ref.getValue().getName().split(Constants.R_REMOTES)[1]; // TODO: replace with logging System.out.println( "Trying to checkout branch: " + branchName + " (" + branchName.split("origin/")[1] + ")"); CheckoutCommand checkoutCommand = this.git.checkout(); checkoutCommand.setForce(true); checkoutCommand.setCreateBranch(true); checkoutCommand.setUpstreamMode(SetupUpstreamMode.TRACK); checkoutCommand.setName(branchName.split("origin/")[1]); checkoutCommand.setStartPoint(branchName); try { checkoutCommand.call(); // TODO: replace with logging // println "Successfully checked out branch " + branchName; } catch (RefAlreadyExistsException e) { // TODO: replace with logging // println "Skipping branch (already exists): " + branchName; } catch (RefNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidRefNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GitAPIException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
/** * This will read from the working copy. File modification date would not be available as it does * not really have any meaningful value. {@inheritDoc} * * @throws ResourceDoesNotExistException when the file does not exist * @throws AuthorizationException when the file cannot be read */ @Override public void fillInputData(final InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { try { final File file = getFileForResource(inputData.getResource().getName()); if (!file.exists()) { throw new ResourceDoesNotExistException( format(R.getString("filenotfound"), file)); // $NON-NLS-1$ } if (!file.canRead()) { throw new AuthorizationException( format(R.getString("cannotreadfile"), file)); // $NON-NLS-1$ } inputData.setInputStream(new FileInputStream(file)); inputData.getResource().setContentLength(file.length()); } catch (final IOException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final GitAPIException e) { throw new TransferFailedException(e.getMessage(), e); } catch (final URISyntaxException e) { throw new TransferFailedException(e.getMessage(), e); } }
/** * Creates a repository for the given project. The repository is created in the .git directory * within the given project. The project is not connected with the new repository * * @param project the project to create the repository for. * @param monitor the monitor to report the progress to * @return * @throws CoreException * @see #connect(IProject, Repository, IProgressMonitor) */ public static Repository createRepository(IProject project, IProgressMonitor monitor) throws CoreException { try { InitCommand init = Git.init(); init.setBare(false).setDirectory(project.getLocation().toFile()); Git git = init.call(); return git.getRepository(); } catch (JGitInternalException e) { throw new CoreException( EGitCoreActivator.createErrorStatus( NLS.bind( "Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e)); } catch (GitAPIException e) { throw new CoreException( EGitCoreActivator.createErrorStatus( NLS.bind( "Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e)); } }
@Override public WikiPage toWikiPage(WikiPage root) { FileSystemPage fsPage = (FileSystemPage) root; WikiPage recentChangesPage = InMemoryPage.createChildPage(RECENT_CHANGES, fsPage); PageData pageData = recentChangesPage.getData(); try { pageData.setContent( convertToWikiText( history( fsPage, new LogCommandSpec() { @Override public LogCommand specify(LogCommand log, String fileSystemPath) { return log.setMaxCount(RECENT_CHANGES_DEPTH); } }))); } catch (GitAPIException e) { pageData.setContent("Unable to read history: " + e.getMessage()); } // No properties, no features. pageData.setProperties(new WikiPageProperties()); recentChangesPage.commit(pageData); return recentChangesPage; }
@Override @Port(name = "files", method = "saveFile") public boolean saveFile(String relativePath, byte[] data) { boolean result = true; // super.saveFile(relativePath, data); File f = new File(baseFolder.getAbsolutePath() + relativePath); if (f.exists()) { result = save(relativePath, data); /*String relativePathClean = relativePath; if (relativePath.startsWith("/")) { relativePathClean = relativePath.substring(relativePath.indexOf("/") + 1); }*/ commitRepository( " File " + relativePath + " saved ", " from site ", " [email protected] "); // TODO fix name and email try { // addFileToRepository(f); git.pull().call(); /*} catch (Exception e) { logger.error("error while unlock and commit git ", e); }*/ } catch (DetachedHeadException e) { try { git.revert().call(); save(relativePath + ".bak_" + new Date(), data); commitRepository( " File " + relativePath + " saved with conflict ", " name ", " email "); // TODO fix name and email UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider( (String) this.getDictionary().get("login"), (String) this.getDictionary().get("pass")); git.push().setCredentialsProvider(user).call(); return false; } catch (GitAPIException e1) { e1.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (NoHeadException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (TransportException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InvalidConfigurationException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InvalidRemoteException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (CanceledException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (WrongRepositoryStateException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (RefNotFoundException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (GitAPIException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } try { UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider( (String) this.getDictionary().get("login"), (String) this.getDictionary().get("pass")); git.push().setCredentialsProvider(user).call(); return true; } catch (GitAPIException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } return true; }
/** * If a {@link GitAPIException} is thrown, a developer can handle it here. Defaults to printing * out stacktrace. * * @param e the exception that might be thrown from {@link #addAndCommitSelectedFiles()} */ protected void handleGitAPIException(GitAPIException e) { e.printStackTrace(); }
private boolean rebase( HttpServletRequest request, HttpServletResponse response, Repository db, String commitToRebase, String rebaseOperation) throws ServletException, JSONException, AmbiguousObjectException, IOException { JSONObject result = new JSONObject(); try { Git git = new Git(db); RebaseCommand rebase = git.rebase(); Operation operation; if (rebaseOperation != null) { operation = Operation.valueOf(rebaseOperation); } else { operation = Operation.BEGIN; } if (commitToRebase != null && !commitToRebase.isEmpty()) { ObjectId objectId = db.resolve(commitToRebase); rebase.setUpstream(objectId); } else if (operation.equals(Operation.BEGIN)) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit refId.", null)); } rebase.setOperation(operation); RebaseResult rebaseResult = rebase.call(); result.put(GitConstants.KEY_RESULT, rebaseResult.getStatus().name()); } catch (UnmergedPathsException e) { // this error should be handled by client, so return a proper status result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_UNMERGED_PATHS.name()); } catch (WrongRepositoryStateException e) { // this error should be handled by client, so return a proper status result.put( GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_WRONG_REPOSITORY_STATE.name()); } catch (IllegalArgumentException e) { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Invalid rebase operation.", e)); } catch (GitAPIException e) { // get cause and try to handle if (e.getCause() instanceof org.eclipse.jgit.errors.CheckoutConflictException) { // this error should be handled by client, so return a proper status result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_PENDING_CHANGES.name()); } else { return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when rebasing.", e)); } } OrionServlet.writeJSONResponse( request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT); return true; }