summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/main/java/com/google/gerrit/server/project/DashboardsCollection.java
blob: d43a066b6b76d6ecb10c73d06f0cc7f8305bc706 (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
// Copyright (C) 2012 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.project;

import static com.google.gerrit.reviewdb.client.RefNames.REFS_DASHBOARDS;

import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.api.projects.DashboardInfo;
import com.google.gerrit.extensions.api.projects.DashboardSectionInfo;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.AcceptsCreate;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ChildCollection;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.extensions.restapi.Url;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.UrlEncoded;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.permissions.RefPermission;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.List;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.BlobBasedConfig;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;

@Singleton
public class DashboardsCollection
    implements ChildCollection<ProjectResource, DashboardResource>, AcceptsCreate<ProjectResource> {
  public static final String DEFAULT_DASHBOARD_NAME = "default";

  private final GitRepositoryManager gitManager;
  private final DynamicMap<RestView<DashboardResource>> views;
  private final Provider<ListDashboards> list;
  private final Provider<SetDefaultDashboard.CreateDefault> createDefault;
  private final PermissionBackend permissionBackend;

  @Inject
  DashboardsCollection(
      GitRepositoryManager gitManager,
      DynamicMap<RestView<DashboardResource>> views,
      Provider<ListDashboards> list,
      Provider<SetDefaultDashboard.CreateDefault> createDefault,
      PermissionBackend permissionBackend) {
    this.gitManager = gitManager;
    this.views = views;
    this.list = list;
    this.createDefault = createDefault;
    this.permissionBackend = permissionBackend;
  }

  public static boolean isDefaultDashboard(@Nullable String id) {
    return DEFAULT_DASHBOARD_NAME.equals(id);
  }

  public static boolean isDefaultDashboard(@Nullable IdString id) {
    return id != null && isDefaultDashboard(id.toString());
  }

  @Override
  public RestView<ProjectResource> list() throws ResourceNotFoundException {
    return list.get();
  }

  @Override
  public RestModifyView<ProjectResource, ?> create(ProjectResource parent, IdString id)
      throws RestApiException {
    if (isDefaultDashboard(id)) {
      return createDefault.get();
    }
    throw new ResourceNotFoundException(id);
  }

  @Override
  public DashboardResource parse(ProjectResource parent, IdString id)
      throws ResourceNotFoundException, IOException, ConfigInvalidException,
          PermissionBackendException {
    ProjectControl myCtl = parent.getControl();
    if (isDefaultDashboard(id)) {
      return DashboardResource.projectDefault(myCtl);
    }

    DashboardInfo info;
    try {
      info = newDashboardInfo(id.get());
    } catch (InvalidDashboardId e) {
      throw new ResourceNotFoundException(id);
    }

    CurrentUser user = myCtl.getUser();
    for (ProjectState ps : myCtl.getProjectState().tree()) {
      try {
        return parse(ps.controlFor(user), info, myCtl);
      } catch (AmbiguousObjectException | ConfigInvalidException | IncorrectObjectTypeException e) {
        throw new ResourceNotFoundException(id);
      } catch (ResourceNotFoundException e) {
        continue;
      }
    }
    throw new ResourceNotFoundException(id);
  }

  public static String normalizeDashboardRef(String ref) {
    if (!ref.startsWith(REFS_DASHBOARDS)) {
      return REFS_DASHBOARDS + ref;
    }
    return ref;
  }

  private DashboardResource parse(ProjectControl ctl, DashboardInfo info, ProjectControl myCtl)
      throws ResourceNotFoundException, IOException, AmbiguousObjectException,
          IncorrectObjectTypeException, ConfigInvalidException, PermissionBackendException {
    String ref = normalizeDashboardRef(info.ref);
    try {
      permissionBackend
          .user(ctl.getUser())
          .project(ctl.getProject().getNameKey())
          .ref(ref)
          .check(RefPermission.READ);
    } catch (AuthException e) {
      // Don't leak the project's existence
      throw new ResourceNotFoundException(info.id);
    }
    if (!Repository.isValidRefName(ref)) {
      throw new ResourceNotFoundException(info.id);
    }

    try (Repository git = gitManager.openRepository(ctl.getProject().getNameKey())) {
      ObjectId objId = git.resolve(ref + ":" + info.path);
      if (objId == null) {
        throw new ResourceNotFoundException(info.id);
      }
      BlobBasedConfig cfg = new BlobBasedConfig(null, git, objId);
      return new DashboardResource(myCtl, ref, info.path, cfg, false);
    } catch (RepositoryNotFoundException e) {
      throw new ResourceNotFoundException(info.id);
    }
  }

  @Override
  public DynamicMap<RestView<DashboardResource>> views() {
    return views;
  }

  public static DashboardInfo newDashboardInfo(String ref, String path) {
    DashboardInfo info = new DashboardInfo();
    info.ref = ref;
    info.path = path;
    info.id = Joiner.on(':').join(Url.encode(ref), Url.encode(path));
    return info;
  }

  public static class InvalidDashboardId extends Exception {
    private static final long serialVersionUID = 1L;

    public InvalidDashboardId(String id) {
      super(id);
    }
  }

  static DashboardInfo newDashboardInfo(String id) throws InvalidDashboardId {
    DashboardInfo info = new DashboardInfo();
    List<String> parts = Lists.newArrayList(Splitter.on(':').limit(2).split(id));
    if (parts.size() != 2) {
      throw new InvalidDashboardId(id);
    }
    info.id = id;
    info.ref = parts.get(0);
    info.path = parts.get(1);
    return info;
  }

  static DashboardInfo parse(
      Project definingProject,
      String refName,
      String path,
      Config config,
      String project,
      boolean setDefault) {
    DashboardInfo info = newDashboardInfo(refName, path);
    info.project = project;
    info.definingProject = definingProject.getName();
    String query = config.getString("dashboard", null, "title");
    info.title = replace(project, query == null ? info.path : query);
    info.description = replace(project, config.getString("dashboard", null, "description"));
    info.foreach = config.getString("dashboard", null, "foreach");

    if (setDefault) {
      String id = refName + ":" + path;
      info.isDefault = id.equals(defaultOf(definingProject)) ? true : null;
    }

    UrlEncoded u = new UrlEncoded("/dashboard/");
    u.put("title", MoreObjects.firstNonNull(info.title, info.path));
    if (info.foreach != null) {
      u.put("foreach", replace(project, info.foreach));
    }
    for (String name : config.getSubsections("section")) {
      DashboardSectionInfo s = new DashboardSectionInfo();
      s.name = name;
      s.query = config.getString("section", name, "query");
      u.put(s.name, replace(project, s.query));
      info.sections.add(s);
    }
    info.url = u.toString().replace("%3A", ":");

    return info;
  }

  private static String replace(String project, String query) {
    return query.replace("${project}", project);
  }

  private static String defaultOf(Project proj) {
    final String defaultId =
        MoreObjects.firstNonNull(
            proj.getLocalDefaultDashboard(), Strings.nullToEmpty(proj.getDefaultDashboard()));
    if (defaultId.startsWith(REFS_DASHBOARDS)) {
      return defaultId.substring(REFS_DASHBOARDS.length());
    }
    return defaultId;
  }
}