summaryrefslogtreecommitdiffstats
path: root/javatests/com/google/gerrit/acceptance/git/AbstractSubmoduleSubscription.java
blob: 943b052e07692931e6de0e0feab821014597401d (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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Copyright (C) 2015 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.acceptance.git;

import static com.google.common.truth.Truth.assertThat;
import static java.util.stream.Collectors.toList;

import com.google.common.collect.Iterables;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.Permission;
import com.google.gerrit.common.data.SubscribeSection;
import com.google.gerrit.extensions.client.SubmitType;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.git.meta.MetaDataUpdate;
import com.google.gerrit.server.project.ProjectConfig;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.StreamSupport;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevObject;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteRefUpdate;
import org.eclipse.jgit.transport.RemoteRefUpdate.Status;

public abstract class AbstractSubmoduleSubscription extends AbstractDaemonTest {

  protected SubmitType getSubmitType() {
    return cfg.getEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
  }

  protected static Config submitByMergeAlways() {
    Config cfg = new Config();
    cfg.setBoolean("change", null, "submitWholeTopic", true);
    cfg.setEnum("project", null, "submitType", SubmitType.MERGE_ALWAYS);
    return cfg;
  }

  protected static Config submitByMergeIfNecessary() {
    Config cfg = new Config();
    cfg.setBoolean("change", null, "submitWholeTopic", true);
    cfg.setEnum("project", null, "submitType", SubmitType.MERGE_IF_NECESSARY);
    return cfg;
  }

  protected static Config submitByCherryPickConfig() {
    Config cfg = new Config();
    cfg.setBoolean("change", null, "submitWholeTopic", true);
    cfg.setEnum("project", null, "submitType", SubmitType.CHERRY_PICK);
    return cfg;
  }

  protected static Config submitByRebaseAlwaysConfig() {
    Config cfg = new Config();
    cfg.setBoolean("change", null, "submitWholeTopic", true);
    cfg.setEnum("project", null, "submitType", SubmitType.REBASE_ALWAYS);
    return cfg;
  }

  protected static Config submitByRebaseIfNecessaryConfig() {
    Config cfg = new Config();
    cfg.setBoolean("change", null, "submitWholeTopic", true);
    cfg.setEnum("project", null, "submitType", SubmitType.REBASE_IF_NECESSARY);
    return cfg;
  }

  protected TestRepository<?> createProjectWithPush(
      String name,
      @Nullable Project.NameKey parent,
      boolean createEmptyCommit,
      SubmitType submitType)
      throws Exception {
    Project.NameKey project = createProject(name, parent, createEmptyCommit, submitType);
    grant(project, "refs/heads/*", Permission.PUSH);
    grant(project, "refs/for/refs/heads/*", Permission.SUBMIT);
    return cloneProject(project);
  }

  protected TestRepository<?> createProjectWithPush(String name, @Nullable Project.NameKey parent)
      throws Exception {
    return createProjectWithPush(name, parent, true, getSubmitType());
  }

  protected TestRepository<?> createProjectWithPush(String name, boolean createEmptyCommit)
      throws Exception {
    return createProjectWithPush(name, null, createEmptyCommit, getSubmitType());
  }

  protected TestRepository<?> createProjectWithPush(String name) throws Exception {
    return createProjectWithPush(name, null, true, getSubmitType());
  }

  private static AtomicInteger contentCounter = new AtomicInteger(0);

  protected ObjectId pushChangeTo(
      TestRepository<?> repo, String ref, String file, String content, String message, String topic)
      throws Exception {
    ObjectId ret =
        repo.branch("HEAD").commit().insertChangeId().message(message).add(file, content).create();

    String pushedRef = ref;
    if (!topic.isEmpty()) {
      pushedRef += "/" + name(topic);
    }
    String refspec = "HEAD:" + pushedRef;

    Iterable<PushResult> res =
        repo.git().push().setRemote("origin").setRefSpecs(new RefSpec(refspec)).call();

    RemoteRefUpdate u = Iterables.getOnlyElement(res).getRemoteUpdate(pushedRef);
    assertThat(u).isNotNull();
    assertThat(u.getStatus()).isEqualTo(Status.OK);
    assertThat(u.getNewObjectId()).isEqualTo(ret);

    return ret;
  }

  protected ObjectId pushChangeTo(TestRepository<?> repo, String ref, String message, String topic)
      throws Exception {
    return pushChangeTo(
        repo, ref, "a.txt", "a contents: " + contentCounter.incrementAndGet(), message, topic);
  }

  protected ObjectId pushChangeTo(TestRepository<?> repo, String branch) throws Exception {
    return pushChangeTo(repo, "refs/heads/" + branch, "some change", "");
  }

  protected ObjectId pushChangesTo(TestRepository<?> repo, String branch, int numChanges)
      throws Exception {
    for (int i = 0; i < numChanges; i++) {
      repo.branch("HEAD")
          .commit()
          .insertChangeId()
          .message("Message " + i)
          .add(name("file"), "content" + i)
          .create();
    }
    String remoteBranch = "refs/heads/" + branch;
    Iterable<PushResult> res =
        repo.git()
            .push()
            .setRemote("origin")
            .setRefSpecs(new RefSpec("HEAD:" + remoteBranch))
            .call();
    List<Status> status =
        StreamSupport.stream(res.spliterator(), false)
            .map(r -> r.getRemoteUpdate(remoteBranch).getStatus())
            .collect(toList());
    assertThat(status).containsExactly(Status.OK);
    return Iterables.getLast(res).getRemoteUpdate(remoteBranch).getNewObjectId();
  }

  protected void allowSubmoduleSubscription(
      String submodule, String subBranch, String superproject, String superBranch, boolean match)
      throws Exception {
    Project.NameKey sub = new Project.NameKey(name(submodule));
    Project.NameKey superName = new Project.NameKey(name(superproject));
    try (MetaDataUpdate md = metaDataUpdateFactory.create(sub)) {
      md.setMessage("Added superproject subscription");
      SubscribeSection s;
      ProjectConfig pc = ProjectConfig.read(md);
      if (pc.getSubscribeSections().containsKey(superName)) {
        s = pc.getSubscribeSections().get(superName);
      } else {
        s = new SubscribeSection(superName);
      }
      String refspec;
      if (superBranch == null) {
        refspec = subBranch;
      } else {
        refspec = subBranch + ":" + superBranch;
      }
      if (match) {
        s.addMatchingRefSpec(refspec);
      } else {
        s.addMultiMatchRefSpec(refspec);
      }
      pc.addSubscribeSection(s);
      ObjectId oldId = pc.getRevision();
      ObjectId newId = pc.commit(md);
      assertThat(newId).isNotEqualTo(oldId);
      projectCache.evict(pc.getProject());
    }
  }

  protected void allowMatchingSubmoduleSubscription(
      String submodule, String subBranch, String superproject, String superBranch)
      throws Exception {
    allowSubmoduleSubscription(submodule, subBranch, superproject, superBranch, true);
  }

  protected void createSubmoduleSubscription(
      TestRepository<?> repo, String branch, String subscribeToRepo, String subscribeToBranch)
      throws Exception {
    Config config = new Config();
    prepareSubmoduleConfigEntry(config, subscribeToRepo, subscribeToBranch);
    pushSubmoduleConfig(repo, branch, config);
  }

  protected void createRelativeSubmoduleSubscription(
      TestRepository<?> repo,
      String branch,
      String subscribeToRepoPrefix,
      String subscribeToRepo,
      String subscribeToBranch)
      throws Exception {
    Config config = new Config();
    prepareRelativeSubmoduleConfigEntry(
        config, subscribeToRepoPrefix, subscribeToRepo, subscribeToBranch);
    pushSubmoduleConfig(repo, branch, config);
  }

  protected void prepareRelativeSubmoduleConfigEntry(
      Config config,
      String subscribeToRepoPrefix,
      String subscribeToRepo,
      String subscribeToBranch) {
    subscribeToRepo = name(subscribeToRepo);
    String url = subscribeToRepoPrefix + subscribeToRepo;
    config.setString("submodule", subscribeToRepo, "path", subscribeToRepo);
    config.setString("submodule", subscribeToRepo, "url", url);
    if (subscribeToBranch != null) {
      config.setString("submodule", subscribeToRepo, "branch", subscribeToBranch);
    }
  }

  protected void prepareSubmoduleConfigEntry(
      Config config, String subscribeToRepo, String subscribeToBranch) {
    // The submodule subscription module checks for gerrit.canonicalWebUrl to
    // detect if it's configured for automatic updates. It doesn't matter if
    // it serves from that URL.
    prepareSubmoduleConfigEntry(config, subscribeToRepo, subscribeToRepo, subscribeToBranch);
  }

  protected void prepareSubmoduleConfigEntry(
      Config config, String subscribeToRepo, String subscribeToRepoPath, String subscribeToBranch) {
    subscribeToRepo = name(subscribeToRepo);
    subscribeToRepoPath = name(subscribeToRepoPath);
    // The submodule subscription module checks for gerrit.canonicalWebUrl to
    // detect if it's configured for automatic updates. It doesn't matter if
    // it serves from that URL.
    String url = cfg.getString("gerrit", null, "canonicalWebUrl") + "/" + subscribeToRepo;
    config.setString("submodule", subscribeToRepoPath, "path", subscribeToRepoPath);
    config.setString("submodule", subscribeToRepoPath, "url", url);
    if (subscribeToBranch != null) {
      config.setString("submodule", subscribeToRepoPath, "branch", subscribeToBranch);
    }
  }

  protected void pushSubmoduleConfig(TestRepository<?> repo, String branch, Config config)
      throws Exception {

    repo.branch("HEAD")
        .commit()
        .insertChangeId()
        .message("subject: adding new subscription")
        .add(".gitmodules", config.toText())
        .create();

    repo.git()
        .push()
        .setRemote("origin")
        .setRefSpecs(new RefSpec("HEAD:refs/heads/" + branch))
        .call();
  }

  protected void expectToHaveSubmoduleState(
      TestRepository<?> repo,
      String branch,
      String submodule,
      TestRepository<?> subRepo,
      String subBranch)
      throws Exception {

    submodule = name(submodule);
    ObjectId commitId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();

    ObjectId subHead =
        subRepo
            .git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/" + subBranch)
            .getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    rw.parseBody(c.getTree());

    RevTree tree = c.getTree();
    RevObject actualId = repo.get(tree, submodule);

    assertThat(actualId).isEqualTo(subHead);
  }

  protected void expectToHaveSubmoduleState(
      TestRepository<?> repo, String branch, String submodule, ObjectId expectedId)
      throws Exception {

    submodule = name(submodule);
    ObjectId commitId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    rw.parseBody(c.getTree());

    RevTree tree = c.getTree();
    RevObject actualId = repo.get(tree, submodule);

    assertThat(actualId).isEqualTo(expectedId);
  }

  protected void deleteAllSubscriptions(TestRepository<?> repo, String branch) throws Exception {
    repo.git().fetch().setRemote("origin").call();
    repo.reset("refs/remotes/origin/" + branch);

    ObjectId expectedId =
        repo.branch("HEAD")
            .commit()
            .insertChangeId()
            .message("delete contents in .gitmodules")
            .add(".gitmodules", "") // Just remove the contents of the file!
            .create();
    repo.git()
        .push()
        .setRemote("origin")
        .setRefSpecs(new RefSpec("HEAD:refs/heads/" + branch))
        .call();

    ObjectId actualId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/master")
            .getObjectId();
    assertThat(actualId).isEqualTo(expectedId);
  }

  protected void deleteGitModulesFile(TestRepository<?> repo, String branch) throws Exception {
    repo.git().fetch().setRemote("origin").call();
    repo.reset("refs/remotes/origin/" + branch);

    ObjectId expectedId =
        repo.branch("HEAD")
            .commit()
            .insertChangeId()
            .message("delete .gitmodules")
            .rm(".gitmodules")
            .create();
    repo.git()
        .push()
        .setRemote("origin")
        .setRefSpecs(new RefSpec("HEAD:refs/heads/" + branch))
        .call();

    ObjectId actualId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/master")
            .getObjectId();
    assertThat(actualId).isEqualTo(expectedId);
  }

  protected boolean hasSubmodule(TestRepository<?> repo, String branch, String submodule)
      throws Exception {

    submodule = name(submodule);
    Ref branchTip =
        repo.git().fetch().setRemote("origin").call().getAdvertisedRef("refs/heads/" + branch);
    if (branchTip == null) {
      return false;
    }

    ObjectId commitId = branchTip.getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    rw.parseBody(c.getTree());

    RevTree tree = c.getTree();
    try {
      repo.get(tree, submodule);
      return true;
    } catch (AssertionError e) {
      return false;
    }
  }

  protected void expectToHaveCommitMessage(
      TestRepository<?> repo, String branch, String expectedMessage) throws Exception {

    ObjectId commitId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    assertThat(c.getFullMessage()).isEqualTo(expectedMessage);
  }

  protected PersonIdent getAuthor(TestRepository<?> repo, String branch) throws Exception {
    ObjectId commitId =
        repo.git()
            .fetch()
            .setRemote("origin")
            .call()
            .getAdvertisedRef("refs/heads/" + branch)
            .getObjectId();

    RevWalk rw = repo.getRevWalk();
    RevCommit c = rw.parseCommit(commitId);
    return c.getAuthorIdent();
  }

  protected void directUpdateSubmodule(String project, String refName, String path, AnyObjectId id)
      throws Exception {
    path = name(path);
    try (Repository serverRepo = repoManager.openRepository(new Project.NameKey(name(project)));
        ObjectInserter ins = serverRepo.newObjectInserter();
        RevWalk rw = new RevWalk(serverRepo)) {
      Ref ref = serverRepo.exactRef(refName);
      assertThat(ref).named(refName).isNotNull();
      ObjectId oldCommitId = ref.getObjectId();

      DirCache dc = DirCache.newInCore();
      DirCacheBuilder b = dc.builder();
      b.addTree(
          new byte[0], DirCacheEntry.STAGE_0, rw.getObjectReader(), rw.parseTree(oldCommitId));
      b.finish();
      DirCacheEditor e = dc.editor();
      e.add(
          new PathEdit(path) {
            @Override
            public void apply(DirCacheEntry ent) {
              ent.setFileMode(FileMode.GITLINK);
              ent.setObjectId(id);
            }
          });
      e.finish();

      CommitBuilder cb = new CommitBuilder();
      cb.addParentId(oldCommitId);
      cb.setTreeId(dc.writeTree(ins));
      PersonIdent ident = serverIdent.get();
      cb.setAuthor(ident);
      cb.setCommitter(ident);
      cb.setMessage("Direct update submodule " + path);
      ObjectId newCommitId = ins.insert(cb);
      ins.flush();

      RefUpdate ru = serverRepo.updateRef(refName);
      ru.setExpectedOldObjectId(oldCommitId);
      ru.setNewObjectId(newCommitId);
      assertThat(ru.update()).isEqualTo(RefUpdate.Result.FAST_FORWARD);
    }
  }
}