import org.sonar.core.rule.RuleDto;
import org.sonar.server.db.DbClient;
import org.sonar.server.qualityprofile.RuleActivator;
+import org.sonar.server.rule.index.RuleDoc;
public class RuleDeleter implements ServerComponent {
DbSession dbSession = dbClient.openSession(false);
try {
RuleDto rule = dbClient.ruleDao().getByKey(dbSession, ruleKey);
- if (rule.getTemplateId() == null) {
- throw new IllegalStateException("Only custom rules can be deleted");
+ if (rule.getTemplateId() == null && !rule.getRepositoryKey().equals(RuleDoc.MANUAL_REPOSITORY)) {
+ throw new IllegalStateException("Only custom rules and manual rules can be deleted");
+ }
+
+ // For custom rule, first deactivate the rule on all profiles
+ if (rule.getTemplateId() != null) {
+ ruleActivator.deactivate(dbSession, rule);
}
- ruleActivator.deactivate(dbSession, rule);
rule.setStatus(RuleStatus.REMOVED);
dbClient.ruleDao().update(dbSession, rule);
// Activate the custom rule
tester.get(RuleActivator.class).activate(
new RuleActivation(ActiveRuleKey.of(profileDto.getKey(), customRule.getKey())).setSeverity(Severity.BLOCKER)
- );
+ );
// Delete custom rule
deleter.delete(customRule.getKey());
}
@Test
- public void fail_to_delete_if_not_custom() throws Exception {
+ public void delete_manual_rule() throws Exception {
+ // Create manual rule
+ RuleDto manualRule = RuleTesting.newManualRule("Manual_Rule");
+ dao.insert(dbSession, manualRule);
+
+ dbSession.commit();
+
+ // Delete manual rule
+ deleter.delete(manualRule.getKey());
+
+ // Verify custom rule have status REMOVED
+ Rule result = index.getByKey(manualRule.getKey());
+ assertThat(result).isNotNull();
+ assertThat(result.status()).isEqualTo(RuleStatus.REMOVED);
+ }
+
+ @Test
+ public void fail_to_delete_if_not_custom_or_not_manual() throws Exception {
// Create rule
RuleKey ruleKey = RuleKey.of("java", "S001");
dao.insert(dbSession, RuleTesting.newDto(ruleKey));
// Delete rule
deleter.delete(ruleKey);
} catch (Exception e) {
- assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Only custom rules can be deleted");
+ assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Only custom rules and manual rules can be deleted");
}
}