List of usage examples for org.eclipse.jgit.api Git open
public static Git open(File dir) throws IOException
From source file:org.kie.workbench.common.migration.MigrationToolTest.java
License:Apache License
@Test public void testProjectGitHistory() throws IOException, GitAPIException { final int latestCommit = 0, previousCommit = 1; final String javaComment = "// ", firstCommitMsg = "first", thirdCommitMsg = "third", fourthCommitMsg = "fourth", fifthCommitMsg = "fifth", drl1Location = "src/main/resources/bxms/projectwithhistory1/drlWithGitHistory1.drl", drl2Location = "src/main/resources/bxms/projectwithhistory2/drlWithGitHistory2.drl"; final File projectWithHistory1 = getProjectDir(SPACE_B, PROJECT_WITH_HISTORY_1), projectWithHistory2 = getProjectDir(SPACE_B, PROJECT_WITH_HISTORY_2), drl1 = new File(projectWithHistory1, drl1Location), drl2 = new File(projectWithHistory2, drl2Location); final Git repoFirst = Git.open(projectWithHistory1), repoSecond = Git.open(projectWithHistory2); final List<String> commitMessagesDrl1 = getDrlCommitMessages(repoFirst, drl1Location), commitMessagesDrl2 = getDrlCommitMessages(repoSecond, drl2Location); assertThat(commitMessagesDrl1).hasSize(4); assertThat(commitMessagesDrl2).hasSize(3); assertThat(commitMessagesDrl1.get(latestCommit)).startsWith(fifthCommitMsg); assertThat(commitMessagesDrl1.get(previousCommit)).startsWith(fourthCommitMsg); assertThat(commitMessagesDrl2.get(latestCommit)).startsWith(thirdCommitMsg); assertThat(commitMessagesDrl2.get(previousCommit)).startsWith(firstCommitMsg); assertThat(getDrlLineWithContent(drl1)).isEqualTo(javaComment + fifthCommitMsg); assertThat(getDrlLineWithContent(drl2)).isEqualTo(javaComment + thirdCommitMsg); resetRepoToPreviousDrlCommit(repoFirst); resetRepoToPreviousDrlCommit(repoSecond); assertThat(getDrlLineWithContent(drl1)).isEqualTo(javaComment + fourthCommitMsg); assertThat(getDrlLineWithContent(drl2)).isEqualTo(javaComment + firstCommitMsg); }
From source file:org.komodo.storage.git.GitStorageConnector.java
License:Open Source License
private void cloneRepository() throws Exception { File destination = new File(getDestination()); File destGitDir = new File(destination, ".git"); if (destGitDir.exists()) { git = Git.open(destination); } else {//from w w w.j a v a2 s . c om git = Git.cloneRepository().setURI(getPath()).setDirectory(destination) .setTransportConfigCallback(transportConfigCallback).call(); } }
From source file:org.libx4j.maven.plugin.version.VersionMojo.java
License:Open Source License
@Override public void execute() throws MojoExecutionException, MojoFailureException { try {/* w w w.java2 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.modeshape.connector.git.GitConnectorTest.java
License:Apache License
private static void loadGitRepositoryData() throws Exception { try (Git git = Git.open(new File("../.."))) { // the tests expect a series of remote branches and tags from origin, so if they're not present in the clone // where the test is running, we need to load them... List<RefSpec> refsToFetch = new ArrayList<>(); List<String> tagNames = git.tagList().call().stream() .map(ref -> ref.getName().replace("refs/tags/", "")).collect(Collectors.toList()); Arrays.stream(expectedTagNames()).filter(tagName -> !tagNames.contains(tagName)) .map(tagName -> new RefSpec("+refs/tags/" + tagName + ":refs/remotes/origin/" + tagName)) .forEach(refsToFetch::add); List<String> branchNames = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call().stream() .map(ref -> ref.getName().replace("refs/heads/", "").replace("refs/remotes/origin/", "")) .collect(Collectors.toList()); Arrays.stream(expectedRemoteBranchNames()).filter(branchName -> !branchNames.contains(branchName)).map( branchName -> new RefSpec("+refs/heads/" + branchName + ":refs/remotes/origin/" + branchName)) .forEach(refsToFetch::add); if (!refsToFetch.isEmpty()) { // next fetch all the remote refs which we need for the test git.fetch().setRefSpecs(refsToFetch).call(); }/*from www . j av a2s . c o m*/ } }
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();//from w w w . ja v a2 s .c om 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 List getRepositories(@PName("flags") @POptional List<String> flags, @PName("all") @PDefaultBool(false) @POptional Boolean all) throws RpcException { System.out.println("getRepositories;" + flags + "/" + all); try {//from ww w . java 2 s . c om String gitSpace = System.getProperty("git.repos"); File dir = new File(gitSpace); if (!dir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.gitSpace not exists"); } List<Map> resList = new ArrayList<Map>(); File[] chld = dir.listFiles(); FS fs = FS.detect(); for (int i = 0; i < chld.length; i++) { File file = chld[i]; String fileName = file.getName(); if (!all && hasStoreCfg(file) == false) { continue; } debug("\n---------------->" + fileName); Map map = new HashMap(); if (flags != null && flags.contains("updateAvailable")) { Git gitObject = Git.open(new File(gitSpace, fileName)); map.put("updateAvailable", updateAvailable(gitObject)); } if (flags != null && flags.contains("isModified")) { Git gitObject = Git.open(new File(gitSpace, fileName)); map.put("isModified", isModified(gitObject)); } debug(fileName); FileBasedConfig fbc = new FileBasedConfig(new File(gitSpace + "/" + fileName + "/.git/config"), fs); fbc.load(); debug("FBC:" + fbc); debug("FBC:" + fbc.getSections()); debug("FBC:" + fbc.toText()); String created = fbc.getString("sw", null, "created"); SimpleDateFormat sdf = new SimpleDateFormat(m_datePattern, Locale.GERMAN); map.put("name", fileName); if (created != null) { map.put("created", sdf.parse(created).getTime()); } resList.add(map); } return resList; } catch (Exception e) { if (e instanceof RpcException) throw (RpcException) e; throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.getRepositories:", e); } finally { } }
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 www . j a va 2 s .c om 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 ww . jav a 2 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 commitAll(@PName("name") String name, @PName("message") String message) throws RpcException { try {//w ww. jav a 2 s .co m String gitSpace = System.getProperty("git.repos"); File dir = new File(gitSpace, name); if (!dir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.CommitAll:Repo(" + name + ") not exists"); } Git git = Git.open(dir); CommitCommand ic = git.commit(); ic.setAll(true); ic.setMessage(message); ic.call(); return; } catch (Exception e) { if (e instanceof RpcException) throw (RpcException) e; throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.commitAll:", e); } finally { } }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public void push(@PName("name") String name) throws RpcException { try {//ww w . j a v a 2 s.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.push:Repo(" + name + ") not exists"); } Git git = Git.open(dir); PushCommand push = git.push(); push.setRefSpecs(new RefSpec(REF_PREFIX + "master")).setRemote("origin"); //ic.setPushAll(true); Iterable<PushResult> result = null; try { result = push.call(); } catch (org.eclipse.jgit.api.errors.TransportException e) { if (e.getCause() instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) { info("Push:" + e.getCause().getMessage()); return; } else { throw e; } } for (PushResult pushResult : result) { if (StringUtils.isNotBlank(pushResult.getMessages())) { debug(pushResult.getMessages()); } } return; } catch (Exception e) { throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.push:", e); } finally { } }