@Override
  public boolean load(Properties baseProperties) {
    initialize();
    LOGGER.info("Loading {} ...", propertiesFile);
    if (!Files.exists(propertiesFile)) {
      LOGGER.warn("No {}", propertiesFile);
      return false;
    }

    FileBasedConfig cfg = new FileBasedConfig(propertiesFile.toFile(), FS.DETECTED);
    try {
      cfg.load();
    } catch (ConfigInvalidException e) {
      LOGGER.info("{} has invalid format: {}", propertiesFile, e.getMessage());
      return false;
    } catch (IOException e) {
      LOGGER.info("Cannot read {}: {}", propertiesFile, e.getMessage());
      return false;
    }
    for (Section section : getSections()) {
      if (baseProperties != null) {
        Sections.fromConfig(section, baseProperties.toConfig(), cfg);
      } else {
        Sections.fromConfig(section, cfg);
      }
      Sections.normalize(section);
    }
    return true;
  }
  @Before
  public void setUp() throws Exception {
    super.setUp();

    final TestRepository<FileRepository> src = createTestRepository();
    final String srcName = src.getRepository().getDirectory().getName();

    ServletContextHandler app = server.addContext("/git");
    GitServlet gs = new GitServlet();
    gs.setRepositoryResolver(
        new RepositoryResolver<HttpServletRequest>() {
          public Repository open(HttpServletRequest req, String name)
              throws RepositoryNotFoundException, ServiceNotEnabledException {
            if (!name.equals(srcName)) throw new RepositoryNotFoundException(name);

            final Repository db = src.getRepository();
            db.incrementOpen();
            return db;
          }
        });
    app.addServlet(new ServletHolder(gs), "/*");

    server.setUp();

    remoteRepository = src.getRepository();
    remoteURI = toURIish(app, srcName);

    FileBasedConfig cfg = remoteRepository.getConfig();
    cfg.setBoolean("http", null, "receivepack", true);
    cfg.save();

    a_blob = src.blob("a");
  }
  @Test
  public void testAutoCRLFInput() throws Exception {
    try (Git git = new Git(db)) {
      FileBasedConfig config = db.getConfig();

      // Make sure core.autocrlf is false before adding
      config.setEnum(
          ConfigConstants.CONFIG_CORE_SECTION,
          null,
          ConfigConstants.CONFIG_KEY_AUTOCRLF,
          AutoCRLF.FALSE);
      config.save();

      // File is already in repository with CRLF
      writeTrashFile("crlf.txt", "this\r\ncontains\r\ncrlf\r\n");
      git.add().addFilepattern("crlf.txt").call();
      git.commit().setMessage("Add crlf.txt").call();

      // Now set core.autocrlf to input
      config.setEnum(
          ConfigConstants.CONFIG_CORE_SECTION,
          null,
          ConfigConstants.CONFIG_KEY_AUTOCRLF,
          AutoCRLF.INPUT);
      config.save();

      FileTreeIterator iterator = new FileTreeIterator(db);
      IndexDiff diff = new IndexDiff(db, Constants.HEAD, iterator);
      diff.diff();

      assertTrue(
          "Expected no modified files, but there were: " + diff.getModified(),
          diff.getModified().isEmpty());
    }
  }
  @Test
  public void dontPackHEAD_bare() throws Exception {
    BranchBuilder bb = tr.branch("refs/heads/side");
    bb.commit().add("A", "A").add("B", "B").create();
    RevCommit second = bb.commit().add("A", "A2").add("B", "B2").create();

    // Convert the repo to be bare
    FileBasedConfig cfg = repo.getConfig();
    cfg.setBoolean(
        ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_BARE, true);
    cfg.save();
    Git git = Git.open(repo.getDirectory());
    repo = (FileRepository) git.getRepository();

    // check for the unborn branch master. HEAD should point to master and
    // master doesn't exist.
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());

    // check for non-detached HEAD
    repo.updateRef(Constants.HEAD).link("refs/heads/side");
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
    assertEquals(repo.exactRef("HEAD").getTarget().getObjectId(), second.getId());
  }
  public Repository call() throws JGitInternalException {
    checkCallable();
    if (path == null || path.length() == 0)
      throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
    if (uri == null || uri.length() == 0)
      throw new IllegalArgumentException(JGitText.get().uriNotConfigured);

    try {
      if (submoduleExists())
        throw new JGitInternalException(MessageFormat.format(JGitText.get().submoduleExists, path));
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    // Clone submodule repository
    File moduleDirectory = SubmoduleWalk.getSubmoduleDirectory(repo, path);
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(moduleDirectory);
    clone.setURI(uri);
    if (monitor != null) clone.setProgressMonitor(monitor);
    if (credentialsProvider != null) clone.setCredentialsProvider(credentialsProvider);
    Repository subRepo = clone.call().getRepository();

    // Save submodule URL to parent repository's config
    StoredConfig config = repo.getConfig();
    config.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, uri);
    try {
      config.save();
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    // Save path and URL to parent repository's .gitmodules file
    FileBasedConfig modulesConfig =
        new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
    modulesConfig.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_PATH, path);
    modulesConfig.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, uri);
    try {
      modulesConfig.save();
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    AddCommand add = new AddCommand(repo);
    // Add .gitmodules file to parent repository's index
    add.addFilepattern(Constants.DOT_GIT_MODULES);
    // Add submodule directory to parent repository's index
    add.addFilepattern(path);
    try {
      add.call();
    } catch (NoFilepatternException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    return subRepo;
  }
 private void updateGerritConfig(SitePaths sitePaths, String newSecureStore)
     throws IOException, ConfigInvalidException {
   log.info("Set gerrit.secureStoreClass property of gerrit.config to {}", newSecureStore);
   FileBasedConfig config = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
   config.load();
   config.setString("gerrit", null, "secureStoreClass", newSecureStore);
   config.save();
 }
Exemple #7
0
 private FileBasedConfig getGerritConfigFile(SitePaths sitePath) throws IOException {
   FileBasedConfig cfg = new FileBasedConfig(sitePath.gerrit_config.toFile(), FS.DETECTED);
   if (!cfg.getFile().exists()) {
     Path etc_path = Files.createDirectories(sitePath.etc_dir);
     Files.createFile(etc_path.resolve("gerrit.config"));
   }
   return cfg;
 }
Exemple #8
0
 protected void setPluginConfigString(String name, String value)
     throws IOException, ConfigInvalidException {
   SitePaths sitePath = new SitePaths(testSite);
   FileBasedConfig cfg = getGerritConfigFile(sitePath);
   cfg.load();
   cfg.setString("plugin", pluginName, name, value);
   cfg.save();
 }
 private static String getSecureStoreClassFromGerritConfig(SitePaths sitePaths) {
   FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED);
   try {
     cfg.load();
   } catch (IOException | ConfigInvalidException e) {
     throw new RuntimeException("Cannot read gerrit.config file", e);
   }
   return cfg.getString("gerrit", null, "secureStoreClass");
 }
Exemple #10
0
 private void updateAuthorityConfig(UserCertificateModel ucm) {
   File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
   FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
   if (certificatesConfigFile.exists()) {
     try {
       config.load();
     } catch (Exception e) {
       Utils.showException(GitblitAuthority.this, e);
     }
   }
   ucm.update(config);
   try {
     config.save();
   } catch (Exception e) {
     Utils.showException(GitblitAuthority.this, e);
   }
 }
Exemple #11
0
  private void setMetadataDefaults(X509Metadata metadata) {
    metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
    if (StringUtils.isEmpty(metadata.serverHostname)) {
      metadata.serverHostname = Constants.NAME;
    }

    // set default values from config file
    File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
    FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
    if (certificatesConfigFile.exists()) {
      try {
        config.load();
      } catch (Exception e) {
        Utils.showException(GitblitAuthority.this, e);
      }
      NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
      certificateConfig.update(metadata);
    }
  }
  @Test
  public void testListRemote_Smart_UploadPackDisabled() throws Exception {
    FileRepository src = remoteRepository.getRepository();
    final FileBasedConfig cfg = src.getConfig();
    cfg.setBoolean("http", null, "uploadpack", false);
    cfg.save();

    Repository dst = createBareRepository();
    Transport t = Transport.open(dst, smartAuthNoneURI);
    try {
      try {
        t.openFetch();
        fail("connection opened even though service disabled");
      } catch (TransportException err) {
        String exp = smartAuthNoneURI + ": git-upload-pack not permitted";
        assertEquals(exp, err.getMessage());
      }
    } finally {
      t.close();
    }
  }
  @Override
  public List<MenuEntry> getEntries() {
    if (cfg == null || cfgSnapshot.isModified(cfgFile)) {
      cfgSnapshot = FileSnapshot.save(cfgFile);
      cfg = new FileBasedConfig(cfgFile, FS.DETECTED);
      try {
        cfg.load();
      } catch (ConfigInvalidException | IOException e) {
        return Collections.emptyList();
      }
    }

    List<MenuEntry> menuEntries = new ArrayList<>();
    for (String url : cfg.getSubsections(SECTION_MENU_ITEM)) {
      String name = cfg.getString(SECTION_MENU_ITEM, url, KEY_NAME);
      if (Strings.isNullOrEmpty(name)) {
        continue;
      }

      String topMenu = cfg.getString(SECTION_MENU_ITEM, url, KEY_TOP_MENU);
      if (topMenu == null) {
        topMenu = DEFAULT_TOP_MENU;
      }

      String target = cfg.getString(SECTION_MENU_ITEM, url, KEY_TARGET);
      String id = cfg.getString(SECTION_MENU_ITEM, url, KEY_ID);

      menuEntries.add(
          new MenuEntry(topMenu, Collections.singletonList(new MenuItem(name, url, target, id))));
    }
    return menuEntries;
  }
  public IPropertyDescriptor[] getPropertyDescriptors() {
    try {
      systemConfig.load();
      userHomeConfig.load();
      repositoryConfig.load();
      effectiveConfig.load();
    } catch (IOException e) {
      showExceptionMessage(e);
    } catch (ConfigInvalidException e) {
      showExceptionMessage(e);
    }

    List<IPropertyDescriptor> resultList = new ArrayList<IPropertyDescriptor>();

    StoredConfig config;
    String category;
    String prefix;
    switch (getCurrentMode()) {
      case EFFECTIVE:
        prefix = EFFECTIVE_ID_PREFIX;
        category = UIText.RepositoryPropertySource_EffectiveConfigurationCategory;
        config = effectiveConfig;
        break;
      case REPO:
        {
          prefix = REPO_ID_PREFIX;
          String location = ""; // $NON-NLS-1$
          if (repositoryConfig instanceof FileBasedConfig) {
            location = ((FileBasedConfig) repositoryConfig).getFile().getAbsolutePath();
          }
          category =
              NLS.bind(UIText.RepositoryPropertySource_RepositoryConfigurationCategory, location);
          config = repositoryConfig;
          break;
        }
      case USER:
        {
          prefix = USER_ID_PREFIX;
          String location = userHomeConfig.getFile().getAbsolutePath();
          category =
              NLS.bind(UIText.RepositoryPropertySource_GlobalConfigurationCategory, location);
          config = userHomeConfig;
          break;
        }
      case SYSTEM:
        {
          prefix = SYSTEM_ID_PREFIX;
          String location = systemConfig.getFile().getAbsolutePath();
          category =
              NLS.bind(UIText.RepositoryPropertySource_GlobalConfigurationCategory, location);
          config = systemConfig;
          break;
        }
      default:
        return new IPropertyDescriptor[0];
    }
    for (String key : config.getSections()) {
      for (String sectionItem : config.getNames(key)) {
        String sectionId = key + "." + sectionItem; // $NON-NLS-1$
        PropertyDescriptor desc = new PropertyDescriptor(prefix + sectionId, sectionId);
        desc.setCategory(category);
        resultList.add(desc);
      }
      for (String sub : config.getSubsections(key)) {
        for (String sectionItem : config.getNames(key, sub)) {
          String sectionId = key + "." + sub + "." + sectionItem; // $NON-NLS-1$ //$NON-NLS-2$
          PropertyDescriptor desc = new PropertyDescriptor(prefix + sectionId, sectionId);
          desc.setCategory(category);
          resultList.add(desc);
        }
      }
    }

    return resultList.toArray(new IPropertyDescriptor[0]);
  }
Exemple #15
0
  private void load(File folder) {
    this.folder = folder;
    this.userService = loadUsers(folder);
    System.out.println(Constants.baseFolder$ + " set to " + folder);
    if (userService == null) {
      JOptionPane.showMessageDialog(
          this,
          MessageFormat.format("Sorry, {0} doesn't look like a Gitblit GO installation.", folder));
    } else {
      // build empty certificate model for all users
      Map<String, UserCertificateModel> map = new HashMap<String, UserCertificateModel>();
      for (String user : userService.getAllUsernames()) {
        UserModel model = userService.getUserModel(user);
        UserCertificateModel ucm = new UserCertificateModel(model);
        map.put(user, ucm);
      }
      File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
      FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
      if (certificatesConfigFile.exists()) {
        try {
          config.load();
          // replace user certificate model with actual data
          List<UserCertificateModel> list = UserCertificateConfig.KEY.parse(config).list;
          for (UserCertificateModel ucm : list) {
            ucm.user = userService.getUserModel(ucm.user.username);
            map.put(ucm.user.username, ucm);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (ConfigInvalidException e) {
          e.printStackTrace();
        }
      }

      tableModel.list = new ArrayList<UserCertificateModel>(map.values());
      Collections.sort(tableModel.list);
      tableModel.fireTableDataChanged();
      Utils.packColumns(table, Utils.MARGIN);

      File caKeystore = new File(folder, X509Utils.CA_KEY_STORE);
      if (!caKeystore.exists()) {

        if (!X509Utils.unlimitedStrength) {
          // prompt to confirm user understands JCE Standard Strength encryption
          int res =
              JOptionPane.showConfirmDialog(
                  GitblitAuthority.this,
                  Translation.get("gb.jceWarning"),
                  Translation.get("gb.warning"),
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.WARNING_MESSAGE);
          if (res != JOptionPane.YES_OPTION) {
            if (Desktop.isDesktopSupported()) {
              if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                try {
                  Desktop.getDesktop()
                      .browse(
                          URI.create(
                              "http://www.oracle.com/technetwork/java/javase/downloads/index.html"));
                } catch (IOException e) {
                }
              }
            }
            System.exit(1);
          }
        }

        // show certificate defaults dialog
        certificateDefaultsButton.doClick();

        // create "localhost" ssl certificate
        prepareX509Infrastructure();
      }
    }
  }
Exemple #16
0
 private StoredConfig getConfig() throws IOException, ConfigInvalidException {
   File configFile = new File(folder, X509Utils.CA_CONFIG);
   FileBasedConfig config = new FileBasedConfig(configFile, FS.detect());
   config.load();
   return config;
 }