List of usage examples for org.eclipse.jgit.lib ObjectId getName
public final String getName()
From source file:com.microsoft.gittf.core.util.ObjectIdUtil.java
License:Open Source License
/** * Abbreviates an object id to minimum of seven char representation that is * unique to the repository/*w w w .java2 s . c o m*/ * * @param objectID * the object id to abbreviate * * @return String representation of the abbreviated object id */ public static final String abbreviate(final Repository repository, final ObjectId objectID) { Check.notNull(objectID, "objectID"); //$NON-NLS-1$ if (repository != null) { ObjectReader objReader = repository.getObjectDatabase().newReader(); try { return objReader.abbreviate(objectID, ABBREVIATED_LENGTH).name(); } catch (IOException e) { log.warn("Could not read object from object database", e); //$NON-NLS-1$ } finally { if (objReader != null) { objReader.release(); } } } return objectID.getName().substring(0, ABBREVIATED_LENGTH); }
From source file:com.navercorp.svngit.SVNGitUtil.java
License:Apache License
public static long getRevisionFromCommitId(Repository repo, ObjectId lastModified) throws IOException { String name = lastModified.getName(); Ref ref = repo.getRef("refs/svn/id/" + name); Ref target = ref.getTarget(); return getRevisionFromRefName(target.getName()); }
From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractor.java
License:Apache License
/** * Returns the files which have been changed between {@code firstCommit} and {@code secondCommit}. */// w ww . j a va2 s. com private ChangeSet getChanges(final ObjectId firstCommit, final ObjectId secondCommit) throws GitAPIException, IOException { final List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true) .setOldTree(prepareTreeParser(firstCommit)).setNewTree(prepareTreeParser(secondCommit)).call(); try { git.checkout().setName(secondCommit.getName()).call(); final Set<File> changedFiles = diffs.stream().map(DiffEntry::getNewPath).distinct() .filter(fileNameNormalizer::isRelevant) .map(p -> Paths.get(git.getRepository().getWorkTree().getAbsolutePath(), p).toFile()) .filter(File::isFile).collect(Collectors.toSet()); final Set<String> removedFiles = diffs.stream() .filter(d -> d.getChangeType() == DiffEntry.ChangeType.DELETE || d.getChangeType() == DiffEntry.ChangeType.RENAME) .map(DiffEntry::getOldPath).map(fileNameNormalizer::normalize).collect(Collectors.toSet()); final ChangeSet changes = new ChangeSet(); changes.getChangedFiles().putAll(readFileContent(changedFiles)); changes.getRemovedFiles().addAll(removedFiles); return changes; } finally { resetGit(); } }
From source file:com.spotify.docker.DockerBuildInformation.java
License:Apache License
private void updateGitInformation(Log log) { try {/* w ww.jav a 2s . c om*/ final Repository repo = new Git().getRepo(); if (repo != null) { this.repo = repo.getConfig().getString("remote", "origin", "url"); final ObjectId head = repo.resolve("HEAD"); if (head != null && !isNullOrEmpty(head.getName())) { this.commit = head.getName(); } } } catch (IOException e) { log.error("Failed to read Git information", e); } }
From source file:com.spotify.docker.Git.java
License:Apache License
public String getCommitId() throws GitAPIException, DockerException, IOException, MojoExecutionException { if (repo == null) { throw new MojoExecutionException("Cannot tag with git commit ID because directory not a git repo"); }/* w w w. j av a 2s .co m*/ final StringBuilder result = new StringBuilder(); try { // get the first 7 characters of the latest commit final ObjectId head = repo.resolve("HEAD"); if (head == null || isNullOrEmpty(head.getName())) { return null; } result.append(head.getName().substring(0, 7)); final org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo); // append first git tag we find for (final Ref gitTag : git.tagList().call()) { if (gitTag.getObjectId().equals(head)) { // name is refs/tag/name, so get substring after last slash final String name = gitTag.getName(); result.append("."); result.append(name.substring(name.lastIndexOf('/') + 1)); break; } } // append '.DIRTY' if any files have been modified final Status status = git.status().call(); if (status.hasUncommittedChanges()) { result.append(".DIRTY"); } } finally { repo.close(); } return result.length() == 0 ? null : result.toString(); }
From source file:com.spotify.docker.Utils.java
License:Apache License
public static String getGitCommitId() throws GitAPIException, DockerException, IOException, MojoExecutionException { final FileRepositoryBuilder builder = new FileRepositoryBuilder(); builder.readEnvironment(); // scan environment GIT_* variables builder.findGitDir(); // scan up the file system tree if (builder.getGitDir() == null) { throw new MojoExecutionException("Cannot tag with git commit ID because directory not a git repo"); }/*from w w w .jav a 2 s . c o m*/ final StringBuilder result = new StringBuilder(); final Repository repo = builder.build(); try { // get the first 7 characters of the latest commit final ObjectId head = repo.resolve("HEAD"); result.append(head.getName().substring(0, 7)); final Git git = new Git(repo); // append first git tag we find for (Ref gitTag : git.tagList().call()) { if (gitTag.getObjectId().equals(head)) { // name is refs/tag/name, so get substring after last slash final String name = gitTag.getName(); result.append("."); result.append(name.substring(name.lastIndexOf('/') + 1)); break; } } // append '.DIRTY' if any files have been modified final Status status = git.status().call(); if (status.hasUncommittedChanges()) { result.append(".DIRTY"); } } finally { repo.close(); } return result.length() == 0 ? null : result.toString(); }
From source file:com.tasktop.c2c.server.scm.service.GitDomain.java
License:Open Source License
/** * @param revCommit//from w w w. j av a 2 s . c om * @return */ public static Commit createCommit(RevCommit revCommit) { Commit commit = new Commit(revCommit.getName(), fromPersonIdent(revCommit.getAuthorIdent()), revCommit.getAuthorIdent().getWhen(), revCommit.getFullMessage()); commit.setParents(new ArrayList<String>(revCommit.getParentCount())); for (ObjectId parentId : revCommit.getParents()) { commit.getParents().add(parentId.getName()); } if (revCommit.getCommitterIdent() != null && !revCommit.getAuthorIdent().equals(revCommit.getCommitterIdent())) { commit.setCommitter(fromPersonIdent(revCommit.getCommitterIdent())); commit.setCommitDate(revCommit.getCommitterIdent().getWhen()); } return commit; }
From source file:de.codesourcery.gittimelapse.MyFrame.java
License:Apache License
public MyFrame(File file, GitHelper gitHelper) throws RevisionSyntaxException, MissingObjectException, IncorrectObjectTypeException, AmbiguousObjectException, IOException, GitAPIException { super("GIT timelapse: " + file.getAbsolutePath()); if (gitHelper == null) { throw new IllegalArgumentException("gitHelper must not be NULL"); }//ww w .ja v a 2 s.c om this.gitHelper = gitHelper; this.file = file; this.diffPanel = new DiffPanel(); final JDialog dialog = new JDialog((Frame) null, "Please wait...", false); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add(new JLabel("Please wait, locating revisions..."), BorderLayout.CENTER); dialog.pack(); dialog.setVisible(true); final IProgressCallback callback = new IProgressCallback() { @Override public void foundCommit(ObjectId commitId) { System.out.println("*** Found commit " + commitId); } }; System.out.println("Locating commits..."); commitList = gitHelper.findCommits(file, callback); dialog.setVisible(false); if (commitList.isEmpty()) { throw new RuntimeException("Found no commits"); } setMenuBar(createMenuBar()); diffModeChooser.setModel(new DefaultComboBoxModel<MyFrame.DiffDisplayMode>(DiffDisplayMode.values())); diffModeChooser.setSelectedItem(DiffDisplayMode.ALIGN_CHANGES); diffModeChooser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final ObjectId commit = commitList.getCommit(revisionSlider.getValue() - 1); try { diffPanel.showRevision(commit); } catch (IOException | PatchApplyException e1) { e1.printStackTrace(); } } }); diffModeChooser.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); DiffDisplayMode mode = (DiffDisplayMode) value; switch (mode) { case ALIGN_CHANGES: setText("Align changes"); break; case REGULAR: setText("Regular"); break; default: setText(mode.toString()); } return result; } }); revisionSlider = new JSlider(1, commitList.size()); revisionSlider.setPaintLabels(true); revisionSlider.setPaintTicks(true); addKeyListener(keyListener); getContentPane().addKeyListener(keyListener); if (commitList.size() < 10) { revisionSlider.setMajorTickSpacing(1); revisionSlider.setMinorTickSpacing(1); } else { revisionSlider.setMajorTickSpacing(5); revisionSlider.setMinorTickSpacing(1); } final ObjectId latestCommit = commitList.getLatestCommit(); if (latestCommit != null) { revisionSlider.setValue(1 + commitList.indexOf(latestCommit)); revisionSlider.setToolTipText(latestCommit.getName()); } revisionSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (!revisionSlider.getValueIsAdjusting()) { final ObjectId commit = commitList.getCommit(revisionSlider.getValue() - 1); long time = -System.currentTimeMillis(); try { diffPanel.showRevision(commit); } catch (IOException | PatchApplyException e1) { e1.printStackTrace(); } finally { time += System.currentTimeMillis(); } if (Main.DEBUG_MODE) { System.out.println("Rendering time: " + time); } } } }); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints cnstrs = new GridBagConstraints(); cnstrs.gridx = 0; cnstrs.gridy = 0; cnstrs.gridwidth = 1; cnstrs.gridheight = 1; cnstrs.weightx = 0; cnstrs.weighty = 0; cnstrs.fill = GridBagConstraints.NONE; getContentPane().add(new JLabel("Diff display mode:"), cnstrs); cnstrs = new GridBagConstraints(); cnstrs.gridx = 1; cnstrs.gridy = 0; cnstrs.gridwidth = 1; cnstrs.gridheight = 1; cnstrs.weightx = 0; cnstrs.weighty = 0; cnstrs.fill = GridBagConstraints.NONE; getContentPane().add(diffModeChooser, cnstrs); cnstrs = new GridBagConstraints(); cnstrs.gridx = 2; cnstrs.gridy = 0; cnstrs.gridwidth = 1; cnstrs.gridheight = 1; cnstrs.weightx = 1.0; cnstrs.weighty = 0; cnstrs.fill = GridBagConstraints.HORIZONTAL; getContentPane().add(revisionSlider, cnstrs); cnstrs = new GridBagConstraints(); cnstrs.gridx = 0; cnstrs.gridy = 1; cnstrs.gridwidth = 3; cnstrs.gridheight = 1; cnstrs.weightx = 1; cnstrs.weighty = 1; cnstrs.fill = GridBagConstraints.BOTH; getContentPane().add(diffPanel, cnstrs); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (latestCommit != null) { diffPanel.showRevision(latestCommit); } }
From source file:elegit.DiffHelper.java
License:Open Source License
private String getDiffString() throws GitAPIException, IOException { ObjectId head = this.repo.resolve("HEAD"); if (head == null) return ""; // The following code is largely written by Tk421 on StackOverflow // (http://stackoverflow.com/q/23486483) // Thanks! NOTE: comments are mine. ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream(); DiffFormatter formatter = new DiffFormatter(diffOutputStream); formatter.setRepository(this.repo); formatter.setPathFilter(PathFilter.create(this.pathFilter.replaceAll("\\\\", "/"))); AbstractTreeIterator commitTreeIterator = prepareTreeParser(this.repo, head.getName()); FileTreeIterator workTreeIterator = new FileTreeIterator(this.repo); // Scan gets difference between the two iterators. formatter.format(commitTreeIterator, workTreeIterator); return diffOutputStream.toString(); }
From source file:fr.brouillard.oss.jgitver.GitVersionCalculator.java
License:Apache License
private Version buildVersion(Git git, VersionStrategy strategy) { try {//from w w w . j a va 2 s .com // metadatas.registerMetadata(Metadatas.DIRTY, "" + GitUtils.isDirty(git)); // retrieve all tags matching a version, and get all info for each of them List<Ref> allTags = git.tagList().call().stream().map(this::peel) .collect(Collectors.toCollection(ArrayList::new)); // let's have tags sorted from most recent to oldest Collections.reverse(allTags); metadatas.registerMetadataTags(Metadatas.ALL_TAGS, allTags.stream()); metadatas.registerMetadataTags(Metadatas.ALL_ANNOTATED_TAGS, allTags.stream().filter(GitUtils::isAnnotated)); metadatas.registerMetadataTags(Metadatas.ALL_LIGHTWEIGHT_TAGS, allTags.stream().filter(as(GitUtils::isAnnotated).negate())); List<Ref> allVersionTags = allTags.stream().filter(strategy::considerTagAsAVersionOne) .collect(Collectors.toCollection(ArrayList::new)); List<Ref> normals = allVersionTags.stream().filter(GitUtils::isAnnotated).collect(Collectors.toList()); List<Ref> lights = allVersionTags.stream().filter(as(GitUtils::isAnnotated).negate()) .collect(Collectors.toList()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_TAGS, allVersionTags.stream()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_ANNOTATED_TAGS, normals.stream()); metadatas.registerMetadataTags(Metadatas.ALL_VERSION_LIGHTWEIGHT_TAGS, lights.stream()); ObjectId rootId = repository.resolve("HEAD"); // handle a call on an empty git repository if (rootId == null) { // no HEAD exist // the GIT repo might just be initialized without any commit return Version.EMPTY_REPOSITORY_VERSION; } git.log().add(rootId).setMaxCount(1).call().spliterator().tryAdvance(rc -> { PersonIdent commitInfo = rc.getAuthorIdent(); metadatas.registerMetadata(Metadatas.HEAD_COMMITTER_NAME, commitInfo.getName()); metadatas.registerMetadata(Metadatas.HEAD_COMMITER_EMAIL, commitInfo.getEmailAddress()); dtfmt.setTimeZone(commitInfo.getTimeZone()); metadatas.registerMetadata(Metadatas.HEAD_COMMIT_DATETIME, dtfmt.format(commitInfo.getWhen())); }); metadatas.registerMetadataTags(Metadatas.HEAD_TAGS, tagsOf(allTags, rootId).stream()); metadatas.registerMetadataTags(Metadatas.HEAD_ANNOTATED_TAGS, tagsOf(allTags.stream().filter(GitUtils::isAnnotated).collect(Collectors.toList()), rootId) .stream()); metadatas.registerMetadataTags(Metadatas.HEAD_LIGHTWEIGHT_TAGS, tagsOf(allTags.stream().filter(as(GitUtils::isAnnotated).negate()).collect(Collectors.toList()), rootId).stream()); metadatas.registerMetadata(Metadatas.GIT_SHA1_FULL, rootId.getName()); metadatas.registerMetadata(Metadatas.GIT_SHA1_8, rootId.getName().substring(0, 8)); Commit head = new Commit(rootId, 0, tagsOf(normals, rootId), tagsOf(lights, rootId)); List<Commit> commits = new LinkedList<>(); try (RevWalk revWalk = new RevWalk(repository)) { revWalk.markStart(revWalk.parseCommit(rootId)); int depth = 0; ObjectId id = null; for (RevCommit rc : revWalk) { id = rc.getId(); List<Ref> annotatedCommitTags = tagsOf(normals, id); List<Ref> lightCommitTags = tagsOf(lights, id); if (annotatedCommitTags.size() > 0 || lightCommitTags.size() > 0) { // we found a commit with version tags Commit c = new Commit(id, depth, annotatedCommitTags, lightCommitTags); commits.add(c); // shall we stop searching for commits if (StrategySearchMode.STOP_AT_FIRST.equals(strategy.searchMode())) { break; // let's stop } else if (depth >= strategy.searchDepthLimit()) { break; // let's stop } } depth++; } // handle the case where we reached the first commit without finding anything if (commits.size() == 0) { commits.add(new Commit(id, depth - 1, Collections.emptyList(), Collections.emptyList())); } } return strategy.build(head, commits); } catch (Exception ex) { throw new IllegalStateException("failure calculating version", ex); } }