List of usage examples for org.eclipse.jgit.lib Repository isValidRefName
public static boolean isValidRefName(String refName)
From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.dialogs.CreateChangeBranchDialog.java
License:Open Source License
@Override protected IStatus validate(String property, Object value) { if (property.equals(PROP_CHANGE_BRANCH_NAME)) { String branchName = (String) value; String refName = "refs/heads/change/" + getSetting(PROP_STABLE_BRANCH) + "/" + branchName; //$NON-NLS-1$ //$NON-NLS-2$ if (branchName.length() < 4) { return createErrorStatus("Branch name must have at least 4 characters"); } else if (branchName.endsWith("/") || branchName.startsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$ return createErrorStatus("Branch name cannot start or end with ''/''"); } else if (!Repository.isValidRefName(refName)) { return createErrorStatus("Branch name {0} is not allowed", branchName); } else/*from w w w . j ava2 s . c o m*/ try { if (repositories.get(0).getRef(refName) != null) { return createErrorStatus( "You already have a change branch with this name. Choose a different name."); } } catch (IOException e) { return createErrorStatus("Error: {0}", e.getLocalizedMessage()); } } return super.validate(property, value); }
From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.dialogs.CreateFeatureBranchDialog.java
License:Open Source License
@Override protected IStatus validate(String property, Object value) { if (property.equals(PROP_BRANCH_NAME)) { String branchName = (String) value; String refName = "refs/heads/features/" + userId + "/" + branchName; //$NON-NLS-1$ //$NON-NLS-2$ if (branchName.length() < 4) { return createErrorStatus("Branch name must have at least 4 characters"); } else if (branchName.endsWith("/") || branchName.startsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$ return createErrorStatus("Branch name cannot start or end with ''/''"); } else if (!Repository.isValidRefName(refName)) { return createErrorStatus("Branch name {0} is not allowed", branchName); } else//www .ja v a2s. c o m try { for (Repository repository : repositories) { if (repository.getRef(refName) != null) { return createErrorStatus( "You already have a feature branch with this name in repository {0}. Choose a different name", repository.getDirectory().getParentFile().getName()); } } } catch (IOException e) { GerritToolsPlugin.getDefault().log(e); return createErrorStatus("Error: {0}", e.getLocalizedMessage()); } } return super.validate(property, value); }
From source file:com.genuitec.eclipse.gerrit.tools.internal.utils.dialogs.TagAndPushDialog.java
License:Open Source License
@Override protected IStatus validate(String property, Object value) { if (property.equals(TagAndPushHandler.PROP_CREATE_TAG) || property.equals(TagAndPushHandler.PROP_PUSH_TAG)) { if (!(Boolean) getSetting(TagAndPushHandler.PROP_CREATE_TAG) && !(Boolean) getSetting(TagAndPushHandler.PROP_PUSH_TAG)) { return createErrorStatus("You must create or push tag(s)"); }//w w w . j av a2 s . co m } else if (property.equals(TagAndPushHandler.PROP_TAG_NAME)) { String tagName = (String) value; if (tagName.length() < 2) { return createErrorStatus("Tag name must be longer then 1 character"); } if (tagName.startsWith("refs/tags/")) { //$NON-NLS-1$ return createErrorStatus("Do not prefix tag name with ''refs/tags/''"); } if (tagName.startsWith("/") || tagName.endsWith("/")) { //$NON-NLS-1$ //$NON-NLS-2$ return createErrorStatus("Tag name should not end or start with ''/''"); } if (!Repository.isValidRefName("refs/tags/" + tagName)) { //$NON-NLS-1$ return createErrorStatus("Tag name {0} is not allowed", tagName); } } else if (property.equals(TagAndPushHandler.PROP_TAG_MESSAGE)) { if (((String) value).length() <= 3) { return createErrorStatus("Tag message must be longer then 3 characters"); } } return Status.OK_STATUS; }
From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java
License:Apache License
@Override public ListBranchesResult call() throws NoSuchProjectException, InvalidNameException, InvalidRevisionException, IOException, BranchCreationNotAllowedException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); String refname = branchName;// ww w .j a v a 2 s . c o m while (refname.startsWith("/")) { refname = refname.substring(1); } if (!refname.startsWith(Constants.R_REFS)) { refname = Constants.R_HEADS + refname; } if (!Repository.isValidRefName(refname)) { throw new InvalidNameException(); } if (refname.startsWith(ReceiveCommits.NEW_CHANGE)) { throw new BranchCreationNotAllowedException(ReceiveCommits.NEW_CHANGE); } final Branch.NameKey name = new Branch.NameKey(projectName, refname); final RefControl refControl = projectControl.controlForRef(name); final Repository repo = repoManager.openRepository(projectName); try { final ObjectId revid = parseStartingRevision(repo); final RevWalk rw = verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); if (refname.startsWith(Constants.R_HEADS)) { // Ensure that what we start the branch from is a commit. If we // were given a tag, deference to the commit instead. // try { object = rw.parseCommit(object); } catch (IncorrectObjectTypeException notCommit) { throw new IllegalStateException(startingRevision + " not a commit"); } } if (!refControl.canCreate(rw, object)) { throw new IllegalStateException("Cannot create " + refname); } try { final RefUpdate u = repo.updateRef(refname); u.setExpectedOldObjectId(ObjectId.zeroId()); u.setNewObjectId(object.copy()); u.setRefLogIdent(identifiedUser.newRefLogIdent()); u.setRefLogMessage("created via web from " + startingRevision, false); final RefUpdate.Result result = u.update(rw); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: replication.scheduleUpdate(name.getParentKey(), refname); hooks.doRefUpdatedHook(name, u, identifiedUser.getAccount()); break; default: { throw new IOException(result.name()); } } } catch (IOException err) { log.error("Cannot create branch " + name, err); throw err; } } finally { repo.close(); } return listBranchesFactory.create(projectName).call(); }
From source file:com.google.gerrit.httpd.rpc.project.AddRefRight.java
License:Apache License
@Override public ProjectDetail call() throws NoSuchProjectException, OrmException, NoSuchGroupException, InvalidNameException, NoSuchRefException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); final ApprovalType at = approvalTypes.getApprovalType(categoryId); if (at == null || at.getValue(min) == null || at.getValue(max) == null) { throw new IllegalArgumentException("Invalid category " + categoryId + " or range " + min + ".." + max); }/* ww w . j a v a 2 s . c o m*/ String refPattern = this.refPattern; if (refPattern == null || refPattern.isEmpty()) { if (categoryId.equals(ApprovalCategory.SUBMIT) || categoryId.equals(ApprovalCategory.PUSH_HEAD)) { // Explicitly related to a branch head. refPattern = Constants.R_HEADS + "*"; } else if (!at.getCategory().isAction()) { // Non actions are approval votes on a change, assume these apply // to branch heads only. refPattern = Constants.R_HEADS + "*"; } else if (categoryId.equals(ApprovalCategory.PUSH_TAG)) { // Explicitly related to the tag namespace. refPattern = Constants.R_TAGS + "*"; } else if (categoryId.equals(ApprovalCategory.READ) || categoryId.equals(ApprovalCategory.OWN)) { // Currently these are project-wide rights, so apply that way. refPattern = RefRight.ALL; } else { // Assume project wide for the default. refPattern = RefRight.ALL; } } boolean exclusive = refPattern.startsWith("-"); if (exclusive) { refPattern = refPattern.substring(1); } while (refPattern.startsWith("/")) { refPattern = refPattern.substring(1); } if (refPattern.startsWith(RefRight.REGEX_PREFIX)) { String example = RefControl.shortestExample(refPattern); if (!example.startsWith(Constants.R_REFS)) { refPattern = RefRight.REGEX_PREFIX + Constants.R_HEADS + refPattern.substring(RefRight.REGEX_PREFIX.length()); example = RefControl.shortestExample(refPattern); } if (!Repository.isValidRefName(example)) { throw new InvalidNameException(); } } else { if (!refPattern.startsWith(Constants.R_REFS)) { refPattern = Constants.R_HEADS + refPattern; } if (refPattern.endsWith("/*")) { final String prefix = refPattern.substring(0, refPattern.length() - 2); if (!"refs".equals(prefix) && !Repository.isValidRefName(prefix)) { throw new InvalidNameException(); } } else { if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(); } } } if (!projectControl.controlForRef(refPattern).isOwner()) { throw new NoSuchRefException(refPattern); } if (exclusive) { refPattern = "-" + refPattern; } final AccountGroup group = groupCache.get(groupName); if (group == null) { throw new NoSuchGroupException(groupName); } final RefRight.Key key = new RefRight.Key(projectName, new RefRight.RefPattern(refPattern), categoryId, group.getId()); RefRight rr = db.refRights().get(key); if (rr == null) { rr = new RefRight(key); rr.setMinValue(min); rr.setMaxValue(max); db.refRights().insert(Collections.singleton(rr)); } else { rr.setMinValue(min); rr.setMaxValue(max); db.refRights().update(Collections.singleton(rr)); } projectCache.evictAll(); return projectDetailFactory.create(projectName).call(); }
From source file:com.google.gerrit.server.git.ReceiveCommits.java
License:Apache License
private void parseCommands(final Collection<ReceiveCommand> commands) { for (final ReceiveCommand cmd : commands) { if (cmd.getResult() != NOT_ATTEMPTED) { // Already rejected by the core receive process. ////from w ww . j av a2 s . c om continue; } if (!Repository.isValidRefName(cmd.getRefName()) || cmd.getRefName().contains("//")) { reject(cmd, "not valid ref"); continue; } HookResult result = hooks.doRefUpdateHook(project, cmd.getRefName(), currentUser.getAccount(), cmd.getOldId(), cmd.getNewId()); if (result != null) { final String message = result.toString().trim(); if (result.getExitValue() != 0) { reject(cmd, message); continue; } rp.sendMessage(message); } if (MagicBranch.isMagicBranch(cmd.getRefName())) { parseMagicBranch(cmd); continue; } final Matcher m = NEW_PATCHSET.matcher(cmd.getRefName()); if (m.matches()) { // The referenced change must exist and must still be open. // final Change.Id changeId = Change.Id.parse(m.group(1)); parseReplaceCommand(cmd, changeId); continue; } switch (cmd.getType()) { case CREATE: parseCreate(cmd); break; case UPDATE: parseUpdate(cmd); break; case DELETE: parseDelete(cmd); break; case UPDATE_NONFASTFORWARD: parseRewind(cmd); break; default: reject(cmd); continue; } if (cmd.getResult() != NOT_ATTEMPTED) { continue; } if (isConfig(cmd)) { if (!projectControl.isOwner()) { reject(cmd, "not project owner"); continue; } switch (cmd.getType()) { case CREATE: case UPDATE: case UPDATE_NONFASTFORWARD: try { ProjectConfig cfg = new ProjectConfig(project.getNameKey()); cfg.load(repo, cmd.getNewId()); if (!cfg.getValidationErrors().isEmpty()) { addError("Invalid project configuration:"); for (ValidationError err : cfg.getValidationErrors()) { addError(" " + err.getMessage()); } reject(cmd, "invalid project configuration"); log.error("User " + currentUser.getUserName() + " tried to push invalid project configuration " + cmd.getNewId().name() + " for " + project.getName()); continue; } Project.NameKey newParent = cfg.getProject().getParent(allProjectsName); Project.NameKey oldParent = project.getParent(allProjectsName); if (oldParent == null) { // update of the 'All-Projects' project if (newParent != null) { reject(cmd, "invalid project configuration: root project cannot have parent"); continue; } } else { if (!oldParent.equals(newParent) && !currentUser.getCapabilities().canAdministrateServer()) { reject(cmd, "invalid project configuration: only Gerrit admin can set parent"); continue; } if (projectCache.get(newParent) == null) { reject(cmd, "invalid project configuration: parent does not exist"); continue; } } for (Entry<ProjectConfigEntry> e : pluginConfigEntries) { PluginConfig pluginCfg = cfg.getPluginConfig(e.getPluginName()); ProjectConfigEntry configEntry = e.getProvider().get(); String value = pluginCfg.getString(e.getExportName()); String oldValue = projectControl.getProjectState().getConfig() .getPluginConfig(e.getPluginName()).getString(e.getExportName()); if (configEntry.getType() == ProjectConfigEntry.Type.ARRAY) { List<String> l = Arrays.asList(projectControl.getProjectState().getConfig() .getPluginConfig(e.getPluginName()).getStringList(e.getExportName())); oldValue = Joiner.on("\n").join(l); } if ((value == null ? oldValue != null : !value.equals(oldValue)) && !configEntry.isEditable(projectControl.getProjectState())) { reject(cmd, String.format( "invalid project configuration: Not allowed to set parameter" + " '%s' of plugin '%s' on project '%s'.", e.getExportName(), e.getPluginName(), project.getName())); continue; } if (ProjectConfigEntry.Type.LIST.equals(configEntry.getType()) && value != null && !configEntry.getPermittedValues().contains(value)) { reject(cmd, String.format( "invalid project configuration: The value '%s' is " + "not permitted for parameter '%s' of plugin '%s'.", value, e.getExportName(), e.getPluginName())); } } } catch (Exception e) { reject(cmd, "invalid project configuration"); log.error("User " + currentUser.getUserName() + " tried to push invalid project configuration " + cmd.getNewId().name() + " for " + project.getName(), e); continue; } break; case DELETE: break; default: reject(cmd); continue; } } } }
From source file:com.google.gerrit.server.project.CreateBranch.java
License:Apache License
@Override public BranchInfo apply(ProjectResource rsrc, Input input) throws BadRequestException, AuthException, ResourceConflictException, IOException { if (input == null) { input = new Input(); }//w w w . j a va2 s .co m if (input.ref != null && !ref.equals(input.ref)) { throw new BadRequestException("ref must match URL"); } if (input.revision == null) { input.revision = Constants.HEAD; } while (ref.startsWith("/")) { ref = ref.substring(1); } ref = RefNames.fullName(ref); if (!Repository.isValidRefName(ref)) { throw new BadRequestException("invalid branch name \"" + ref + "\""); } if (MagicBranch.isMagicBranch(ref)) { throw new BadRequestException( "not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\""); } final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref); final RefControl refControl = rsrc.getControl().controlForRef(name); try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) { final ObjectId revid = parseBaseRevision(repo, rsrc.getNameKey(), input.revision); final RevWalk rw = verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); if (ref.startsWith(Constants.R_HEADS)) { // Ensure that what we start the branch from is a commit. If we // were given a tag, deference to the commit instead. // try { object = rw.parseCommit(object); } catch (IncorrectObjectTypeException notCommit) { throw new BadRequestException("\"" + input.revision + "\" not a commit"); } } rw.reset(); if (!refControl.canCreate(db.get(), rw, object)) { throw new AuthException("Cannot create \"" + ref + "\""); } try { final RefUpdate u = repo.updateRef(ref); u.setExpectedOldObjectId(ObjectId.zeroId()); u.setNewObjectId(object.copy()); u.setRefLogIdent(identifiedUser.get().newRefLogIdent()); u.setRefLogMessage("created via REST from " + input.revision, false); final RefUpdate.Result result = u.update(rw); switch (result) { case FAST_FORWARD: case NEW: case NO_CHANGE: referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE); hooks.doRefUpdatedHook(name, u, identifiedUser.get().getAccount()); break; case LOCK_FAILURE: if (repo.getRefDatabase().exactRef(ref) != null) { throw new ResourceConflictException("branch \"" + ref + "\" already exists"); } String refPrefix = getRefPrefix(ref); while (!Constants.R_HEADS.equals(refPrefix)) { if (repo.getRefDatabase().exactRef(refPrefix) != null) { throw new ResourceConflictException("Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\"."); } refPrefix = getRefPrefix(refPrefix); } //$FALL-THROUGH$ default: { throw new IOException(result.name()); } } BranchInfo info = new BranchInfo(); info.ref = ref; info.revision = revid.getName(); info.canDelete = refControl.canDelete() ? true : null; return info; } catch (IOException err) { log.error("Cannot create branch \"" + name + "\"", err); throw err; } } catch (InvalidRevisionException e) { throw new BadRequestException("invalid revision \"" + input.revision + "\""); } }
From source file:com.google.gerrit.server.project.CreateProject.java
License:Apache License
private List<String> normalizeBranchNames(List<String> branches) throws BadRequestException { if (branches == null || branches.isEmpty()) { return Collections.singletonList(Constants.R_HEADS + Constants.MASTER); }/*from w w w . jav a 2 s . c om*/ List<String> normalizedBranches = new ArrayList<>(); for (String branch : branches) { while (branch.startsWith("/")) { branch = branch.substring(1); } branch = RefNames.fullName(branch); if (!Repository.isValidRefName(branch)) { throw new BadRequestException(String.format("Branch \"%s\" is not a valid name.", branch)); } if (!normalizedBranches.contains(branch)) { normalizedBranches.add(branch); } } return normalizedBranches; }
From source file:com.google.gerrit.server.project.CreateTag.java
License:Apache License
@Override public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException { if (input == null) { input = new TagInput(); }//from w ww. ja v a2 s. co m if (input.ref != null && !ref.equals(input.ref)) { throw new BadRequestException("ref must match URL"); } if (input.revision == null) { input.revision = Constants.HEAD; } while (ref.startsWith("/")) { ref = ref.substring(1); } if (ref.startsWith(R_REFS) && !ref.startsWith(R_TAGS)) { throw new BadRequestException("invalid tag name \"" + ref + "\""); } if (!ref.startsWith(R_TAGS)) { ref = R_TAGS + ref; } if (!Repository.isValidRefName(ref)) { throw new BadRequestException("invalid tag name \"" + ref + "\""); } RefControl refControl = resource.getControl().controlForRef(ref); try (Repository repo = repoManager.openRepository(resource.getNameKey())) { ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision); RevWalk rw = RefUtil.verifyConnected(repo, revid); RevObject object = rw.parseAny(revid); rw.reset(); boolean isAnnotated = Strings.emptyToNull(input.message) != null; boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n"); if (isSigned) { throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\""); } else if (isAnnotated && !refControl.canPerform(Permission.PUSH_TAG)) { throw new AuthException("Cannot create annotated tag \"" + ref + "\""); } else if (!refControl.canPerform(Permission.CREATE)) { throw new AuthException("Cannot create tag \"" + ref + "\""); } if (repo.getRefDatabase().exactRef(ref) != null) { throw new ResourceConflictException("tag \"" + ref + "\" already exists"); } try (Git git = new Git(repo)) { TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())) .setAnnotated(isAnnotated).setSigned(isSigned); if (isAnnotated) { tag.setMessage(input.message).setTagger( identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault())); } Ref result = tag.call(); tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId()); referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), identifiedUser.get().getAccount()); try (RevWalk w = new RevWalk(repo)) { return ListTags.createTagInfo(result, w); } } } catch (InvalidRevisionException e) { throw new BadRequestException("Invalid base revision"); } catch (GitAPIException e) { log.error("Cannot create tag \"" + ref + "\"", e); throw new IOException(e); } }
From source file:com.google.gerrit.server.project.DashboardsCollection.java
License:Apache License
private DashboardResource parse(ProjectControl ctl, String ref, String path, ProjectControl myCtl) throws ResourceNotFoundException, IOException, AmbiguousObjectException, IncorrectObjectTypeException, ConfigInvalidException {/* ww w. j ava2s . com*/ String id = ref + ":" + path; if (!ref.startsWith(REFS_DASHBOARDS)) { ref = REFS_DASHBOARDS + ref; } if (!Repository.isValidRefName(ref) || !ctl.controlForRef(ref).canRead()) { throw new ResourceNotFoundException(id); } try (Repository git = gitManager.openRepository(ctl.getProject().getNameKey())) { ObjectId objId = git.resolve(ref + ":" + path); if (objId == null) { throw new ResourceNotFoundException(id); } BlobBasedConfig cfg = new BlobBasedConfig(null, git, objId); return new DashboardResource(myCtl, ref, path, cfg, false); } catch (RepositoryNotFoundException e) { throw new ResourceNotFoundException(id); } }