View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.scm.provider.git.jgit.command.blame;
20  
21  import java.io.File;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import org.apache.maven.scm.ScmException;
26  import org.apache.maven.scm.ScmFileSet;
27  import org.apache.maven.scm.command.blame.AbstractBlameCommand;
28  import org.apache.maven.scm.command.blame.BlameLine;
29  import org.apache.maven.scm.command.blame.BlameScmResult;
30  import org.apache.maven.scm.provider.ScmProviderRepository;
31  import org.apache.maven.scm.provider.git.command.GitCommand;
32  import org.apache.maven.scm.provider.git.jgit.command.JGitUtils;
33  import org.eclipse.jgit.api.Git;
34  import org.eclipse.jgit.blame.BlameResult;
35  
36  /**
37   * @author Dominik Bartholdi (imod)
38   * @since 1.9
39   */
40  public class JGitBlameCommand extends AbstractBlameCommand implements GitCommand {
41  
42      @Override
43      public BlameScmResult executeBlameCommand(ScmProviderRepository repo, ScmFileSet workingDirectory, String filename)
44              throws ScmException {
45  
46          Git git = null;
47          File basedir = workingDirectory.getBasedir();
48          try {
49              git = JGitUtils.openRepo(basedir);
50              BlameResult blameResult = git.blame().setFilePath(filename).call();
51  
52              List<BlameLine> lines = new ArrayList<BlameLine>();
53  
54              int i = 0;
55              while ((i = blameResult.computeNext()) != -1) {
56                  lines.add(new BlameLine(
57                          blameResult.getSourceAuthor(i).getWhen(),
58                          blameResult.getSourceCommit(i).getName(),
59                          blameResult.getSourceAuthor(i).getName(),
60                          blameResult.getSourceCommitter(i).getName()));
61              }
62  
63              return new BlameScmResult("JGit blame", lines);
64          } catch (Exception e) {
65              throw new ScmException("JGit blame failure!", e);
66          } finally {
67              JGitUtils.closeRepo(git);
68          }
69      }
70  }