1   /*
2    * Copyright 2024 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.server.metadata;
17  
18  import java.util.Map.Entry;
19  import java.util.function.BiFunction;
20  
21  import com.google.common.collect.ImmutableMap;
22  
23  import com.linecorp.centraldogma.common.Revision;
24  import com.linecorp.centraldogma.server.internal.metadata.ProjectMetadataTransformer;
25  
26  final class RepositoryMetadataTransformer extends ProjectMetadataTransformer {
27  
28      RepositoryMetadataTransformer(String repoName,
29                                    BiFunction<Revision, RepositoryMetadata, RepositoryMetadata> transformer) {
30          super((headRevision, projectMetadata) -> {
31              final RepositoryMetadata repositoryMetadata = projectMetadata.repo(repoName);
32              assert repositoryMetadata.name().equals(repoName);
33              final RepositoryMetadata newRepositoryMetadata =
34                      transformer.apply(headRevision, repositoryMetadata);
35              return newProjectMetadata(projectMetadata, newRepositoryMetadata);
36          });
37      }
38  
39      private static ProjectMetadata newProjectMetadata(ProjectMetadata projectMetadata,
40                                                        RepositoryMetadata repositoryMetadata) {
41          final ImmutableMap.Builder<String, RepositoryMetadata> builder =
42                  ImmutableMap.builderWithExpectedSize(projectMetadata.repos().size());
43          for (Entry<String, RepositoryMetadata> entry : projectMetadata.repos().entrySet()) {
44              if (entry.getKey().equals(repositoryMetadata.name())) {
45                  builder.put(entry.getKey(), repositoryMetadata);
46              } else {
47                  builder.put(entry);
48              }
49          }
50          final ImmutableMap<String, RepositoryMetadata> newRepos = builder.build();
51          return new ProjectMetadata(projectMetadata.name(),
52                                     newRepos,
53                                     projectMetadata.members(),
54                                     projectMetadata.tokens(),
55                                     projectMetadata.creation(),
56                                     projectMetadata.removal());
57      }
58  }