ConfigCtrl.java
package org.docascode.git;
import org.docascode.utils.DocAsCodeException;
import org.docascode.utils.DocAsCodeRepository;
import org.docascode.utils.DocAsCodeRepository.ConfigLevel;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.SystemReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConfigCtrl {
private DocAsCodeRepository repository = null;
public ConfigCtrl(DocAsCodeRepository repository){
this.repository = repository;
}
public ConfigCtrl(File directory) throws IOException {
new ConfigCtrl(new DocAsCodeRepository(directory));
}
public void add(ConfigLevel level, String section, String subsection, String name, String value) throws DocAsCodeException {
StoredConfig config = this.repository.getConfig(level);
try {
config.load();
} catch (IOException e) {
throw new DocAsCodeException("Unable to load Git configuration",e);
} catch (ConfigInvalidException e) {
throw new DocAsCodeException("Unable to load Git configuration",e);
}
List<String> configList = new ArrayList<String>(Arrays.asList(config.getStringList(section,subsection,name)));
if(!configList.contains(value)){
configList.add(value);
config.setStringList(section,subsection,name,configList);
try {
config.save();
} catch (IOException e) {
throw new DocAsCodeException("Unable to save Git configuration",e);
}
}
}
public String get(ConfigLevel level, String section, String subsection, String name){
StoredConfig config = this.repository.getConfig(level);
try {
return config.getString(section,subsection,name);
} catch (DocAsCodeException e) {
return SystemReader.getInstance().openUserConfig(null, FS.detect()).getString(section,subsection,name);
}
}
public void set(ConfigLevel level, String section, String subsection, String name, String value){
StoredConfig config = this.repository.getConfig(level);
config.setString(section,subsection,name,value);
try {
config.save();
} catch (IOException e) {
throw new DocAsCodeException("Unable to save Git configuration",e);
}
}
}