Exemple #1
0
  @Test
  public void listProjectsWithTree() throws Exception {
    Project.NameKey someParentProject = createProject("some-parent-project");
    Project.NameKey someChildProject = createProject("some-child-project", someParentProject);

    Map<String, ProjectInfo> result = gApi.projects().list().withTree(true).getAsMap();
    assertThat(result).containsKey(someChildProject.get());
    assertThat(result.get(someChildProject.get()).parent).isEqualTo(someParentProject.get());
  }
 List<URIish> getURIs(Project.NameKey project, String urlMatch) {
   List<URIish> r = Lists.newArrayListWithCapacity(config.getRemoteConfig().getURIs().size());
   for (URIish uri : config.getRemoteConfig().getURIs()) {
     if (matches(uri, urlMatch)) {
       String name = project.get();
       if (needsUrlEncoding(uri)) {
         name = encode(name);
       }
       String remoteNameStyle = config.getRemoteNameStyle();
       if (remoteNameStyle.equals("dash")) {
         name = name.replace("/", "-");
       } else if (remoteNameStyle.equals("underscore")) {
         name = name.replace("/", "_");
       } else if (remoteNameStyle.equals("basenameOnly")) {
         name = FilenameUtils.getBaseName(name);
       } else if (!remoteNameStyle.equals("slash")) {
         repLog.debug(
             String.format("Unknown remoteNameStyle: %s, falling back to slash", remoteNameStyle));
       }
       String replacedPath =
           ReplicationQueue.replaceName(uri.getPath(), name, isSingleProjectMatch());
       if (replacedPath != null) {
         uri = uri.setPath(replacedPath);
         r.add(uri);
       }
     }
   }
   return r;
 }
 private void beforeTest(Config cfg, boolean memory, boolean enableHttpd) throws Exception {
   server = startServer(cfg, memory, enableHttpd);
   server.getTestInjector().injectMembers(this);
   admin = accounts.admin();
   user = accounts.user();
   adminSession = new RestSession(server, admin);
   userSession = new RestSession(server, user);
   initSsh(admin);
   db = reviewDbProvider.open();
   Context ctx = newRequestContext(admin);
   atrScope.set(ctx);
   sshSession = ctx.getSession();
   project = new Project.NameKey("p");
   createProject(sshSession, project.get());
   git = cloneProject(sshSession.getUrl() + "/" + project.get());
 }
  protected ChangeInserter newChange(
      TestRepository<Repo> repo,
      @Nullable RevCommit commit,
      @Nullable String key,
      @Nullable Integer owner,
      @Nullable String branch)
      throws Exception {
    if (commit == null) {
      commit = repo.parseBody(repo.commit().message("message").create());
    }
    Account.Id ownerId = owner != null ? new Account.Id(owner) : userId;
    branch = MoreObjects.firstNonNull(branch, "refs/heads/master");
    if (!branch.startsWith("refs/heads/")) {
      branch = "refs/heads/" + branch;
    }
    Project.NameKey project =
        new Project.NameKey(repo.getRepository().getDescription().getRepositoryName());

    Change.Id id = new Change.Id(db.nextChangeId());
    if (key == null) {
      key =
          "I"
              + Hashing.sha1()
                  .newHasher()
                  .putInt(id.get())
                  .putString(project.get(), UTF_8)
                  .putString(commit.name(), UTF_8)
                  .putInt(ownerId.get())
                  .putString(branch, UTF_8)
                  .hash()
                  .toString();
    }

    Change change =
        new Change(
            new Change.Key(key),
            id,
            ownerId,
            new Branch.NameKey(project, branch),
            TimeUtil.nowTs());
    IdentifiedUser user = userFactory.create(Providers.of(db), ownerId);
    return changeFactory.create(projectControlFactory.controlFor(project, user), change, commit);
  }
      @Override
      protected void setCurrentUrl(DownloadUrlLink link) {
        widget.setVisible(true);

        String sshPort = "29418";
        String sshAddr = Gerrit.getConfig().getSshdAddress();
        int p = sshAddr.lastIndexOf(':');
        if (p != -1 && !sshAddr.endsWith(":")) {
          sshPort = sshAddr.substring(p + 1);
        }

        StringBuilder cmd = new StringBuilder();
        cmd.append("git clone ");
        cmd.append(link.getUrlData());
        cmd.append(" && scp -p -P ");
        cmd.append(sshPort);
        cmd.append(" ");
        cmd.append(Gerrit.getUserAccount().getUserName());
        cmd.append("@");

        if (sshAddr.startsWith("*:") || p == -1) {
          cmd.append(Window.Location.getHostName());
        } else {
          cmd.append(sshAddr.substring(0, p));
        }

        cmd.append(":hooks/commit-msg ");

        p = project.get().lastIndexOf('/');
        if (p != -1) {
          cmd.append(project.get().substring(p + 1));
        } else {
          cmd.append(project.get());
        }

        cmd.append("/.git/hooks/");

        copyLabel.setText(cmd.toString());
      }
  void schedule(Project.NameKey project, String ref, URIish uri, ReplicationState state) {
    repLog.info("scheduling replication {}:{} => {}", project, ref, uri);
    if (!shouldReplicate(project, ref, state)) {
      return;
    }

    if (!config.replicatePermissions()) {
      PushOne e;
      synchronized (stateLock) {
        e = pending.get(uri);
      }
      if (e == null) {
        try (Repository git = gitManager.openRepository(project)) {
          try {
            Ref head = git.exactRef(Constants.HEAD);
            if (head != null
                && head.isSymbolic()
                && RefNames.REFS_CONFIG.equals(head.getLeaf().getName())) {
              return;
            }
          } catch (IOException err) {
            stateLog.error(String.format("cannot check type of project %s", project), err, state);
            return;
          }
        } catch (IOException err) {
          stateLog.error(String.format("source project %s not available", project), err, state);
          return;
        }
      }
    }

    synchronized (stateLock) {
      PushOne e = pending.get(uri);
      if (e == null) {
        e = opFactory.create(project, uri);
        pool.schedule(e, config.getDelay(), TimeUnit.SECONDS);
        pending.put(uri, e);
      }
      e.addRef(ref);
      state.increasePushTaskCount(project.get(), ref);
      e.addState(ref, state);
      repLog.info("scheduled {}:{} => {} to run after {}s", project, ref, e, config.getDelay());
    }
  }
Exemple #7
0
  private void openRepository(Project.NameKey name)
      throws IntegrationException, NoSuchProjectException {
    try {
      repo = repoManager.openRepository(name);
    } catch (RepositoryNotFoundException notFound) {
      throw new NoSuchProjectException(name, notFound);
    } catch (IOException err) {
      String m = "Error opening repository \"" + name.get() + '"';
      throw new IntegrationException(m, err);
    }

    rw = CodeReviewCommit.newRevWalk(repo);
    rw.sort(RevSort.TOPO);
    rw.sort(RevSort.COMMIT_TIME_DESC, true);
    rw.setRetainBody(false);
    canMergeFlag = rw.newFlag("CAN_MERGE");

    inserter = repo.newObjectInserter();
  }
 private static Predicate<ChangeData> project(Project.NameKey project) {
   return new ProjectPredicate(project.get());
 }
    @Override
    public void onPreMerge(
        final Repository repo,
        final CodeReviewCommit commit,
        final ProjectState destProject,
        final Branch.NameKey destBranch,
        final PatchSet.Id patchSetId)
        throws MergeValidationException {
      if (RefNames.REFS_CONFIG.equals(destBranch.get())) {
        final Project.NameKey newParent;
        try {
          ProjectConfig cfg = new ProjectConfig(destProject.getProject().getNameKey());
          cfg.load(repo, commit);
          newParent = cfg.getProject().getParent(allProjectsName);
          final Project.NameKey oldParent = destProject.getProject().getParent(allProjectsName);
          if (oldParent == null) {
            // update of the 'All-Projects' project
            if (newParent != null) {
              throw new MergeValidationException(ROOT_NO_PARENT);
            }
          } else {
            if (!oldParent.equals(newParent)) {
              PatchSetApproval psa = approvalsUtil.getSubmitter(db, commit.notes(), patchSetId);
              if (psa == null) {
                throw new MergeValidationException(SET_BY_ADMIN);
              }
              final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId());
              if (!submitter.getCapabilities().canAdministrateServer()) {
                throw new MergeValidationException(SET_BY_ADMIN);
              }

              if (projectCache.get(newParent) == null) {
                throw new MergeValidationException(PARENT_NOT_FOUND);
              }
            }
          }

          for (Entry<ProjectConfigEntry> e : pluginConfigEntries) {
            PluginConfig pluginCfg = cfg.getPluginConfig(e.getPluginName());
            ProjectConfigEntry configEntry = e.getProvider().get();

            String value = pluginCfg.getString(e.getExportName());
            String oldValue =
                destProject
                    .getConfig()
                    .getPluginConfig(e.getPluginName())
                    .getString(e.getExportName());

            if ((value == null ? oldValue != null : !value.equals(oldValue))
                && !configEntry.isEditable(destProject)) {
              throw new MergeValidationException(PLUGIN_VALUE_NOT_EDITABLE);
            }

            if (ProjectConfigEntry.Type.LIST.equals(configEntry.getType())
                && value != null
                && !configEntry.getPermittedValues().contains(value)) {
              throw new MergeValidationException(PLUGIN_VALUE_NOT_PERMITTED);
            }
          }
        } catch (ConfigInvalidException | IOException e) {
          throw new MergeValidationException(INVALID_CONFIG);
        }
      }
    }