001package org.apache.maven.scm.provider.git.gitexe.command.checkin;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import org.apache.commons.io.FilenameUtils;
023import org.apache.maven.scm.ScmException;
024import org.apache.maven.scm.ScmFile;
025import org.apache.maven.scm.ScmFileSet;
026import org.apache.maven.scm.ScmFileStatus;
027import org.apache.maven.scm.ScmVersion;
028import org.apache.maven.scm.command.checkin.AbstractCheckInCommand;
029import org.apache.maven.scm.command.checkin.CheckInScmResult;
030import org.apache.maven.scm.log.ScmLogger;
031import org.apache.maven.scm.provider.ScmProviderRepository;
032import org.apache.maven.scm.provider.git.command.GitCommand;
033import org.apache.maven.scm.provider.git.repository.GitScmProviderRepository;
034import org.apache.maven.scm.provider.git.util.GitUtil;
035import org.apache.maven.scm.provider.git.gitexe.command.GitCommandLineUtils;
036import org.apache.maven.scm.provider.git.gitexe.command.add.GitAddCommand;
037import org.apache.maven.scm.provider.git.gitexe.command.branch.GitBranchCommand;
038import org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusCommand;
039import org.apache.maven.scm.provider.git.gitexe.command.status.GitStatusConsumer;
040import org.codehaus.plexus.util.FileUtils;
041import org.codehaus.plexus.util.cli.CommandLineUtils;
042import org.codehaus.plexus.util.cli.Commandline;
043
044import java.io.File;
045import java.io.IOException;
046import java.net.URI;
047import java.util.ArrayList;
048import java.util.List;
049
050/**
051 * @author <a href="mailto:struberg@yahoo.de">Mark Struberg</a>
052 * @author Olivier Lamy
053 *
054 */
055public class GitCheckInCommand
056    extends AbstractCheckInCommand
057    implements GitCommand
058{
059    /** {@inheritDoc} */
060    protected CheckInScmResult executeCheckInCommand( ScmProviderRepository repo, ScmFileSet fileSet, String message,
061                                                      ScmVersion version )
062        throws ScmException
063    {
064        GitScmProviderRepository repository = (GitScmProviderRepository) repo;
065
066        CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
067        CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
068
069        int exitCode;
070
071        File messageFile = FileUtils.createTempFile( "maven-scm-", ".commit", null );
072        try
073        {
074            FileUtils.fileWrite( messageFile.getAbsolutePath(), message );
075        }
076        catch ( IOException ex )
077        {
078            return new CheckInScmResult( null, "Error while making a temporary file for the commit message: "
079                + ex.getMessage(), null, false );
080        }
081
082        try
083        {
084            if ( !fileSet.getFileList().isEmpty() )
085            {
086                // if specific fileSet is given, we have to git-add them first
087                // otherwise we will use 'git-commit -a' later
088
089                Commandline clAdd = GitAddCommand.createCommandLine( fileSet.getBasedir(), fileSet.getFileList() );
090
091                exitCode = GitCommandLineUtils.execute( clAdd, stdout, stderr, getLogger() );
092
093                if ( exitCode != 0 )
094                {
095                    return new CheckInScmResult( clAdd.toString(), "The git-add command failed.", stderr.getOutput(),
096                                                 false );
097                }
098
099            }
100            
101         // SCM-709: statusCommand uses repositoryRoot instead of workingDirectory, adjust it with relativeRepositoryPath
102            Commandline clRevparse = GitStatusCommand.createRevparseShowToplevelCommand( fileSet );
103            
104            stdout = new CommandLineUtils.StringStreamConsumer();
105            stderr = new CommandLineUtils.StringStreamConsumer();
106
107            URI relativeRepositoryPath = null;
108            
109            exitCode = GitCommandLineUtils.execute( clRevparse, stdout, stderr, getLogger() );
110            if ( exitCode != 0 )
111            {
112                // git-status returns non-zero if nothing to do
113                if ( getLogger().isInfoEnabled() )
114                {
115                    getLogger().info( "Could not resolve toplevel" );
116                }
117            }
118            else
119            {
120                relativeRepositoryPath = GitStatusConsumer.resolveURI( stdout.getOutput().trim(), fileSet.getBasedir().toURI() ); 
121            }
122
123            // git-commit doesn't show single files, but only summary :/
124            // so we must run git-status and consume the output
125            // borrow a few things from the git-status command
126            Commandline clStatus = GitStatusCommand.createCommandLine( repository, fileSet );
127
128            GitStatusConsumer statusConsumer = new GitStatusConsumer( getLogger(), fileSet.getBasedir(), relativeRepositoryPath );
129            exitCode = GitCommandLineUtils.execute( clStatus, statusConsumer, stderr, getLogger() );
130            if ( exitCode != 0 )
131            {
132                // git-status returns non-zero if nothing to do
133                if ( getLogger().isInfoEnabled() )
134                {
135                    getLogger().info( "nothing added to commit but untracked files present (use \"git add\" to " +
136                            "track)" );
137                }
138            }
139            
140            if ( statusConsumer.getChangedFiles().isEmpty() )
141            {
142                return new CheckInScmResult( null, statusConsumer.getChangedFiles() );
143            }
144
145            Commandline clCommit = createCommitCommandLine( repository, fileSet, messageFile );
146
147            exitCode = GitCommandLineUtils.execute( clCommit, stdout, stderr, getLogger() );
148            if ( exitCode != 0 )
149            {
150                return new CheckInScmResult( clCommit.toString(), "The git-commit command failed.", stderr.getOutput(),
151                                             false );
152            }
153
154            if( repo.isPushChanges() ) 
155            {
156                Commandline cl = createPushCommandLine( getLogger(), repository, fileSet, version );
157
158                exitCode = GitCommandLineUtils.execute( cl, stdout, stderr, getLogger() );
159                if ( exitCode != 0 )
160                {
161                    return new CheckInScmResult( cl.toString(), "The git-push command failed.", stderr.getOutput(), false );
162                }                
163            }
164
165            List<ScmFile> checkedInFiles = new ArrayList<ScmFile>( statusConsumer.getChangedFiles().size() );
166
167            // rewrite all detected files to now have status 'checked_in'
168            for ( ScmFile changedFile : statusConsumer.getChangedFiles() )
169            {
170                ScmFile scmfile = new ScmFile( changedFile.getPath(), ScmFileStatus.CHECKED_IN );
171
172                if ( fileSet.getFileList().isEmpty() )
173                {
174                    checkedInFiles.add( scmfile );
175                }
176                else
177                {
178                    // if a specific fileSet is given, we have to check if the file is really tracked
179                    for ( File f : fileSet.getFileList() )
180                    {
181                        if ( FilenameUtils.separatorsToUnix( f.getPath() ).equals( scmfile.getPath() ) )
182                        {
183                            checkedInFiles.add( scmfile );
184                        }
185
186                    }
187                }
188            }
189
190            return new CheckInScmResult( clCommit.toString(), checkedInFiles );
191        }
192        finally
193        {
194            try
195            {
196                FileUtils.forceDelete( messageFile );
197            }
198            catch ( IOException ex )
199            {
200                // ignore
201            }
202        }
203
204    }
205
206    // ----------------------------------------------------------------------
207    //
208    // ----------------------------------------------------------------------
209
210    public static Commandline createPushCommandLine( ScmLogger logger, GitScmProviderRepository repository,
211                                                     ScmFileSet fileSet, ScmVersion version )
212        throws ScmException
213    {
214        Commandline cl = GitCommandLineUtils.getBaseGitCommandLine( fileSet.getBasedir(), "push" );
215
216        String branch = GitBranchCommand.getCurrentBranch( logger, repository, fileSet );
217        
218        if ( branch == null || branch.length() == 0 )
219        {
220            throw new ScmException( "Could not detect the current branch. Don't know where I should push to!" );
221        }
222        
223        cl.createArg().setValue( repository.getPushUrl() );
224        
225        cl.createArg().setValue( "refs/heads/" + branch + ":" + "refs/heads/" + branch );
226
227        return cl;
228    }
229
230    public static Commandline createCommitCommandLine( GitScmProviderRepository repository, ScmFileSet fileSet,
231                                                       File messageFile )
232        throws ScmException
233    {
234        Commandline cl = GitCommandLineUtils.getBaseGitCommandLine( fileSet.getBasedir(), "commit" );
235
236        cl.createArg().setValue( "--verbose" );
237
238        cl.createArg().setValue( "-F" );
239
240        cl.createArg().setValue( messageFile.getAbsolutePath() );
241
242        if ( fileSet.getFileList().isEmpty() )
243        {
244            // commit all tracked files
245            cl.createArg().setValue( "-a" );
246        }
247        else
248        {
249            // specify exactly which files to commit
250            GitCommandLineUtils.addTarget( cl, fileSet.getFileList() );
251        }
252
253        if ( GitUtil.getSettings().isCommitNoVerify() )
254        {
255            cl.createArg().setValue( "--no-verify" );
256        }
257
258        return cl;
259    }
260
261}