/**
  * Creates new PersonIdent from config info in repository, with current time. This new PersonIdent
  * gets the info from the default committer as available from the configuration.
  *
  * @param repo
  */
 public PersonIdent(final Repository repo) {
   final UserConfig config = repo.getConfig().get(UserConfig.KEY);
   name = config.getCommitterName();
   emailAddress = config.getCommitterEmail();
   when = SystemReader.getInstance().getCurrentTime();
   tzOffset = SystemReader.getInstance().getTimezone(when);
 }
Exemple #2
0
  private static boolean isValidPathSegment(CanonicalTreeParser t) {
    boolean isWindows = SystemReader.getInstance().isWindows();
    boolean isOSX = SystemReader.getInstance().isMacOS();
    boolean ignCase = isOSX || isWindows;

    int ptr = t.getNameOffset();
    byte[] raw = t.getEntryPathBuffer();
    int end = ptr + t.getNameLength();

    // Validate path component at this level of the tree
    int start = ptr;
    while (ptr < end) {
      if (raw[ptr] == '/') return false;
      if (isWindows) {
        if (raw[ptr] == '\\') return false;
        if (raw[ptr] == ':') return false;
      }
      ptr++;
    }
    // '.' and '.'' are invalid here
    if (ptr - start == 1) {
      if (raw[start] == '.') return false;
    } else if (ptr - start == 2) {
      if (raw[start] == '.') if (raw[start + 1] == '.') return false;
    } else if (ptr - start == 4) {
      // .git (possibly case insensitive) is disallowed
      if (raw[start] == '.')
        if (raw[start + 1] == 'g' || (ignCase && raw[start + 1] == 'G'))
          if (raw[start + 2] == 'i' || (ignCase && raw[start + 2] == 'I'))
            if (raw[start + 3] == 't' || (ignCase && raw[start + 3] == 'T')) return false;
    }
    if (isWindows) {
      // Space or period at end of file name is ignored by Windows.
      // Treat this as a bad path for now. We may want to handle
      // this as case insensitivity in the future.
      if (raw[ptr - 1] == '.' || raw[ptr - 1] == ' ') return false;
      int i;
      // Bad names, eliminate suffix first
      for (i = start; i < ptr; ++i) if (raw[i] == '.') break;
      int len = i - start;
      if (len == 3 || len == 4) {
        for (int j = 0; j < forbidden.length; ++j) {
          if (forbidden[j].length == len) {
            if (toUpper(raw[start]) < forbidden[j][0]) break;
            int k;
            for (k = 0; k < len; ++k) {
              if (toUpper(raw[start + k]) != forbidden[j][k]) break;
            }
            if (k == len) return false;
          }
        }
      }
    }

    return true;
  }
 private String getGerritHost() {
   String url = urlProvider.get();
   if (url != null) {
     try {
       return new URL(url).getHost();
     } catch (MalformedURLException e) {
     }
   }
   return SystemReader.getInstance().getHostname();
 }
  public PersonIdent newCommitterIdent(final Date when, final TimeZone tz) {
    final Account ua = getAccount();
    String name = ua.getFullName();
    String email = ua.getPreferredEmail();

    if (email == null || email.isEmpty()) {
      // No preferred email is configured. Use a generic identity so we
      // don't leak an address the user may have given us, but doesn't
      // necessarily want to publish through Git records.
      //
      String user = getUserName();
      if (user == null || user.isEmpty()) {
        user = "******" + ua.getId().toString();
      }

      String host;
      if (canonicalUrl.get() != null) {
        try {
          host = new URL(canonicalUrl.get()).getHost();
        } catch (MalformedURLException e) {
          host = SystemReader.getInstance().getHostname();
        }
      } else {
        host = SystemReader.getInstance().getHostname();
      }

      email = user + "@" + host;
    }

    if (name == null || name.isEmpty()) {
      final int at = email.indexOf('@');
      if (0 < at) {
        name = email.substring(0, at);
      } else {
        name = anonymousCowardName;
      }
    }

    return new PersonIdent(name, email, when, tz);
  }
  @Test
  public void testRejectInvalidWindowsPaths() throws Exception {
    SystemReader.setInstance(
        new MockSystemReader() {
          {
            setUnix();
          }
        });

    String path = "src/con.txt";
    DirCache dc = db.lockDirCache();
    DirCacheBuilder b = dc.builder();
    DirCacheEntry e = new DirCacheEntry(path);
    e.setFileMode(FileMode.REGULAR_FILE);
    try (ObjectInserter.Formatter formatter = new ObjectInserter.Formatter()) {
      e.setObjectId(formatter.idFor(Constants.OBJ_BLOB, Constants.encode(path)));
    }
    b.add(e);
    b.commit();
    db.readDirCache();

    SystemReader.setInstance(
        new MockSystemReader() {
          {
            setWindows();
          }
        });

    try {
      db.readDirCache();
      fail("should have rejected " + path);
    } catch (CorruptObjectException err) {
      assertEquals(MessageFormat.format(JGitText.get().invalidPath, path), err.getMessage());
      assertNotNull(err.getCause());
      assertEquals("invalid name 'CON'", err.getCause().getMessage());
    }
  }
Exemple #6
0
  @BeforeClass
  public static void beforeClass() throws Exception {

    MockSystemReader mockSystemReader = new MockSystemReader();
    SystemReader.setInstance(mockSystemReader);
    mockSystemReader.setProperty(
        Constants.GIT_CEILING_DIRECTORIES_KEY,
        ResourcesPlugin.getWorkspace()
            .getRoot()
            .getLocation()
            .toFile()
            .getParentFile()
            .getAbsoluteFile()
            .toString());

    TestUtil.showExplorerView();

    ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
  }
 /** Creates a new statistics page */
 public RepositoryStatisticsPage() {
   bigFpFmt = NumberFormat.getInstance(SystemReader.getInstance().getLocale());
   bigFpFmt.setMaximumFractionDigits(2);
   bigIntFmt = NumberFormat.getInstance(SystemReader.getInstance().getLocale());
 }
Exemple #8
0
 @AfterClass
 public static void afterClass() {
   SystemReader.setInstance(null);
 }
 private static SystemReader system() {
   return SystemReader.getInstance();
 }
  /**
   * @param repository the repository
   * @param page the page showing the properties
   */
  public RepositoryPropertySource(Repository repository, PropertySheetPage page) {
    myPage = page;

    effectiveConfig = repository.getConfig();
    systemConfig = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
    userHomeConfig = SystemReader.getInstance().openUserConfig(systemConfig, FS.DETECTED);

    if (effectiveConfig instanceof FileBasedConfig) {
      File configFile = ((FileBasedConfig) effectiveConfig).getFile();
      repositoryConfig = new FileBasedConfig(configFile, repository.getFS());
    } else {
      repositoryConfig = effectiveConfig;
    }

    synchronized (myPage) {
      // check if the actions are already there, if not, create them
      IActionBars bars = myPage.getSite().getActionBars();

      changeModeAction = (ActionContributionItem) bars.getToolBarManager().find(CHANGEMODEACTIONID);
      singleValueToggleAction =
          (ActionContributionItem) bars.getToolBarManager().find(SINGLEVALUEACTIONID);

      if (changeModeAction != null) {
        return;
      }

      changeModeAction =
          new ActionContributionItem(
              new Action(DisplayMode.REPO.getText(), IAction.AS_DROP_DOWN_MENU) {
                @Override
                public String getId() {
                  return CHANGEMODEACTIONID;
                }

                @Override
                public void run() {
                  MenuManager mgr = new MenuManager();
                  ToolItem item = (ToolItem) changeModeAction.getWidget();
                  ToolBar control = item.getParent();
                  final Menu ctxMenu = mgr.createContextMenu(control);

                  for (final DisplayMode aMode : DisplayMode.values()) {
                    mgr.add(
                        new Action(aMode.getText()) {
                          @Override
                          public void run() {
                            changeModeAction.getAction().setText(aMode.getText());
                            editAction.getAction().setEnabled(aMode != DisplayMode.EFFECTIVE);
                            myPage.refresh();
                          }

                          @Override
                          public boolean isEnabled() {
                            return aMode != getCurrentMode();
                          }

                          @Override
                          public boolean isChecked() {
                            return aMode == getCurrentMode();
                          }

                          @Override
                          public int getStyle() {
                            return IAction.AS_CHECK_BOX;
                          }
                        });
                  }

                  ctxMenu.setVisible(true);
                }

                @Override
                public String getToolTipText() {
                  return UIText.RepositoryPropertySource_SelectModeTooltip;
                }

                @Override
                public int getStyle() {
                  return IAction.AS_DROP_DOWN_MENU;
                }
              });

      editAction =
          new ActionContributionItem(
              new Action(UIText.RepositoryPropertySource_EditConfigButton, UIIcons.EDITCONFIG) {
                @Override
                public String getId() {
                  return EDITACTIONID;
                }

                @Override
                public void run() {

                  final StoredConfig config;

                  switch (getCurrentMode()) {
                    case EFFECTIVE:
                      return;
                    case SYSTEM:
                      config = systemConfig;
                      break;
                    case USER:
                      config = userHomeConfig;
                      break;
                    case REPO:
                      config = repositoryConfig;
                      break;
                    default:
                      return;
                  }

                  new EditDialog(
                          myPage.getSite().getShell(),
                          (FileBasedConfig) config,
                          getCurrentMode().getText())
                      .open();
                  myPage.refresh();
                }

                @Override
                public int getStyle() {
                  return IAction.AS_PUSH_BUTTON;
                }
              });

      singleValueToggleAction =
          new ActionContributionItem(
              new Action(UIText.RepositoryPropertySource_SingleValueButton) {
                @Override
                public String getId() {
                  return SINGLEVALUEACTIONID;
                }

                @Override
                public void run() {
                  myPage.refresh();
                }

                @Override
                public int getStyle() {
                  return IAction.AS_CHECK_BOX;
                }

                @Override
                public String getToolTipText() {
                  return UIText.RepositoryPropertySource_SuppressMultipleValueTooltip;
                }
              });

      bars.getToolBarManager().add(new Separator());
      bars.getToolBarManager().add(changeModeAction);
      bars.getToolBarManager().add(singleValueToggleAction);
      bars.getToolBarManager().add(editAction);

      bars.getToolBarManager().update(false);
    }
  }
 /**
  * Construct a new {@link PersonIdent} with current time.
  *
  * @param aName
  * @param aEmailAddress
  */
 public PersonIdent(final String aName, final String aEmailAddress) {
   name = aName;
   emailAddress = aEmailAddress;
   when = SystemReader.getInstance().getCurrentTime();
   tzOffset = SystemReader.getInstance().getTimezone(when);
 }
  @Override
  protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    Repository git;
    try {
      git = mgr.openRepository(allProjects);
    } catch (IOException e) {
      throw new OrmException(e);
    }
    try {
      MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allProjects, git);
      ProjectConfig config = ProjectConfig.read(md);
      Map<Integer, ContributorAgreement> agreements = getAgreementToAdd(db, config);
      if (agreements.isEmpty()) {
        return;
      }
      ui.message("Moved contributor agreements to project.config");

      // Create the auto verify groups.
      List<AccountGroup.UUID> adminGroupUUIDs = getAdministrateServerGroups(db, config);
      for (ContributorAgreement agreement : agreements.values()) {
        if (agreement.getAutoVerify() != null) {
          getOrCreateGroupForIndividuals(db, config, adminGroupUUIDs, agreement);
        }
      }

      // Scan AccountAgreement
      long minTime = addAccountAgreements(db, config, adminGroupUUIDs, agreements);

      ProjectConfig base = ProjectConfig.read(md, null);
      for (ContributorAgreement agreement : agreements.values()) {
        base.replace(agreement);
      }
      base.getAccountsSection()
          .setSameGroupVisibility(config.getAccountsSection().getSameGroupVisibility());

      BatchMetaDataUpdate batch = base.openUpdate(md);
      try {
        // Scan AccountGroupAgreement
        List<AccountGroupAgreement> groupAgreements = getAccountGroupAgreements(db, agreements);

        // Find the earliest change
        for (AccountGroupAgreement aga : groupAgreements) {
          minTime = Math.min(minTime, aga.getTime());
        }
        minTime -= 60 * 1000; // 1 Minute

        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(new PersonIdent(serverUser, new Date(minTime)));
        commit.setCommitter(new PersonIdent(serverUser, new Date(minTime)));
        commit.setMessage(
            "Add the ContributorAgreements for upgrade to Gerrit Code Review schema 65\n");
        batch.write(commit);

        for (AccountGroupAgreement aga : groupAgreements) {
          AccountGroup group = db.accountGroups().get(aga.groupId);
          if (group == null) {
            continue;
          }

          ContributorAgreement agreement = agreements.get(aga.claId);
          agreement.getAccepted().add(new PermissionRule(config.resolve(group)));
          base.replace(agreement);

          PersonIdent ident = null;
          if (aga.reviewedBy != null) {
            Account ua = db.accounts().get(aga.reviewedBy);
            if (ua != null) {
              String name = ua.getFullName();
              String email = ua.getPreferredEmail();

              if (email == null || email.isEmpty()) {
                // No preferred email is configured. Use a generic identity so we
                // don't leak an address the user may have given us, but doesn't
                // necessarily want to publish through Git records.
                //
                String user = ua.getUserName();
                if (user == null || user.isEmpty()) {
                  user = "******" + ua.getId().toString();
                }

                String host = SystemReader.getInstance().getHostname();
                email = user + "@" + host;
              }

              if (name == null || name.isEmpty()) {
                final int at = email.indexOf('@');
                if (0 < at) {
                  name = email.substring(0, at);
                } else {
                  name = anonymousCowardName;
                }
              }

              ident = new PersonIdent(name, email, new Date(aga.getTime()), TimeZone.getDefault());
            }
          }
          if (ident == null) {
            ident = new PersonIdent(serverUser, new Date(aga.getTime()));
          }

          // Build the commits such that it keeps track of the date added and
          // who added it.
          commit = new CommitBuilder();
          commit.setAuthor(ident);
          commit.setCommitter(new PersonIdent(serverUser, new Date(aga.getTime())));

          String msg =
              String.format(
                  "Accept %s contributor agreement for %s\n", agreement.getName(), group.getName());
          if (!Strings.isNullOrEmpty(aga.reviewComments)) {
            msg += "\n" + aga.reviewComments + "\n";
          }
          commit.setMessage(msg);
          batch.write(commit);
        }

        // Merge the agreements with the other data in project.config.
        commit = new CommitBuilder();
        commit.setAuthor(serverUser);
        commit.setCommitter(serverUser);
        commit.setMessage("Upgrade to Gerrit Code Review schema 65\n");
        commit.addParentId(config.getRevision());
        batch.write(config, commit);

        // Save the the final metadata.
        batch.commitAt(config.getRevision());
      } finally {
        batch.close();
      }
    } catch (IOException e) {
      throw new OrmException(e);
    } catch (ConfigInvalidException e) {
      throw new OrmException(e);
    } finally {
      git.close();
    }
  }