Search in sources :

Example 16 with FileRepositoryBuilder

use of org.eclipse.jgit.storage.file.FileRepositoryBuilder in project maven-git-versioning-extension by qoomon.

the class VersioningModelProcessor method deduceProjectVersion.

private ProjectVersion deduceProjectVersion(GAV gav, File gitDir) throws IOException {
    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder().findGitDir(gitDir);
    logger.debug(gav + "git directory " + repositoryBuilder.getGitDir());
    try (Repository repository = repositoryBuilder.build()) {
        final String headCommit = getHeadCommit(repository);
        String projectBranchName = null;
        String projectTagName = null;
        VersionFormatDescription projectVersionFormatDescription = null;
        Map<String, String> projectVersionDataMap = buildCommonVersionDataMap(headCommit, gav);
        if (!configuration.getTagVersionDescriptions().isEmpty()) {
            final List<String> headTags = getHeadTags(repository);
            if (!headTags.isEmpty()) {
                for (VersionFormatDescription versionFormatDescription : configuration.getTagVersionDescriptions()) {
                    String tagName = headTags.stream().sequential().filter(tag -> tag.matches(versionFormatDescription.pattern)).sorted((versionLeft, versionRight) -> {
                        DefaultArtifactVersion tagVersionLeft = new DefaultArtifactVersion(removePrefix(versionLeft, versionFormatDescription.prefix));
                        DefaultArtifactVersion tagVersionRight = new DefaultArtifactVersion(removePrefix(versionRight, versionFormatDescription.prefix));
                        // -1 revert sorting, latest version first
                        return tagVersionLeft.compareTo(tagVersionRight) * -1;
                    }).findFirst().orElse(null);
                    if (tagName != null) {
                        projectTagName = tagName;
                        projectVersionFormatDescription = versionFormatDescription;
                        projectVersionDataMap.put("tag", removePrefix(projectTagName, projectVersionFormatDescription.prefix));
                        projectVersionDataMap.putAll(getRegexGroupValueMap(projectVersionFormatDescription.pattern, projectTagName));
                        break;
                    }
                }
            }
        }
        if (projectTagName == null) {
            final String branchName = getHeadBranch(repository).orElseThrow(() -> new ModelParseException(gitDir + ": No Branch Name provided in Detached HEAD state. See documentation.", 0, 0));
            projectBranchName = branchName;
            projectVersionFormatDescription = configuration.getBranchVersionDescriptions().stream().filter(versionFormatDescription -> branchName.matches(versionFormatDescription.pattern)).findFirst().orElseThrow(() -> new ModelParseException(gitDir + ": No version format for branch '" + branchName + "' found.", 0, 0));
            projectVersionDataMap.put("branch", removePrefix(projectBranchName, projectVersionFormatDescription.prefix));
            projectVersionDataMap.putAll(getRegexGroupValueMap(projectVersionFormatDescription.pattern, projectBranchName));
        }
        String version = StrSubstitutor.replace(projectVersionFormatDescription.versionFormat, projectVersionDataMap);
        ProjectVersion projectVersion = new ProjectVersion(escapeVersion(version), headCommit, projectBranchName, projectTagName);
        logger.info(gav.getArtifactId() + ":" + gav.getVersion() + (projectVersion.getTag() != null ? " - tag: " + projectVersion.getTag() : "") + (projectVersion.getTag() != null ? " - branch: " + projectVersion.getBranch() : "") + " -> version: " + projectVersion.getVersion());
        return projectVersion;
    }
}
Also used : ModelParseException(org.apache.maven.model.io.ModelParseException) PluginExecution(org.apache.maven.model.PluginExecution) java.util(java.util) DefaultArtifactVersion(org.apache.maven.artifact.versioning.DefaultArtifactVersion) VersionFormatDescription(com.qoomon.maven.extension.gitversioning.config.model.VersionFormatDescription) Component(org.codehaus.plexus.component.annotations.Component) Build(org.apache.maven.model.Build) Inject(javax.inject.Inject) Matcher(java.util.regex.Matcher) ModelProcessor(org.apache.maven.model.building.ModelProcessor) ModelUtil(com.qoomon.maven.ModelUtil) Source(org.apache.maven.building.Source) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) DefaultModelProcessor(org.apache.maven.model.building.DefaultModelProcessor) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) MavenSession(org.apache.maven.execution.MavenSession) Constants(org.eclipse.jgit.lib.Constants) IOException(java.io.IOException) Reader(java.io.Reader) SessionScopeUtil(com.qoomon.maven.extension.gitversioning.SessionScopeUtil) Collectors(java.util.stream.Collectors) File(java.io.File) ObjectId(org.eclipse.jgit.lib.ObjectId) GAV(com.qoomon.maven.GAV) Plugin(org.apache.maven.model.Plugin) SessionScope(org.apache.maven.session.scope.internal.SessionScope) Stream(java.util.stream.Stream) BuildProperties(com.qoomon.maven.BuildProperties) VersioningConfigurationProvider(com.qoomon.maven.extension.gitversioning.config.VersioningConfigurationProvider) Logger(org.codehaus.plexus.logging.Logger) Pattern(java.util.regex.Pattern) VersioningConfiguration(com.qoomon.maven.extension.gitversioning.config.VersioningConfiguration) Repository(org.eclipse.jgit.lib.Repository) Model(org.apache.maven.model.Model) InputStream(java.io.InputStream) Repository(org.eclipse.jgit.lib.Repository) ModelParseException(org.apache.maven.model.io.ModelParseException) DefaultArtifactVersion(org.apache.maven.artifact.versioning.DefaultArtifactVersion) VersionFormatDescription(com.qoomon.maven.extension.gitversioning.config.model.VersionFormatDescription) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder)

Example 17 with FileRepositoryBuilder

use of org.eclipse.jgit.storage.file.FileRepositoryBuilder 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 18 with FileRepositoryBuilder

use of org.eclipse.jgit.storage.file.FileRepositoryBuilder in project fabric8 by jboss-fuse.

the class CartridgeGitRepository method cloneOrPull.

/**
 * Clones or pulls the remote repository and returns the directory with the checkout
 */
public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
        throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
        LOG.info("Cloning remote repo " + repo);
        CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentials).setURI(repo).setDirectory(localRepo).setRemote(remoteName);
        git = command.call();
    } else {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
        git = new Git(repository);
        // update the remote repo just in case
        StoredConfig config = repository.getConfig();
        config.setString("remote", remoteName, "url", repo);
        config.setString("remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");
        String branch = "master";
        config.setString("branch", branch, "remote", remoteName);
        config.setString("branch", branch, "merge", "refs/heads/" + branch);
        try {
            config.save();
        } catch (IOException e) {
            LOG.error("Failed to save the git configuration to " + localRepo + " with remote repo: " + repo + ". " + e, e);
        }
        // now pull
        LOG.info("Pulling from remote repo " + repo);
        git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) Git(org.eclipse.jgit.api.Git) IOException(java.io.IOException) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder)

Example 19 with FileRepositoryBuilder

use of org.eclipse.jgit.storage.file.FileRepositoryBuilder in project fabric8-maven-plugin by fabric8io.

the class GitUtil method getGitRepository.

public static Repository getGitRepository(MavenProject project) throws IOException {
    MavenProject rootProject = MavenUtil.getRootProject(project);
    File baseDir = rootProject.getBasedir();
    if (baseDir == null) {
        baseDir = project.getBasedir();
    }
    if (baseDir == null) {
        // TODO: Why is this check needed ?
        baseDir = new File(System.getProperty("basedir", "."));
    }
    File gitFolder = GitHelpers.findGitFolder(baseDir);
    if (gitFolder == null) {
        // No git repository found
        return null;
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.readEnvironment().setGitDir(gitFolder).build();
    return repository;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) MavenProject(org.apache.maven.project.MavenProject) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder)

Example 20 with FileRepositoryBuilder

use of org.eclipse.jgit.storage.file.FileRepositoryBuilder in project liferay-docs by liferay.

the class GitCompare method openGitRepository.

private static Repository openGitRepository() throws IOException {
    FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    Repository repo = repoBuilder.readEnvironment().findGitDir().build();
    return repo;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder)

Aggregations

FileRepositoryBuilder (org.eclipse.jgit.storage.file.FileRepositoryBuilder)32 Repository (org.eclipse.jgit.lib.Repository)30 File (java.io.File)25 Git (org.eclipse.jgit.api.Git)12 IOException (java.io.IOException)8 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)6 ObjectId (org.eclipse.jgit.lib.ObjectId)4 Path (java.nio.file.Path)3 CloneCommand (org.eclipse.jgit.api.CloneCommand)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 Ref (org.eclipse.jgit.lib.Ref)3 RevCommit (org.eclipse.jgit.revwalk.RevCommit)3 CredentialsProvider (org.eclipse.jgit.transport.CredentialsProvider)3 URIish (org.eclipse.jgit.transport.URIish)3 RefLogEntry (com.gitblit.models.RefLogEntry)2 Reader (java.io.Reader)2 PersonIdent (org.eclipse.jgit.lib.PersonIdent)2 TaskAction (org.gradle.api.tasks.TaskAction)2 Test (org.junit.Test)2 GHRepository (org.kohsuke.github.GHRepository)2