/// <exception cref="InvalidOptionException">On error.</exception> public void Parse(string[] args, ScriptRuntimeSetup setup, LanguageSetup languageSetup, PlatformAdaptationLayer platform) { ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(setup, "setup"); ContractUtils.RequiresNotNull(languageSetup, "languageSetup"); ContractUtils.RequiresNotNull(platform, "platform"); _args = args; _runtimeSetup = setup; _languageSetup = languageSetup; _platform = platform; _current = 0; try { BeforeParse(); while (_current < args.Length) { ParseArgument(args[_current++]); } AfterParse(); } finally { _args = null; _runtimeSetup = null; _languageSetup = null; _platform = null; _current = -1; } }
private static IEnumerable<string> GetMatches(PlatformAdaptationLayer pal, string pattern, Constants flags) { if (pattern.Length == 0) { yield break; } var noEscape = ((flags & Constants.NoEscape) != 0); var groups = UngroupGlobs(pattern, noEscape); if (groups.Length == 0) { yield break; } foreach (var group in groups) { var matcher = new GlobMatcher(pal, group, flags); foreach (var filename in matcher.DoGlob()) { yield return filename.Replace("//", "/"); } } }
private static IEnumerable <string> /*!*/ GetExecutableFiles(PlatformAdaptationLayer /*!*/ pal, string /*!*/ path) { if (path[0] == '"' || path[path.Length - 1] == '"') { if (path.Length >= 3 && path[0] == '"' && path[path.Length - 1] == '"') { path = path.Substring(1, path.Length - 2); } else { yield break; } } string extension = RubyUtils.GetExtension(path); bool hasExtension = !String.IsNullOrEmpty(extension); bool isExecutable = hasExtension && Array.IndexOf(_ExecutableExtensions, extension.ToLowerInvariant()) >= 0; if (!hasExtension || isExecutable) { foreach (var fullPath in GetAbsolutePaths(pal, path)) { if (hasExtension) { yield return(fullPath); } else { foreach (var ext in _ExecutableExtensions) { yield return(fullPath + ext); } } } } }
private static string GetFullPathAndValidateCase(LanguageContext /*!*/ context, string path, bool isDir) { PlatformAdaptationLayer pal = context.DomainManager.Platform; string dir = pal.GetDirectoryName(path); if (!pal.DirectoryExists(dir)) { return(null); } try { string file = pal.GetFileName(path); string[] files = pal.GetFileSystemEntries(dir, file, !isDir, isDir); if (files.Length != 1 || pal.GetFileName(files[0]) != file) { return(null); } return(pal.GetFullPath(files[0])); } catch (IOException) { return(null); } }
private static PythonTuple FindModulePath(CodeContext /*!*/ context, string name, List path) { Debug.Assert(path != null); if (name == null) { throw PythonOps.TypeError("find_module() argument 1 must be string, not None"); } PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; foreach (object d in path) { if (!(d is string dir)) { continue; // skip invalid entries } string pathName = Path.Combine(dir, name); if (pal.DirectoryExists(pathName)) { if (pal.FileExists(Path.Combine(pathName, "__init__.py"))) { return(PythonTuple.MakeTuple(null, pathName, PythonTuple.MakeTuple("", "", PackageDirectory))); } } string fileName = pathName + ".py"; if (pal.FileExists(fileName)) { Stream fs = pal.OpenInputFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PythonFile pf = PythonFile.Create(context, fs, fileName, "U"); return(PythonTuple.MakeTuple(pf, fileName, PythonTuple.MakeTuple(".py", "U", PythonSource))); } } throw PythonOps.ImportError("No module named {0}", name); }
public FileIO(CodeContext /*!*/ context, string name, string mode = "r", bool closefd = true, object opener = null) : base(context) { if (!closefd) { throw PythonOps.ValueError("Cannot use closefd=False with file name"); } this.name = name; PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; _context = context.LanguageContext; this.mode = NormalizeMode(mode, out int flags); if (opener is null) { switch (this.mode) { case "rb": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); break; case "wb": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); break; case "xb": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); break; case "ab": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); _readStream.Seek(0L, SeekOrigin.End); break; case "rb+": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); break; case "wb+": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); break; case "xb+": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); break; case "ab+": _readStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _writeStream = OpenFile(context, pal, name, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); _readStream.Seek(0L, SeekOrigin.End); _writeStream.Seek(0L, SeekOrigin.End); break; default: throw new InvalidOperationException(); } } else { object fdobj = PythonOps.CallWithContext(context, opener, name, flags); if (fdobj is int fd) { if (fd < 0) { throw PythonOps.ValueError("opener returned {0}", fd); } if (_context.FileManager.TryGetFileFromId(_context, fd, out FileIO file)) { _readStream = file._readStream; _writeStream = file._writeStream; } else if (_context.FileManager.TryGetObjectFromId(_context, fd, out object fileObj) && fileObj is Stream stream) { _readStream = stream; _writeStream = stream; } } else { throw PythonOps.TypeError("expected integer from opener"); } } _closefd = true; }
public RhoHost() { _pal = new WP_PlatformAdaptationLayer(); }
/// <summary> /// ValidateProperties associated with Host -- compare test and expected PAL value(s) /// </summary> internal void ValidateProperties(PlatformAdaptationLayer testHostPAL, PlatformAdaptationLayer expectedPAL) { Assert.AreEqual(testHostPAL, expectedPAL); }
public CassettePlatformAdaptationLayer(PlatformAdaptationLayer innerPal, Func <IDirectory> getDirectory) { this.innerPal = innerPal; this.getDirectory = getDirectory; }
public zipimporter(CodeContext /*!*/ context, object pathObj, [ParamDictionary] IDictionary <object, object> kwArgs) { PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; string prefix, input, path; if (pathObj == null) { throw PythonOps.TypeError("must be string, not None"); } if (!(pathObj is string)) { throw PythonOps.TypeError("must be string, not {0}", pathObj.GetType()); } if (kwArgs.Count > 0) { throw PythonOps.TypeError("zipimporter() does not take keyword arguments"); } path = pathObj as string; if (path.Length == 0) { throw MakeError(context, "archive path is empty"); } if (path.Length > MAXPATHLEN) { throw MakeError(context, "archive path too long"); } string buf = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); input = buf; path = string.Empty; prefix = string.Empty; try { while (!string.IsNullOrEmpty(buf)) { if (pal.FileExists(buf)) { path = buf; break; } buf = Path.GetDirectoryName(buf); } } catch { throw MakeError(context, "not a Zip file"); } if (!string.IsNullOrEmpty(path)) { PythonDictionary zip_directory_cache = context.LanguageContext.GetModuleState( _zip_directory_cache_key) as PythonDictionary; if (zip_directory_cache != null && zip_directory_cache.ContainsKey(path)) { _files = zip_directory_cache[path] as PythonDictionary; } else { _files = ReadDirectory(context, path); zip_directory_cache.Add(path, _files); } } else { throw MakeError(context, "not a Zip file"); } _prefix = input.Replace(path, string.Empty); // add trailing SEP if (!string.IsNullOrEmpty(_prefix) && !_prefix.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { _prefix = _prefix.Substring(1); _prefix += Path.DirectorySeparatorChar; } _archive = path; }
/// <summary> /// ValidateProperties associated with Host -- Maybe blocked by bug 462717 /// </summary> internal void ValidateProperties(PlatformAdaptationLayer testHostPAL, string expectedPath) { Assert.AreEqual(testHostPAL.CurrentDirectory, expectedPath); }
private static IList <string> /*!*/ DoGlob(PlatformAdaptationLayer /*!*/ pal, string /*!*/ pattern, int flags) { GlobMatcher matcher = new GlobMatcher(pal, pattern, flags); return(matcher.DoGlob()); }
public SassCompilerScriptHost(PlatformAdaptationLayer pal) { _pal = pal; }
/// <summary> /// Initializes environment according to the setup information. /// </summary> private ScriptDomainManager() { // create local environment for the host: _environment = new ScriptEnvironment(this); _host = new ScriptHost(_environment); // initialize snippets: _snippets = new Snippets(); _pal = null; }
internal GlobMatcher(PlatformAdaptationLayer pal, string pattern, Constants flags) { this.pal = pal; this.pattern = (pattern == "**") ? "*" : pattern; this.flags = flags | Constants.IgnoreCase; result = new List<string>(); dirOnly = this.pattern.Substring(this.pattern.Length - 1, 1) == "/"; stripTwo = false; }
/// <summary> /// ValidateProperties associated with Host -- compare test and expected PAL value(s) /// </summary> internal void ValidateProperties(PlatformAdaptationLayer testHostPAL, PlatformAdaptationLayer expectedPAL) { Assert.AreEqual(testHostPAL, expectedPAL); }
private static void GetExecutable(PlatformAdaptationLayer /*!*/ pal, string /*!*/ command, out string executable, out string arguments) { command = command.Trim(' '); if (command.Length == 0) { throw RubyExceptions.CreateEINVAL(command); } // This seems to be quite complicated: // 1) If the first part of the command is a shell command (DIR, ECHO, ...) or // if the command contains unquoted <, > or | then // it uses ENV['COMSPEC'] to execute the command: %COMSPEC% /c "COMMAND" // 2) It looks for the shortest prefix of command that is separated by space from the rest of the command that is either // a) An absolute path to an executable file. // b) Try prepend paths from ENV['PATH'] // c) Try Environment.SpecialFolder.System. // d) Try SHGetFolderPath(CSIDL_WINDOWS) - we can't get this from Environment.SpecialFolder, so we need to use // ENV["SystemRoot"] environment variable. // In each step it tries to append ".exe" or ".com" extension if the path doesn't exist. // // For example, if the command is `x/a b/x` and the directory structure is // x\a b\x.exe // x\a.exe // it executes a.exe. // // MRI probably calls CreateProcess Win32 API with lpApplicationName it resolves as described above and // lpCommandLine == command. System.Diagnostics.Process also uses this API with lpApplicationName == NULL and // lpCommandLine == '"{ProcessStartInfo.FileName}" {ProcessStartInfo.Arguments}'. // // Although CreateProcess does all the searching for an executable if passed no lpApplicationName, // we need to do it ourselves because it is slightly different in MRI (is that a bug?) and also because System.Diagnostics.Process // quotes the FileName :( // string comspec = pal.GetEnvironmentVariable("COMSPEC"); if (!pal.FileExists(comspec)) { comspec = null; } if (comspec != null && IndexOfUnquotedSpecialCharacter(command) >= 0) { executable = comspec; arguments = "/c \"" + command + "\""; return; } int start = 0; while (true) { int next = command.IndexOf(' ', start); executable = (next >= 0) ? command.Substring(0, next) : command; arguments = (next >= 0) ? command.Substring(next + 1) : ""; if (start == 0 && comspec != null && IsShellCommand(executable)) { executable = comspec; arguments = "/c \"" + command + "\""; return; } try { foreach (var path in GetExecutableFiles(pal, executable)) { if (pal.FileExists(path)) { // We need to set the path we found as executable. Althought makes command line of the target process // different from when called by MRI it will execute the right process. If we passed the original executable name // CreateProcess might resolve it to a different executable. executable = path; return; } } } catch (Exception e) { if (next < 0) { throw RubyExceptions.CreateENOENT(command, e); } } if (next < 0) { throw RubyExceptions.CreateENOENT(command); } start = next + 1; while (start < command.Length && command[start] == ' ') { start++; } } }
public static bool HasKey(RubyContext /*!*/ context, object /*!*/ self, [DefaultProtocol, NotNull] MutableString /*!*/ key) { PlatformAdaptationLayer pal = context.DomainManager.Platform; return(pal.GetEnvironmentVariable(key.ConvertToString()) != null); }
public RhoHost() { _pal = new WP_PlatformAdaptationLayer(); }
public static int Length(RubyContext /*!*/ context, object /*!*/ self) { PlatformAdaptationLayer pal = context.DomainManager.Platform; return(pal.GetEnvironmentVariables().Count); }
public FileIO(CodeContext /*!*/ context, string name, string mode = "r", bool closefd = true, object opener = null) : base(context) { if (!closefd) { throw PythonOps.ValueError("Cannot use closefd=False with file name"); } this.name = name; PlatformAdaptationLayer pal = context.LanguageContext.DomainManager.Platform; int flags = 0; switch (StandardizeMode(mode)) { case "r": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); this.mode = "rb"; flags |= O_RDONLY; break; case "w": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); this.mode = "wb"; flags |= O_CREAT | O_TRUNC | O_WRONLY; break; case "a": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); _readStream.Seek(0L, SeekOrigin.End); this.mode = "ab"; flags |= O_APPEND | O_CREAT; break; case "r+": case "+r": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); this.mode = "rb+"; flags |= O_RDWR; break; case "w+": case "+w": _readStream = _writeStream = OpenFile(context, pal, name, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); this.mode = "rb+"; flags |= O_CREAT | O_TRUNC | O_RDWR; break; case "a+": case "+a": _readStream = OpenFile(context, pal, name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _writeStream = OpenFile(context, pal, name, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); _readStream.Seek(0L, SeekOrigin.End); _writeStream.Seek(0L, SeekOrigin.End); this.mode = "ab+"; flags |= O_APPEND | O_CREAT | O_RDWR; break; default: BadMode(mode); break; } _closefd = true; _context = context.LanguageContext; if (opener != null) { object fdobj = PythonOps.CallWithContext(context, opener, name, flags); if (fdobj is int fd) { if (fd < 0) { throw PythonOps.ValueError("opener returned {0}", fd); } if (_context.FileManager.TryGetFileFromId(_context, fd, out FileIO file)) { _readStream = file._readStream; _writeStream = file._writeStream; } else if (_context.FileManager.TryGetObjectFromId(_context, fd, out object fileObj) && fileObj is Stream stream) { _readStream = stream; _writeStream = stream; } } else { throw PythonOps.TypeError("expected integer from opener"); } } }
internal PALHolder(PlatformAdaptationLayer pal) { _pal = pal; }
/// <summary> /// ValidateProperties associated with Host -- Maybe blocked by bug 462717 /// </summary> internal void ValidateProperties(PlatformAdaptationLayer testHostPAL, string expectedPath) { Assert.AreEqual(testHostPAL.CurrentDirectory, expectedPath); }
public TestHost(OptionsAttribute/*!*/ options) { _options = options; _pal = options.Pal != null ? (PlatformAdaptationLayer)Activator.CreateInstance(options.Pal) : PlatformAdaptationLayer.Default; }
/// <exception cref="InvalidOptionException">On error.</exception> public void Parse(string[] args, ScriptRuntimeSetup setup, LanguageSetup languageSetup, PlatformAdaptationLayer platform) { ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(setup, "setup"); ContractUtils.RequiresNotNull(languageSetup, "languageSetup"); ContractUtils.RequiresNotNull(platform, "platform"); _args = args; _runtimeSetup = setup; _languageSetup = languageSetup; _platform = platform; _current = 0; try { BeforeParse(); while (_current < args.Length) { ParseArgument(args[_current++]); } AfterParse(); } finally { _args = null; _runtimeSetup = null; _languageSetup = null; _platform = null; _current = -1; } }
public SassCompilerScriptHost(PlatformAdaptationLayer pal) { _pal = pal; }