summaryrefslogtreecommitdiffstats
path: root/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/StagingCommand.java
blob: 91fa618369beba12c09ec6c911db77f9c578b67b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.sshd.commands;

import com.google.gerrit.reviewdb.Branch;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gerrit.reviewdb.PatchSetAccess;
import com.google.gerrit.reviewdb.Project;
import com.google.gerrit.reviewdb.RevId;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gwtorm.client.OrmException;

import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.FooterKey;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Constants and utility methods for staging commands.
 *
 */
public class StagingCommand {
  public static class BranchNotFoundException extends Exception {
    private static final long serialVersionUID = 1L;
    public BranchNotFoundException(final String message) {
      super(message);
    }
  }

  public static class UpdateRefException extends Exception {
    private static final long serialVersionUID = 1L;
    public UpdateRefException(final String message) {
      super(message);
    }
  }

  /** Prefix for head refs. */
  public static final String R_HEADS = "refs/heads/";
  /** Prefix for build refs. */
  public static final String R_BUILDS = "refs/builds/";
  /** Prefix for staging refs. */
  public static final String R_STAGING = "refs/staging/";

  /** Private constructor. This class should not be instantiated. */
  private StagingCommand() {

  }

  /**
   * Creates a branch key including ref prefix.
   * @param project Project for the branch key.
   * @param prefix Expected prefix.
   * @param branch Branch name with or without prefix.
   * @return Branch name key with prefix.
   */
  public static Branch.NameKey getNameKey(final String project,
      final String prefix, final String branch) {
    final Project.NameKey projectKey = getProjectKey(project);
    if (branch.startsWith(prefix)) {
      return new Branch.NameKey(projectKey, branch);
    } else {
      return new Branch.NameKey(projectKey, prefix + branch);
    }
  }

  /**
   * Creates a branch key without any prefix.
   * @param project Project for the branch key.
   * @param prefix Prefix to remove.
   * @param branch Branch name with or without prefix.
   * @return Branch name key without prefix.
   */
  public static Branch.NameKey getShortNameKey(final String project,
      final String prefix, final String branch) {
    final Project.NameKey projectKey = getProjectKey(project);
    if (branch.startsWith(prefix)) {
      return new Branch.NameKey(projectKey, branch.substring(prefix.length()));
    } else {
      return new Branch.NameKey(projectKey, branch);
    }
  }

  public static Branch.NameKey getDestinationKey(final Branch.NameKey key) {
    final String branch = key.get();
    if (branch.startsWith(R_STAGING)) {
      return new Branch.NameKey(key.getParentKey(),
          R_HEADS + branch.substring(R_STAGING.length()));
    } else if (branch.startsWith(R_BUILDS)) {
      return new Branch.NameKey(key.getParentKey(),
          R_HEADS + branch.substring(R_BUILDS.length()));
    } else {
      return key;
    }
  }

  public static Project.NameKey getProjectKey(final String project) {
    String projectName = project;
    if (project.endsWith(Constants.DOT_GIT_EXT)) {
      projectName = project.substring(0, //
          project.length() - Constants.DOT_GIT_EXT.length());
    }

    return new Project.NameKey(projectName);
  }

  /**
   * Lists open changes in a branch.
   * @param git jGit Repository. Must be open.
   * @param db ReviewDb of a Gerrit site.
   * @param branch Branch to search for open changes.
   * @param destination Destination branch for changes.
   * @return List of open changes.
   * @throws IOException Thrown by Repository or RevWalk if repository is not
   *         accessible.
   * @throws OrmException Thrown if ReviewDb is not accessible.
   */
  public static List<PatchSet> openChanges(Repository git, ReviewDb db,
      final Branch.NameKey branch, final Branch.NameKey destination)
      throws IOException, OrmException, BranchNotFoundException {
    List<PatchSet> open = new ArrayList<PatchSet>();
    PatchSetAccess patchSetAccess = db.patchSets();

    RevWalk revWalk = new RevWalk(git);

    try {
      Ref ref = git.getRef(branch.get());
      if (ref == null) {
        throw new BranchNotFoundException("No such branch: " + branch);
      }
      RevCommit firstCommit = revWalk.parseCommit(ref.getObjectId());
      revWalk.markStart(firstCommit);
      Iterator<RevCommit> i = revWalk.iterator();

      final String changeIdFooter = "Change-Id";
      FooterKey changeIdKey = new FooterKey(changeIdFooter);
      while (i.hasNext()) {
        RevCommit commit = i.next();
        RevId revId = new RevId(ObjectId.toString(commit));
        List<String> changeIds = commit.getFooterLines(changeIdKey);

        if (changeIds.isEmpty()) {
          // No Change-Id footer available. Search by patch set revision.
          List<PatchSet> patchSets = patchSetAccess.byRevision(revId).toList();
          for (PatchSet patchSet : patchSets) {
            Change.Id changeId = patchSet.getId().getParentKey();
            final Change change = db.changes().get(changeId);
            if (change.getStatus().isOpen()) {
              open.add(patchSet);
              break;
            }
          }
        } else {
          final Branch.NameKey destinationKey =
            getNameKey(destination.getParentKey().get(), R_HEADS,
                destination.get());
          // Change-Id footer found in commit message. Search by Change-Id
          // value.  Usually, there is only 1 Change-Id footer.
          for (String changeId : changeIds) {
            List<Change> changes =
              db.changes().byKey(Change.Key.parse(changeId)).toList();
            for (Change change : changes) {
              if (!change.getDest().equals(destinationKey)) {
                continue;
              }
              if (change.getStatus().isOpen()) {
                open.add(patchSetAccess.get(change.currentPatchSetId()));
              }
            }
          }
        }
      }
    } finally {
      revWalk.dispose();
    }
    return open;
  }
}