final Change.Id changeId = patchSetId.getParentKey();
result.setChangeId(changeId);
final ChangeControl control = changeControlFactory.validateFor(changeId);
final PatchSet patch = db.patchSets().get(patchSetId);
if (patch == null) {
throw new NoSuchChangeException(changeId);
}
if (!patch.isDraft()) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.NOT_A_DRAFT));
return result;
}
if (!control.canDeleteDraft(db)) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.DELETE_NOT_PERMITTED));
return result;
}
final Change change = control.getChange();
try {
ChangeUtil.deleteOnlyDraftPatchSet(patch, change, gitManager, replication, db);
} catch (IOException e) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.GIT_ERROR, e.getMessage()));
}
List<PatchSet> restOfPatches = db.patchSets().byChange(changeId).toList();
if (restOfPatches.size() == 0) {
try {
ChangeUtil.deleteDraftChange(patchSetId, gitManager, replication, db);
result.setChangeId(null);
} catch (IOException e) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.GIT_ERROR, e.getMessage()));
}
} else {
PatchSet.Id highestId = null;
for (PatchSet ps : restOfPatches) {
if (highestId == null || ps.getPatchSetId() > highestId.get()) {
highestId = ps.getId();
}
}
if (change.currentPatchSetId().equals(patchSetId)) {
change.removeLastPatchSetId();
try {
change.setCurrentPatchSet(patchSetInfoFactory.get(db, change.currPatchSetId()));
} catch (PatchSetInfoNotAvailableException e) {
throw new NoSuchChangeException(changeId);
}
db.changes().update(Collections.singleton(change));
}
}
return result;