List of usage examples for org.eclipse.jgit.lib Repository getConfig
@NonNull public abstract StoredConfig getConfig();
From source file:com.gitblit.manager.RepositoryManager.java
License:Apache License
/** * Creates/updates the repository model keyed by repositoryName. Saves all * repository settings in .git/config. This method allows for renaming * repositories and will update user access permissions accordingly. * * All repositories created by this method are bare and automatically have * .git appended to their names, which is the standard convention for bare * repositories./* w w w . j a va2 s . com*/ * * @param repositoryName * @param repository * @param isCreate * @throws GitBlitException */ @Override public void updateRepositoryModel(String repositoryName, RepositoryModel repository, boolean isCreate) throws GitBlitException { if (isCollectingGarbage(repositoryName)) { throw new GitBlitException( MessageFormat.format("sorry, Gitblit is busy collecting garbage in {0}", repositoryName)); } Repository r = null; String projectPath = StringUtils.getFirstPathElement(repository.name); if (!StringUtils.isEmpty(projectPath)) { if (projectPath.equalsIgnoreCase(settings.getString(Keys.web.repositoryRootGroupName, "main"))) { // strip leading group name repository.name = repository.name.substring(projectPath.length() + 1); } } boolean isRename = false; if (isCreate) { // ensure created repository name ends with .git if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) { repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT; } if (hasRepository(repository.name)) { throw new GitBlitException(MessageFormat .format("Can not create repository ''{0}'' because it already exists.", repository.name)); } // create repository logger.info("create repository " + repository.name); String shared = settings.getString(Keys.git.createRepositoriesShared, "FALSE"); r = JGitUtils.createRepository(repositoriesFolder, repository.name, shared); } else { // rename repository isRename = !repositoryName.equalsIgnoreCase(repository.name); if (isRename) { if (!repository.name.toLowerCase().endsWith(org.eclipse.jgit.lib.Constants.DOT_GIT_EXT)) { repository.name += org.eclipse.jgit.lib.Constants.DOT_GIT_EXT; } if (new File(repositoriesFolder, repository.name).exists()) { throw new GitBlitException( MessageFormat.format("Failed to rename ''{0}'' because ''{1}'' already exists.", repositoryName, repository.name)); } close(repositoryName); File folder = new File(repositoriesFolder, repositoryName); File destFolder = new File(repositoriesFolder, repository.name); if (destFolder.exists()) { throw new GitBlitException(MessageFormat.format( "Can not rename repository ''{0}'' to ''{1}'' because ''{1}'' already exists.", repositoryName, repository.name)); } File parentFile = destFolder.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { throw new GitBlitException( MessageFormat.format("Failed to create folder ''{0}''", parentFile.getAbsolutePath())); } if (!folder.renameTo(destFolder)) { throw new GitBlitException(MessageFormat.format( "Failed to rename repository ''{0}'' to ''{1}''.", repositoryName, repository.name)); } // rename the roles if (!userManager.renameRepositoryRole(repositoryName, repository.name)) { throw new GitBlitException( MessageFormat.format("Failed to rename repository permissions ''{0}'' to ''{1}''.", repositoryName, repository.name)); } // rename fork origins in their configs if (!ArrayUtils.isEmpty(repository.forks)) { for (String fork : repository.forks) { Repository rf = getRepository(fork); try { StoredConfig config = rf.getConfig(); String origin = config.getString("remote", "origin", "url"); origin = origin.replace(repositoryName, repository.name); config.setString("remote", "origin", "url", origin); config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.name); config.save(); } catch (Exception e) { logger.error("Failed to update repository fork config for " + fork, e); } rf.close(); } } // update this repository's origin's fork list if (!StringUtils.isEmpty(repository.originRepository)) { String originKey = getRepositoryKey(repository.originRepository); RepositoryModel origin = repositoryListCache.get(originKey); if (origin != null && !ArrayUtils.isEmpty(origin.forks)) { origin.forks.remove(repositoryName); origin.forks.add(repository.name); } } // clear the cache clearRepositoryMetadataCache(repositoryName); repository.resetDisplayName(); } // load repository logger.info("edit repository " + repository.name); r = getRepository(repository.name); } // update settings if (r != null) { updateConfiguration(r, repository); // Update the description file File descFile = new File(r.getDirectory(), "description"); if (repository.description != null) { com.gitblit.utils.FileUtils.writeContent(descFile, repository.description); } else if (descFile.exists() && !descFile.isDirectory()) { descFile.delete(); } // only update symbolic head if it changes String currentRef = JGitUtils.getHEADRef(r); if (!StringUtils.isEmpty(repository.HEAD) && !repository.HEAD.equals(currentRef)) { logger.info(MessageFormat.format("Relinking {0} HEAD from {1} to {2}", repository.name, currentRef, repository.HEAD)); if (JGitUtils.setHEADtoRef(r, repository.HEAD)) { // clear the cache clearRepositoryMetadataCache(repository.name); } } // Adjust permissions in case we updated the config files JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "config"), settings.getString(Keys.git.createRepositoriesShared, "FALSE")); JGitUtils.adjustSharedPerm(new File(r.getDirectory().getAbsolutePath(), "HEAD"), settings.getString(Keys.git.createRepositoriesShared, "FALSE")); // close the repository object r.close(); } // update repository cache removeFromCachedRepositoryList(repositoryName); // model will actually be replaced on next load because config is stale addToCachedRepositoryList(repository); if (isCreate && pluginManager != null) { for (RepositoryLifeCycleListener listener : pluginManager .getExtensions(RepositoryLifeCycleListener.class)) { try { listener.onCreation(repository); } catch (Throwable t) { logger.error(String.format("failed to call plugin onCreation %s", repositoryName), t); } } } else if (isRename && pluginManager != null) { for (RepositoryLifeCycleListener listener : pluginManager .getExtensions(RepositoryLifeCycleListener.class)) { try { listener.onRename(repositoryName, repository); } catch (Throwable t) { logger.error(String.format("failed to call plugin onRename %s", repositoryName), t); } } } }
From source file:com.gitblit.manager.RepositoryManager.java
License:Apache License
/** * Updates the Gitblit configuration for the specified repository. * * @param r/*from ww w . ja v a 2s . c o m*/ * the Git repository * @param repository * the Gitblit repository model */ @Override public void updateConfiguration(Repository r, RepositoryModel repository) { StoredConfig config = r.getConfig(); config.setString(Constants.CONFIG_GITBLIT, null, "description", repository.description); config.setString(Constants.CONFIG_GITBLIT, null, "originRepository", repository.originRepository); config.setString(Constants.CONFIG_GITBLIT, null, "owner", ArrayUtils.toString(repository.owners)); config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewPatchsets", repository.acceptNewPatchsets); config.setBoolean(Constants.CONFIG_GITBLIT, null, "acceptNewTickets", repository.acceptNewTickets); if (settings.getBoolean(Keys.tickets.requireApproval, false) == repository.requireApproval) { // use default config.unset(Constants.CONFIG_GITBLIT, null, "requireApproval"); } else { // override default config.setBoolean(Constants.CONFIG_GITBLIT, null, "requireApproval", repository.requireApproval); } if (!StringUtils.isEmpty(repository.mergeTo)) { config.setString(Constants.CONFIG_GITBLIT, null, "mergeTo", repository.mergeTo); } if (repository.mergeType == null || repository.mergeType == MergeType.fromName(settings.getString(Keys.tickets.mergeType, null))) { // use default config.unset(Constants.CONFIG_GITBLIT, null, "mergeType"); } else { // override default config.setString(Constants.CONFIG_GITBLIT, null, "mergeType", repository.mergeType.name()); } config.setBoolean(Constants.CONFIG_GITBLIT, null, "useIncrementalPushTags", repository.useIncrementalPushTags); if (StringUtils.isEmpty(repository.incrementalPushTagPrefix) || repository.incrementalPushTagPrefix .equals(settings.getString(Keys.git.defaultIncrementalPushTagPrefix, "r"))) { config.unset(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix"); } else { config.setString(Constants.CONFIG_GITBLIT, null, "incrementalPushTagPrefix", repository.incrementalPushTagPrefix); } config.setBoolean(Constants.CONFIG_GITBLIT, null, "allowForks", repository.allowForks); config.setString(Constants.CONFIG_GITBLIT, null, "accessRestriction", repository.accessRestriction.name()); config.setString(Constants.CONFIG_GITBLIT, null, "authorizationControl", repository.authorizationControl.name()); config.setBoolean(Constants.CONFIG_GITBLIT, null, "verifyCommitter", repository.verifyCommitter); config.setBoolean(Constants.CONFIG_GITBLIT, null, "showRemoteBranches", repository.showRemoteBranches); config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFrozen", repository.isFrozen); config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSizeCalculation", repository.skipSizeCalculation); config.setBoolean(Constants.CONFIG_GITBLIT, null, "skipSummaryMetrics", repository.skipSummaryMetrics); config.setString(Constants.CONFIG_GITBLIT, null, "federationStrategy", repository.federationStrategy.name()); config.setBoolean(Constants.CONFIG_GITBLIT, null, "isFederated", repository.isFederated); config.setString(Constants.CONFIG_GITBLIT, null, "gcThreshold", repository.gcThreshold); if (repository.gcPeriod == settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7)) { // use default from config config.unset(Constants.CONFIG_GITBLIT, null, "gcPeriod"); } else { config.setInt(Constants.CONFIG_GITBLIT, null, "gcPeriod", repository.gcPeriod); } if (repository.lastGC != null) { config.setString(Constants.CONFIG_GITBLIT, null, "lastGC", new SimpleDateFormat(Constants.ISO8601).format(repository.lastGC)); } if (repository.maxActivityCommits == settings.getInteger(Keys.web.maxActivityCommits, 0)) { // use default from config config.unset(Constants.CONFIG_GITBLIT, null, "maxActivityCommits"); } else { config.setInt(Constants.CONFIG_GITBLIT, null, "maxActivityCommits", repository.maxActivityCommits); } CommitMessageRenderer defaultRenderer = CommitMessageRenderer .fromName(settings.getString(Keys.web.commitMessageRenderer, null)); if (repository.commitMessageRenderer == null || repository.commitMessageRenderer == defaultRenderer) { // use default from config config.unset(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer"); } else { // repository overrides default config.setString(Constants.CONFIG_GITBLIT, null, "commitMessageRenderer", repository.commitMessageRenderer.name()); } updateList(config, "federationSets", repository.federationSets); updateList(config, "preReceiveScript", repository.preReceiveScripts); updateList(config, "postReceiveScript", repository.postReceiveScripts); updateList(config, "mailingList", repository.mailingLists); updateList(config, "indexBranch", repository.indexedBranches); updateList(config, "metricAuthorExclusions", repository.metricAuthorExclusions); // User Defined Properties if (repository.customFields != null) { if (repository.customFields.size() == 0) { // clear section config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS); } else { for (Entry<String, String> property : repository.customFields.entrySet()) { // set field String key = property.getKey(); String value = property.getValue(); config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, key, value); } } } try { config.save(); } catch (IOException e) { logger.error("Failed to save repository config!", e); } }
From source file:com.gitblit.models.RepositoryModelTest.java
License:Apache License
@Before public void initializeConfiguration() throws Exception { Repository r = GitBlitSuite.getHelloworldRepository(); StoredConfig config = r.getConfig(); config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS); config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, "commitMessageRegEx", "\\d"); config.setString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, "anotherProperty", "Hello"); config.save();//w w w . j a v a 2 s . c om }
From source file:com.gitblit.models.RepositoryModelTest.java
License:Apache License
@After public void teardownConfiguration() throws Exception { Repository r = GitBlitSuite.getHelloworldRepository(); StoredConfig config = r.getConfig(); config.unsetSection(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS); config.save();/*from w w w. j a v a2 s . c o m*/ }
From source file:com.gitblit.service.MirrorService.java
License:Apache License
@Override public void run() { if (!isReady()) { return;//from w w w.jav a 2 s. co m } running.set(true); for (String repositoryName : repositoryManager.getRepositoryList()) { if (forceClose.get()) { break; } if (repositoryManager.isCollectingGarbage(repositoryName)) { logger.debug("mirror is skipping {} garbagecollection", repositoryName); continue; } RepositoryModel model = null; Repository repository = null; try { model = repositoryManager.getRepositoryModel(repositoryName); if (!model.isMirror && !model.isBare) { // repository must be a valid bare git mirror logger.debug("mirror is skipping {} !mirror !bare", repositoryName); continue; } repository = repositoryManager.getRepository(repositoryName); if (repository == null) { logger.warn( MessageFormat.format("MirrorExecutor is missing repository {0}?!?", repositoryName)); continue; } // automatically repair (some) invalid fetch ref specs if (!repairAttempted.contains(repositoryName)) { repairAttempted.add(repositoryName); JGitUtils.repairFetchSpecs(repository); } // find the first mirror remote - there should only be one StoredConfig rc = repository.getConfig(); RemoteConfig mirror = null; List<RemoteConfig> configs = RemoteConfig.getAllRemoteConfigs(rc); for (RemoteConfig config : configs) { if (config.isMirror()) { mirror = config; break; } } if (mirror == null) { // repository does not have a mirror remote logger.debug("mirror is skipping {} no mirror remote found", repositoryName); continue; } logger.debug("checking {} remote {} for ref updates", repositoryName, mirror.getName()); final boolean testing = false; Git git = new Git(repository); FetchResult result = git.fetch().setRemote(mirror.getName()).setDryRun(testing).call(); Collection<TrackingRefUpdate> refUpdates = result.getTrackingRefUpdates(); if (refUpdates.size() > 0) { ReceiveCommand ticketBranchCmd = null; for (TrackingRefUpdate ru : refUpdates) { StringBuilder sb = new StringBuilder(); sb.append("updated mirror "); sb.append(repositoryName); sb.append(" "); sb.append(ru.getRemoteName()); sb.append(" -> "); sb.append(ru.getLocalName()); if (ru.getResult() == Result.FORCED) { sb.append(" (forced)"); } sb.append(" "); sb.append(ru.getOldObjectId() == null ? "" : ru.getOldObjectId().abbreviate(7).name()); sb.append(".."); sb.append(ru.getNewObjectId() == null ? "" : ru.getNewObjectId().abbreviate(7).name()); logger.info(sb.toString()); if (BranchTicketService.BRANCH.equals(ru.getLocalName())) { ReceiveCommand.Type type = null; switch (ru.getResult()) { case NEW: type = Type.CREATE; break; case FAST_FORWARD: type = Type.UPDATE; break; case FORCED: type = Type.UPDATE_NONFASTFORWARD; break; default: type = null; break; } if (type != null) { ticketBranchCmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(), ru.getLocalName(), type); } } } if (ticketBranchCmd != null) { repository.fireEvent(new ReceiveCommandEvent(model, ticketBranchCmd)); } } } catch (Exception e) { logger.error("Error updating mirror " + repositoryName, e); } finally { // cleanup if (repository != null) { repository.close(); } } } running.set(false); }
From source file:com.gitblit.tests.JGitUtilsTest.java
License:Apache License
@Test public void testCreateRepositoryShared() throws Exception { String[] repositories = { "NewSharedTestRepository.git" }; for (String repositoryName : repositories) { Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName, "group"); File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED); assertNotNull(repository);//from ww w. j a v a2 s . com assertFalse(JGitUtils.hasCommits(repository)); assertNull(JGitUtils.getFirstCommit(repository, null)); assertEquals("1", repository.getConfig().getString("core", null, "sharedRepository")); assertTrue(folder.exists()); if (!JnaUtils.isWindows()) { int mode = JnaUtils.getFilemode(folder); assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID); assertEquals(JnaUtils.S_IRWXG, mode & JnaUtils.S_IRWXG); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/HEAD"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/config"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); } repository.close(); RepositoryCache.close(repository); FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE); } }
From source file:com.gitblit.tests.JGitUtilsTest.java
License:Apache License
@Test public void testCreateRepositorySharedCustom() throws Exception { String[] repositories = { "NewSharedTestRepository.git" }; for (String repositoryName : repositories) { Repository repository = JGitUtils.createRepository(GitBlitSuite.REPOSITORIES, repositoryName, "660"); File folder = FileKey.resolve(new File(GitBlitSuite.REPOSITORIES, repositoryName), FS.DETECTED); assertNotNull(repository);/*w w w . j a va2 s . co m*/ assertFalse(JGitUtils.hasCommits(repository)); assertNull(JGitUtils.getFirstCommit(repository, null)); assertEquals("0660", repository.getConfig().getString("core", null, "sharedRepository")); assertTrue(folder.exists()); if (!JnaUtils.isWindows()) { int mode = JnaUtils.getFilemode(folder); assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID); assertEquals(JnaUtils.S_IRWXG, mode & JnaUtils.S_IRWXG); assertEquals(0, mode & JnaUtils.S_IRWXO); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/HEAD"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); assertEquals(0, mode & JnaUtils.S_IRWXO); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/config"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); assertEquals(0, mode & JnaUtils.S_IRWXO); } repository.close(); RepositoryCache.close(repository); FileUtils.delete(repository.getDirectory(), FileUtils.RECURSIVE); } }
From source file:com.gitblit.tests.JGitUtilsTest.java
License:Apache License
@Test public void testCreateRepositorySharedSgidParent() throws Exception { if (!JnaUtils.isWindows()) { String repositoryAll = "NewTestRepositoryAll.git"; String repositoryUmask = "NewTestRepositoryUmask.git"; String sgidParent = "sgid"; File parent = new File(GitBlitSuite.REPOSITORIES, sgidParent); File folder = null;/*from w w w .j a va 2 s. com*/ boolean parentExisted = parent.exists(); try { if (!parentExisted) { assertTrue("Could not create SGID parent folder.", parent.mkdir()); } int mode = JnaUtils.getFilemode(parent); assertTrue(mode > 0); assertEquals(0, JnaUtils.setFilemode(parent, mode | JnaUtils.S_ISGID | JnaUtils.S_IWGRP)); Repository repository = JGitUtils.createRepository(parent, repositoryAll, "all"); folder = FileKey.resolve(new File(parent, repositoryAll), FS.DETECTED); assertNotNull(repository); assertEquals("2", repository.getConfig().getString("core", null, "sharedRepository")); assertTrue(folder.exists()); mode = JnaUtils.getFilemode(folder); assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/HEAD"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); assertEquals(JnaUtils.S_IROTH, mode & JnaUtils.S_IRWXO); mode = JnaUtils.getFilemode(folder.getAbsolutePath() + "/config"); assertEquals(JnaUtils.S_IRGRP | JnaUtils.S_IWGRP, mode & JnaUtils.S_IRWXG); assertEquals(JnaUtils.S_IROTH, mode & JnaUtils.S_IRWXO); repository.close(); RepositoryCache.close(repository); repository = JGitUtils.createRepository(parent, repositoryUmask, "umask"); folder = FileKey.resolve(new File(parent, repositoryUmask), FS.DETECTED); assertNotNull(repository); assertEquals(null, repository.getConfig().getString("core", null, "sharedRepository")); assertTrue(folder.exists()); mode = JnaUtils.getFilemode(folder); assertEquals(JnaUtils.S_ISGID, mode & JnaUtils.S_ISGID); repository.close(); RepositoryCache.close(repository); } finally { FileUtils.delete(new File(parent, repositoryAll), FileUtils.RECURSIVE | FileUtils.IGNORE_ERRORS); FileUtils.delete(new File(parent, repositoryUmask), FileUtils.RECURSIVE | FileUtils.IGNORE_ERRORS); if (!parentExisted) { FileUtils.delete(parent, FileUtils.RECURSIVE | FileUtils.IGNORE_ERRORS); } } } }
From source file:com.gitblit.tickets.ITicketService.java
License:Apache License
/** * Returns the list of labels for the repository. * * @param repository// w ww . j a v a2 s. co m * @return the list of labels * @since 1.4.0 */ public List<TicketLabel> getLabels(RepositoryModel repository) { String key = repository.name; if (labelsCache.containsKey(key)) { return labelsCache.get(key); } List<TicketLabel> list = new ArrayList<TicketLabel>(); Repository db = repositoryManager.getRepository(repository.name); try { StoredConfig config = db.getConfig(); Set<String> names = config.getSubsections(LABEL); for (String name : names) { TicketLabel label = new TicketLabel(name); label.color = config.getString(LABEL, name, COLOR); list.add(label); } labelsCache.put(key, Collections.unmodifiableList(list)); } catch (Exception e) { log.error("invalid tickets settings for " + repository, e); } finally { db.close(); } return list; }
From source file:com.gitblit.tickets.ITicketService.java
License:Apache License
/** * Creates a label.// ww w.j ava 2 s. c o m * * @param repository * @param milestone * @param createdBy * @return the label * @since 1.4.0 */ public synchronized TicketLabel createLabel(RepositoryModel repository, String label, String createdBy) { TicketLabel lb = new TicketMilestone(label); Repository db = null; try { db = repositoryManager.getRepository(repository.name); StoredConfig config = db.getConfig(); config.setString(LABEL, label, COLOR, lb.color); config.save(); } catch (IOException e) { log.error("failed to create label " + label + " in " + repository, e); } finally { if (db != null) { db.close(); } } return lb; }