package urban.transformers;
import java.io.File;
import java.io.FileReader;
import urban.model.Comment;
import urban.model.ImportStatement;
import urban.model.Model;
import urban.model.Statement;
import urban.parser.UrbanParser;
/**
* <p>Replaces ImportStatements with the statements from the file to be imported.</p>
* <p>If unable to find the file, or the file is not parseable, a comment with an error message will
* be added instead.</p>
*/
public class ResolveImports implements ModelTransformer {
private File baseDir;
/**
* @param baseDir the directory from which import will be resolved from
*/
public ResolveImports(File baseDir) {
this.baseDir = baseDir;
}
@Override
public Model transform(Model in) {
Model out = new Model();
for (Statement line : in.getLines()){
if (line instanceof ImportStatement){
out.addStatements(getModel(((ImportStatement)line).getFilename()).getLines());
} else {
out.addStatement(line);
}
}
return out;
}
private Model getModel(String filename){
try {
return new UrbanParser(new FileReader(new File(baseDir,filename))).model();
} catch (Exception e) {
e.printStackTrace();
Model m = new Model();
m.addStatement(new Comment("Unable to import the file:"+filename+" due to "+e.toString()));
return m;
}
}
}