List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:org.libx4j.maven.plugin.version.VersionMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {//from w ww . java 2 s . co m final File repoDir = GitUtil.findRepositoryDir(project.getBasedir()); final Git git = Git.open(repoDir); final POMFile pomFile = POMFile.entry(new File(project.getBasedir(), "pom.xml")); final Set<String> changedFilePaths = GitUtil.lookupChangedFiles(pomFile, git); if (changedFilePaths.size() == 0) { getLog().info("Detected 0 changed files staged to commit. Will skip POM version check."); return; } try (final OriginalResolver originals = new OriginalResolver(git.getRepository())) { getLog().info("Detected " + changedFilePaths.size() + " changed files staged to commit. Will check POM version..."); pomFile.checkIncreaseVersion(incrementPart); final Set<POMFile> updates = new HashSet<>(); for (final POMFile update : POMFile.getPendingUpdates()) { final String previousText = originals.fetchBlob(Paths.canonicalize( pomFile.file().getAbsolutePath().substring(repoDir.getAbsolutePath().length() + 1))); final Version previousVersion = POMFile.parse(null, previousText).version(); if (!incrementSnapshot && update.version().suffix() != null && update.version().suffix().endsWith("SNAPSHOT")) { getLog().info("[SKIPPING] " + ModuleId.toString(update)); getLog().info(" Reason: Not incrementing SNAPSHOT versions; see -DincrementSnapshot"); } else if (previousVersion == null) { getLog().info("[SKIPPING] " + ModuleId.toString(update)); getLog().info(" Reason: New module."); } else { final int comparison = update.version().compareTo(previousVersion); if (comparison == 0) { getLog().info("[UPDATING] " + ModuleId.toString(update) + " -> " + update.newVersion()); getLog().info(" Reason: Current version not updated since last git commit."); updates.add(update); } else if (comparison > 0) { getLog().info("[SKIPPING] " + ModuleId.toString(update)); getLog().info(" Reason: Current version is higher than in last git commit."); } else if (comparison < 0) { getLog().info("[UPDATING] " + ModuleId.toString(update)); getLog().info(" Reason: Current version is lower than in last git commit."); updates.add(update); } } } executeUpdate(updates); } } catch (final GitAPIException | IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:org.moxie.ant.Main.java
License:Apache License
private void initGit() throws GitAPIException { // create the repository InitCommand init = Git.init();/*from w w w. ja va 2 s. c o m*/ init.setBare(false); init.setDirectory(newProject.dir); Git git = init.call(); if (!StringUtils.isEmpty(newProject.gitOrigin)) { // set the origin and configure the master branch for merging StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", getGitUrl()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.setString("branch", "master", "remote", "origin"); config.setString("branch", "master", "merge", "refs/heads/master"); try { config.save(); } catch (IOException e) { throw new MoxieException(e); } } // prepare a common gitignore file StringBuilder sb = new StringBuilder(); sb.append("/.directory\n"); sb.append("/.DS_STORE\n"); sb.append("/.DS_Store\n"); sb.append("/.settings\n"); sb.append("/bin\n"); sb.append("/build\n"); sb.append("/ext\n"); sb.append("/target\n"); sb.append("/tmp\n"); sb.append("/temp\n"); if (!newProject.eclipse.includeClasspath()) { // ignore hard-coded .classpath sb.append("/.classpath\n"); } FileUtils.writeContent(new File(newProject.dir, ".gitignore"), sb.toString()); AddCommand add = git.add(); add.addFilepattern("build.xml"); add.addFilepattern("build.moxie"); add.addFilepattern(".gitignore"); if (newProject.eclipse.includeProject()) { add.addFilepattern(".project"); } if (newProject.eclipse.includeClasspath()) { // MOXIE_HOME relative dependencies in .classpath add.addFilepattern(".classpath"); } if (newProject.idea.includeProject()) { add.addFilepattern(".project"); } if (newProject.idea.includeClasspath()) { // MOXIE_HOME relative dependencies in .iml add.addFilepattern("*.iml"); } try { add.call(); CommitCommand commit = git.commit(); PersonIdent moxie = new PersonIdent("Moxie", "moxie@localhost"); commit.setAuthor(moxie); commit.setCommitter(moxie); commit.setMessage("Project structure created"); commit.call(); } catch (Exception e) { throw new MoxieException(e); } }
From source file:org.moxie.utils.JGitUtils.java
License:Apache License
public static String commitFiles(File dir, List<String> files, String message, String tagName, String tagMessage) throws IOException, GitAPIException { Git git = Git.open(dir); AddCommand add = git.add();// w ww . ja va 2 s . co m for (String file : files) { add.addFilepattern(file); } add.call(); // execute the commit CommitCommand commit = git.commit(); commit.setMessage(message); RevCommit revCommit = commit.call(); if (!StringUtils.isEmpty(tagName) && !StringUtils.isEmpty(tagMessage)) { // tag the commit TagCommand tagCommand = git.tag(); tagCommand.setName(tagName); tagCommand.setMessage(tagMessage); tagCommand.setForceUpdate(true); tagCommand.setObjectId(revCommit); tagCommand.call(); } git.getRepository().close(); return revCommit.getId().getName(); }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public Map getWorkingTree(@PName("name") String repoName, @PName("path") @POptional String path, @PName("depth") @POptional @PDefaultInt(100) Integer depth, @PName("includeTypeList") @POptional List<String> includeTypeList, @PName("includePathList") @POptional List<String> includePathList, @PName("excludePathList") @POptional List<String> excludePathList, @PName("mapping") @POptional Map mapping) throws RpcException { try {/*from w w w. j av a 2s. c o m*/ if (depth == null) depth = 100; String gitSpace = System.getProperty("git.repos"); File gitDir = new File(gitSpace, repoName + "/.git"); if (!gitDir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.getWorkingTree:Repo(" + repoName + ") not exists"); } File repoDir = new File(gitSpace, repoName); Git gitObject = Git.open(new File(gitSpace, repoName)); TreeWalk treeWalk = new TreeWalk(gitObject.getRepository()); FileTreeIterator newTree = null; String rootPath = "root"; String type = "sw.project"; File basePath = repoDir; String title = repoName; if (path == null) { newTree = new FileTreeIterator(gitObject.getRepository()); } else { File f = new File(gitObject.getRepository().getDirectory().getParentFile(), path); debug("f:" + f); newTree = new FileTreeIterator(f, FS.detect(), gitObject.getRepository().getConfig().get(WorkingTreeOptions.KEY)); rootPath = path; type = "sw.directory"; title += "/" + path; basePath = new File(basePath, path); } treeWalk.addTree(newTree); treeWalk.setRecursive(true); Collection<TreeFilter> filterList = new HashSet(); TreeFilter pathFilter = PathPatternFilter.create("^[a-zA-Z].*$", includePathList, excludePathList, 0); filterList.add(pathFilter); if (includeTypeList != null && includeTypeList.size() > 0) { filterList.add(TypeFilter.create(basePath, includeTypeList)); } if (filterList.size() > 1) { TreeFilter andFilter = AndTreeFilter.create(filterList); treeWalk.setFilter(andFilter); } else { treeWalk.setFilter(pathFilter); } treeWalk.setPostOrderTraversal(true); Map<String, Map> parentMap = new HashMap(); Map root = new HashMap(); root.put("path", rootPath); root.put("title", repoName); root.put("value", rootPath); root.put("type", type); root.put("children", new ArrayList()); parentMap.put("root", root); while (true) { if (!treeWalk.next()) { break; } String pathString = new String(treeWalk.getRawPath()); // String pathString = treeWalk.getPathString(); Node[] nodes = getNodes(pathString); for (int i = 0; i < nodes.length && i < depth; i++) { if (parentMap.get(nodes[i].path) == null) { Map map = getNodeMap(nodes[i], i < (nodes.length - 1), basePath, mapping); map.put("children", new ArrayList()); parentMap.put(nodes[i].path, map); Map pmap = parentMap.get(nodes[i].parent); if (pmap != null) { List<Map> children = (List) pmap.get("children"); children.add(map); } } } } // m_js.prettyPrint(true); // String ser = m_js.deepSerialize(parentMap.get("root")); // debug("Tree" + ser); return parentMap.get("root"); } catch (Exception e) { if (e instanceof RpcException) throw (RpcException) e; throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.getWorkingTree:", e); } finally { } }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public List<String> assetList(@PName("reponame") String repoName, @PName("name") String name, @PName("type") String type, @PName("onlyFirst") @POptional @PDefaultBool(false) Boolean onlyFirst) throws RpcException { try {// w w w. j ava2 s . c o m String gitSpace = System.getProperty("git.repos"); File gitDir = new File(gitSpace, repoName); if (!gitDir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.getContent:Repo(" + repoName + ") not exists"); } List<String> typeList = new ArrayList(); List<String> hitList = new ArrayList(); typeList.add(type); Git gitObject = Git.open(new File(gitSpace, repoName)); TreeWalk treeWalk = new TreeWalk(gitObject.getRepository()); FileTreeIterator newTree = new FileTreeIterator(gitObject.getRepository()); treeWalk.addTree(newTree); treeWalk.setRecursive(true); treeWalk.setPostOrderTraversal(true); File basePath = new File(gitSpace, repoName); while (true) { if (!treeWalk.next()) { break; } String pathString = new String(treeWalk.getRawPath()); File file = new File(basePath, pathString); if (file.isDirectory() || pathString.startsWith("store") || pathString.startsWith(".git")) { continue; } if (typeList.contains("all") || typeList.contains(getFileType(file))) { if (name == null || name.equals(getBasename(pathString))) { debug("\tTreffer:" + pathString); hitList.add(pathString); if (onlyFirst) { return hitList; } } } } return hitList; } catch (Exception e) { if (e instanceof RpcException) throw (RpcException) e; throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.assetList:", e); } finally { } }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public void addRemoteOrigin(@PName("name") String name, @PName("url") String url) { try {//from www .jav a 2s. c o m String gitSpace = System.getProperty("git.repos"); File dir = new File(gitSpace, name); if (!dir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.setAddRemoteOrigin:Repo(" + name + ") not exists"); } Git git = Git.open(dir); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", url); config.save(); } catch (Exception e) { throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.addRemoteOrigin:", e); } finally { } }
From source file:org.n52.wps.repository.git.GitAlgorithmRepository.java
License:Open Source License
private File[] cloneToLocalRepository() throws GitAlgorithmsRepositoryConfigException { try {/*from w w w .j av a 2s.c om*/ Git git = Git.cloneRepository().setDirectory(new File(localPath)).setURI(remotePath).call(); return getFiles(git.getRepository().getWorkTree()); } catch (GitAPIException e) { throw new GitAlgorithmsRepositoryConfigException("Cloning failed: " + remotePath, e); } }
From source file:org.obiba.git.command.CommitLogCommand.java
License:Open Source License
@Override public CommitInfo execute(Git git) { Repository repository = git.getRepository(); RevWalk walk = new RevWalk(repository); try {/* w ww . ja v a2 s . com*/ RevCommit commit = walk.parseCommit(ObjectId.fromString(commitId)); if (TreeWalk.forPath(repository, path, commit.getTree()) != null) { // There is indeed the path in this commit PersonIdent personIdent = commit.getAuthorIdent(); return new CommitInfo.Builder().authorName(personIdent.getName()) // .authorEmail(personIdent.getEmailAddress()) // .date(personIdent.getWhen()) // .comment(commit.getFullMessage()) // .commitId(commit.getName()) // .head(GitUtils.isHead(repository, commitId)).build(); } } catch (IOException e) { throw new GitException(e); } throw new GitException(String.format("Path '%s' was not found in commit '%s'", path, commitId)); }
From source file:org.obiba.git.command.DiffAsStringCommand.java
License:Open Source License
@Override public Iterable<String> execute(Git git) { try {/*from w w w. j a v a2 s . c om*/ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { DiffFormatter formatter = new DiffFormatter(out); formatter.setRepository(git.getRepository()); formatter.setDiffComparator(RawTextComparator.DEFAULT); formatter.setDetectRenames(true); DiffCommand diffCommand = new DiffCommand.Builder(getRepositoryPath(), commitId).path(path) .previousCommitId(previousCommitId).nthCommit(nthCommit).build(); Collection<String> diffEntries = new ArrayList<>(); for (DiffEntry diffEntry : diffCommand.execute(git)) { formatter.format(diffEntry); diffEntry.getOldId(); diffEntries.add(out.toString("UTF-8")); out.reset(); } return diffEntries; } } catch (IOException e) { throw new GitException(e); } }
From source file:org.obiba.git.command.DiffCommand.java
License:Open Source License
@Override public Iterable<DiffEntry> execute(Git git) { Repository repository = git.getRepository(); ObjectReader reader = repository.newObjectReader(); try {/*w w w . ja v a2s . c om*/ DiffCurrentPreviousTreeParsersFactory parsersFactory = new DiffCurrentPreviousTreeParsersFactory( repository, reader); return compareDiffTrees(repository, parsersFactory); } catch (IOException e) { throw new GitException(e); } finally { reader.release(); } }