summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/main/java/com/google/gerrit/server/change/CreateChange.java
blob: bbc3de0027ebe0e5114ab0b9de1c6448b770e51e (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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright (C) 2014 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.server.change;

import static org.eclipse.jgit.lib.Constants.SIGNED_OFF_BY_TAG;

import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Iterables;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.extensions.client.ChangeStatus;
import com.google.gerrit.extensions.client.GeneralPreferencesInfo;
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.ChangeInput;
import com.google.gerrit.extensions.common.MergeInput;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.TopLevelResource;
import com.google.gerrit.extensions.restapi.UnprocessableEntityException;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeFinder;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.PatchSetUtil;
import com.google.gerrit.server.Sequences;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.config.AnonymousCowardName;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MergeUtil;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.permissions.ChangePermission;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.permissions.RefPermission;
import com.google.gerrit.server.project.CommitsCollection;
import com.google.gerrit.server.project.ContributorAgreementsChecker;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.ProjectResource;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.project.ProjectsCollection;
import com.google.gerrit.server.update.BatchUpdate;
import com.google.gerrit.server.update.RetryHelper;
import com.google.gerrit.server.update.RetryingRestModifyView;
import com.google.gerrit.server.update.UpdateException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TreeFormatter;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.ChangeIdUtil;

@Singleton
public class CreateChange
    extends RetryingRestModifyView<TopLevelResource, ChangeInput, Response<ChangeInfo>> {
  private final String anonymousCowardName;
  private final Provider<ReviewDb> db;
  private final GitRepositoryManager gitManager;
  private final AccountCache accountCache;
  private final Sequences seq;
  private final TimeZone serverTimeZone;
  private final PermissionBackend permissionBackend;
  private final Provider<CurrentUser> user;
  private final ProjectsCollection projectsCollection;
  private final CommitsCollection commits;
  private final ChangeInserter.Factory changeInserterFactory;
  private final ChangeJson.Factory jsonFactory;
  private final ChangeFinder changeFinder;
  private final PatchSetUtil psUtil;
  private final MergeUtil.Factory mergeUtilFactory;
  private final SubmitType submitType;
  private final NotifyUtil notifyUtil;
  private final ContributorAgreementsChecker contributorAgreements;
  private final boolean disablePrivateChanges;

  @Inject
  CreateChange(
      @AnonymousCowardName String anonymousCowardName,
      Provider<ReviewDb> db,
      GitRepositoryManager gitManager,
      AccountCache accountCache,
      Sequences seq,
      @GerritPersonIdent PersonIdent myIdent,
      PermissionBackend permissionBackend,
      Provider<CurrentUser> user,
      ProjectsCollection projectsCollection,
      CommitsCollection commits,
      ChangeInserter.Factory changeInserterFactory,
      ChangeJson.Factory json,
      ChangeFinder changeFinder,
      RetryHelper retryHelper,
      PatchSetUtil psUtil,
      @GerritServerConfig Config config,
      MergeUtil.Factory mergeUtilFactory,
      NotifyUtil notifyUtil,
      ContributorAgreementsChecker contributorAgreements) {
    super(retryHelper);
    this.anonymousCowardName = anonymousCowardName;
    this.db = db;
    this.gitManager = gitManager;
    this.accountCache = accountCache;
    this.seq = seq;
    this.serverTimeZone = myIdent.getTimeZone();
    this.permissionBackend = permissionBackend;
    this.user = user;
    this.projectsCollection = projectsCollection;
    this.commits = commits;
    this.changeInserterFactory = changeInserterFactory;
    this.jsonFactory = json;
    this.changeFinder = changeFinder;
    this.psUtil = psUtil;
    this.submitType = config.getEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
    this.disablePrivateChanges = config.getBoolean("change", null, "disablePrivateChanges", false);
    this.mergeUtilFactory = mergeUtilFactory;
    this.notifyUtil = notifyUtil;
    this.contributorAgreements = contributorAgreements;
  }

  @Override
  protected Response<ChangeInfo> applyImpl(
      BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input)
      throws OrmException, IOException, InvalidChangeOperationException, RestApiException,
          UpdateException, PermissionBackendException, ConfigInvalidException {
    if (Strings.isNullOrEmpty(input.project)) {
      throw new BadRequestException("project must be non-empty");
    }

    if (Strings.isNullOrEmpty(input.branch)) {
      throw new BadRequestException("branch must be non-empty");
    }

    String subject = clean(Strings.nullToEmpty(input.subject));
    if (Strings.isNullOrEmpty(subject)) {
      throw new BadRequestException("commit message must be non-empty");
    }

    if (input.status != null) {
      if (input.status != ChangeStatus.NEW) {
        throw new BadRequestException("unsupported change status");
      }
    }

    ProjectResource rsrc = projectsCollection.parse(input.project);
    boolean privateByDefault = rsrc.getProjectState().isPrivateByDefault();
    boolean isPrivate = input.isPrivate == null ? privateByDefault : input.isPrivate;

    if (isPrivate && disablePrivateChanges) {
      throw new MethodNotAllowedException("private changes are disabled");
    }

    contributorAgreements.check(rsrc.getNameKey(), rsrc.getUser());

    Project.NameKey project = rsrc.getNameKey();
    String refName = RefNames.fullName(input.branch);
    permissionBackend.user(user).project(project).ref(refName).check(RefPermission.CREATE_CHANGE);

    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
      ObjectId parentCommit;
      List<String> groups;
      if (input.baseChange != null) {
        List<ChangeNotes> notes = changeFinder.find(input.baseChange);
        if (notes.size() != 1) {
          throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
        }
        ChangeNotes change = Iterables.getOnlyElement(notes);
        if (!permissionBackend.user(user).change(change).database(db).test(ChangePermission.READ)) {
          throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
        }
        PatchSet ps = psUtil.current(db.get(), change);
        parentCommit = ObjectId.fromString(ps.getRevision().get());
        groups = ps.getGroups();
      } else {
        Ref destRef = git.getRefDatabase().exactRef(refName);
        if (destRef != null) {
          if (Boolean.TRUE.equals(input.newBranch)) {
            throw new ResourceConflictException(
                String.format("Branch %s already exists.", refName));
          }
          parentCommit = destRef.getObjectId();
        } else {
          if (Boolean.TRUE.equals(input.newBranch)) {
            parentCommit = null;
          } else {
            throw new UnprocessableEntityException(
                String.format("Branch %s does not exist.", refName));
          }
        }
        groups = Collections.emptyList();
      }
      RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);

      Timestamp now = TimeUtil.nowTs();
      IdentifiedUser me = user.get().asIdentifiedUser();
      PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
      AccountState account = accountCache.get(me.getAccountId());
      GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();

      boolean isWorkInProgress =
          input.workInProgress == null
              ? rsrc.getProjectState().isWorkInProgressByDefault()
                  || MoreObjects.firstNonNull(info.workInProgressByDefault, false)
              : input.workInProgress;

      // Add a Change-Id line if there isn't already one
      String commitMessage = subject;
      if (ChangeIdUtil.indexOfChangeId(commitMessage, "\n") == -1) {
        ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
        ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, commitMessage);
        commitMessage = ChangeIdUtil.insertId(commitMessage, id);
      }

      if (Boolean.TRUE.equals(info.signedOffBy)) {
        commitMessage =
            Joiner.on("\n")
                .join(
                    commitMessage.trim(),
                    String.format(
                        "%s%s",
                        SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName)));
      }

      RevCommit c;
      if (input.merge != null) {
        // create a merge commit
        if (!(submitType.equals(SubmitType.MERGE_ALWAYS)
            || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
          throw new BadRequestException("Submit type: " + submitType + " is not supported");
        }
        c =
            newMergeCommit(
                git, oi, rw, rsrc.getProjectState(), mergeTip, input.merge, author, commitMessage);
      } else {
        // create an empty commit
        c = newCommit(oi, rw, author, mergeTip, commitMessage);
      }

      Change.Id changeId = new Change.Id(seq.nextChangeId());
      ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
      ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
      String topic = input.topic;
      if (topic != null) {
        topic = Strings.emptyToNull(topic.trim());
      }
      ins.setTopic(topic);
      ins.setPrivate(isPrivate);
      ins.setWorkInProgress(isWorkInProgress);
      ins.setGroups(groups);
      ins.setNotify(input.notify);
      ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
      try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
        bu.setRepository(git, rw, oi);
        bu.insertChange(ins);
        bu.execute();
      }
      ChangeJson json = jsonFactory.noOptions();
      return Response.created(json.format(ins.getChange()));
    } catch (IllegalArgumentException e) {
      throw new BadRequestException(e.getMessage());
    }
  }

  private static RevCommit newCommit(
      ObjectInserter oi,
      RevWalk rw,
      PersonIdent authorIdent,
      RevCommit mergeTip,
      String commitMessage)
      throws IOException {
    CommitBuilder commit = new CommitBuilder();
    if (mergeTip == null) {
      commit.setTreeId(emptyTreeId(oi));
    } else {
      commit.setTreeId(mergeTip.getTree().getId());
      commit.setParentId(mergeTip);
    }
    commit.setAuthor(authorIdent);
    commit.setCommitter(authorIdent);
    commit.setMessage(commitMessage);
    return rw.parseCommit(insert(oi, commit));
  }

  private RevCommit newMergeCommit(
      Repository repo,
      ObjectInserter oi,
      RevWalk rw,
      ProjectState projectState,
      RevCommit mergeTip,
      MergeInput merge,
      PersonIdent authorIdent,
      String commitMessage)
      throws RestApiException, IOException {
    if (Strings.isNullOrEmpty(merge.source)) {
      throw new BadRequestException("merge.source must be non-empty");
    }

    RevCommit sourceCommit = MergeUtil.resolveCommit(repo, rw, merge.source);
    if (!commits.canRead(projectState, repo, sourceCommit)) {
      throw new BadRequestException("do not have read permission for: " + merge.source);
    }

    MergeUtil mergeUtil = mergeUtilFactory.create(projectState);
    // default merge strategy from project settings
    String mergeStrategy =
        MoreObjects.firstNonNull(
            Strings.emptyToNull(merge.strategy), mergeUtil.mergeStrategyName());

    return MergeUtil.createMergeCommit(
        oi,
        repo.getConfig(),
        mergeTip,
        sourceCommit,
        mergeStrategy,
        authorIdent,
        commitMessage,
        rw);
  }

  private static ObjectId insert(ObjectInserter inserter, CommitBuilder commit)
      throws IOException, UnsupportedEncodingException {
    ObjectId id = inserter.insert(commit);
    inserter.flush();
    return id;
  }

  private static ObjectId emptyTreeId(ObjectInserter inserter) throws IOException {
    return inserter.insert(new TreeFormatter());
  }

  /**
   * Remove comment lines from a commit message.
   *
   * <p>Based on {@link org.eclipse.jgit.util.ChangeIdUtil#clean}.
   *
   * @param msg
   * @return message without comment lines, possibly empty.
   */
  private String clean(String msg) {
    return msg.replaceAll("(?m)^#.*$\n?", "").trim();
  }
}