List of usage examples for org.eclipse.jgit.lib Repository close
@Override public void close()
Decrement the use count, and maybe close resources.
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.SubmoduleTest.java
License:Apache License
/** * Test loading mapping for submodules//from w w w . ja v a 2 s.com * * @throws IOException if there is IO problem */ @Test public void testSubmoduleMapping() throws Exception { File masterRep = dataFile("repo.git"); Repository r = new RepositoryBuilder().setGitDir(masterRep).build(); try { SubmodulesConfig s = new SubmodulesConfig(r.getConfig(), new BlobBasedConfig(null, r, r.resolve(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_ADDED_VERSION)), ".gitmodules")); assertTrue(s.isSubmodulePrefix("")); assertFalse(s.isSubmodulePrefix("submodule")); Submodule m = s.findSubmodule("submodule"); assertEquals(m.getName(), "submodule"); assertEquals(m.getPath(), "submodule"); assertEquals(m.getUrl(), "../submodule.git"); } finally { r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.SubmoduleTest.java
License:Apache License
/** * Test loading mapping for submodules/* ww w .j a va2 s .co m*/ * * @throws IOException if there is IO problem */ @Test public void testSubmoduleMultiEntryMapping() throws Exception { File masterRep = dataFile("repo.git"); File submodulesFile = dataFile("content", "dotgitmodules"); Repository r = new RepositoryBuilder().setGitDir(masterRep).build(); try { FileBasedConfig config = new FileBasedConfig(null, submodulesFile, FS.DETECTED); config.load(); SubmodulesConfig s = new SubmodulesConfig(r.getConfig(), config); assertTrue(s.isSubmodulePrefix("")); assertFalse(s.isSubmodulePrefix("c/")); Submodule m = s.findSubmodule("b"); assertEquals(m.getName(), "b"); assertEquals(m.getPath(), "b"); assertEquals(m.getUrl(), "git@gitrep:/git/b.git"); m = s.findSubmodule("c/D"); assertEquals(m.getName(), "c/D"); assertEquals(m.getPath(), "c/D"); assertEquals(m.getUrl(), "git@gitrep:/git/d.git"); } finally { r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.SubmoduleTest.java
License:Apache License
/** * Test tree walk over submodules/* ww w . j ava2 s . com*/ * * @throws IOException in case of test failure */ @Test public void testSubmoduleTreeWalk() throws IOException { File masterRep = dataFile("repo.git"); Repository rm = new RepositoryBuilder().setGitDir(masterRep).build(); try { File submoduleRep = dataFile("submodule.git"); final Repository rs = new RepositoryBuilder().setGitDir(submoduleRep).build(); RevWalk revWalk = new RevWalk(rm); try { final RevCommit submoduleTxtAdded = revWalk.parseCommit(ObjectId .fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_TXT_ADDED_VERSION))); final RevCommit submoduleModified = revWalk.parseCommit(ObjectId .fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_MODIFIED_VERSION))); final RevCommit submoduleAdded = revWalk.parseCommit( ObjectId.fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_ADDED_VERSION))); final RevCommit beforeSubmoduleAdded = revWalk.parseCommit(ObjectId .fromString(GitUtils.versionRevision(GitVcsSupportTest.BEFORE_SUBMODULE_ADDED_VERSION))); SubmoduleResolverImpl r = new MySubmoduleResolver( myGitSupport.createContext(vcsRoot().withFetchUrl("whatever").build(), "testing"), myCommitLoader, rm, submoduleAdded, rs); TreeWalk tw = new TreeWalk(rm); tw.setRecursive(true); tw.reset(); tw.addTree(create(rm, beforeSubmoduleAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true)); tw.addTree(create(rm, submoduleAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true)); tw.setFilter(TreeFilter.ANY_DIFF); checkElement(tw, ".gitmodules"); assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rm); checkElement(tw, "submodule/file.txt"); assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rs); assertFalse(tw.next()); tw.reset(); tw.addTree(create(rm, submoduleModified, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true)); tw.addTree(create(rm, submoduleTxtAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true)); tw.setFilter(TreeFilter.ANY_DIFF); checkElement(tw, "submodule.txt"); assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rm); checkElement(tw, "submodule/new file.txt"); assertSame(tw.getTree(0, SubmoduleAwareTreeIterator.class).getRepository(), rs); assertFalse(tw.next()); } finally { rs.close(); } } finally { rm.close(); } }
From source file:main.Repositories.java
/** * Get the files from a given repository on github * @param localPath The folder on disk where the files will be placed * @param location The username/repository identification. We'd * expect something like triplecheck/reporter *///from ww w. jav a 2s . c om public void download(final File localPath, final String location) { // we can't have any older files files.deleteDir(localPath); final String REMOTE_URL = "https://github.com/" + location + ".git"; try { Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath).call(); // now open the created repository FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); System.out.println("Downloaded repository: " + repository.getDirectory()); repository.close(); } catch (IOException ex) { Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex); } catch (GitAPIException ex) { Logger.getLogger(Repositories.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("--> " + location); }
From source file:me.cmoz.gradle.snapshot.GitSCMCommand.java
License:Apache License
@Override @SneakyThrows(IOException.class) public Commit getLatestCommit(@NonNull final String dateFormat) { if (repoDir == null) { throw new IllegalStateException("'.git' folder could not be found."); }// www. j a va 2 s.com final FileRepositoryBuilder builder = new FileRepositoryBuilder(); final Repository repo = builder.setGitDir(repoDir).readEnvironment().build(); final StoredConfig conf = repo.getConfig(); int abbrev = Commit.ABBREV_LENGTH; if (conf != null) { abbrev = conf.getInt("core", "abbrev", abbrev); } final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); final Ref HEAD = repo.getRef(Constants.HEAD); if (HEAD.getObjectId() == null) { throw new RuntimeException("Could not find any commits from HEAD ref."); } final RevWalk revWalk = new RevWalk(repo); if (HEAD.getObjectId() == null) { throw new RuntimeException("Could not find any commits from HEAD ref."); } final RevCommit revCommit = revWalk.parseCommit(HEAD.getObjectId()); revWalk.markStart(revCommit); try { // git commit time in sec and java datetime is in ms final Date commitTime = new Date(revCommit.getCommitTime() * 1000L); final PersonIdent ident = revCommit.getAuthorIdent(); final UserConfig userConf = conf.get(UserConfig.KEY); return Commit.builder().buildTime(sdf.format(new Date())).buildAuthorName(userConf.getAuthorName()) .buildAuthorEmail(userConf.getAuthorEmail()).branchName(repo.getBranch()) .commitId(revCommit.getName()).commitTime(sdf.format(commitTime)) .commitUserName(ident.getName()).commitUserEmail(ident.getEmailAddress()) .commitMessage(revCommit.getFullMessage().trim()).build(); } finally { revWalk.dispose(); repo.close(); } }
From source file:model.Buildmodel.java
public int build(Git git, List<RevCommit> logs, RepoSettings rs) throws NoHeadException, GitAPIException, IOException { //ObjectId lastCommitId = repository.resolve(Constants.MASTER); ObjectId parentid = null;/*from w w w .ja va 2 s .c o m*/ ObjectId currid = null; Repository repository = git.getRepository(); //a new reader to read objects from getObjectDatabase() ObjectReader reader = repository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); List<DiffEntry> diffs = null; WriteData wd = new WriteData(); //Class to write data to an external file wd.initiate(rs); int cnt = 0; //Commits count that is written in data for (RevCommit rev : logs) { if (rev.getParentCount() == 1) { //Not taking Merge commits, for taking them make it >= . try { parentid = repository.resolve(rev.getParent(0).getName() + "^{tree}"); currid = repository.resolve(rev.getName() + "^{tree}"); //Reset this parser to walk through the given tree oldTreeIter.reset(reader, parentid); newTreeIter.reset(reader, currid); diffs = git.diff() //Returns a command object to execute a diff command .setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); //returns a DiffEntry for each path which is different } catch (RevisionSyntaxException | IOException | GitAPIException e) { e.printStackTrace(); } ByteArrayOutputStream out = new ByteArrayOutputStream(); //Create a new formatter with a default level of context. DiffFormatter df = new DiffFormatter(out); //Set the repository the formatter can load object contents from. df.setRepository(git.getRepository()); ArrayList<String> diffText = new ArrayList<String>(); ArrayList<String> filetypes = new ArrayList<String>(); //A DiffEntry is 'A value class representing a change to a file' therefore for each file you have a diff entry. int ovllineadd = 0; int ovllinerem = 0; int totallinechanged = 0; int totalfilrem = 0; int totalfiladd = 0; for (DiffEntry diff : diffs) { try { df.format(diff); //Format a patch script for one file entry. RawText r = new RawText(out.toByteArray()); r.getLineDelimiter(); diffText.add(out.toString()); String st = out.toString(); String filetype = null; int filerem = 0, fileadd = 0, filtyp = 0; ; int lineadd = 0, linerem = 0; String[] temp = st.split("\n"); for (String tem : temp) { if (tem.startsWith("---") || tem.startsWith("+++")) { if (tem.startsWith("---")) { if (tem.endsWith("null")) { fileadd++; //File added } else { int p = tem.lastIndexOf("/"); if (p >= 0) { tem = tem.substring(p + 1, tem.length()); } int h = tem.lastIndexOf("."); if (h >= 0) { filetype = tem.substring(h, tem.length()); filetype = filetype.replace(" ", ""); filetype = filetype.replace("\"", ""); if (filtyp != 1) { filetypes.add(filetype); filtyp = 1; } } else { //README, LICENSE type wanna do? } } } if (tem.startsWith("+++")) { if (tem.endsWith("null")) { filerem++; //Fil removed } else { int p = tem.lastIndexOf("/"); if (p >= 0) { tem = tem.substring(p + 1, tem.length()); } int h = tem.lastIndexOf("."); if (h >= 0) { filetype = tem.substring(h, tem.length()); filetype = filetype.replace(" ", ""); filetype = filetype.replace("\"", ""); if (filtyp != 1) { filetypes.add(filetype); filtyp = 1; } } else { //README, LICENSE type wanna do? } } } } if (tem.startsWith("+") && !tem.startsWith("+++")) { lineadd++; } else if (tem.startsWith("-") && !tem.startsWith("---")) { linerem++; } } ovllineadd += lineadd; ovllinerem += linerem; totallinechanged += (lineadd + linerem); totalfiladd += fileadd; totalfilrem += filerem; out.reset(); } catch (IOException e) { e.printStackTrace(); } } PersonIdent p = rev.getAuthorIdent(); //DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); DateFormat formatter = new SimpleDateFormat("HH"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); String email = p.getEmailAddress(); //So that email folder is created properly if (email.contains("://") || email.contains("//")) { email = email.replace(":", ""); email = email.replace("//", ""); } String[] commsgwords = rev.getFullMessage().split(" "); wd.write(rev.getName(), email, totallinechanged, ovllineadd, ovllinerem, filetypes.size(), totalfiladd, totalfilrem, Integer.parseInt(formatter.format(p.getWhen())), filetypes, commsgwords.length); cnt++; } } repository.close(); return cnt; }
From source file:net.aprendizajengrande.gitrecommender.ExtractLog.java
License:Open Source License
public static void main(String[] args) throws Exception { FileRepositoryBuilder builder = new FileRepositoryBuilder(); System.out.println("Git dir: " + args[0]); Repository repository = builder.setGitDir(new File(args[0])).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build();//from w ww . j a v a 2s. c o m Git git = new Git(repository); Iterable<RevCommit> log = git.log().call(); RevCommit previous = null; String previousAuthor = null; // author -> file -> counts Map<String, Map<String, Counter>> counts = new HashMap<>(); Map<String, Counter> commitCounts = new HashMap<>(); // author -> counts Map<String, Integer> authorIds = new HashMap<>(); Map<String, Integer> fileIds = new HashMap<>(); List<String> authors = new ArrayList<>(); List<String> files = new ArrayList<>(); int commitNum = 0; for (RevCommit commit : log) { commitNum++; if (commitNum % 1000 == 0) { System.out.println(commitNum); // compute affinity for files as % of commits that touch that // file PrintWriter pw = new PrintWriter(args[1] + "." + commitNum + ".dat"); for (String author : commitCounts.keySet()) { double totalCommits = commitCounts.get(author).intValue(); for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) { pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t" + ((c.getValue().intValue() / totalCommits) * 10000) + "\t" + c.getValue().intValue()); } } pw.close(); pw = new PrintWriter(args[1] + "." + commitNum + ".users"); int id = 1; for (String author : authors) { pw.println(id + "\t" + author); id++; } pw.close(); pw = new PrintWriter(args[1] + "." + commitNum + ".files"); id = 1; for (String file : files) { pw.println(id + "\t" + file); id++; } pw.close(); } // System.out.println("Author: " + // commit.getAuthorIdent().getName()); String author = commit.getAuthorIdent().getName(); if (!counts.containsKey(author)) { counts.put(author, new HashMap<String, Counter>()); commitCounts.put(author, new Counter(1)); authorIds.put(author, authorIds.size() + 1); authors.add(author); } else { commitCounts.get(author).inc(); } if (previous != null) { AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, previous); AbstractTreeIterator newTreeParser = prepareTreeParser(repository, commit); // then the procelain diff-command returns a list of diff // entries List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call(); for (DiffEntry entry : diff) { // System.out.println("\tFile: " + entry.getNewPath()); String file = entry.getNewPath(); if (!fileIds.containsKey(file)) { fileIds.put(file, fileIds.size() + 1); files.add(file); } if (!counts.get(previousAuthor).containsKey(file)) { counts.get(previousAuthor).put(file, new Counter(1)); } else { counts.get(previousAuthor).get(file).inc(); } } // diff.dispose(); // previous.dispose(); } previous = commit; previousAuthor = author; } // compute affinity for files as % of commits that touch that file PrintWriter pw = new PrintWriter(args[1] + ".dat"); for (String author : commitCounts.keySet()) { double totalCommits = commitCounts.get(author).intValue(); for (Map.Entry<String, Counter> c : counts.get(author).entrySet()) { pw.println(authorIds.get(author) + "\t" + fileIds.get(c.getKey()) + "\t" + ((c.getValue().intValue() / totalCommits) * 10000) + "\t" + c.getValue().intValue()); } } pw.close(); pw = new PrintWriter(args[1] + ".users"); int id = 1; for (String author : authors) { pw.println(id + "\t" + author); id++; } pw.close(); pw = new PrintWriter(args[1] + ".files"); id = 1; for (String file : files) { pw.println(id + "\t" + file); id++; } pw.close(); repository.close(); }
From source file:net.aprendizajengrande.gitrecommender.UpdateLog.java
License:Open Source License
public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("Usage: UpdateLog <git dir> <db dir>"); System.exit(-1);/*from ww w. ja va 2 s. co m*/ } File gitDir = new File(args[0]); File dbDir = new File(args[1]); DB db = new DB(dbDir); System.out.println("Git dir: " + gitDir); System.out.println("DB dir: " + dbDir); FileRepositoryBuilder builder = new FileRepositoryBuilder(); // scan environment GIT_* variables Repository repository = builder.setGitDir(gitDir).readEnvironment().findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); Iterable<RevCommit> log = git.log().call(); // go through all commits and process them in reverse order List<RevCommit> allCommits = new ArrayList<RevCommit>(); int newCommits = 0; boolean seen = false; for (RevCommit commit : log) { String name = commit.name(); if (db.lastCommit().equals(name)) { seen = true; } if (!seen) newCommits++; allCommits.add(commit); } System.out.println("Found " + allCommits.size() + " commits (" + newCommits + " new)."); int commitNum = 0; List<Integer> files = new ArrayList<Integer>(); for (int i = newCommits - 1; i >= 0; i--) { if (commitNum % 500 == 0) db.save(); RevCommit commit = allCommits.get(i); String author = commit.getAuthorIdent().getName(); int authorId = db.idAuthor(author); files.clear(); if (i < allCommits.size() - 1) { AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, allCommits.get(i + 1)); AbstractTreeIterator newTreeParser = prepareTreeParser(repository, commit); // then the procelain diff-command returns a list of diff // entries List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).setNewTree(newTreeParser).call(); for (DiffEntry entry : diff) { // System.out.println("\tFile: " + entry.getNewPath()); String file = entry.getNewPath(); files.add(db.idFile(file)); } } db.observeCommit(commit.name(), authorId, files); } db.save(); repository.close(); }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java
License:Apache License
@Test public void testOpenExistingRepository() throws Exception { final String REPO_NAME = "testOpenExistingRepository"; File expected = new File(reposDir, REPO_NAME + Constants.DOT_GIT_EXT); if (!expected.exists()) { Repository repo = new FileRepository(expected); try {//from w w w . j a v a 2s .c o m repo.create(true); } finally { repo.close(); } } else { assertTrue("Test repo not a folder: " + expected, expected.isDirectory()); } for (String ext : TEST_EXTS) { Repository repo = resolver.open(null, REPO_NAME + ext); assertNotNull("No resolution result for ext=" + ext, repo); try { File actual = repo.getDirectory(); assertEquals("Mismatched resolved location for ext=" + ext, expected, actual); } finally { repo.close(); } } }
From source file:net.community.chest.gitcloud.facade.backend.git.BackendRepositoryResolverTest.java
License:Apache License
@Test public void testOpenNonExistingRepository() throws Exception { final String REPO_NAME = "testOpenNonExistingRepository"; File gitDir = new File(reposDir, REPO_NAME + Constants.DOT_GIT_EXT); FileUtils.deleteDirectory(gitDir);/*ww w . j av a 2 s. c o m*/ assertFalse("Failed to delete " + gitDir, gitDir.exists()); for (String ext : TEST_EXTS) { try { Repository repo = resolver.open(null, REPO_NAME + ext); try { fail("Unexpected success for ext=" + ext + ": " + repo.getDirectory()); } finally { repo.close(); } } catch (RepositoryNotFoundException e) { // expected - ignored } } }