use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class DeleteRef method createDeleteCommand.
private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String refName) throws OrmException, IOException, ResourceConflictException, PermissionBackendException {
Ref ref = r.getRefDatabase().getRef(refName);
ReceiveCommand command;
if (ref == null) {
command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), refName);
command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
return command;
}
command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
try {
permissionBackend.user(identifiedUser).project(project.getNameKey()).ref(refName).check(RefPermission.DELETE);
} catch (AuthException denied) {
command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
}
if (!refName.startsWith(R_TAGS)) {
Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
}
}
RefUpdate u = r.updateRef(refName);
u.setForceUpdate(true);
u.setExpectedOldObjectId(r.exactRef(refName).getObjectId());
u.setNewObjectId(ObjectId.zeroId());
refDeletionValidator.validateRefOperation(project.getName(), identifiedUser.get(), u);
return command;
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class CreateBranch method apply.
@Override
public BranchInfo apply(ProjectResource rsrc, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException {
if (input == null) {
input = new BranchInput();
}
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())) {
ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
RevWalk rw = RefUtil.verifyConnected(repo, revid);
RevObject object = rw.parseAny(revid);
if (ref.startsWith(Constants.R_HEADS)) {
//
try {
object = rw.parseCommit(object);
} catch (IncorrectObjectTypeException notCommit) {
throw new BadRequestException("\"" + input.revision + "\" not a commit");
}
}
if (!refControl.canCreate(db.get(), repo, 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);
refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u);
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, identifiedUser.get().getAccount());
break;
case LOCK_FAILURE:
if (repo.getRefDatabase().exactRef(ref) != null) {
throw new ResourceConflictException("branch \"" + ref + "\" already exists");
}
String refPrefix = RefUtil.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 = RefUtil.getRefPrefix(refPrefix);
}
//$FALL-THROUGH$
case FORCED:
case IO_FAILURE:
case NOT_ATTEMPTED:
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
default:
{
throw new IOException(result.name());
}
}
BranchInfo info = new BranchInfo();
info.ref = ref;
info.revision = revid.getName();
info.canDelete = permissionBackend.user(identifiedUser).ref(name).testOrFalse(RefPermission.DELETE) ? true : null;
return info;
} catch (IOException err) {
log.error("Cannot create branch \"" + name + "\"", err);
throw err;
}
} catch (RefUtil.InvalidRevisionException e) {
throw new BadRequestException("invalid revision \"" + input.revision + "\"");
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class GetReflog method apply.
@Override
public List<ReflogEntryInfo> apply(BranchResource rsrc) throws AuthException, ResourceNotFoundException, RepositoryNotFoundException, IOException {
if (!rsrc.getControl().isOwner()) {
throw new AuthException("not project owner");
}
try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
ReflogReader r = repo.getReflogReader(rsrc.getRef());
if (r == null) {
throw new ResourceNotFoundException(rsrc.getRef());
}
List<ReflogEntry> entries;
if (from == null && to == null) {
entries = limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
} else {
entries = limit > 0 ? new ArrayList<>(limit) : new ArrayList<>();
for (ReflogEntry e : r.getReverseEntries()) {
Timestamp timestamp = new Timestamp(e.getWho().getWhen().getTime());
if ((from == null || from.before(timestamp)) && (to == null || to.after(timestamp))) {
entries.add(e);
}
if (limit > 0 && entries.size() >= limit) {
break;
}
}
}
return Lists.transform(entries, ReflogEntryInfo::new);
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class PutDescription method apply.
@Override
public Response<String> apply(ProjectResource resource, DescriptionInput input) throws AuthException, ResourceConflictException, ResourceNotFoundException, IOException {
if (input == null) {
// Delete would set description to null.
input = new DescriptionInput();
}
ProjectControl ctl = resource.getControl();
IdentifiedUser user = ctl.getUser().asIdentifiedUser();
if (!ctl.isOwner()) {
throw new AuthException("not project owner");
}
try (MetaDataUpdate md = updateFactory.create(resource.getNameKey())) {
ProjectConfig config = ProjectConfig.read(md);
Project project = config.getProject();
project.setDescription(Strings.emptyToNull(input.description));
String msg = MoreObjects.firstNonNull(Strings.emptyToNull(input.commitMessage), "Updated description.\n");
if (!msg.endsWith("\n")) {
msg += "\n";
}
md.setAuthor(user);
md.setMessage(msg);
config.commit(md);
cache.evict(ctl.getProject());
md.getRepository().setGitwebDescription(project.getDescription());
return Strings.isNullOrEmpty(project.getDescription()) ? Response.<String>none() : Response.ok(project.getDescription());
} catch (RepositoryNotFoundException notFound) {
throw new ResourceNotFoundException(resource.getName());
} catch (ConfigInvalidException e) {
throw new ResourceConflictException(String.format("invalid project.config: %s", e.getMessage()));
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class MergeOp method merge.
/**
* Merges the given change.
*
* <p>Depending on the server configuration, more changes may be affected, e.g. by submission of a
* topic or via superproject subscriptions. All affected changes are integrated using the projects
* integration strategy.
*
* @param db the review database.
* @param change the change to be merged.
* @param caller the identity of the caller
* @param checkSubmitRules whether the prolog submit rules should be evaluated
* @param submitInput parameters regarding the merge
* @throws OrmException an error occurred reading or writing the database.
* @throws RestApiException if an error occurred.
*/
public void merge(ReviewDb db, Change change, IdentifiedUser caller, boolean checkSubmitRules, SubmitInput submitInput, boolean dryrun) throws OrmException, RestApiException {
this.submitInput = submitInput;
this.accountsToNotify = notifyUtil.resolveAccounts(submitInput.notifyDetails);
this.dryrun = dryrun;
this.caller = caller;
this.ts = TimeUtil.nowTs();
submissionId = RequestId.forChange(change);
this.db = db;
orm.setContext(db, ts, caller, submissionId);
logDebug("Beginning integration of {}", change);
try {
ChangeSet cs = mergeSuperSet.setMergeOpRepoManager(orm).completeChangeSet(db, change, caller);
checkState(cs.ids().contains(change.getId()), "change %s missing from %s", change.getId(), cs);
if (cs.furtherHiddenChanges()) {
throw new AuthException("A change to be submitted with " + change.getId() + " is not visible");
}
this.commitStatus = new CommitStatus(cs);
MergeSuperSet.reloadChanges(cs);
logDebug("Calculated to merge {}", cs);
if (checkSubmitRules) {
logDebug("Checking submit rules and state");
checkSubmitRulesAndState(cs);
} else {
logDebug("Bypassing submit rules");
bypassSubmitRules(cs);
}
try {
integrateIntoHistory(cs);
} catch (IntegrationException e) {
logError("Error from integrateIntoHistory", e);
throw new ResourceConflictException(e.getMessage(), e);
}
} catch (IOException e) {
// Anything before the merge attempt is an error
throw new OrmException(e);
}
}
Aggregations