Search in sources :

Example 1 with InitCommand

use of org.eclipse.jgit.api.InitCommand in project fabric8 by fabric8io.

the class BuildConfigHelper method importNewGitProject.

public static CreateGitProjectResults importNewGitProject(KubernetesClient kubernetesClient, UserDetails userDetails, File basedir, String namespace, String projectName, String origin, String message, boolean apply, boolean useLocalGitAddress) throws GitAPIException, JsonProcessingException {
    GitUtils.disableSslCertificateChecks();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);
    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(resolveToRoot(address), user, projectName);
    String localCloneUrl = URLUtils.pathJoin(resolveToRoot(internalAddress), user, projectName + ".git");
    String cloneUrl = htmlUrl + ".git";
    String defaultCloneUrl = cloneUrl;
    // lets default to using the local git clone URL
    if (useLocalGitAddress && Strings.isNotBlank(internalAddress)) {
        defaultCloneUrl = localCloneUrl;
    }
    // now lets import the code and publish
    GitUtils.configureBranch(git, branch, origin, defaultCloneUrl);
    GitUtils.addDummyFileToEmptyFolders(basedir);
    LOG.info("About to git commit and push to: " + defaultCloneUrl + " and remote name " + origin);
    GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true);
    Map<String, String> annotations = new HashMap<>();
    annotations.put(Annotations.Builds.GIT_CLONE_URL, cloneUrl);
    annotations.put(Annotations.Builds.LOCAL_GIT_CLONE_URL, localCloneUrl);
    BuildConfig buildConfig;
    if (apply) {
        buildConfig = createAndApplyBuildConfig(kubernetesClient, namespace, projectName, defaultCloneUrl, annotations);
    } else {
        buildConfig = createBuildConfig(kubernetesClient, namespace, projectName, defaultCloneUrl, annotations);
    }
    return new CreateGitProjectResults(buildConfig, fullName, htmlUrl, localCloneUrl, cloneUrl);
}
Also used : Git(org.eclipse.jgit.api.Git) CreateRepositoryDTO(io.fabric8.repo.git.CreateRepositoryDTO) PersonIdent(org.eclipse.jgit.lib.PersonIdent) HashMap(java.util.HashMap) InitCommand(org.eclipse.jgit.api.InitCommand) GitRepoClient(io.fabric8.repo.git.GitRepoClient) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) RepositoryDTO(io.fabric8.repo.git.RepositoryDTO) CreateRepositoryDTO(io.fabric8.repo.git.CreateRepositoryDTO)

Example 2 with InitCommand

use of org.eclipse.jgit.api.InitCommand in project stdlib by petergeneric.

the class ConfigGuiceModule method getRepository.

@Provides
@Singleton
@Named("config")
public ConfigRepository getRepository(@Named("repo.config.path") final File workingDirectory, @Named("repo.config.force-reclone-on-startup") final boolean reclone, @Named("repo.config.remote") final String remote) throws IOException, URISyntaxException, GitAPIException {
    log.info("Repo path " + workingDirectory + ", reclone: " + reclone);
    if (reclone && workingDirectory.exists()) {
        log.info("Recloning " + workingDirectory);
        File[] files = workingDirectory.listFiles();
        if (files != null)
            for (File file : files) {
                FileUtils.deleteQuietly(file);
                if (!file.exists()) {
                    throw new RuntimeException("Tried to delete local checkout contents but did not succeed. File was: " + file);
                }
            }
    }
    final File gitDir = new File(workingDirectory, ".git");
    final boolean newlyCreated;
    // Create the git repository if it doesn't already exist
    if (!gitDir.exists()) {
        log.info("Initialising new git dir at: " + workingDirectory);
        FileUtils.forceMkdir(workingDirectory);
        InitCommand init = new InitCommand();
        init.setBare(false).setDirectory(workingDirectory).setGitDir(gitDir).call();
        newlyCreated = true;
    } else {
        newlyCreated = false;
    }
    FileRepositoryBuilder frb = new FileRepositoryBuilder();
    Repository repo = frb.setGitDir(gitDir).readEnvironment().findGitDir().build();
    final boolean hasRemote = !remote.equalsIgnoreCase("none");
    final CredentialsProvider credentials;
    if (hasRemote) {
        // Try to extract username/password from the remote URL
        final URIish uri = new URIish(remote);
        if (uri.getUser() != null && uri.getPass() != null)
            credentials = new UsernamePasswordCredentialsProvider(uri.getUser(), uri.getPass());
        else
            credentials = null;
    } else {
        credentials = null;
    }
    if (newlyCreated) {
        // Add the remote and pull from it
        if (hasRemote) {
            RepoHelper.addRemote(repo, "origin", remote);
            RepoHelper.pull(repo, "origin", credentials);
        }
        Git git = new Git(repo);
        // If there are no commits in this repository, create one
        if (!git.log().setMaxCount(1).call().iterator().hasNext()) {
            git.commit().setAll(true).setAuthor("system", "system@localhost").setMessage("initial commit").call();
            if (hasRemote)
                RepoHelper.push(repo, "origin", credentials);
        }
    }
    return new ConfigRepository(repo, hasRemote, credentials);
}
Also used : URIish(org.eclipse.jgit.transport.URIish) ConfigRepository(com.peterphi.configuration.service.git.ConfigRepository) Repository(org.eclipse.jgit.lib.Repository) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) InitCommand(org.eclipse.jgit.api.InitCommand) ConfigRepository(com.peterphi.configuration.service.git.ConfigRepository) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) Named(com.google.inject.name.Named) Singleton(com.google.inject.Singleton) Provides(com.google.inject.Provides)

Example 3 with InitCommand

use of org.eclipse.jgit.api.InitCommand in project jbosstools-openshift by jbosstools.

the class EGitUtils method createRepository.

/**
 * Creates a repository for the given project. The repository is created in
 * the .git directory within the given project. The project is not connected
 * with the new repository
 *
 * @param project
 *            the project to create the repository for.
 * @param monitor
 *            the monitor to report the progress to
 * @return
 * @throws CoreException
 *
 * @see #connect(IProject, Repository, IProgressMonitor)
 */
public static Repository createRepository(IProject project, IProgressMonitor monitor) throws CoreException {
    try {
        InitCommand init = Git.init();
        init.setBare(false).setDirectory(project.getLocation().toFile());
        Git git = init.call();
        return git.getRepository();
    } catch (JGitInternalException | GitAPIException e) {
        throw new CoreException(EGitCoreActivator.createErrorStatus(NLS.bind("Could not initialize a git repository at {0}: {1}", getRepositoryPathFor(project), e.getMessage()), e));
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) CoreException(org.eclipse.core.runtime.CoreException) InitCommand(org.eclipse.jgit.api.InitCommand) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException)

Example 4 with InitCommand

use of org.eclipse.jgit.api.InitCommand in project fabric8 by jboss-fuse.

the class CreateBranchMojo method initGitRepo.

protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();
    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).setBranch(oldBranchName).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);
            initCommand.setGitDir(gitDir);
            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().findGitDir().build();
        git = new Git(repository);
        if (pullOnStartup) {
            doPull();
        } else {
            getLog().info("git pull from remote config repo on startup is disabled");
        }
    }
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) InitCommand(org.eclipse.jgit.api.InitCommand) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) Date(java.util.Date)

Example 5 with InitCommand

use of org.eclipse.jgit.api.InitCommand in project archi-modelrepository-plugin by archi-contribs.

the class ArchiRepository method createNewLocalGitRepository.

@Override
public Git createNewLocalGitRepository(String URL) throws GitAPIException, IOException, URISyntaxException {
    if (getLocalRepositoryFolder().exists() && getLocalRepositoryFolder().list().length > 0) {
        // $NON-NLS-1$ //$NON-NLS-2$
        throw new IOException("Directory: " + getLocalRepositoryFolder().getAbsolutePath() + " is not empty.");
    }
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(getLocalRepositoryFolder());
    Git git = initCommand.call();
    RemoteAddCommand remoteAddCommand = git.remoteAdd();
    remoteAddCommand.setName(IGraficoConstants.ORIGIN);
    remoteAddCommand.setUri(new URIish(URL));
    remoteAddCommand.call();
    // Use the same line endings
    setConfigLineEndings(git);
    // Set tracked master branch
    setTrackedMasterBranch(git);
    return git;
}
Also used : URIish(org.eclipse.jgit.transport.URIish) Git(org.eclipse.jgit.api.Git) InitCommand(org.eclipse.jgit.api.InitCommand) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) IOException(java.io.IOException)

Aggregations

Git (org.eclipse.jgit.api.Git)5 InitCommand (org.eclipse.jgit.api.InitCommand)5 File (java.io.File)2 Repository (org.eclipse.jgit.lib.Repository)2 FileRepositoryBuilder (org.eclipse.jgit.storage.file.FileRepositoryBuilder)2 URIish (org.eclipse.jgit.transport.URIish)2 Provides (com.google.inject.Provides)1 Singleton (com.google.inject.Singleton)1 Named (com.google.inject.name.Named)1 ConfigRepository (com.peterphi.configuration.service.git.ConfigRepository)1 BuildConfig (io.fabric8.openshift.api.model.BuildConfig)1 CreateRepositoryDTO (io.fabric8.repo.git.CreateRepositoryDTO)1 GitRepoClient (io.fabric8.repo.git.GitRepoClient)1 RepositoryDTO (io.fabric8.repo.git.RepositoryDTO)1 IOException (java.io.IOException)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 CoreException (org.eclipse.core.runtime.CoreException)1 CloneCommand (org.eclipse.jgit.api.CloneCommand)1 RemoteAddCommand (org.eclipse.jgit.api.RemoteAddCommand)1