List of usage examples for org.eclipse.jgit.lib Repository getConfig
@NonNull public abstract StoredConfig getConfig();
From source file:com.pieceof8.gradle.snapshot.GitScmProvider.java
License:Apache License
/** {@inheritDoc} */ @Override/*from w w w . jav a 2 s. c o m*/ @SneakyThrows(IOException.class) public Commit getCommit() { if (repoDir == null) { throw new IllegalArgumentException("'repoDir' must not be null"); } FileRepositoryBuilder builder = new FileRepositoryBuilder(); @Cleanup Repository repo = builder.setGitDir(repoDir).readEnvironment().findGitDir().build(); StoredConfig conf = repo.getConfig(); int abbrev = Commit.ABBREV_LENGTH; if (conf != null) { abbrev = conf.getInt("core", "abbrev", abbrev); } val sdf = new SimpleDateFormat(extension.getDateFormat()); val HEAD = repo.getRef(Constants.HEAD); if (HEAD == null) { val msg = "Could not get HEAD Ref, the repository may be corrupt."; throw new RuntimeException(msg); } RevWalk revWalk = new RevWalk(repo); if (HEAD.getObjectId() == null) { val msg = "Could not find any commits from HEAD ref."; throw new RuntimeException(msg); } RevCommit commit = revWalk.parseCommit(HEAD.getObjectId()); revWalk.markStart(commit); try { // git commit time in sec and java datetime is in ms val commitTime = new Date(commit.getCommitTime() * 1000L); val ident = commit.getAuthorIdent(); return new Commit(sdf.format(new Date()), // build time conf.getString("user", null, "name"), conf.getString("user", null, "email"), repo.getBranch(), commit.getName(), sdf.format(commitTime), ident.getName(), ident.getEmailAddress(), commit.getFullMessage().trim()); } finally { revWalk.dispose(); } }
From source file:com.puppetlabs.geppetto.forge.jenkins.RepositoryInfo.java
License:Open Source License
/** * Obtains the remote URL that is referenced by the given <code>branchName</code> * * @return The URL or <code>null</code> if it hasn't been configured * for the given branch.// ww w. j a va2 s .c om */ public static String getRemoteURL(Repository repository) throws IOException { StoredConfig repoConfig = repository.getConfig(); String configuredRemote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, repository.getBranch(), ConfigConstants.CONFIG_KEY_REMOTE); return configuredRemote == null ? null : repoConfig.getString(ConfigConstants.CONFIG_REMOTE_SECTION, configuredRemote, ConfigConstants.CONFIG_KEY_URL); }
From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java
License:Open Source License
/** * /* w w w . j a v a2 s . c om*/ * Gets org.eclipse.jgit.lib.Repository object for existing Git Repository. * * @param repositoryPath * the path to an existing Git Repository * @return {@link org.eclipse.jgit.lib.Repository} object * * * @throws IOException */ public static Repository getRepository(String repositoryPath) throws IOException { RepositoryBuilder repositoryBuilder = new RepositoryBuilder(); repositoryBuilder.findGitDir(new File(repositoryPath)); Repository repository = repositoryBuilder.build(); repository.getConfig().setString(BRANCH, MASTER, MERGE, REFS_HEADS_MASTER); return repository; }
From source file:com.smartbear.collab.util.ChangeListUtils.java
License:Apache License
public static List<ChangeList> VcsFileRevisionToChangeList(String rootDirectory, ScmToken scmToken, Map<VcsFileRevision, CommittedChangeList> commits, Project project) { List<ChangeList> changeLists = new ArrayList<ChangeList>(); ProjectLevelVcsManager projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project); for (Map.Entry<VcsFileRevision, CommittedChangeList> commit : commits.entrySet()) { VcsFileRevision fileRevision = commit.getKey(); CommittedChangeList committedChangeList = commit.getValue(); CommitInfo commitInfo = new CommitInfo(fileRevision.getCommitMessage(), fileRevision.getRevisionDate(), fileRevision.getAuthor(), false, fileRevision.getRevisionNumber().asString(), ""); List<Version> versions = new ArrayList<Version>(); String scmRepoURL = ""; String scmRepoUUID = ""; for (Change change : committedChangeList.getChanges()) { String fileContent = ""; try { fileContent = change.getAfterRevision().getContent(); } catch (VcsException ve) { log.severe(scmToken.name() + " error: " + ve.getMessage()); }/* w ww .j a v a 2s. c om*/ ContentRevision baseRevision = change.getBeforeRevision(); BaseVersion baseVersion; if (baseRevision == null) { baseVersion = null; } else { String baseMd5 = ""; String baseScmPath = getScmPath(rootDirectory, baseRevision.getFile().getPath()); try { baseMd5 = getMD5(baseRevision.getContent().getBytes()); } catch (VcsException ve) { log.severe(scmToken.name() + " error: " + ve.getMessage()); } String baseVersionName = ""; baseVersionName = getScmVersionName(scmToken, baseRevision); baseVersion = new BaseVersion(change.getFileStatus().getId(), baseMd5, commitInfo, CollabConstants.SOURCE_TYPE_SCM, baseVersionName, baseScmPath); } //Version String localPath = change.getAfterRevision().getFile().getPath(); String scmPath = getScmPath(rootDirectory, change.getAfterRevision().getFile().getPath()); String md5 = getMD5(fileContent.getBytes()); String action = change.getFileStatus().getId(); String scmVersionName = getScmVersionName(scmToken, change.getAfterRevision()); Version version = new Version(scmPath, md5, scmVersionName, localPath, action, CollabConstants.SOURCE_TYPE_SCM, baseVersion); versions.add(version); if (scmRepoURL.equals("")) { switch (scmToken) { case SUBVERSION: // TODO: can probably get this in a less hacky way with svnkit, since we need that anyway now? String fullPath = fileRevision.getChangedRepositoryPath().toPresentableString(); // this gives the full path down to the file, so: if (fullPath.endsWith(scmPath) && fullPath.indexOf(scmPath) > 0) { scmRepoURL = fullPath.substring(0, fullPath.indexOf(scmPath) - 1); // -1 to trim off trailing "/" } break; case GIT: VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile()); FileRepositoryBuilder builder = new FileRepositoryBuilder(); try { Repository gitRepo = builder.readEnvironment() .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build(); Config gitConfig = gitRepo.getConfig(); Set<String> remotes = gitConfig.getSubsections("remote"); Set<String> remoteURLs = new HashSet<String>(); if (remotes.isEmpty()) { // TODO: figure out what existing collab clients use for git repo url for local-only situation scmRepoURL = "git: local-only"; } else { for (String remoteName : remotes) { remoteURLs.add(gitConfig.getString("remote", remoteName, "url")); } Iterator<String> urlitr = remoteURLs.iterator(); if (remoteURLs.size() == 1) { // the easy case scmRepoURL = urlitr.next(); } else { // TODO we have more than one, so figure out what the existing clients do here // for now, just grab the first one scmRepoURL = urlitr.next(); } } } catch (Exception e) { log.severe("GIT interaction error: " + e.getMessage()); } break; default: log.severe("Unsupported SCM: " + scmToken); break; } } if (scmRepoUUID.equals("")) { switch (scmToken) { case SUBVERSION: if (!scmRepoURL.equals("")) { try { SVNURL svnURL = SVNURL.parseURIEncoded(scmRepoURL); SVNClientManager cm = SVNClientManager.newInstance(); SVNWCClient workingCopyClient = cm.getWCClient(); SVNInfo svnInfo = workingCopyClient.doInfo(svnURL, SVNRevision.UNDEFINED, SVNRevision.HEAD); scmRepoUUID = svnInfo.getRepositoryUUID(); } catch (SVNException svne) { log.severe("SVN error: " + svne.getMessage()); } } break; case GIT: // for this, we use the sha1 of the first git commit in the project FileRepositoryBuilder builder = new FileRepositoryBuilder(); try { VcsRoot vcsRoot = projectLevelVcsManager.getVcsRootObjectFor(change.getVirtualFile()); Repository gitRepo = builder.readEnvironment() .findGitDir(new File(vcsRoot.getPath().getCanonicalPath())).build(); Git git = new Git(gitRepo); Iterable<RevCommit> gitCommits = git.log().all().call(); Iterator<RevCommit> gitr = gitCommits.iterator(); RevCommit firstCommit = null; while (gitr.hasNext()) { // run through log, firstCommit = gitr.next(); } if (firstCommit != null) { scmRepoUUID = firstCommit.getName(); // sha1 of first commit in repo, lower-case hexadecimal } } catch (Exception e) { log.severe("GIT interaction error: " + e.getMessage()); } break; default: log.severe("Unsupported SCM: " + scmToken); break; } } } // we might have to do something more sophisticated once we support other SCMs, but for git and svn // collab only really needs an URL and some sort of UUID-ish value ArrayList<String> scmConnectionParameters = new ArrayList<String>(2); scmConnectionParameters.add(scmRepoURL); scmConnectionParameters.add(scmRepoUUID); ChangeList changeList = new ChangeList(scmToken, scmConnectionParameters, commitInfo, versions); changeLists.add(changeList); } return changeLists; }
From source file:com.spotify.docker.DockerBuildInformation.java
License:Apache License
private void updateGitInformation(Log log) { try {/*www. j a v 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.surevine.gateway.scm.git.jgit.JGitGitFacade.java
License:Open Source License
@Override public boolean repoAlreadyCloned(final LocalRepoBean repoBean) throws GitException { boolean alreadyCloned = false; // if the enclosing directory exists then examine the repository to check it's the right one if (Files.exists(repoBean.getRepoDirectory())) { try {//from ww w . ja v a 2 s. c o m // load the repository into jgit FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir() .build(); // examine the repository configuration and confirm whether it has a remote named "origin" // that points to the clone URL in the argument repo information. If it does the repo has // already been cloned. Config storedConfig = repository.getConfig(); String originURL = storedConfig.getString("remote", "origin", "url"); alreadyCloned = originURL != null && repoBean.getCloneSourceURI() != null && originURL.equals(repoBean.getCloneSourceURI()); repository.close(); } catch (IOException e) { LOGGER.error(e); throw new GitException(e); } } return alreadyCloned; }
From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java
License:Open Source License
public static LocalRepoBean createTestRepoMultipleBranches() throws Exception { final String projectKey = "test_" + UUID.randomUUID().toString(); final String repoSlug = "testRepo"; final String remoteURL = "ssh://fake_url"; final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug); Files.createDirectories(repoPath); final Repository repo = new FileRepository(repoPath.resolve(".git").toFile()); repo.create();// w ww . ja va2 s . com final StoredConfig config = repo.getConfig(); config.setString("remote", "origin", "url", remoteURL); config.save(); final LocalRepoBean repoBean = new LocalRepoBean(); repoBean.setProjectKey(projectKey); repoBean.setSlug(repoSlug); repoBean.setLocalBare(false); final Git git = new Git(repo); // add some files to some branches for (int i = 0; i < 3; i++) { final String filename = "newfile" + i + ".txt"; Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); git.add().addFilepattern(filename).call(); git.commit().setMessage("Added " + filename).call(); } git.checkout().setName("branch1").setCreateBranch(true).call(); for (int i = 0; i < 3; i++) { final String filename = "branch1" + i + ".txt"; Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); git.add().addFilepattern(filename).call(); git.commit().setMessage("Added " + filename).call(); } git.checkout().setName("master").call(); git.checkout().setName("branch2").setCreateBranch(true).call(); for (int i = 0; i < 3; i++) { final String filename = "branch2" + i + ".txt"; Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); git.add().addFilepattern(filename).call(); git.commit().setMessage("Added " + filename).call(); } repo.close(); return repoBean; }
From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java
License:Open Source License
public static LocalRepoBean createTestRepo() throws Exception { final String projectKey = "test_" + UUID.randomUUID().toString(); final String repoSlug = "testRepo"; final String remoteURL = "ssh://fake_url"; final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug); Files.createDirectories(repoPath); final Repository repo = new FileRepository(repoPath.resolve(".git").toFile()); repo.create();//from ww w . j a va 2s. c o m final StoredConfig config = repo.getConfig(); config.setString("remote", "origin", "url", remoteURL); config.save(); final LocalRepoBean repoBean = new LocalRepoBean(); repoBean.setProjectKey(projectKey); repoBean.setSlug(repoSlug); repoBean.setLocalBare(false); repoBean.setSourcePartner("partner"); final Git git = new Git(repo); for (int i = 0; i < 3; i++) { final String filename = "newfile" + i + ".txt"; Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); git.add().addFilepattern(filename).call(); git.commit().setMessage("Added " + filename).call(); } git.checkout().setName("master").call(); repo.close(); return repoBean; }
From source file:com.unboundid.buildtools.repositoryinfo.RepositoryInfo.java
License:Open Source License
/** * Obtains information about the git repository from which the LDAP SDK source * was obtained.// ww w .j av a2 s . co m * * @throws Exception If a problem is encountered while attempting to obtain * information about the git repository. */ private void getGitInfo() throws Exception { final Repository r = new FileRepositoryBuilder().readEnvironment().findGitDir(baseDir).build(); final String repoURL = r.getConfig().getString("remote", "origin", "url"); final String repoRevision = r.resolve("HEAD").getName(); final String canonicalWorkspacePath = baseDir.getCanonicalPath(); final String canonicalRepositoryBaseDir = r.getDirectory().getParentFile().getCanonicalPath(); String repoPath = canonicalWorkspacePath.substring(canonicalRepositoryBaseDir.length()); if (!repoPath.startsWith("/")) { repoPath = '/' + repoPath; } getProject().setProperty(repositoryTypePropertyName, "git"); getProject().setProperty(repositoryURLPropertyName, repoURL); getProject().setProperty(repositoryPathPropertyName, repoPath); getProject().setProperty(repositoryRevisionPropertyName, repoRevision); getProject().setProperty(repositoryRevisionNumberPropertyName, "-1"); }
From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java
License:Open Source License
public void importSampleContents() throws IOException, GitAPIException { // TODO: synchronization is not quite correct here, but should be okay in this edge case if (listBranches().isEmpty()) { ILock lock = lockManager.lockAll(); List<String> branches; try {//from w ww . j av a 2s . c o m File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$ FileUtils.forceDelete(gitDir); Git.cloneRepository().setURI(DocumentrConstants.SAMPLE_REPO_URL).setDirectory(gitDir).setBare(true) .call(); Repository centralRepo = null; File centralRepoGitDir; try { centralRepo = getCentralRepositoryInternal(true); centralRepoGitDir = centralRepo.getDirectory(); StoredConfig config = centralRepo.getConfig(); config.unsetSection("remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ config.unsetSection("branch", "master"); //$NON-NLS-1$ //$NON-NLS-2$ config.save(); } finally { RepositoryUtil.closeQuietly(centralRepo); } branches = listBranches(); for (String branchName : branches) { File repoDir = new File(reposDir, branchName); Repository repo = null; try { repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString()) .setDirectory(repoDir).call().getRepository(); Git git = Git.wrap(repo); RefSpec refSpec = new RefSpec( "refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$ git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$ git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$ git.checkout().setName(branchName).call(); } finally { RepositoryUtil.closeQuietly(repo); } } } finally { lockManager.unlock(lock); } for (String branch : branches) { eventBus.post(new BranchCreatedEvent(projectName, branch)); } } }