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:io.fabric8.git.zkbridge.BridgeTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());/*from www .  j  av  a 2  s.c om*/
    delete(sfb.getDataLogDir());
    sfb.afterPropertiesSet();

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString("localhost:" + sfb.getClientPortAddress().getPort())
            .retryPolicy(new RetryOneTime(1000)).connectionTimeoutMs(360000);

    curator = builder.build();
    curator.start();
    curator.getZookeeperClient().blockUntilConnectedOrTimedOut();

    File root = new File(System.getProperty("basedir", ".") + "/target/git").getCanonicalFile();
    delete(root);

    new File(root, "remote").mkdirs();
    remote = Git.init().setDirectory(new File(root, "remote")).call();
    remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();

    new File(root, "local").mkdirs();
    git = Git.init().setDirectory(new File(root, "local")).call();
    git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", "file://" + new File(root, "remote").getCanonicalPath());
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

}

From source file:io.fabric8.maven.CreateBranchMojo.java

License:Apache License

protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();// w  w w.  j  a  va2  s . c om
    File gitDir = new File(buildDir, ".git");
    if (!gitDir.exists()) {
        String repo = gitUrl;
        if (Strings.isNotBlank(repo)) {
            getLog().info("Cloning git repo " + repo + " into directory " + getGitBuildPathDescription()
                    + " cloneAllBranches: " + cloneAll);
            CloneCommand command = Git.cloneRepository().setCloneAllBranches(cloneAll).setURI(repo)
                    .setDirectory(buildDir).setRemote(remoteName);
            // .setCredentialsProvider(getCredentials()).
            try {
                git = command.call();
                return;
            } catch (Throwable e) {
                getLog().error("Failed to command remote repo " + repo + " due: " + e.getMessage(), e);
                // lets just use an empty repo instead
            }
        } else {
            InitCommand initCommand = Git.init();
            initCommand.setDirectory(buildDir);
            git = initCommand.call();
            getLog().info("Initialised an empty git configuration repo at " + getGitBuildPathDescription());

            // lets add a dummy file
            File readMe = new File(buildDir, "ReadMe.md");
            getLog().info("Generating " + readMe);
            Files.writeToFile(readMe, "fabric8 git repository created by fabric8-maven-plugin at " + new Date(),
                    Charset.forName("UTF-8"));
            git.add().addFilepattern("ReadMe.md").call();
            commit("Initial commit");
        }
        String branch = git.getRepository().getBranch();
        configureBranch(branch);
    } else {
        getLog().info("Reusing existing git repository at " + getGitBuildPathDescription());

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);
        if (pullOnStartup) {
            doPull();
        } else {
            getLog().info("git pull from remote config repo on startup is disabled");
        }
    }
}

From source file:io.fabric8.openshift.OpenShiftPomDeployerTest.java

License:Apache License

protected void doTest(String folder, String[] artifactUrls, String[] repoUrls,
        String expectedCamelDependencyScope, String expectedHawtioDependencyScope) throws Exception {
    File sourceDir = new File(baseDir, "src/test/resources/" + folder);
    assertDirectoryExists(sourceDir);// ww  w .  ja  va  2s  . co m
    File pomSource = new File(sourceDir, "pom.xml");
    assertFileExists(pomSource);

    File outputDir = new File(baseDir, "target/" + getClass().getName() + "/" + folder);
    outputDir.mkdirs();
    assertDirectoryExists(outputDir);
    File pom = new File(outputDir, "pom.xml");
    Files.copy(pomSource, pom);
    assertFileExists(pom);

    git = Git.init().setDirectory(outputDir).call();
    assertDirectoryExists(new File(outputDir, ".git"));

    git.add().addFilepattern("pom.xml").call();
    git.commit().setMessage("Initial import").call();

    // now we have the git repo setup; lets run the update
    OpenShiftPomDeployer deployer = new OpenShiftPomDeployer(git, outputDir, deployDir, webAppDir);
    System.out.println("About to update the pom " + pom + " with artifacts: " + Arrays.asList(artifactUrls));

    List<Parser> artifacts = new ArrayList<Parser>();
    for (String artifactUrl : artifactUrls) {
        artifacts.add(Parser.parsePathWithSchemePrefix(artifactUrl));
    }
    List<MavenRepositoryURL> repos = new ArrayList<MavenRepositoryURL>();
    for (String repoUrl : repoUrls) {
        repos.add(new MavenRepositoryURL(repoUrl));
    }
    deployer.update(artifacts, repos);

    System.out.println("Completed the new pom is: ");
    System.out.println(Files.toString(pom));

    Document xml = XmlUtils.parseDoc(pom);
    Element plugins = assertXPathElement(xml, "project/profiles/profile[id = 'openshift']/build/plugins");

    Element cleanExecution = assertXPathElement(plugins,
            "plugin[artifactId = 'maven-clean-plugin']/executions/execution[id = 'fuse-fabric-clean']");

    Element dependencySharedExecution = assertXPathElement(plugins,
            "plugin[artifactId = 'maven-dependency-plugin']/executions/execution[id = 'fuse-fabric-deploy-shared']");

    Element dependencyWebAppsExecution = assertXPathElement(plugins,
            "plugin[artifactId = 'maven-dependency-plugin']/executions/execution[id = 'fuse-fabric-deploy-webapps']");

    Element warPluginWarName = xpath("plugin[artifactId = 'maven-war-plugin']/configuration/warName")
            .element(plugins);
    if (warPluginWarName != null) {
        String warName = warPluginWarName.getTextContent();
        System.out.println("WarName is now:  " + warName);
        assertTrue("Should not have ROOT war name", !"ROOT".equals(warName));
    }

    Element dependencies = assertXPathElement(xml, "project/dependencies");
    Element repositories = assertXPathElement(xml, "project/repositories");

    for (Parser artifact : artifacts) {
        // lets check there's only 1 dependency for group & artifact and it has the right version
        String group = groupId(artifact);
        String artifactId = artifact.getArtifact();
        Element dependency = assertSingleDependencyForGroupAndArtifact(dependencies, group, artifactId);
        Element version = assertXPathElement(dependency, "version");
        assertEquals("Version", artifact.getVersion(), version.getTextContent());
    }

    // lets check we either preserve scope, add provided or don't add a scope if there's none present in the underlying pom
    assertDependencyScope(dependencies, "org.apache.camel", "camel-core", expectedCamelDependencyScope);
    assertDependencyScope(dependencies, "org.drools", "drools-wb-distribution-wars", "provided");
    assertDependencyScope(dependencies, "io.hawt", "hawtio-web", expectedHawtioDependencyScope);

    assertRepositoryUrl(repositories, "http://repository.jboss.org/nexus/content/groups/public/");
    assertRepositoryUrl(repositories, "https://repo.fusesource.com/nexus/content/groups/ea/");
}

From source file:io.fabric8.profiles.containers.GitRemoteProcessor.java

License:Apache License

@Override
public void process(String name, Properties config, Path containerDir) throws IOException {
    // get or create remote repo URL
    String remoteUri = config.getProperty(GIT_REMOTE_URI_PROPERTY);
    if (remoteUri == null || remoteUri.isEmpty()) {
        remoteUri = getRemoteUri(config, name);
    }/*from w w w  .j  a v a2  s. c  om*/

    // try to clone remote repo in temp dir
    String remote = config.getProperty(GIT_REMOTE_NAME_PROPERTY, Constants.DEFAULT_REMOTE_NAME);
    Path tempDirectory = null;
    try {
        tempDirectory = Files.createTempDirectory(containerDir, "cloned-remote-");
    } catch (IOException e) {
        throwException("Error creating temp directory while cloning ", remoteUri, e);
    }

    final String userName = config.getProperty("gogsUsername");
    final String password = config.getProperty("gogsPassword");
    final UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            userName, password);

    Git clonedRepo = null;
    try {
        try {
            clonedRepo = Git.cloneRepository().setDirectory(tempDirectory.toFile()).setBranch(currentVersion)
                    .setRemote(remote).setURI(remoteUri).setCredentialsProvider(credentialsProvider).call();
        } catch (InvalidRemoteException e) {
            // TODO handle creating new remote repo in github, gogs, etc. using fabric8 devops connector
            if (e.getCause() instanceof NoRemoteRepositoryException) {
                final String address = "http://" + config.getProperty("gogsServiceHost", "gogs.vagrant.f8");

                GitRepoClient client = new GitRepoClient(address, userName, password);

                CreateRepositoryDTO request = new CreateRepositoryDTO();
                request.setName(name);
                request.setDescription("Fabric8 Profiles generated project for container " + name);
                RepositoryDTO repository = client.createRepository(request);

                // create new repo with Gogs clone URL
                clonedRepo = Git.init().setDirectory(tempDirectory.toFile()).call();
                final RemoteAddCommand remoteAddCommand = clonedRepo.remoteAdd();
                remoteAddCommand.setName(remote);
                try {
                    remoteAddCommand.setUri(new URIish(repository.getCloneUrl()));
                } catch (URISyntaxException e1) {
                    throwException("Error creating remote repo ", repository.getCloneUrl(), e1);
                }
                remoteAddCommand.call();

                // add currentVersion branch
                clonedRepo.add().addFilepattern(".").call();
                clonedRepo.commit().setMessage("Adding version " + currentVersion).call();
                try {
                    clonedRepo.branchRename().setNewName(currentVersion).call();
                } catch (RefAlreadyExistsException ignore) {
                    // ignore
                }

            } else {
                throwException("Error cloning ", remoteUri, e);
            }
        }

        // handle missing remote branch
        if (!clonedRepo.getRepository().getBranch().equals(currentVersion)) {
            clonedRepo.branchCreate().setName(currentVersion)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
        }

        // move .git dir to parent and drop old source altogether
        // TODO things like .gitignore, etc. need to be handled, perhaps through Profiles??
        Files.move(tempDirectory.resolve(".git"), containerDir.resolve(".git"));

    } catch (GitAPIException e) {
        throwException("Error cloning ", remoteUri, e);
    } catch (IOException e) {
        throwException("Error copying files from ", remoteUri, e);
    } finally {
        // close clonedRepo
        if (clonedRepo != null) {
            try {
                clonedRepo.close();
            } catch (Exception ignored) {
            }
        }
        // cleanup tempDirectory
        try {
            ProfilesHelpers.deleteDirectory(tempDirectory);
        } catch (IOException e) {
            // ignore
        }
    }

    try (Git containerRepo = Git.open(containerDir.toFile())) {

        // diff with remote
        List<DiffEntry> diffEntries = containerRepo.diff().call();
        if (!diffEntries.isEmpty()) {

            // add all changes
            containerRepo.add().addFilepattern(".").call();

            // with latest Profile repo commit ID in message
            // TODO provide other identity properties
            containerRepo.commit().setMessage("Container updated for commit " + currentCommitId).call();

            // push to remote
            containerRepo.push().setRemote(remote).setCredentialsProvider(credentialsProvider).call();
        } else {
            LOG.debug("No changes to container" + name);
        }

    } catch (GitAPIException e) {
        throwException("Error processing container Git repo ", containerDir, e);
    } catch (IOException e) {
        throwException("Error reading container Git repo ", containerDir, e);
    }
}

From source file:io.fabric8.profiles.PluginTestHelpers.java

License:Apache License

public static Git initRepo(Path sourceDirectory) throws GitAPIException {
    Git sourceRepo = Git.init().setDirectory(sourceDirectory.toFile()).call();
    sourceRepo.add().addFilepattern(".").call();
    sourceRepo.commit().setMessage("Adding version 1.0").call();
    try {//from www  .j  a v a 2  s .  c  o m
        sourceRepo.branchRename().setNewName("1.0").call();
    } catch (RefAlreadyExistsException ignore) {
        // ignore
    }

    return sourceRepo;
}

From source file:io.fabric8.project.support.BuildConfigHelper.java

License:Apache License

public static CreateGitProjectResults importNewGitProject(KubernetesClient kubernetesClient,
        UserDetails userDetails, File basedir, String namespace, String projectName, String origin,
        String message, boolean apply) throws GitAPIException, JsonProcessingException {
    GitUtils.disableSslCertificateChecks();

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);//from  w ww .  j a va  2  s.co m
    Git git = initCommand.call();
    LOG.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());

    PersonIdent personIdent = userDetails.createPersonIdent();

    String user = userDetails.getUser();
    String address = userDetails.getAddress();
    String internalAddress = userDetails.getInternalAddress();
    String branch = userDetails.getBranch();

    // lets create the repository
    GitRepoClient repoClient = userDetails.createRepoClient();
    CreateRepositoryDTO createRepository = new CreateRepositoryDTO();
    createRepository.setName(projectName);

    String fullName = null;
    RepositoryDTO repository = repoClient.createRepository(createRepository);
    if (repository != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Got repository: " + toJson(repository));
        }
        fullName = repository.getFullName();
    }
    if (Strings.isNullOrBlank(fullName)) {
        fullName = user + "/" + projectName;
    }

    String htmlUrl = URLUtils.pathJoin(address, user, projectName);
    String remoteUrl = URLUtils.pathJoin(internalAddress, user, projectName + ".git");
    String cloneUrl = htmlUrl + ".git";

    // now lets import the code and publish
    LOG.info("Using remoteUrl: " + remoteUrl + " and remote name " + origin);
    GitUtils.configureBranch(git, branch, origin, remoteUrl);

    GitUtils.addDummyFileToEmptyFolders(basedir);
    LOG.info("About to git commit and push to: " + remoteUrl + " and remote name " + origin);
    GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true);

    BuildConfig buildConfig;
    if (apply) {
        buildConfig = createAndApplyBuildConfig(kubernetesClient, namespace, projectName, cloneUrl);
    } else {
        buildConfig = createBuildConfig(kubernetesClient, namespace, projectName, cloneUrl);
    }
    return new CreateGitProjectResults(buildConfig, fullName, htmlUrl, remoteUrl, cloneUrl);
}

From source file:io.fabric8.vertx.maven.plugin.it.ExtraManifestInfoIT.java

License:Apache License

private Git prepareGitSCM(File testDir, Verifier verifier) throws IOException, GitAPIException {
    Git git = Git.init().setDirectory(testDir).call();
    File gitFolder = GitUtil.findGitFolder(testDir);
    assertThat(gitFolder).isNotNull();/*w w  w.j  av  a  2 s .co  m*/
    return git;
}

From source file:io.github.gitfx.util.GitFXGsonUtil.java

License:Apache License

public static void initializeGitRepository(String serverName, String projectName, String projectPath) {
    try {/*  www. j a v a  2  s.  com*/
        File localPath = new File(projectPath);
        Git git;
        git = Git.init().setDirectory(localPath).call();
        git.close();
    } catch (GitAPIException e) {
        logger.debug("Error creating Git repository", e.getMessage());
    }
}

From source file:io.syndesis.git.GitWorkflow.java

License:Apache License

/**
 * Creates a new remote git repository and does the initial commit&push of all the project files
 * the files to it./*w  ww  .jav a  2s  . c  o  m*/
 *
 * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository
 * @param repoName              - the name of the git repository
 * @param author                author
 * @param message-              commit message
 * @param files-                map of file paths along with their content
 * @param credentials-          Git credentials, for example username/password, authToken, personal access token
 */
public void createFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message,
        Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) {

    try {
        // create temporary directory
        Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created temporary directory {}", workingDir.toString());
        }

        // git init
        Git git = Git.init().setDirectory(workingDir.toFile()).call();
        writeFiles(workingDir, files);

        RemoteAddCommand remoteAddCommand = git.remoteAdd();
        remoteAddCommand.setName("origin");
        remoteAddCommand.setUri(new URIish(remoteGitRepoHttpUrl));
        remoteAddCommand.call();

        commitAndPush(git, authorName(author), author.getEmail(), message, credentials);
        removeWorkingDir(workingDir);
    } catch (IOException | GitAPIException | URISyntaxException e) {
        throw SyndesisServerException.launderThrowable(e);
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private Git createBareRepository(File root) throws GitAPIException {
    return Git.init().setDirectory(root).setBare(true).call();
}