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:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

/**
 * List all GIT Tags of an application with an index
 * After this index is use to choose on which tag user want to restre his application
 * with resetOnChosenGitTag() method/*from   ww  w.  j av  a  2  s . co m*/
 *
 * @param application
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> listGitTagsOfApplication(Application application, String dockerManagerAddress,
        String containerGitAddress) throws GitAPIException, IOException {

    List<String> listTagsName = new ArrayList<>();

    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;

    Path myTempDirPath = Files.createTempDirectory(Paths.get("/tmp"), null);
    File gitworkDir = myTempDirPath.toFile();

    InitCommand initCommand = Git.init();
    initCommand.setDirectory(gitworkDir);
    initCommand.call();
    FileRepository gitRepo = new FileRepository(gitworkDir);
    LsRemoteCommand lsRemoteCommand = new LsRemoteCommand(gitRepo);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);

    lsRemoteCommand.setCredentialsProvider(credentialsProvider);
    lsRemoteCommand.setRemote(remoteRepository);
    lsRemoteCommand.setTags(true);
    Collection<Ref> collectionRefs = lsRemoteCommand.call();
    List<Ref> listRefs = new ArrayList<>(collectionRefs);

    for (Ref ref : listRefs) {
        listTagsName.add(ref.getName());
    }
    Collections.sort(listTagsName);
    FilesUtils.deleteDirectory(gitworkDir);

    return listTagsName;

}

From source file:fr.xebia.workshop.git.GithubRepositoriesCreator.java

License:Apache License

private Git initGitLocalRepository(File tmpRepoDir) {
    Git git;/*from   w w  w .  j a  va  2s .  c  o  m*/
    if (sourceGitHubRepositoryUrl != null) {
        logger.info("Repository {} is cloning into {}",
                new Object[] { sourceGitHubRepositoryUrl, tmpRepoDir.getAbsolutePath() });
        git = Git.cloneRepository().setURI(sourceGitHubRepositoryUrl).setDirectory(tmpRepoDir).call();
    } else {
        logger.info("Repository is initiating into {}", tmpRepoDir);
        git = Git.init().setDirectory(tmpRepoDir).call();
    }
    return git;
}

From source file:GitBackend.GitAPI.java

License:Apache License

/**
 * Initialize a new repository/*from   w w w.j a va2  s . c  o m*/
 *
 * @param path
 * @throws IOException
 */
public void initRepository(String path) throws IOException {
    File localPath = new File(path);
    this.openRepository(localPath);
    /*
            // create the directory
            try (Git newGit = Git.init().setDirectory(localPath).call()) {
    this.git = newGit;
    System.out.println("Having repository: " + git.getRepository().getDirectory());
            } catch (GitAPIException e) {
    e.printStackTrace();
            }
            
            repository = FileRepositoryBuilder.create(new File(localPath.getAbsolutePath(), ".git"));
            */
    try {
        git = Git.init().setDirectory(localPath).call();
        repository = git.getRepository();
        logger.info("Init");

    } catch (GitAPIException e) {
        e.printStackTrace();
    }
    /*
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    repositoryBuilder.setMustExist( true );
    repositoryBuilder.setGitDir(localPath);
    repository = repositoryBuilder.build();
    */

}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public void initRepo() {
    if (repoExists()) {
        System.out.println("Repo already exists!");
        return;//from   w w w.  ja  v  a2s .  co  m
    }

    try {
        //         System.out.println(gitDir.getAbsolutePath());
        Git.init().setDirectory(thisDir).setBare(false).call();
        getConfigParameters();
        createGitIgnore();
        System.out.println("New repo created.");
    } catch (InvalidRemoteException e) {
        e.printStackTrace();
    } catch (TransportException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
}

From source file:griffon.plugins.git.GitManager.java

License:Apache License

private void initIfNeeded() throws IOException {
    try {/*from  w w  w  .j  a  va 2  s .com*/
        git();
    } catch (IOException e) {
        File basedir = new File(buildSettings.getBaseDir(), ".");
        InitCommand init = Git.init();
        init.setDirectory(basedir);
        init.call();

        System.out.println("Initialized Git repository in " + basedir.getAbsolutePath() + "git");

        addIgnoreFile(basedir);
    }
}

From source file:io.fabric8.deployer.ProjectDeployerTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    URL.setURLStreamHandlerFactory(new CustomBundleURLStreamHandlerFactory());

    basedir = System.getProperty("basedir", ".");
    String karafRoot = basedir + "/target/karaf";
    System.setProperty("karaf.root", karafRoot);
    System.setProperty("karaf.data", karafRoot + "/data");

    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());/*from   w w  w  .j  ava2  s. co  m*/
    delete(sfb.getDataLogDir());
    sfb.setPort(9123);
    sfb.afterPropertiesSet();

    int zkPort = sfb.getClientPortAddress().getPort();
    LOG.info("Connecting to ZK on port: " + zkPort);
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString("localhost:" + zkPort).retryPolicy(new RetryOneTime(1000))
            .connectionTimeoutMs(360000);

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

    // setup a local and remote git repo
    File root = new File(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();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();

    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", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    runtimeProperties = EasyMock.createMock(RuntimeProperties.class);
    EasyMock.expect(runtimeProperties.getRuntimeIdentity()).andReturn("root").anyTimes();
    EasyMock.expect(runtimeProperties.getHomePath()).andReturn(Paths.get("target")).anyTimes();
    EasyMock.expect(runtimeProperties.getDataPath()).andReturn(Paths.get("target/data")).anyTimes();
    EasyMock.expect(runtimeProperties.getProperty(EasyMock.eq(SystemProperties.FABRIC_ENVIRONMENT)))
            .andReturn("").anyTimes();
    EasyMock.expect(runtimeProperties.removeRuntimeAttribute(DataStoreTemplate.class)).andReturn(null)
            .anyTimes();
    EasyMock.replay(runtimeProperties);

    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.bindRuntimeProperties(runtimeProperties);
    gitService.activate();
    gitService.setGitForTesting(git);

    /*
    dataStore = new GitDataStoreImpl();
    dataStore.bindCurator(curator);
    dataStore.bindGitService(gitService);
    dataStore.bindRuntimeProperties(runtimeProperties);
    dataStore.bindConfigurer(new Configurer() {
            
            
    @Override
    public <T> Map<String, ?> configure(Map<String, ?> configuration, T target, String... ignorePrefix) throws Exception {
        return null;
    }
            
    @Override
    public <T> Map<String, ?> configure(Dictionary<String, ?> configuration, T target, String... ignorePrefix) throws Exception {
        return null;
    }
    });
    Map<String, Object> datastoreProperties = new HashMap<String, Object>();
    datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl);
    dataStore.activate(datastoreProperties);
    */

    fabricService = new FabricServiceImpl();
    //fabricService.bindDataStore(dataStore);
    fabricService.bindRuntimeProperties(runtimeProperties);
    fabricService.bindPlaceholderResolver(new DummyPlaceholerResolver("port"));
    fabricService.bindPlaceholderResolver(new DummyPlaceholerResolver("zk"));
    fabricService.bindPlaceholderResolver(new ProfilePropertyPointerResolver());
    fabricService.bindPlaceholderResolver(new ChecksumPlaceholderResolver());
    fabricService.bindPlaceholderResolver(new VersionPropertyPointerResolver());
    fabricService.bindPlaceholderResolver(new EnvPlaceholderResolver());
    fabricService.activateComponent();

    projectDeployer = new ProjectDeployerImpl();
    projectDeployer.bindFabricService(fabricService);
    projectDeployer.bindMBeanServer(ManagementFactory.getPlatformMBeanServer());

    String defaultVersion = null; //dataStore.getDefaultVersion();
    assertEquals("defaultVersion", "1.0", defaultVersion);

    // now lets import some data - using the old non-git file layout...
    String importPath = basedir + "/../fabric8-karaf/src/main/resources/distro/fabric/import";
    assertFolderExists(importPath);
    dataStore.importFromFileSystem(importPath);
    assertHasVersion(defaultVersion);
}

From source file:io.fabric8.forge.generator.git.AbstractGitRepoStep.java

License:Apache License

public static void importNewGitProject(UserDetails userDetails, File basedir, String message, String gitUrl,
        String branch, String origin, Logger logger) throws GitAPIException {
    GitUtils.disableSslCertificateChecks();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);/*from   w  w w  .j  ava2  s.c  o m*/
    Git git = initCommand.call();
    logger.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());
    gitAddCommitAndPush(git, gitUrl, userDetails, basedir, message, branch, origin, logger);
}

From source file:io.fabric8.forge.rest.main.GitCommandCompletePostProcessor.java

License:Apache License

@Override
public void firePostCompleteActions(String name, ExecutionRequest executionRequest, RestUIContext context,
        CommandController controller, ExecutionResult results, HttpServletRequest request) {
    UserDetails userDetails = gitUserHelper.createUserDetails(request);

    String user = userDetails.getUser();
    String password = userDetails.getPassword();
    String authorEmail = userDetails.getEmail();
    String address = userDetails.getAddress();
    String branch = userDetails.getBranch();
    String origin = projectFileSystem.getRemote();

    try {//from w ww.  j a  v  a 2  s  .c  o  m
        CredentialsProvider credentials = userDetails.createCredentialsProvider();
        PersonIdent personIdent = new PersonIdent(user, authorEmail);

        if (name.equals(PROJECT_NEW_COMMAND)) {
            String targetLocation = null;
            String named = null;
            List<Map<String, String>> inputList = executionRequest.getInputList();
            for (Map<String, String> map : inputList) {
                if (Strings.isNullOrEmpty(targetLocation)) {
                    targetLocation = map.get("targetLocation");
                }
                if (Strings.isNullOrEmpty(named)) {
                    named = map.get("named");
                }
            }
            if (Strings.isNullOrEmpty(targetLocation)) {
                LOG.warn("No targetLocation could be found!");
            } else if (Strings.isNullOrEmpty(named)) {
                LOG.warn("No named could be found!");
            } else {
                File basedir = new File(targetLocation, named);
                if (!basedir.isDirectory() || !basedir.exists()) {
                    LOG.warn("Generated project folder does not exist: " + basedir.getAbsolutePath());
                } else {
                    InitCommand initCommand = Git.init();
                    initCommand.setDirectory(basedir);
                    Git git = initCommand.call();
                    LOG.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());

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

                    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.isNullOrEmpty(fullName)) {
                        fullName = user + "/" + named;
                    }
                    String htmlUrl = address + user + "/" + named;
                    String remoteUrl = address + user + "/" + named + ".git";
                    //results.appendOut("Created git repository " + fullName + " at: " + htmlUrl);

                    results.setOutputProperty("fullName", fullName);
                    results.setOutputProperty("cloneUrl", remoteUrl);
                    results.setOutputProperty("htmlUrl", htmlUrl);

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

                    createKubernetesResources(user, named, remoteUrl, branch, repoClient, address);

                    String message = createCommitMessage(name, executionRequest);
                    doAddCommitAndPushFiles(git, credentials, personIdent, remoteUrl, branch, origin, message);
                }
            }
        } else {
            File basedir = context.getInitialSelectionFile();
            String absolutePath = basedir != null ? basedir.getAbsolutePath() : null;
            if (basedir != null) {
                File gitFolder = new File(basedir, ".git");
                if (gitFolder.exists() && gitFolder.isDirectory()) {
                    FileRepositoryBuilder builder = new FileRepositoryBuilder();
                    Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                            .findGitDir() // scan up the file system tree
                            .build();

                    Git git = new Git(repository);
                    String remoteUrl = getRemoteURL(git, branch);
                    if (origin == null) {
                        LOG.warn("Could not find remote git URL for folder " + absolutePath);
                    } else {
                        String message = createCommitMessage(name, executionRequest);
                        doAddCommitAndPushFiles(git, credentials, personIdent, remoteUrl, branch, origin,
                                message);
                    }
                }
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:io.fabric8.git.internal.CachingGitDataStoreTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());/*w  ww  .j  av  a2s.  c  o  m*/
    delete(sfb.getDataLogDir());
    sfb.afterPropertiesSet();
    runtimeProperties = EasyMock.createMock(RuntimeProperties.class);
    EasyMock.expect(runtimeProperties.getRuntimeIdentity()).andReturn("root").anyTimes();
    EasyMock.expect(runtimeProperties.getHomePath()).andReturn(Paths.get("target")).anyTimes();
    EasyMock.expect(runtimeProperties.getDataPath()).andReturn(Paths.get("target/data")).anyTimes();
    EasyMock.expect(runtimeProperties.removeRuntimeAttribute(DataStoreTemplate.class)).andReturn(null)
            .anyTimes();
    EasyMock.replay(runtimeProperties);

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

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

    // setup a local and remote git repo
    basedir = System.getProperty("basedir", ".");
    File root = new File(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();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();

    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", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.bindRuntimeProperties(runtimeProperties);
    gitService.activate();
    gitService.setGitForTesting(git);

    dataStore = new GitDataStoreImpl();
    dataStore.bindCurator(curator);
    dataStore.bindGitService(gitService);
    dataStore.bindRuntimeProperties(runtimeProperties);
    dataStore.bindConfigurer(new Configurer() {

        @Override
        public <T> Map<String, ?> configure(Map<String, ?> configuration, T target, String... ignorePrefix)
                throws Exception {
            return null;
        }

        @Override
        public <T> Map<String, ?> configure(Dictionary<String, ?> configuration, T target,
                String... ignorePrefix) throws Exception {
            return null;
        }
    });
    Map<String, Object> datastoreProperties = new HashMap<String, Object>();
    // datastoreProperties.put(GitDataStoreImpl.GIT_REMOTE_URL, remoteUrl);
    dataStore.activate(datastoreProperties);
}

From source file:io.fabric8.git.internal.FabricGitServiceImpl.java

License:Apache License

private Git openOrInit(File localRepo) throws IOException {
    try {//  w w  w.  j a  v  a2s. c om
        return Git.open(localRepo);
    } catch (RepositoryNotFoundException e) {
        try {
            return Git.init().setDirectory(localRepo).call();
        } catch (GitAPIException ex) {
            throw new IOException(ex);
        }
    }
}