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

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

Introduction

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

Prototype

public static InitCommand init() 

Source Link

Document

Return a command object to execute a init command

Usage

From source file:key.secretkey.utils.PasswordStorage.java

License:GNU General Public License

public static void createRepository(File localDir) throws Exception {
    localDir.delete();//from   www . java  2 s  . c o m

    Git.init().setDirectory(localDir).call();
    getRepository(localDir);
}

From source file:net.morimekta.gittool.GitToolTest.java

License:Apache License

@Before
public void setUp() throws IOException, GitAPIException {
    root = tmp.newFolder("repo");
    env = new HashMap<>();
    env.putAll(System.getenv());//from   w w  w  . j a  va2s .co m
    env.put("PWD", root.getCanonicalFile().getAbsolutePath());

    git = Git.init().setDirectory(root).call();
    writeContentTo("a", new File(root, "a.txt"));

    git.add().addFilepattern(".").call();
    git.commit().setMessage("First commit").call();
}

From source file:net.morimekta.idltool.IdlToolTest.java

License:Apache License

@Test
public void testListNoRepository() throws GitAPIException, URISyntaxException, IOException {
    Git.init().setDirectory(tmp.getRoot()).call();
    Git git = Git.open(tmp.getRoot());/*from w  w  w .  ja  v a 2 s  .  c om*/
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName("origin");
    remoteAddCommand.setUri(new URIish("git@github.com/morimekta/idltool.git"));
    remoteAddCommand.call();

    idl.execute("list");

    assertThat(exitCode, is(1));
    assertThat(console.output(), is(""));
    assertThat(console.error(),
            is("I/O Error: No .idlrc file at: " + tmp.getRoot().toString() + " (recursive)\n"));
}

From source file:net.openbyte.gui.WorkFrame.java

License:MIT License

private void menuItem9ActionPerformed(ActionEvent e) {
    menuItem9.setEnabled(false);//from   ww  w  . ja  va2s  .  c  o  m
    try {
        Git.init().setDirectory(this.workDirectory).call();
    } catch (GitAPIException e1) {
        e1.printStackTrace();
    }
    menu5.setEnabled(true);
}

From source file:org.apache.nifi.registry.provider.flow.git.TestGitFlowPersistenceProvider.java

License:Apache License

private void assertProvider(final Map<String, String> properties, final GitConsumer gitConsumer,
        final Consumer<GitFlowPersistenceProvider> assertion, boolean deleteDir)
        throws IOException, GitAPIException {

    final File gitDir = new File(properties.get(GitFlowPersistenceProvider.FLOW_STORAGE_DIR_PROP));
    try {/*w  w  w  . j a  v  a2  s .co m*/
        FileUtils.ensureDirectoryExistAndCanReadAndWrite(gitDir);

        try (final Git git = Git.init().setDirectory(gitDir).call()) {
            logger.debug("Initiated a git repository {}", git);
            final StoredConfig config = git.getRepository().getConfig();
            config.setString("user", null, "name", "git-user");
            config.setString("user", null, "email", "git-user@example.com");
            config.save();
            gitConsumer.accept(git);
        }

        final GitFlowPersistenceProvider persistenceProvider = new GitFlowPersistenceProvider();

        final ProviderConfigurationContext configurationContext = new StandardProviderConfigurationContext(
                properties);
        persistenceProvider.onConfigured(configurationContext);
        assertion.accept(persistenceProvider);

    } finally {
        if (deleteDir) {
            FileUtils.deleteFile(gitDir, true);
        }
    }
}

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

License:Apache License

private static void initializeGitRepository() throws ServletException {
    XacmlAdminUI.repositoryPath = Paths
            .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/* w  w w .ja va  2s .c om*/
        XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment()
                .findGitDir().setBare().build();
        if (Files.notExists(XacmlAdminUI.repositoryPath)
                || Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) {
            //
            // Create it if it doesn't exist. As a bare repository
            //
            logger.info("Creating bare git repository: " + XacmlAdminUI.repositoryPath.toString());
            XacmlAdminUI.repository.create();
            //
            // Add the magic file so remote works.
            //
            Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok");
            Files.createFile(daemon);
        }
    } catch (IOException e) {
        logger.error("Failed to build repository: " + repository, e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
    //
    // Make sure the workspace directory is created
    //
    Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE));
    workspace = workspace.toAbsolutePath();
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to build workspace: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Create the user workspace directory
    //
    workspace = Paths.get(workspace.toString(), "pe");
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Get the path to where the repository is going to be
    //
    Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        try {
            Files.createDirectory(gitPath);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + gitPath, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Initialize the domain structure
    //
    String base = null;
    String domain = XacmlAdminUI.getDomain();
    if (domain != null) {
        for (String part : Splitter.on(':').trimResults().split(domain)) {
            if (base == null) {
                base = part;
            }
            Path subdir = Paths.get(gitPath.toString(), part);
            if (Files.notExists(subdir)) {
                try {
                    Files.createDirectory(subdir);
                    Files.createFile(Paths.get(subdir.toString(), ".svnignore"));
                } catch (IOException e) {
                    logger.error("Failed to create: " + subdir, e);
                    throw new ServletException(e.getMessage(), e.getCause());
                }
            }
        }
    } else {
        try {
            Files.createFile(Paths.get(workspace.toString(), ".svnignore"));
            base = ".svnignore";
        } catch (IOException e) {
            logger.error("Failed to create file", e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    try {
        //
        // These are the sequence of commands that must be done initially to
        // finish setting up the remote bare repository.
        //
        Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call();
        git.add().addFilepattern(base).call();
        git.commit().setMessage("Initialize Bare Repository").call();
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString());
        config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
        config.save();
        git.push().setRemote("origin").add("master").call();
        /*
         * This will not work unless git.push().setRemote("origin").add("master").call();
         * is called first. Otherwise it throws an exception. However, if the push() is
         * called then calling this function seems to add nothing.
         * 
        git.branchCreate().setName("master")
           .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
           .setStartPoint("origin/master").setForce(true).call();
        */
    } catch (GitAPIException | IOException e) {
        logger.error(e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
}

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 . ja va  2  s .  c  o  m*/
                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.GitPgmCommandTest.java

License:Apache License

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

    ///*  www . jav a 2  s.c om*/
    // 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.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

public static void InitGitRepository(File gitRepoDir) throws Exception {

    try {//from  ww  w .j av  a2  s  .c o m
        Git.init().setDirectory(gitRepoDir).setBare(false).call();

    } catch (GitAPIException e) {
        String errorMsg = "Initializing local repo at " + gitRepoDir.getPath() + " failed";
        log.error(errorMsg, e);
        throw new Exception(errorMsg, e);
    }
}

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

License:Open Source License

/**
 * Create a new, local Git repository with name set to "origin"
 * @param localGitFolder//from  ww w.  j  a  v a2s. c  o m
 * @param URL online URL
 * @return The Git object
 * @throws GitAPIException
 * @throws IOException
 * @throws URISyntaxException
 */
public static Git createNewLocalGitRepository(File localGitFolder, String URL)
        throws GitAPIException, IOException, URISyntaxException {
    if (localGitFolder.exists() && localGitFolder.list().length > 0) {
        throw new IOException("Directory: " + localGitFolder + " is not empty."); //$NON-NLS-1$ //$NON-NLS-2$
    }

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(localGitFolder);
    Git git = initCommand.call();

    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName("origin"); //$NON-NLS-1$
    remoteAddCommand.setUri(new URIish(URL));
    remoteAddCommand.call();

    return git;
}