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

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

Introduction

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

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java

License:Apache License

/**
 * Initializes a user's git repository./*from w w w . j a va2s  .c  o  m*/
 * 
 * 
 * @param workspacePath
 * @param userId
 * @param email
 * @return
 * @throws IOException
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 */
private static Path initializeUserRepository(Path workspacePath, String userId, URI email)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    Path gitPath = null;
    //
    // Initialize the User's Git repository
    //
    if (Files.notExists(workspacePath)) {
        logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString());
        //
        // Create our user's directory
        //
        Files.createDirectory(workspacePath);
    }
    gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        //
        // It doesn't exist yet, so Clone it and check it out
        //
        logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString());
        Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString())
                .setDirectory(gitPath.toFile()).setNoCheckout(false).call();
        //
        // Set userid
        //
        Git git = Git.open(gitPath.toFile());
        StoredConfig config = git.getRepository().getConfig();
        config.setString("user", null, "name", userId);
        if (email != null && email.getPath() != null) {
            config.setString("user", null, "email", email.toString());
        }
        config.save();
    }
    return gitPath;
}

From source file:org.apache.sshd.git.pack.GitPackCommandTest.java

License:Apache License

@Test
public void testGitPack() throws Exception {
    Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32());

    Path targetParent = detectTargetFolder().getParent();
    Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName());

    try (SshServer sshd = setupTestServer()) {
        Path serverRootDir = gitRootDir.resolve("server");
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setCommandFactory(// w w w .j ava 2 s. com
                new GitPackCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverRootDir)));
        sshd.start();

        int port = sshd.getPort();
        try {
            Path serverDir = serverRootDir.resolve("test.git");
            Utils.deleteRecursive(serverDir);
            Git.init().setBare(true).setDirectory(serverDir.toFile()).call();

            JSch.setConfig("StrictHostKeyChecking", "no");
            CredentialsProvider.setDefault(
                    new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName()));
            SshSessionFactory.setInstance(new GitSshdSessionFactory());

            Path localRootDir = gitRootDir.resolve("local");
            Path localDir = localRootDir.resolve(serverDir.getFileName());
            Utils.deleteRecursive(localDir);
            Git.cloneRepository().setURI("ssh://" + getCurrentTestName() + "@" + TEST_LOCALHOST + ":" + port
                    + "/" + serverDir.getFileName()).setDirectory(localDir.toFile()).call();

            Git git = Git.open(localDir.toFile());
            git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            Path readmeFile = Files.createFile(localDir.resolve("readme.txt"));
            git.add().addFilepattern(readmeFile.getFileName().toString()).call();
            git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            git.pull().setRebase(true).call();
        } finally {
            sshd.stop();
        }
    }
}

From source file:org.apache.sshd.git.pgm.EmbeddedCommandRunner.java

License:Apache License

/**
 * Evaluate the {@code --git-dir} option and open the repository.
 *
 * @param gitdir//from www . j a v a  2s .co m
 *            the {@code --git-dir} option given on the command line. May be
 *            null if it was not supplied.
 * @return the repository to operate on.
 * @throws IOException
 *             the repository cannot be opened.
 */
protected Repository openGitDir(String gitdir) throws IOException {
    return Git.open(new File(gitdir)).getRepository();
    /*
    RepositoryBuilder rb = new RepositoryBuilder() //
        .setGitDir(gitdir != null ? new File(gitdir) : null) //
        .readEnvironment() //
        .findGitDir();
    if (rb.getGitDir() == null)
    throw new Die(CLIText.get().cantFindGitDirectory);
    return rb.build();
    */
}

From source file:org.apache.sshd.git.pgm.GitPgmCommandTest.java

License:Apache License

@Test
public void testGitPgm() throws Exception {
    Path targetParent = detectTargetFolder().getParent();
    Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName());

    ///* w  w w  .j  a  v a 2 s  .  co m*/
    // TODO: the GitpgmCommandFactory is kept in the test tree
    // TODO: because it's quite limited for now
    //

    try (SshServer sshd = setupTestServer()) {
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setCommandFactory(
                new GitPgmCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverDir)));
        sshd.start();

        int port = sshd.getPort();
        try {
            Utils.deleteRecursive(serverDir);

            try (SshClient client = setupTestClient()) {
                client.start();

                try (ClientSession session = client
                        .connect(getCurrentTestName(), SshdSocketAddress.LOCALHOST_IP, port)
                        .verify(7L, TimeUnit.SECONDS).getSession()) {
                    session.addPasswordIdentity(getCurrentTestName());
                    session.auth().verify(5L, TimeUnit.SECONDS);

                    Path repo = serverDir.resolve(getCurrentTestName());
                    Git.init().setDirectory(repo.toFile()).call();
                    Git git = Git.open(repo.toFile());
                    git.commit().setMessage("First Commit")
                            .setCommitter(getCurrentTestName(), "sshd@apache.org").call();

                    Path readmeFile = Files.createFile(repo.resolve("readme.txt"));
                    String commandPrefix = "git --git-dir " + repo.getFileName();
                    execute(session, commandPrefix + " add " + readmeFile.getFileName());
                    execute(session, commandPrefix + " commit -m \"readme\"");
                } finally {
                    client.stop();
                }
            }
        } finally {
            sshd.stop();
        }
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Commit a model with any changes to local repo
 * @param model/*from  w  w w .  j a va2s .  c  o m*/
 * @param localGitFolder
 * @param personIdent
 * @param commitMessage
 * @return 
 * @throws GitAPIException
 * @throws IOException
 */
public static RevCommit commitModel(IArchimateModel model, File localGitFolder, PersonIdent personIdent,
        String commitMessage) throws GitAPIException, IOException {

    GraficoModelExporter exporter = new GraficoModelExporter();
    exporter.exportModelToLocalGitRepository(model, localGitFolder);

    try (Git git = Git.open(localGitFolder)) {
        Status status = git.status().call();

        // Nothing changed
        if (status.isClean()) {
            return null;
        }

        // Add modified files to index
        AddCommand addCommand = git.add();
        addCommand.addFilepattern("."); //$NON-NLS-1$
        addCommand.setUpdate(false);
        addCommand.call();

        // Add missing files to index
        for (String s : status.getMissing()) {
            git.rm().addFilepattern(s).call();
        }

        // Commit
        CommitCommand commitCommand = git.commit();
        commitCommand.setAuthor(personIdent);
        commitCommand.setMessage(commitMessage);
        return commitCommand.call();
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Push to Remote/*from  w  w  w.j  a  v a  2  s  . co m*/
 * @param localGitFolder
 * @param userName
 * @param userPassword
 * @return 
 * @throws IOException
 * @throws GitAPIException
 */
public static Iterable<PushResult> pushToRemote(File localGitFolder, String userName, String userPassword,
        ProgressMonitor monitor) throws IOException, GitAPIException {
    try (Git git = Git.open(localGitFolder)) {
        PushCommand pushCommand = git.push();
        pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
        pushCommand.setProgressMonitor(monitor);
        return pushCommand.call();
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Pull from Remote//w w  w .ja  va 2 s .c  om
 * @param localGitFolder
 * @param userName
 * @param userPassword
 * @return 
 * @throws IOException
 * @throws GitAPIException
 */
public static PullResult pullFromRemote(File localGitFolder, String userName, String userPassword,
        ProgressMonitor monitor) throws IOException, GitAPIException {
    try (Git git = Git.open(localGitFolder)) {
        PullCommand pullCommand = git.pull();
        pullCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
        pullCommand.setRebase(false); // Merge, not rebase
        pullCommand.setProgressMonitor(monitor);
        return pullCommand.call();
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Fetch from Remote/*from w  w  w . jav a 2  s . c o m*/
 * @param localGitFolder
 * @param userName
 * @param userPassword
 * @throws IOException
 * @throws GitAPIException
 */
public static FetchResult fetchFromRemote(File localGitFolder, String userName, String userPassword,
        ProgressMonitor monitor) throws IOException, GitAPIException {
    try (Git git = Git.open(localGitFolder)) {
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
        fetchCommand.setProgressMonitor(monitor);
        return fetchCommand.call();
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Return the URL of the Git repo, taken from local config file.
 * We assume that there is only one remote per repo, and its name is "origin"
 * @param localGitFolder/*from   w w w. ja v  a 2s  .  c o m*/
 * @return The URL or null if not found
 * @throws IOException
 */
public static String getRepositoryURL(File localGitFolder) throws IOException {
    try (Git git = Git.open(localGitFolder)) {
        return git.getRepository().getConfig().getString("remote", "origin", "url"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }
}

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Retune the contents of a file in the repo given its ref
 * Ref could be "HEAD" or "origin/master" for example
 * @param localGitFolder//from   w  ww.  ja va  2  s  . c o  m
 * @param path
 * @param ref
 * @return
 * @throws IOException
 */
public static String getFileContents(File localGitFolder, String path, String ref) throws IOException {
    String str = ""; //$NON-NLS-1$

    try (Repository repository = Git.open(localGitFolder).getRepository()) {
        ObjectId lastCommitId = repository.resolve(ref);

        try (RevWalk revWalk = new RevWalk(repository)) {
            RevCommit commit = revWalk.parseCommit(lastCommitId);
            RevTree tree = commit.getTree();

            // now try to find a specific file
            try (TreeWalk treeWalk = new TreeWalk(repository)) {
                treeWalk.addTree(tree);
                treeWalk.setRecursive(true);
                treeWalk.setFilter(PathFilter.create(path));

                if (!treeWalk.next()) {
                    return Messages.GraficoUtils_2;
                }

                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = repository.open(objectId);

                str = new String(loader.getBytes());
            }

            revWalk.dispose();
        }
    }

    return str;
}