package com.atlassian.bitbucket.rule;

import org.junit.rules.ExternalResource;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Properties;

public class SystemPropertiesRule extends ExternalResource {

    /**
     * System properties to restore once the test finishes.
     */
    private Properties original;

    public void set(@Nonnull String key, @Nullable String value) {
        if (value == null) {
            System.clearProperty(key);
        } else {
            System.setProperty(key, value);
        }
    }

    @Override
    protected void before() throws Throwable {
        original = System.getProperties();

        Properties revised = new Properties();
        revised.putAll(original);
        System.setProperties(revised);
    }

    @Override
    protected void after() {
        System.setProperties(original);
    }

}
