Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

raise error for empty violation store and delete empty rule file #1405

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright 2014-2025 TNG Technology Consulting GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tngtech.archunit.library.freeze;

class StoreEmptyException extends RuntimeException {
StoreEmptyException(String message) {
super(message);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,17 @@ public final class TextFileBasedViolationStore implements ViolationStore {
private static final String ALLOW_STORE_CREATION_DEFAULT = "false";
private static final String ALLOW_STORE_UPDATE_PROPERTY_NAME = "default.allowStoreUpdate";
private static final String ALLOW_STORE_UPDATE_DEFAULT = "true";
private static final String DELETE_EMPTY_RULE_VIOLATION_PROPERTY_NAME = "default.deleteEmptyRuleViolation";
private static final String DELETE_EMPTY_RULE_VIOLATION_DEFAULT = "false";
Copy link
Author

@maxxkia maxxkia Jan 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can discuss the above default value. I would prefer to have default true here, but I'd like to first hear the opinions from the maintainers.

private static final String WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME = "default.warnEmptyRuleViolation";
private static final String WARN_EMPTY_RULE_VIOLATION_DEFAULT = "false";

private final RuleViolationFileNameStrategy ruleViolationFileNameStrategy;

private boolean storeCreationAllowed;
private boolean storeUpdateAllowed;
private boolean deleteEmptyRule;
private boolean warnEmptyRuleViolation;
private File storeFolder;
private FileSyncedProperties storedRules;

Expand All @@ -103,6 +109,8 @@ public TextFileBasedViolationStore(RuleViolationFileNameStrategy ruleViolationFi
public void initialize(Properties properties) {
storeCreationAllowed = Boolean.parseBoolean(properties.getProperty(ALLOW_STORE_CREATION_PROPERTY_NAME, ALLOW_STORE_CREATION_DEFAULT));
storeUpdateAllowed = Boolean.parseBoolean(properties.getProperty(ALLOW_STORE_UPDATE_PROPERTY_NAME, ALLOW_STORE_UPDATE_DEFAULT));
deleteEmptyRule = Boolean.parseBoolean(properties.getProperty(DELETE_EMPTY_RULE_VIOLATION_PROPERTY_NAME, DELETE_EMPTY_RULE_VIOLATION_DEFAULT));
warnEmptyRuleViolation = Boolean.parseBoolean(properties.getProperty(WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME, WARN_EMPTY_RULE_VIOLATION_DEFAULT));
String path = properties.getProperty(STORE_PATH_PROPERTY_NAME, STORE_PATH_DEFAULT);
storeFolder = new File(path);
ensureExistence(storeFolder);
Expand Down Expand Up @@ -140,15 +148,38 @@ public boolean contains(ArchRule rule) {
@Override
public void save(ArchRule rule, List<String> violations) {
log.trace("Storing evaluated rule '{}' with {} violations: {}", rule.getDescription(), violations.size(), violations);
if (violations.isEmpty() && warnEmptyRuleViolation) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this check has to be placed here at the top, because for empty frozen rule violations you don't necessarily need to update the store. By seeing such warning the developer could change the test to non-freezing rather than decide to update the store.

throw new StoreEmptyException(String.format("Saving empty violations for freezing rule is disabled (enable by configuration %s.%s=true)",
ViolationStoreFactory.FREEZE_STORE_PROPERTY_NAME, WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME));
}
if (violations.isEmpty() && deleteEmptyRule && !contains(rule)) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another way to write this check would be

Suggested change
if (violations.isEmpty() && deleteEmptyRule && !contains(rule)) {
if (violations.isEmpty() && (deleteEmptyRule || skipEmptyRule) && !contains(rule)) {

where skipEmptyRule condition is only used for skipping creation of empty rule file. To keep the configuration simple, I decided to use deleteEmptyRule for both skipping file creation and deleting the empty file.

// do nothing, new rule file should not be created
return;
}
if (!storeUpdateAllowed) {
throw new StoreUpdateFailedException(String.format(
"Updating frozen violations is disabled (enable by configuration %s.%s=true)",
ViolationStoreFactory.FREEZE_STORE_PROPERTY_NAME, ALLOW_STORE_UPDATE_PROPERTY_NAME));
}
if (violations.isEmpty() && deleteEmptyRule) {
deleteRuleFile(rule);
return;
}

String ruleFileName = ensureRuleFileName(rule);
write(violations, new File(storeFolder, ruleFileName));
}

private void deleteRuleFile(ArchRule rule) {
try {
String ruleFileName = storedRules.getProperty(rule.getDescription());
Files.delete(storeFolder.toPath().resolve(ruleFileName));
} catch (IOException e) {
throw new StoreUpdateFailedException(e);
}
storedRules.removeProperty(rule.getDescription());
}

private void write(List<String> violations, File ruleDetails) {
StringBuilder builder = new StringBuilder();
for (String violation : violations) {
Expand Down Expand Up @@ -255,6 +286,11 @@ void setProperty(String propertyName, String value) {
syncFileSystem();
}

void removeProperty(String propertyName) {
loadedProperties.remove(ensureUnixLineBreaks(propertyName));
syncFileSystem();
}

private void syncFileSystem() {
try (FileOutputStream outputStream = new FileOutputStream(propertiesFile)) {
loadedProperties.store(outputStream, "");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.tngtech.archunit.library.freeze;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
Expand Down Expand Up @@ -53,8 +54,11 @@ public class FreezingArchRuleTest {

private static final String STORE_PROPERTY_NAME = "freeze.store";
private static final String STORE_DEFAULT_PATH_PROPERTY_NAME = "freeze.store.default.path";
private static final String FREEZE_REFREEZE = "freeze.refreeze";
private static final String ALLOW_STORE_CREATION_PROPERTY_NAME = "freeze.store.default.allowStoreCreation";
private static final String ALLOW_STORE_UPDATE_PROPERTY_NAME = "freeze.store.default.allowStoreUpdate";
private static final String DELETE_EMPTY_RULE_VIOLATION_PROPERTY_NAME = "freeze.store.default.deleteEmptyRuleViolation";
private static final String WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME = "freeze.store.default.warnEmptyRuleViolation";
private static final String LINE_MATCHER_PROPERTY_NAME = "freeze.lineMatcher";

@Rule
Expand Down Expand Up @@ -152,13 +156,13 @@ public void allows_to_overwrite_frozen_violations_if_configured() {
ArchRule anotherViolation = rule("some description").withViolations("first violation", "second violation").create();
ArchRule frozenWithNewViolation = freeze(anotherViolation).persistIn(violationStore);

ArchConfiguration.get().setProperty("freeze.refreeze", Boolean.TRUE.toString());
ArchConfiguration.get().setProperty(FREEZE_REFREEZE, Boolean.TRUE.toString());

assertThatRule(frozenWithNewViolation)
.checking(importClasses(getClass()))
.hasNoViolation();

ArchConfiguration.get().setProperty("freeze.refreeze", Boolean.FALSE.toString());
ArchConfiguration.get().setProperty(FREEZE_REFREEZE, Boolean.FALSE.toString());

assertThatRule(frozenWithNewViolation)
.checking(importClasses(getClass()))
Expand Down Expand Up @@ -482,6 +486,72 @@ public void can_prevent_default_ViolationStore_from_updating_existing_rules() th
expectStoreUpdateDisabledException(() -> frozenRule.check(importClasses(getClass())));
}

@Test
public void warns_when_default_ViolationStore_is_empty() throws IOException {
useTemporaryDefaultStorePath();
ArchConfiguration.get().setProperty(ALLOW_STORE_CREATION_PROPERTY_NAME, "true");
ArchConfiguration.get().setProperty(FREEZE_REFREEZE, "true");
FreezingArchRule frozenRule = freeze(rule("some description").withoutViolations().create());
frozenRule.check(importClasses(getClass()));

// disallowing empty violation file should throw
ArchConfiguration.get().setProperty(WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME, "true");
assertThatThrownBy(() -> frozenRule.check(importClasses(getClass())))
.isInstanceOf(StoreEmptyException.class)
.hasMessageContaining("Saving empty violations for freezing rule is disabled (enable by configuration " + WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME + "=true)");
}

@Test
public void warns_when_default_ViolationStore_gets_empty() throws IOException {
useTemporaryDefaultStorePath();
ArchConfiguration.get().setProperty(ALLOW_STORE_CREATION_PROPERTY_NAME, "true");
RuleCreator someRule = rule("some description");
freeze(someRule.withViolations("remaining", "will be solved").create()).check(importClasses(getClass()));

// disallowing empty violation file should throw
ArchConfiguration.get().setProperty(WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME, "true");
FreezingArchRule frozenRule = freeze(someRule.withoutViolations().create());
assertThatThrownBy(() -> frozenRule.check(importClasses(getClass())))
.isInstanceOf(StoreEmptyException.class)
.hasMessageContaining("Saving empty violations for freezing rule is disabled (enable by configuration " + WARN_EMPTY_RULE_VIOLATION_PROPERTY_NAME + "=true)");
}

@Test
public void can_skip_default_ViolationStore_creation_for_empty_violations() throws IOException {
File storeFolder = useTemporaryDefaultStorePath();
ArchConfiguration.get().setProperty(STORE_PROPERTY_NAME, MyTextFileBasedViolationStore.class.getName());
ArchConfiguration.get().setProperty(ALLOW_STORE_CREATION_PROPERTY_NAME, "true");
ArchConfiguration.get().setProperty(DELETE_EMPTY_RULE_VIOLATION_PROPERTY_NAME, "true");

ArchRule rule = rule("some description").withoutViolations().create();
freeze(rule).check(importClasses(getClass()));

assertThat(storeFolder.list()).containsOnly("stored.rules");
Properties properties = readProperties(storeFolder.toPath().resolve("stored.rules").toFile());
assertThat(properties).isEmpty();
}

@Test
public void can_delete_default_ViolationStore_rule_file_for_empty_violations() throws IOException {
// given
File storeFolder = useTemporaryDefaultStorePath();
ArchConfiguration.get().setProperty(STORE_PROPERTY_NAME, MyTextFileBasedViolationStore.class.getName());
ArchConfiguration.get().setProperty(ALLOW_STORE_CREATION_PROPERTY_NAME, "true");
ArchConfiguration.get().setProperty(DELETE_EMPTY_RULE_VIOLATION_PROPERTY_NAME, "true");

freeze(rule("some description").withViolations("violation 1").create()).check(importClasses(getClass()));
assertThat(storeFolder.list()).containsOnly("stored.rules", "some description test");

// when
ArchRule rule = rule("some description").withoutViolations().create();
freeze(rule).check(importClasses(getClass()));

// then
assertThat(storeFolder.list()).containsOnly("stored.rules");
Properties properties = readProperties(storeFolder.toPath().resolve("stored.rules").toFile());
assertThat(properties).isEmpty();
}

@Test
public void allows_to_adjust_default_store_file_names_via_delegation() throws IOException {
// GIVEN
Expand Down Expand Up @@ -538,6 +608,14 @@ private File useTemporaryDefaultStorePath() throws IOException {
return folder;
}

private Properties readProperties(File file) throws IOException {
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream(file)) {
properties.load(inputStream);
}
return properties;
}

private static RuleCreator rule(String description) {
return new RuleCreator(description);
}
Expand Down