Example usage for org.eclipse.jgit.api Git getRepository

List of usage examples for org.eclipse.jgit.api Git getRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git getRepository.

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

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;/* w  w  w. ja v a  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:models.PullRequestTest.java

License:Apache License

@Before
public void initRepositories() throws Exception {
    GitRepository.setRepoPrefix(REPO_PREFIX);

    app = support.Helpers.makeTestApplication();
    Helpers.start(app);/*from   ww  w .  ja  va  2  s.c  o  m*/

    Project project = Project.findByOwnerAndProjectName("yobi", "projectYobi");
    forkedProject = Project.findByOwnerAndProjectName("yobi", "projectYobi-1");

    // 1. projectYobi  
    RepositoryService.createRepository(project);

    // 2. projectYobi ?  
    {
        String localRepoPath = LOCAL_REPO_PREFIX + project.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(project))
                .setDirectory(new File(localRepoPath)).call();
        Repository repo = git.getRepository();
        baseCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncat\n", "commit 1");
        git.push().setRefSpecs(new RefSpec("+refs/heads/master:refs/heads/master")).call();
    }

    // 3. ??? ? ??  
    GitRepository.cloneLocalRepository(project, forkedProject);

    // 4. ??? ?     ? ? ? 
    {
        String localRepoPath = LOCAL_REPO_PREFIX + forkedProject.name;
        Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(forkedProject))
                .setDirectory(new File(localRepoPath)).call();
        git.branchCreate().setName("fix/1").call();
        git.checkout().setName("fix/1").call();
        Repository repo = git.getRepository();
        assertThat(repo.isBare()).describedAs("projectYobi-1 must be non-bare").isFalse();
        firstCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncorn\n", "commit 1");
        secondCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncake\n", "commit 2");
        git.push().setRefSpecs(new RefSpec("+refs/heads/fix/1:refs/heads/fix/1")).call();
    }

    // 5.   projectYobi? pullrequest .
    pullRequest = PullRequest.createNewPullRequest(forkedProject, project, "refs/heads/fix/1",
            "refs/heads/master");
    pullRequest.save();

    // 6. attempt merge
    boolean isConflict = pullRequest.updateMerge().conflicts();

    assertThat(isConflict).isFalse();
}

From source file:net.mobid.codetraq.runnables.GitChecker.java

License:Open Source License

private void attachHead(Git g, String branch) {
    LogService.writeMessage("Trying to attach HEAD to " + g.getRepository().toString());
    try {/*from  w  w  w. j a v a  2 s .com*/
        CheckoutCommand temp = g.checkout();
        temp.setCreateBranch(true);
        temp.setName("temp");
        Ref tRef = temp.call();
        CheckoutCommand b = g.checkout();
        b.setName(branch);
        b.setCreateBranch(true);
        b.call();
        MergeCommand merge = g.merge();
        merge.include(tRef);
        merge.call();
    } catch (Exception ex) {
        LogService.getLogger(GitChecker.class.getName()).log(Level.SEVERE, null, ex);
        LogService.writeLog(Level.SEVERE, ex);
    }
}

From source file:net.morimekta.idltool.cmd.RemotePublish.java

License:Apache License

@Override
public void execute(IdlTool idlTool) throws IOException, GitAPIException {
    String repository = idlTool.getIdl().getUpstreamRepository();
    File pwd = idlTool.getIdl().getWorkingGitDir();

    Git cacheRepository = idlTool.getRepositoryGitCache(repository);

    Path localIDL = pwd.toPath().resolve(Idl_Constants.IDL);
    Path localPath = localIDL.resolve(idlTool.getLocalRemoteName());

    if (!Files.exists(localPath)) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL dir in local remote location: .../" + relative);
        return;//from w  ww .  j a va  2s  .  co m
    }

    Map<String, String> localSha1sums = IdlUtils.buildSha1Sums(localPath);
    if (localSha1sums.isEmpty()) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL files in local remote location: .../" + relative);
        return;
    }

    Meta cacheMeta = IdlUtils.getMetaInRegistry(cacheRepository.getRepository());
    Remote cacheRemote = cacheMeta.hasRemotes()
            && cacheMeta.getRemotes().containsKey(idlTool.getLocalRemoteName())
                    ? cacheMeta.getRemotes().get(idlTool.getLocalRemoteName())
                    : Remote.builder().build();

    Map<String, String> publishedSha1sums = ImmutableMap.of();
    if (cacheRemote.hasShasums()) {
        publishedSha1sums = cacheMeta.getRemotes().get(idlTool.getLocalRemoteName()).getShasums();
    }

    if (localSha1sums.equals(publishedSha1sums)) {
        // No change.
        System.out.println("No change.");
        return;
    }

    Path remoteIDL = cacheRepository.getRepository().getWorkTree().toPath().resolve(Idl_Constants.IDL);
    Path remotePath = remoteIDL.resolve(idlTool.getLocalRemoteName());
    if (Files.isDirectory(remotePath)) {
        Files.list(remotePath).forEach(file -> {
            try {
                String name = file.getFileName().toString();
                if (Files.isHidden(file) || !Files.isRegularFile(file)) {
                    // Hidden and special files are ignored.
                    return;
                }
                if (!localSha1sums.containsKey(name)) {
                    Files.delete(file);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e.getMessage(), e);
            }
        });
    } else {
        Files.createDirectories(remotePath);
    }

    for (String file : localSha1sums.keySet()) {
        Path source = localPath.resolve(file);
        Path target = remotePath.resolve(file);

        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
    }

    ZonedDateTime now = ZonedDateTime.now(Clock.systemUTC());
    long timestamp = now.toInstant().toEpochMilli();
    String isoNow = DateTimeFormatter.ISO_DATE_TIME.format(now);

    Remote._Builder remoteBuilder = Remote.builder();
    remoteBuilder.setVersion(timestamp);
    remoteBuilder.setTime(timestamp);
    remoteBuilder.setShasums(localSha1sums);

    Meta._Builder metaBuilder = cacheMeta.mutate();
    metaBuilder.putInRemotes(idlTool.getLocalRemoteName(), remoteBuilder.build());
    metaBuilder.setVersion(timestamp);
    metaBuilder.setTime(isoNow);

    try (FileOutputStream out = new FileOutputStream(
            new File(cacheRepository.getRepository().getWorkTree(), Idl_Constants.META_JSON))) {
        new JsonSerializer().pretty().serialize(out, metaBuilder.build());
        out.write('\n');
    }

    Process add = Runtime.getRuntime().exec(new String[] { "git", "add", "." }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = add.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(add.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    cacheRepository.commit().setMessage("Updating " + idlTool.getLocalRemoteName() + " to latest version")
            .call();
    cacheRepository.tag().setName("v" + timestamp).setMessage(isoNow + " " + idlTool.getLocalRemoteName())
            .call();

    Process commit = Runtime.getRuntime().exec(new String[] { "git", "push" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    commit = Runtime.getRuntime().exec(new String[] { "git", "push", "--tags" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:net.rohanpm.camel.jgit.JGitConverters.java

License:Apache License

@Converter
public static Repository toRepository(Git git) {
    return git.getRepository();
}

From source file:net.yacy.grid.tools.GitTool.java

License:Open Source License

public GitTool() {
    File gitWorkDir = new File(".");
    try {//from   w ww  . jav a  2s  .co  m
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String install(String path) throws Exception {
    //staticDir.mkdirs();
    Git result = null;
    try {/* w  ww.  j a v a2s  . c  o m*/
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //make log name
        String logFile = "output.log";
        File output = new File(installLogDir, logFile);
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        String gitPath = github + path + ".git";
        logger.debug("Cloning from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        try {
            result = Git.cloneRepository().setURI(gitPath).setDirectory(destDir).call();
            result.fetch().setRemote(gitPath);
            logger.debug("Cloned " + gitPath + " repository: " + result.getRepository().getDirectory());
            FileUtils.writeStringToFile(output,
                    "DONE: Cloned " + gitPath + " repository: " + result.getRepository().getDirectory(), true);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        }
        /*try{
           //now run npm install
           runNpmInstall(output, destDir);
        }catch(Exception e){
           FileUtils.writeStringToFile(output, e.getMessage(),true);
           FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
           logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
        }*/
        return logFile;

    } finally {
        if (result != null)
            result.close();
    }

}

From source file:org.apache.maven.scm.provider.git.jgit.command.branch.JGitBranchCommand.java

License:Apache License

/**
 * {@inheritDoc}//from   w ww.  ja va2s  .  com
 */
@Override
protected ScmResult executeBranchCommand(ScmProviderRepository repo, ScmFileSet fileSet, String branch,
        String message) throws ScmException {
    if (branch == null || StringUtils.isEmpty(branch.trim())) {
        throw new ScmException("branch name must be specified");
    }

    if (!fileSet.getFileList().isEmpty()) {
        throw new ScmException("This provider doesn't support branching subsets of a directory");
    }

    Git git = null;
    try {
        git = Git.open(fileSet.getBasedir());
        Ref branchResult = git.branchCreate().setName(branch).call();
        getLogger().info("created [" + branchResult.getName() + "]");

        if (getLogger().isDebugEnabled()) {
            for (String branchName : getShortLocalBranchNames(git)) {
                getLogger().debug("local branch available: " + branchName);
            }
        }

        if (repo.isPushChanges()) {
            getLogger().info("push branch [" + branch + "] to remote...");
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo,
                    new RefSpec(Constants.R_HEADS + branch));
        }

        // search for the tagged files
        final RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(branchResult.getObjectId());
        revWalk.release();

        final TreeWalk walk = new TreeWalk(git.getRepository());
        walk.reset(); // drop the first empty tree, which we do not need here
        walk.setRecursive(true);
        walk.addTree(commit.getTree());

        List<ScmFile> files = new ArrayList<ScmFile>();
        while (walk.next()) {
            files.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();

        return new BranchScmResult("JGit branch", files);

    } catch (Exception e) {
        throw new ScmException("JGit branch failed!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.changelog.JGitChangeLogCommand.java

License:Apache License

protected ChangeLogScmResult executeChangeLogCommand(ScmProviderRepository repo, ScmFileSet fileSet,
        Date startDate, Date endDate, ScmBranch branch, String datePattern, ScmVersion startVersion,
        ScmVersion endVersion) throws ScmException {
    Git git = null;
    try {//from  w  w w . ja  v  a2s .co  m
        git = Git.open(fileSet.getBasedir());

        String startRev = startVersion != null ? startVersion.getName() : null;
        String endRev = endVersion != null ? endVersion.getName() : null;

        List<ChangeEntry> gitChanges = this.whatchanged(git.getRepository(), null, startRev, endRev, startDate,
                endDate, -1);

        List<ChangeSet> modifications = new ArrayList<ChangeSet>(gitChanges.size());

        for (ChangeEntry change : gitChanges) {
            ChangeSet scmChange = new ChangeSet();

            scmChange.setAuthor(change.getAuthorName());
            scmChange.setComment(change.getBody());
            scmChange.setDate(change.getAuthorDate());
            scmChange.setRevision(change.getCommitHash());
            // X TODO scmChange.setFiles( change.get )

            modifications.add(scmChange);
        }

        ChangeLogSet changeLogSet = new ChangeLogSet(modifications, startDate, endDate);
        changeLogSet.setStartVersion(startVersion);
        changeLogSet.setEndVersion(endVersion);

        return new ChangeLogScmResult("JGit changelog", changeLogSet);
    } catch (Exception e) {
        throw new ScmException("JGit changelog failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

/**
 * {@inheritDoc}// www  . j  av  a  2s . c  o m
 */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        ScmVersion version) throws ScmException {

    Git git = null;
    try {
        File basedir = fileSet.getBasedir();
        git = Git.open(basedir);

        boolean doCommit = false;

        if (!fileSet.getFileList().isEmpty()) {
            doCommit = JGitUtils.addAllFiles(git, fileSet).size() > 0;
        } else {
            // add all tracked files which are modified manually
            Set<String> changeds = git.status().call().getModified();
            if (changeds.isEmpty()) {
                // warn there is nothing to add
                getLogger().warn("there are no files to be added");
                doCommit = false;
            } else {
                AddCommand add = git.add();
                for (String changed : changeds) {
                    getLogger().debug("add manualy: " + changed);
                    add.addFilepattern(changed);
                    doCommit = true;
                }
                add.call();
            }
        }

        List<ScmFile> checkedInFiles = Collections.emptyList();
        if (doCommit) {
            UserInfo author = getAuthor(repo, git);
            UserInfo committer = getCommitter(repo, git);

            CommitCommand command = git.commit().setMessage(message).setAuthor(author.name, author.email);
            command.setCommitter(committer.name, committer.email);
            RevCommit commitRev = command.call();

            getLogger().info("commit done: " + commitRev.getShortMessage());
            checkedInFiles = JGitUtils.getFilesInCommit(git.getRepository(), commitRev);
            if (getLogger().isDebugEnabled()) {
                for (ScmFile scmFile : checkedInFiles) {
                    getLogger().debug("in commit: " + scmFile);
                }
            }
        }

        if (repo.isPushChanges()) {
            String branch = version != null ? version.getName() : null;
            if (StringUtils.isBlank(branch)) {
                branch = git.getRepository().getBranch();
            }
            RefSpec refSpec = new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_HEADS + branch);
            getLogger().info("push changes to remote... " + refSpec.toString());
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, refSpec);
        }

        return new CheckInScmResult("JGit checkin", checkedInFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkin failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}