Search in sources :

Example 1 with GitScmProviderRepository

use of org.apache.maven.scm.provider.git.repository.GitScmProviderRepository in project maven-scm by apache.

the class JGitCheckOutCommand method executeCheckOutCommand.

/**
 * For git, the given repository is a remote one. We have to clone it first if the working directory does not
 * contain a git repo yet, otherwise we have to git-pull it.
 * <p/>
 * {@inheritDoc}
 */
protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet, ScmVersion version, boolean recursive, boolean shallow) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;
    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol()) && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }
    Git git = null;
    try {
        ProgressMonitor monitor = JGitUtils.getMonitor(getLogger());
        String branch = version != null ? version.getName() : null;
        if (StringUtils.isBlank(branch)) {
            branch = Constants.MASTER;
        }
        getLogger().debug("try checkout of branch: " + branch);
        if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) {
            if (fileSet.getBasedir().exists()) {
                // git refuses to clone otherwise
                fileSet.getBasedir().delete();
            }
            // FIXME only if windauze
            WindowCacheConfig cfg = new WindowCacheConfig();
            cfg.setPackedGitMMAP(false);
            cfg.install();
            // no git repo seems to exist, let's clone the original repo
            CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo);
            getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir());
            CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl());
            command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir());
            command.setProgressMonitor(monitor);
            git = command.call();
        }
        JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand();
        remoteInfoCommand.setLogger(getLogger());
        RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null);
        if (git == null) {
            // deliberately not using JGitUtils.openRepo(), the caller told us exactly where to checkout
            git = Git.open(fileSet.getBasedir());
        }
        if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists() && result.getBranches().size() > 0) {
            // git repo exists, so we must git-pull the changes
            CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository);
            if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) {
                // A tag will not be pulled but we only fetch all the commits from the upstream repo
                // This is done because checking out a tag might not happen on the current branch
                // but create a 'detached HEAD'.
                // In fact, a tag in git may be in multiple branches. This occurs if
                // you create a branch after the tag has been created
                getLogger().debug("fetch...");
                git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            } else {
                getLogger().debug("pull...");
                git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call();
            }
        }
        Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git);
        if (version instanceof ScmTag) {
            getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else if (localBranchNames.contains(branch)) {
            getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).call();
        } else {
            getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir());
            git.checkout().setName(branch).setCreateBranch(true).setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call();
        }
        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD));
        revWalk.release();
        final TreeWalk walk = new TreeWalk(git.getRepository());
        // drop the first empty tree, which we do not need here
        walk.reset();
        walk.setRecursive(true);
        walk.addTree(commit.getTree());
        List<ScmFile> listedFiles = new ArrayList<ScmFile>();
        while (walk.next()) {
            listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT));
        }
        walk.release();
        getLogger().debug("current branch: " + git.getRepository().getBranch());
        return new CheckOutScmResult("checkout via JGit", listedFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkout failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) ScmException(org.apache.maven.scm.ScmException) WindowCacheConfig(org.eclipse.jgit.storage.file.WindowCacheConfig) GitScmProviderRepository(org.apache.maven.scm.provider.git.repository.GitScmProviderRepository) ArrayList(java.util.ArrayList) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) RevWalk(org.eclipse.jgit.revwalk.RevWalk) JGitRemoteInfoCommand(org.apache.maven.scm.provider.git.jgit.command.remoteinfo.JGitRemoteInfoCommand) RemoteInfoScmResult(org.apache.maven.scm.command.remoteinfo.RemoteInfoScmResult) ScmException(org.apache.maven.scm.ScmException) ScmFile(org.apache.maven.scm.ScmFile) ProgressMonitor(org.eclipse.jgit.lib.ProgressMonitor) Git(org.eclipse.jgit.api.Git) ScmTag(org.apache.maven.scm.ScmTag) CheckOutScmResult(org.apache.maven.scm.command.checkout.CheckOutScmResult) ScmFile(org.apache.maven.scm.ScmFile) File(java.io.File) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 2 with GitScmProviderRepository

use of org.apache.maven.scm.provider.git.repository.GitScmProviderRepository in project maven-scm by apache.

the class JGitRemoteInfoCommand method executeRemoteInfoCommand.

@Override
public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters) throws ScmException {
    GitScmProviderRepository repo = (GitScmProviderRepository) repository;
    Git git = null;
    try {
        git = JGitUtils.openRepo(fileSet.getBasedir());
        CredentialsProvider credentials = JGitUtils.getCredentials(repo);
        LsRemoteCommand lsCommand = git.lsRemote().setRemote(repo.getPushUrl()).setCredentialsProvider(credentials);
        Map<String, String> tag = new HashMap<String, String>();
        Collection<Ref> allTags = lsCommand.setHeads(false).setTags(true).call();
        for (Ref ref : allTags) {
            tag.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }
        Map<String, String> heads = new HashMap<String, String>();
        Collection<Ref> allHeads = lsCommand.setHeads(true).setTags(false).call();
        for (Ref ref : allHeads) {
            heads.put(Repository.shortenRefName(ref.getName()), ref.getObjectId().name());
        }
        return new RemoteInfoScmResult("JGit remoteinfo", heads, tag);
    } catch (Exception e) {
        throw new ScmException("JGit remoteinfo failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}
Also used : Ref(org.eclipse.jgit.lib.Ref) ScmException(org.apache.maven.scm.ScmException) Git(org.eclipse.jgit.api.Git) GitScmProviderRepository(org.apache.maven.scm.provider.git.repository.GitScmProviderRepository) HashMap(java.util.HashMap) CredentialsProvider(org.eclipse.jgit.transport.CredentialsProvider) LsRemoteCommand(org.eclipse.jgit.api.LsRemoteCommand) RemoteInfoScmResult(org.apache.maven.scm.command.remoteinfo.RemoteInfoScmResult) ScmException(org.apache.maven.scm.ScmException)

Example 3 with GitScmProviderRepository

use of org.apache.maven.scm.provider.git.repository.GitScmProviderRepository in project maven-scm by apache.

the class GitCheckInCommand method executeCheckInCommand.

/**
 * {@inheritDoc}
 */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message, ScmVersion version) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
    int exitCode;
    File messageFile = FileUtils.createTempFile("maven-scm-", ".commit", null);
    try {
        FileUtils.fileWrite(messageFile.getAbsolutePath(), message);
    } catch (IOException ex) {
        return new CheckInScmResult(null, "Error while making a temporary file for the commit message: " + ex.getMessage(), null, false);
    }
    try {
        if (!fileSet.getFileList().isEmpty()) {
            // if specific fileSet is given, we have to git-add them first
            // otherwise we will use 'git-commit -a' later
            Commandline clAdd = GitAddCommand.createCommandLine(fileSet.getBasedir(), fileSet.getFileList());
            exitCode = GitCommandLineUtils.execute(clAdd, stdout, stderr, getLogger());
            if (exitCode != 0) {
                return new CheckInScmResult(clAdd.toString(), "The git-add command failed.", stderr.getOutput(), false);
            }
        }
        // SCM-709: statusCommand uses repositoryRoot instead of workingDirectory, adjust it with
        // relativeRepositoryPath
        Commandline clRevparse = GitStatusCommand.createRevparseShowToplevelCommand(fileSet);
        stdout = new CommandLineUtils.StringStreamConsumer();
        stderr = new CommandLineUtils.StringStreamConsumer();
        URI relativeRepositoryPath = null;
        exitCode = GitCommandLineUtils.execute(clRevparse, stdout, stderr, getLogger());
        if (exitCode != 0) {
            // git-status returns non-zero if nothing to do
            if (getLogger().isInfoEnabled()) {
                getLogger().info("Could not resolve toplevel");
            }
        } else {
            relativeRepositoryPath = GitStatusConsumer.resolveURI(stdout.getOutput().trim(), fileSet.getBasedir().toURI());
        }
        // git-commit doesn't show single files, but only summary :/
        // so we must run git-status and consume the output
        // borrow a few things from the git-status command
        Commandline clStatus = GitStatusCommand.createCommandLine(repository, fileSet);
        GitStatusConsumer statusConsumer = new GitStatusConsumer(getLogger(), fileSet.getBasedir(), relativeRepositoryPath);
        exitCode = GitCommandLineUtils.execute(clStatus, statusConsumer, stderr, getLogger());
        if (exitCode != 0) {
            // git-status returns non-zero if nothing to do
            if (getLogger().isInfoEnabled()) {
                getLogger().info("nothing added to commit but untracked files present (use \"git add\" to " + "track)");
            }
        }
        if (statusConsumer.getChangedFiles().isEmpty()) {
            return new CheckInScmResult(null, statusConsumer.getChangedFiles());
        }
        Commandline clCommit = createCommitCommandLine(repository, fileSet, messageFile);
        exitCode = GitCommandLineUtils.execute(clCommit, stdout, stderr, getLogger());
        if (exitCode != 0) {
            return new CheckInScmResult(clCommit.toString(), "The git-commit command failed.", stderr.getOutput(), false);
        }
        if (repo.isPushChanges()) {
            Commandline cl = createPushCommandLine(getLogger(), repository, fileSet, version);
            exitCode = GitCommandLineUtils.execute(cl, stdout, stderr, getLogger());
            if (exitCode != 0) {
                return new CheckInScmResult(cl.toString(), "The git-push command failed.", stderr.getOutput(), false);
            }
        }
        List<ScmFile> checkedInFiles = new ArrayList<ScmFile>(statusConsumer.getChangedFiles().size());
        // rewrite all detected files to now have status 'checked_in'
        for (ScmFile changedFile : statusConsumer.getChangedFiles()) {
            ScmFile scmfile = new ScmFile(changedFile.getPath(), ScmFileStatus.CHECKED_IN);
            if (fileSet.getFileList().isEmpty()) {
                checkedInFiles.add(scmfile);
            } else {
                // if a specific fileSet is given, we have to check if the file is really tracked
                for (File f : fileSet.getFileList()) {
                    if (FilenameUtils.separatorsToUnix(f.getPath()).equals(scmfile.getPath())) {
                        checkedInFiles.add(scmfile);
                    }
                }
            }
        }
        return new CheckInScmResult(clCommit.toString(), checkedInFiles);
    } finally {
        try {
            FileUtils.forceDelete(messageFile);
        } catch (IOException ex) {
        // ignore
        }
    }
}
Also used : GitScmProviderRepository(org.apache.maven.scm.provider.git.repository.GitScmProviderRepository) Commandline(org.codehaus.plexus.util.cli.Commandline) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CheckInScmResult(org.apache.maven.scm.command.checkin.CheckInScmResult) URI(java.net.URI) ScmFile(org.apache.maven.scm.ScmFile) CommandLineUtils(org.codehaus.plexus.util.cli.CommandLineUtils) GitCommandLineUtils(org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils) GitStatusConsumer(org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusConsumer) ScmFile(org.apache.maven.scm.ScmFile) File(java.io.File)

Example 4 with GitScmProviderRepository

use of org.apache.maven.scm.provider.git.repository.GitScmProviderRepository in project maven-scm by apache.

the class GitListCommand method executeListCommand.

/**
 * {@inheritDoc}
 */
protected ListScmResult executeListCommand(ScmProviderRepository repo, ScmFileSet fileSet, boolean recursive, ScmVersion scmVersion) throws ScmException {
    GitScmProviderRepository repository = (GitScmProviderRepository) repo;
    if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol()) && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) {
        throw new ScmException("remote repository must not be the working directory");
    }
    int exitCode;
    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
    GitListConsumer consumer = new GitListConsumer(getLogger(), fileSet.getBasedir().getParentFile(), ScmFileStatus.CHECKED_IN);
    Commandline cl = createCommandLine(repository, fileSet.getBasedir());
    exitCode = GitCommandLineUtils.execute(cl, consumer, stderr, getLogger());
    if (exitCode != 0) {
        return new ListScmResult(cl.toString(), "The git-ls-files command failed.", stderr.getOutput(), false);
    }
    return new ListScmResult(cl.toString(), consumer.getListedFiles());
}
Also used : ScmException(org.apache.maven.scm.ScmException) GitScmProviderRepository(org.apache.maven.scm.provider.git.repository.GitScmProviderRepository) Commandline(org.codehaus.plexus.util.cli.Commandline) GitCommandLineUtils(org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils) CommandLineUtils(org.codehaus.plexus.util.cli.CommandLineUtils) ListScmResult(org.apache.maven.scm.command.list.ListScmResult)

Example 5 with GitScmProviderRepository

use of org.apache.maven.scm.provider.git.repository.GitScmProviderRepository in project maven-scm by apache.

the class GitChangeLogCommandTest method testCommandLine.

private void testCommandLine(String scmUrl, ScmBranch branch, ScmVersion startVersion, ScmVersion endVersion, String commandLine) throws Exception {
    ScmRepository repository = getScmManager().makeScmRepository(scmUrl);
    GitScmProviderRepository gitRepository = (GitScmProviderRepository) repository.getProviderRepository();
    Commandline cl = GitChangeLogCommand.createCommandLine(gitRepository, workingDirectory, branch, null, null, startVersion, endVersion);
    assertCommandLine(commandLine, workingDirectory, cl);
}
Also used : ScmRepository(org.apache.maven.scm.repository.ScmRepository) GitScmProviderRepository(org.apache.maven.scm.provider.git.repository.GitScmProviderRepository) Commandline(org.codehaus.plexus.util.cli.Commandline)

Aggregations

GitScmProviderRepository (org.apache.maven.scm.provider.git.repository.GitScmProviderRepository)19 Commandline (org.codehaus.plexus.util.cli.Commandline)16 File (java.io.File)9 ScmException (org.apache.maven.scm.ScmException)9 GitCommandLineUtils (org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils)8 ScmRepository (org.apache.maven.scm.repository.ScmRepository)8 CommandLineUtils (org.codehaus.plexus.util.cli.CommandLineUtils)8 ArrayList (java.util.ArrayList)3 ScmFile (org.apache.maven.scm.ScmFile)3 CheckOutScmResult (org.apache.maven.scm.command.checkout.CheckOutScmResult)3 RemoteInfoScmResult (org.apache.maven.scm.command.remoteinfo.RemoteInfoScmResult)3 GitListConsumer (org.apache.maven.scm.provider.git.gitexe.command.list.GitListConsumer)3 IOException (java.io.IOException)2 URI (java.net.URI)2 GitStatusConsumer (org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusConsumer)2 Git (org.eclipse.jgit.api.Git)2 CredentialsProvider (org.eclipse.jgit.transport.CredentialsProvider)2 HashMap (java.util.HashMap)1 ScmFileSet (org.apache.maven.scm.ScmFileSet)1 ScmRevision (org.apache.maven.scm.ScmRevision)1