List of usage examples for org.eclipse.jgit.lib Constants HEAD
String HEAD
To view the source code for org.eclipse.jgit.lib Constants HEAD.
Click Source Link
From source file:net.erdfelt.android.sdkfido.git.internal.GitCloneCommand.java
License:Apache License
private Ref guessHEAD(final FetchResult result) { final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD); final List<Ref> availableRefs = new ArrayList<Ref>(); Ref head = null;/*from w w w . j ava 2s . co m*/ for (final Ref r : result.getAdvertisedRefs()) { final String n = r.getName(); if (!n.startsWith(Constants.R_HEADS)) continue; availableRefs.add(r); if (idHEAD == null || head != null) continue; if (r.getObjectId().equals(idHEAD.getObjectId())) head = r; } Collections.sort(availableRefs, RefComparator.INSTANCE); if (idHEAD != null && head == null) head = idHEAD; return head; }
From source file:net.erdfelt.android.sdkfido.git.internal.GitCloneCommand.java
License:Apache License
private void checkoutRef(Ref ref) throws IOException { LOG.info("checkoutRef: ref:" + ref); if (ref == null) { throw new IllegalArgumentException("Unable to checkout from a null ref"); }/*from ww w . j a v a 2 s . c om*/ if (!Constants.HEAD.equals(ref.getName())) { RefUpdate u = repo.updateRef(Constants.HEAD); u.disableRefLog(); u.link(ref.getName()); } ObjectId commitId = ref.getObjectId(); RevCommit commit = parseCommit(commitId); RefUpdate u = repo.updateRef(Constants.HEAD); u.setNewObjectId(commit.getId()); u.forceUpdate(); DirCache dc = repo.lockDirCache(); DirCacheCheckout co = new DirCacheCheckout(repo, dc, commit.getTree()); co.checkout(); }
From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java
License:Apache License
private static void infoRefs(Repository db) { Map<String, Ref> refs = db.getAllRefs(); System.out.printf("%nAll Refs (%d)%n", refs.size()); Ref head = refs.get(Constants.HEAD); if (head == null) { System.out.println(" HEAD ref is dead and/or non-existent?"); return;/*w ww.ja va2 s . c om*/ } Map<String, Ref> printRefs = new TreeMap<String, Ref>(); String current = head.getLeaf().getName(); if (current.equals(Constants.HEAD)) { printRefs.put("(no branch)", head); } for (Ref ref : RefComparator.sort(refs.values())) { String name = ref.getName(); if (name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_REMOTES)) { printRefs.put(name, ref); } } int maxLength = 0; for (String name : printRefs.keySet()) { maxLength = Math.max(maxLength, name.length()); } System.out.printf("Refs (Heads/Remotes) (%d)%n", printRefs.size()); for (Entry<String, Ref> e : printRefs.entrySet()) { Ref ref = e.getValue(); ObjectId objectId = ref.getObjectId(); System.out.printf("%c %-" + maxLength + "s %s%n", (current.equals(ref.getName()) ? '*' : ' '), e.getKey(), objectId.abbreviate(ABBREV_LEN).name()); } }
From source file:net.fatlenny.datacitation.service.GitCitationDBService.java
License:Apache License
private ObjectId checkoutBranch(String commit) throws CitationDBException { try (Git git = new Git(repository)) { git.checkout().setName(commit).call(); return repository.resolve(Constants.HEAD); } catch (GitAPIException e) { throw new CitationDBException("Error checking out master branch: ", e); } catch (NoWorkTreeException e) { throw new CitationDBException("Error retrieving data folder: ", e); } catch (IOException e) { throw new CitationDBException("Error resolving head revision"); }/* w w w . j a v a2s .c o m*/ }
From source file:net.morimekta.idltool.IdlUtils.java
License:Apache License
public static Meta getMetaInRegistry(Repository repo) throws IOException, GitAPIException { // use tree and meta.json file to show available services. ObjectId lastCommitId = repo.resolve(Constants.HEAD); // now we have to get the commit RevWalk revWalk = new RevWalk(repo); RevCommit commit = revWalk.parseCommit(lastCommitId); // and using commit's tree find the path RevTree tree = commit.getTree();//from w w w. j av a2s . co m TreeWalk treeWalk = new TreeWalk(repo); treeWalk.addTree(tree); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(Idl_Constants.META_JSON)); if (!treeWalk.next()) { throw new RuntimeException("No registry meta file found, should be at " + new File(repo.getDirectory(), Idl_Constants.META_JSON).getCanonicalFile().getAbsolutePath()); } ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = repo.open(objectId); // and then one can use either InputStream in = loader.openStream(); return new JsonSerializer().deserialize(in, Meta.kDescriptor); }
From source file:net.polydawn.mdm.commands.MdmUpdateCommand.java
License:Open Source License
public MdmExitMessage call() throws ConfigInvalidException, IOException { try {/* w w w. ja va 2 s.c om*/ assertInRepo(); } catch (MdmExitMessage e) { return e; } MdmModuleSet moduleSet; try { moduleSet = new MdmModuleSet(repo); } catch (ConfigInvalidException e) { throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES); } Map<String, MdmModuleDependency> modules = moduleSet.getDependencyModules(); // Go over every module and do what we can to it, keeping a list of who each kind of operation was performed on for summary output later. List<MdmModule> impacted = new ArrayList<MdmModule>(); List<MdmModule> unphased = new ArrayList<MdmModule>(); List<MdmModule> contorted = new ArrayList<MdmModule>(); int hashMismatchWarnings = 0; int i = 0; boolean fancy = System.console() != null; for (MdmModuleDependency module : modules.values()) { i++; try { os.print((fancy ? "\033[2K\r" : "") + "updating module " + i + " of " + modules.size() + ": " + module.getHandle() + " ..." + (fancy ? "" : "\n")); if (Plumbing.fetch(repo, module)) { impacted.add(module); if (!module.getRepo().resolve(Constants.HEAD).equals(module.getIndexId())) { // in putting the module to the version named in .gitmodules, we made it disagree with the parent index. // this probably indicates oddness. hashMismatchWarnings++; os.println((fancy ? "\033[2K\r" : "") + "notice: in updating " + module.getHandle() + " to version " + module.getVersionName() + ", mdm left the submodule with a different hash checked out than the parent repo expected."); } } else unphased.add(module); } catch (MdmException e) { os.println((fancy ? "\033[2K\r" : "") + "error: in updating " + module.getHandle() + " to version " + module.getVersionName() + ", " + e); contorted.add(module); } } os.print((fancy ? "\033[2K\r" : "")); // explain notices about hash mismatches, if any occured. if (hashMismatchWarnings > 0) { os.println(); os.println( "warnings about submodule checkouts not matching the hash expected by the parent repo may indicate a problem which you should investigate immediately to make sure your dependencies are repeatable to others."); os.println( "this issue may be because the repository you are fetching from has moved what commit the version branch points to (which is cause for concern), or it may be a local misconfiguration (did you resolve a merge conflict recently? audit your log; the version name in gitmodules config must move at the same time as the submodule hash)."); os.println(); } else if (contorted.size() > 0) { os.println(); } // That's all. Compose a status string. StringBuilder status = new StringBuilder(); status.append("mdm dependencies have been updated ("); status.append(impacted.size()).append(" changed, "); status.append(unphased.size()).append(" unaffected"); if (contorted.size() > 0) status.append(", ").append(contorted.size()).append(" contorted"); status.append(")"); if (impacted.size() > 0) status.append("\n changed: \t").append(join(toHandles(impacted), "\n\t\t")); if (contorted.size() > 0) status.append("\n contorted: \t").append(join(toHandles(contorted), "\n\t\t")); return new MdmExitMessage(contorted.size() > 0 ? ":(" : ":D", status.toString()); }
From source file:net.polydawn.mdm.MdmModule.java
License:Open Source License
/** * @param repo/* w ww. jav a2s . c om*/ * required. * * well, unless you're about to create one, in which case not even. * @param handle * required. * @param parent * null if repository stands alone, otherwise if we are a submodule * required. * @param gitmodulesCfg * ignored if parent null, otherwise required. * @param indexId * ignored if parent null, otherwise will be automatically loaded * if not provided. * * the commit hash known to the parent repo index for this * submodule (or null if it's not handy; we'll load it in that * case). * * @throws MdmModuleTypeException * if the {@code gitmodulesCfg} entries for {@code handle} don't * concur with the {@code type} expected. * @throws MdmRepositoryIOException * if disks reject our advances */ protected MdmModule(Repository repo, String handle, Repository parent, Config gitmodulesCfg, ObjectId indexId) throws MdmRepositoryIOException, MdmModuleTypeException { handle = (File.separatorChar != '/') ? handle.replace(File.separatorChar, '/') : handle; this.handle = handle; this.repo = repo; if (repo == null) { this.headId = null; this.dirtyFiles = false; } else { try { this.headId = repo.resolve(Constants.HEAD); } catch (IOException e) { throw new MdmRepositoryIOException(false, handle, e); } boolean dirtyFiles; try { dirtyFiles = !new Git(repo).status().call().isClean(); } catch (NoWorkTreeException e) { throw new RuntimeException("wat", e); } catch (GitAPIException e) { dirtyFiles = false; } this.dirtyFiles = dirtyFiles; } if (parent != null) { // sanity check the expected module type if we're a submodule (if we're not a submodule, we can't make any such check since there's no gitmodules file to refer to). MdmModuleType type = getType(); MdmModuleType type_configured = MdmModuleType .fromString(gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, MdmConfigConstants.Module.MODULE_TYPE.toString())); if (type == null) throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle + ", but gitmodules file has no known type for this module."); if (type != type_configured) throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle + ", but gitmodules file states this is a " + type_configured + " module."); // load real path from gitmodule config (probably same as handle, but theoretically allowed to be different) String path = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_PATH); this.path = (File.separatorChar != '/') ? path.replace(File.separatorChar, '/') : path; // load remote urls this.urlHistoric = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_URL); this.urlLocal = parent.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle, ConfigConstants.CONFIG_KEY_URL); // load indexId the parent expects the submodule to be at (if not already provided) if (indexId != null) this.indexId = indexId; else try { SubmoduleWalk generator = SubmoduleWalk.forIndex(parent).setFilter(PathFilter.create(path)); this.indexId = generator.next() ? generator.getObjectId() : null; } catch (IOException e) { throw new MdmRepositoryIOException(false, parent.getWorkTree().getPath(), e); } // review the submodule and summarize a status. SubmoduleStatusType statusType; if (path == null) // jgit report SubmoduleStatusType.MISSING if no path in .gitmodules file, but I don't even want to deal with that. throw new MdmModuleTypeException("no path for module " + handle + " listed in gitmodules file."); else if (urlLocal == null) // Report uninitialized if no URL in config file statusType = SubmoduleStatusType.UNINITIALIZED; else if (repo == null) // Report uninitialized if no submodule repository statusType = SubmoduleStatusType.UNINITIALIZED; else if (headId == null) // Report uninitialized if no HEAD commit in submodule repository statusType = SubmoduleStatusType.UNINITIALIZED; else if (!headId.equals(indexId)) // Report checked out if HEAD commit is different than index commit statusType = SubmoduleStatusType.REV_CHECKED_OUT; else // Report initialized if HEAD commit is the same as the index commit statusType = SubmoduleStatusType.INITIALIZED; this.status = new SubmoduleStatus(statusType, path, indexId, headId); } else { this.path = handle; this.indexId = null; this.urlHistoric = null; this.urlLocal = null; this.status = null; } }
From source file:net.sf.authorship.AuthorshipReportMojo.java
License:Open Source License
/** * @return list of authors from SCM.//from ww w . j av a2 s.co m */ private Set<Author> getScmAuthors() { Set<Author> authors = new LinkedHashSet<Author>(); final Scm scm = project.getScm(); if (scm != null) { final String connection = project.getScm().getConnection(); if (connection == null) { getLog().info("Empty <connection> in pom.xml SCM information (<scm> XML tag)."); } else { ScmProvider scmProvider; try { scmProvider = scmManager.getProviderByUrl(connection); AuthorshipStrategy<Author> strategy = null; if (SCM_PROVIDER_SVN_TYPE.equals(scmProvider.getScmType())) { final String svnUrl = this.getSvnUrl(connection); final PROTOCOL protocol = this.geSvnProtocol(connection); final SvnOptions options = new SvnOptions(); // TODO: map from mojo config strategy = new SvnStrategy(protocol, svnUrl, options); // FIXME } else if (GIT_PROVIDER_SVN_TYPE.equals(scmProvider.getScmType())) { final String folder = new File(System.getProperty("java.io.tmpdir"), Long.toString(System.nanoTime())).getAbsolutePath(); // FIXME: avoid exceptions with index out of bound strategy = new GitStrategy( connection.substring(connection.indexOf("scm:git:") + 8, connection.length()), folder, Constants.HEAD, null); } if (strategy != null) { authors = strategy.getAuthors(); } } catch (ScmRepositoryException e) { getLog().warn("Failed to retrieve authorship from <scm>: " + e.getMessage(), e); } catch (NoSuchScmProviderException e) { getLog().warn("Failed to retrieve authorship from <scm>: " + e.getMessage(), e); } catch (AuthorshipException ae) { getLog().warn("Failed to retrieve authorship from <scm>: " + ae.getMessage(), ae); } } } else { getLog().info("No project SCM information found. Skipping authorship from SCM (<scm> XML tag info)."); } return authors; }
From source file:net.sf.authorship.strategies.GitStrategy.java
License:Open Source License
public Set<Author> getAuthors() throws AuthorshipException { try {/*from w ww. j a va 2s . c o m*/ this.cloneRepository(this.readOnlyUrl, this.folder); } catch (IOException ioe) { throw new AuthorshipException("Failed to clone git repository [" + this.readOnlyUrl + "]", ioe); } final Set<Author> authorEmails = new HashSet<Author>(); final File directory = new File(this.folder); try { final Repository repository; try { repository = RepositoryCache.open(RepositoryCache.FileKey.lenient(directory, FS.DETECTED), true); } catch (IOException ioe) { throw new AuthorshipException("Failed to open git repository [" + this.readOnlyUrl + "] cloned into local repository [" + this.folder + "]", ioe); } final RevWalk walk; try { walk = new RevWalk(repository); if (StringUtils.isNotBlank(this.fromRevision)) { this.fromRevision = Constants.HEAD; } ObjectId revId = repository.resolve(this.fromRevision); RevCommit root = walk.parseCommit(revId); walk.markStart(root); if (StringUtils.isNotBlank(this.toRevision)) { ObjectId to = repository.resolve(this.toRevision); RevCommit end = walk.parseCommit(to); walk.markUninteresting(end); } } catch (IOException ioe) { throw new AuthorshipException("Failed to analyse revisions from git repository [" + this.folder + "]: " + ioe.getMessage(), ioe); } for (RevCommit commit : walk) { Author author = new Author(null, commit.getAuthorIdent().getName(), commit.getAuthorIdent().getEmailAddress(), null); authorEmails.add(author); } walk.dispose(); } finally { try { if (!directory.delete()) { directory.deleteOnExit(); } } catch (RuntimeException re) { LOGGER.warning(re.getMessage()); } } return authorEmails; }
From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommandCommitterAuthorTckTest.java
License:Apache License
private RevCommit getHeadCommit(Repository repository) throws Exception { RevWalk rw = new RevWalk(repository); AnyObjectId headId = repository.resolve(Constants.HEAD); RevCommit head = rw.parseCommit(headId); rw.release();/*from ww w .j ava 2 s.co m*/ return head; }