import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.IOError;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.simantics.scl.runtime.reporting.SCLReporting;
import org.simantics.scl.runtime.reporting.SCLReportingHandler;
import org.simantics.scl.runtime.tuple.Tuple0;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import gnu.trove.map.hash.THashMap;
import gnu.trove.procedure.TObjectProcedure;
public class CommandSession {
+ private static final Logger LOGGER = LoggerFactory.getLogger(CommandSession.class);
+
ModuleRepository moduleRepository;
SCLReportingHandler defaultHandler;
updateRuntimeEnvironment(true);
}
+ public static final Type MAYBE_PATH = Types.apply(Types.MAYBE, Types.con("Files", "Path"));
+
+ private static final String VAR_SCRIPT_DIR = "__SCRIPT_DIR__";
+ private static final String VAR_SCRIPT_PATH = "__SCRIPT_PATH__";
+
public void runFromFile(String fileName, SCLReportingHandler handler) {
- try {
- Reader reader = new LaxUTF8Reader(fileName);
+ try (Reader reader = new LaxUTF8Reader(fileName)) {
+ Type prevPathType = getVariableType(VAR_SCRIPT_PATH);
+ Object prevPathValue = getVariableValue(VAR_SCRIPT_PATH);
+ Type prevDirType = getVariableType(VAR_SCRIPT_DIR);
+ Object prevDirValue = getVariableValue(VAR_SCRIPT_DIR);
try {
+ Path absPath = Paths.get(fileName).toAbsolutePath();
+ setVariable(VAR_SCRIPT_PATH, MAYBE_PATH, absPath);
+ setVariable(VAR_SCRIPT_DIR, MAYBE_PATH, absPath != null ? absPath.getParent() : null);
+ execute(reader, handler);
+ } catch (InvalidPathException | IOError e) {
+ LOGGER.error("Failed to resolve absolute script path from provided fileName \"{}\"", fileName, e);
+ // Just evaluate the script without script paths
+ removeVariable(VAR_SCRIPT_PATH);
+ removeVariable(VAR_SCRIPT_DIR);
execute(reader, handler);
} finally {
- reader.close();
+ if (prevPathValue != null && prevPathType != null)
+ setVariable(VAR_SCRIPT_PATH, prevPathType, prevPathValue);
+ else
+ removeVariable(VAR_SCRIPT_PATH);
+ if (prevDirValue != null && prevDirType != null)
+ setVariable(VAR_SCRIPT_DIR, prevDirType, prevDirValue);
+ else
+ removeVariable(VAR_SCRIPT_DIR);
}
} catch(IOException e) {
formatException(handler, e);