Exemple #1
0
        protected virtual FilePreProcessorResult Process(Action <FileParserContext> parseAction)
        {
            Guard.AgainstNullArgument("parseAction", parseAction);

            var context = new FileParserContext();

            _logger.DebugFormat("Starting pre-processing");

            parseAction(context);

            var code = GenerateCode(context);

            _logger.DebugFormat("Pre-processing finished successfully");

            return(new FilePreProcessorResult
            {
                Namespaces = context.Namespaces,
                LoadedScripts = context.LoadedScripts,
                References = context.References,
                Code = code
            });
        }
Exemple #2
0
        public static void WriteVersion(this IConsole console, string version)
        {
            Guard.AgainstNullArgument("console", console);

            var lines = new[]
            {
                @"+cyan               _       _",
                @"+cyan ___  ___ _ __(_)_ __ | |__+darkMagenta ___ ___",
                @"+cyan/ __|/ __| '__| | '_ \| __/+darkMagenta/ __/ __|",
                @"+cyan\__ \ (__| |  | | |_) | |_+darkMagenta| (__\__ \",
                @"+cyan|___/\___|_|  |_| .__/ \__\+darkMagenta\___|___/",
                string.Format(@"+cyan                |_|+white Version: {0}", version)
            };

            foreach (var lineMatches in lines.Select(line => colorRegex.Matches(line)))
            {
                foreach (Match match in lineMatches)
                {
                    ConsoleColor color;
                    if (Enum.TryParse(match.Groups["color"].Value, true, out color))
                    {
                        console.ForegroundColor = color;
                    }

                    try
                    {
                        console.Write(match.Groups["ascii"].Value);
                    }
                    finally
                    {
                        console.ResetColor();
                    }
                }

                console.WriteLine();
            }

            console.WriteLine();
        }
        public static ConfigMask Create(ScriptCsArgs args)
        {
            Guard.AgainstNullArgument("args", args);

            return(new ConfigMask
            {
                AllowPreRelease = args.AllowPreRelease ? (bool?)true : null,
                Cache = args.Cache ? (bool?)true : null,
                Clean = args.Clean ? (bool?)true : null,
                Debug = args.Debug ? (bool?)true : null,
                Global = args.Global ? (bool?)true : null,
                Install = args.Install,
                LogLevel = args.LogLevel,
                Modules = args.Modules,
                Output = args.Output,
                PackageVersion = args.PackageVersion,
                Repl = args.Repl ? (bool?)true : null,
                Save = args.Save ? (bool?)true : null,
                ScriptName = args.ScriptName,
                Eval = args.Eval,
                Watch = args.Watch ? (bool?)true : null,
            });
        }
        protected virtual void ParseScript(List <string> scriptLines, FilePreProcessorContext context, string path = null)
        {
            Guard.AgainstNullArgument("scriptLines", scriptLines);
            Guard.AgainstNullArgument("context", context);

            // Insert line directive if there's a path
            if (path != null)
            {
                InsertLineDirective(path, scriptLines);
            }

            var codeIndex = scriptLines.FindIndex(PreProcessorUtil.IsNonDirectiveLine);

            for (var index = 0; index < scriptLines.Count; index++)
            {
                ProcessLine(context, scriptLines[index], index < codeIndex || codeIndex < 0);
            }

            if (path != null)
            {
                context.LoadedScripts.Add(path);
            }
        }
Exemple #5
0
        public virtual void ParseFile(string path, FileParserContext context)
        {
            Guard.AgainstNullArgument("path", path);
            Guard.AgainstNullArgument("context", context);

            var fullPath = _fileSystem.GetFullPath(path);
            var filename = Path.GetFileName(path);

            if (context.LoadedScripts.Contains(fullPath))
            {
                _logger.DebugFormat("Skipping {0} because it's already been loaded.", filename);
                return;
            }

            _logger.DebugFormat("Processing {0}...", filename);

            var scriptLines = _fileSystem.ReadFileLines(fullPath).ToList();

            InsertLineDirective(fullPath, scriptLines);
            InDirectory(fullPath, () => ParseScript(scriptLines, context));

            context.LoadedScripts.Add(fullPath);
        }
Exemple #6
0
        public static void WriteAsciiArt(this IConsole console, string version)
        {
            Guard.AgainstNullArgument("console", console);

            var lines = new[]
            {
                @"+cyan               _       _",
                @"+cyan ___  ___ _ __(_)_ __ | |__+darkMagenta ___ ___",
                @"+cyan/ __|/ __| '__| | '_ \| __/+darkMagenta/ __/ __|",
                @"+cyan\__ \ (__| |  | | |_) | |_+darkMagenta| (__\__ \",
                @"+cyan|___/\___|_|  |_| .__/ \__\+darkMagenta\___|___/",
                string.Format(@"+cyan                |_|+white Version: {0}", version)
            };

            var colorRegex = new Regex(@"\+(?<color>\w*)(?<ascii>(.*(?=\+))|.*)",
                                       RegexOptions.Compiled | RegexOptions.Singleline);

            foreach (var matches in lines.Select(line => colorRegex.Matches(line)))
            {
                foreach (Match match in matches)
                {
                    ConsoleColor color;
                    if (Enum.TryParse(match.Groups["color"].Value, true, out color))
                    {
                        console.ForegroundColor = color;
                    }

                    console.Write(match.Groups["ascii"].Value);

                    console.ResetColor();
                }

                console.WriteLine();
            }

            console.WriteLine();
        }
Exemple #7
0
        protected virtual string ParseArguments(string command)
        {
            string script;
            var    arguments  = command.Split(new string[0], StringSplitOptions.None);
            var    commandKey = arguments.Length > 0 ? arguments[0] : command;

            Guard.AgainstNullArgument("_replCommands", _replCommands);

            if (!_replCommands.ContainsKey(commandKey))
            {
                return(string.Empty);
            }

            if (arguments.Length <= 0)
            {
                script = _replCommands[commandKey];
            }
            else
            {
                script = _replCommands[commandKey];
                var argumentCount = 0;
                foreach (var argument in arguments)
                {
                    if (argumentCount != 0)
                    {
                        var argumentToken = string.Format("arg{0}", argumentCount);
                        if (script.Contains(argumentToken))
                        {
                            script = script.Replace(argumentToken, argument);
                        }
                    }
                    argumentCount++;
                }
            }

            return(script);
        }
Exemple #8
0
        protected internal virtual void InjectScriptLibraries(
            string workingDirectory,
            FilePreProcessorResult result,
            IDictionary <string, object> state
            )
        {
            Guard.AgainstNullArgument("result", result);
            Guard.AgainstNullArgument("state", state);

            if (state.ContainsKey(ScriptLibrariesInjected))
            {
                return;
            }

            var scriptLibrariesPreProcessorResult = LoadScriptLibraries(workingDirectory);

            if (scriptLibrariesPreProcessorResult != null)
            {
                result.Code = scriptLibrariesPreProcessorResult.Code + Environment.NewLine + result.Code;
                result.References.AddRange(scriptLibrariesPreProcessorResult.References);
                result.Namespaces.AddRange(scriptLibrariesPreProcessorResult.Namespaces);
            }
            state.Add(ScriptLibrariesInjected, null);
        }
        public IEnumerable <string> GetAssemblyPaths(string path, bool binariesOnly = false)
        {
            Guard.AgainstNullArgument("path", path);

            List <string> assemblies;

            if (!_assemblyPathCache.TryGetValue(path, out assemblies))
            {
                var packageAssemblies = GetPackageAssemblies(path);
                var binAssemblies     = GetBinAssemblyPaths(path);

                assemblies = packageAssemblies.Union(binAssemblies).ToList();

                _assemblyPathCache.Add(path, assemblies);
            }

            if (binariesOnly)
            {
                return(assemblies.Where(
                           m => m.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase) || m.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase)));
            }

            return(assemblies);
        }
        protected void RegisterOverrideOrDefault <T>(ContainerBuilder builder, Action <ContainerBuilder> registrationAction)
        {
            Guard.AgainstNullArgument("registrationAction", registrationAction);

            if (_overrides.ContainsKey(typeof(T)))
            {
                var reg = _overrides[typeof(T)];
                this.Logger.Debug(string.Format("Registering override: {0}", reg));

                if (reg.GetType().IsSubclassOf(typeof(Type)))
                {
                    builder.RegisterType((Type)reg).As <T>().SingleInstance();
                }
                else
                {
                    builder.RegisterInstance(reg).As <T>();
                }
            }
            else
            {
                this.Logger.Debug(string.Format("Registering default: {0}", typeof(T)));
                registrationAction(builder);
            }
        }
Exemple #11
0
        public ScriptExecutor(
            IFileSystem fileSystem,
            IFilePreProcessor filePreProcessor,
            IScriptEngine scriptEngine,
            ILog logger,
            IScriptLibraryComposer composer)
        {
            Guard.AgainstNullArgument("fileSystem", fileSystem);
            Guard.AgainstNullArgumentProperty("fileSystem", "BinFolder", fileSystem.BinFolder);
            Guard.AgainstNullArgumentProperty("fileSystem", "DllCacheFolder", fileSystem.DllCacheFolder);
            Guard.AgainstNullArgument("filePreProcessor", filePreProcessor);
            Guard.AgainstNullArgument("scriptEngine", scriptEngine);
            Guard.AgainstNullArgument("logger", logger);
            Guard.AgainstNullArgument("composer", composer);

            References = new AssemblyReferences(DefaultReferences);
            Namespaces = new Collection <string>();
            ImportNamespaces(DefaultNamespaces);
            FileSystem            = fileSystem;
            FilePreProcessor      = filePreProcessor;
            ScriptEngine          = scriptEngine;
            Logger                = logger;
            ScriptLibraryComposer = composer;
        }
Exemple #12
0
        public Repl(
            string[] scriptArgs,
            IFileSystem fileSystem,
            IScriptEngine scriptEngine,
            IObjectSerializer serializer,
            ILogProvider logProvider,
            IScriptLibraryComposer composer,
            IConsole console,
            IFilePreProcessor filePreProcessor,
            IEnumerable <IReplCommand> replCommands,
            Printers printers)
            : base(fileSystem, filePreProcessor, scriptEngine, logProvider, composer)
        {
            Guard.AgainstNullArgument("serializer", serializer);
            Guard.AgainstNullArgument("logProvider", logProvider);
            Guard.AgainstNullArgument("console", console);

            _scriptArgs = scriptArgs;
            _serializer = serializer;
            _printers   = printers;
            _log        = logProvider.ForCurrentType();
            Console     = console;
            Commands    = replCommands != null?replCommands.Where(x => x.CommandName != null).ToDictionary(x => x.CommandName, x => x) : new Dictionary <string, IReplCommand>();
        }
        public bool ProcessLine(IFileParser parser, FileParserContext context, string line, bool isBeforeCode)
        {
            Guard.AgainstNullArgument("context", context);

            if (!IsUsingLine(line))
            {
                return(false);
            }

            // for using static, we will not extract the import into the context, but rather let it be treated as code
            if (line.Contains(" static "))
            {
                return(false);
            }

            var @namespace = GetNamespace(line);

            if (!context.Namespaces.Contains(@namespace))
            {
                context.Namespaces.Add(@namespace);
            }

            return(true);
        }
Exemple #14
0
        public virtual void AddReferences(params Assembly[] assemblies)
        {
            Guard.AgainstNullArgument("assemblies", assemblies);

            References = References.Union(assemblies);
        }
Exemple #15
0
 public virtual void RemoveNamespaces(params string[] namespaces)
 {
     Guard.AgainstNullArgument("namespaces", namespaces);
     Namespaces = new ReadOnlyCollection <string>(Namespaces.Except(namespaces).ToArray());
 }
Exemple #16
0
        public static bool IsLoadLine(string line)
        {
            Guard.AgainstNullArgument("line", line);

            return(line.TrimStart(' ').StartsWith(LoadString));
        }
Exemple #17
0
        public static bool IsUsingLine(string line)
        {
            Guard.AgainstNullArgument("line", line);

            return(line.TrimStart(' ').StartsWith(UsingString) && !line.Contains("{") && line.Contains(";"));
        }
Exemple #18
0
        public virtual void RemoveReferences(params string[] paths)
        {
            Guard.AgainstNullArgument("paths", paths);

            References = References.Except(paths);
        }
Exemple #19
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            Guard.AgainstNullArgument("script", script);

            try
            {
                if (script.StartsWith("#clear", StringComparison.OrdinalIgnoreCase))
                {
                    Console.Clear();
                    return(new ScriptResult());
                }

                if (script.StartsWith("#reset"))
                {
                    Reset();
                    return(new ScriptResult());
                }

                var preProcessResult = FilePreProcessor.ProcessScript(script);

                ImportNamespaces(preProcessResult.Namespaces.ToArray());

                foreach (var reference in preProcessResult.References)
                {
                    var referencePath = FileSystem.GetFullPath(Path.Combine(Constants.BinFolder, reference));
                    AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference);
                }

                Console.ForegroundColor = ConsoleColor.Cyan;

                Buffer += preProcessResult.Code;

                var result = ScriptEngine.Execute(Buffer, _scriptArgs, References, DefaultNamespaces, ScriptPackSession);
                if (result == null)
                {
                    return(new ScriptResult());
                }

                if (result.CompileExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.CompileExceptionInfo.SourceException.Message);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.ExecuteExceptionInfo.SourceException.Message);
                }

                if (result.IsPendingClosingChar)
                {
                    return(result);
                }

                if (result.ReturnValue != null)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;

                    var serializedResult = _serializer.Serialize(result.ReturnValue);

                    Console.WriteLine(serializedResult);
                }

                Buffer = null;
                return(result);
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + fileEx + "\r\n");
                return(new ScriptResult {
                    CompileExceptionInfo = ExceptionDispatchInfo.Capture(fileEx)
                });
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\r\n" + ex + "\r\n");
                return(new ScriptResult {
                    ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(ex)
                });
            }
            finally
            {
                Console.ResetColor();
            }
        }
Exemple #20
0
 protected virtual string GenerateCode(FileParserContext context)
 {
     Guard.AgainstNullArgument("context", context);
     return(string.Join(_fileSystem.NewLine, context.BodyLines));
 }
        public ReferenceLineProcessor(IFileSystem fileSystem)
        {
            Guard.AgainstNullArgument("fileSystem", fileSystem);

            _fileSystem = fileSystem;
        }
        public static void AddReference <T>(this IScriptExecutor executor)
        {
            Guard.AgainstNullArgument("executor", executor);

            executor.AddReferences(typeof(T));
        }
        public static void ImportNamespace <T>(this IScriptExecutor executor)
        {
            Guard.AgainstNullArgument("executor", executor);

            executor.ImportNamespaces(typeof(T));
        }
Exemple #24
0
        public virtual void RemoveReferences(params Assembly[] assemblies)
        {
            Guard.AgainstNullArgument("assemblies", assemblies);

            References = References.Except(assemblies);
        }
Exemple #25
0
        public virtual void AddReferences(params string[] paths)
        {
            Guard.AgainstNullArgument("paths", paths);

            References = References.Union(paths);
        }
Exemple #26
0
        public IEnumerable <string> SplitLines(string value)
        {
            Guard.AgainstNullArgument("value", value);

            return(value.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
        }
Exemple #27
0
        public ScriptCsLogger(ILog log)
        {
            Guard.AgainstNullArgument("log", log);

            _log = log;
        }
        public CommonLoggingLogProvider(Common.Logging.ILog logger)
        {
            Guard.AgainstNullArgument("logger", logger);

            _logger = logger;
        }
Exemple #29
0
        public override ScriptResult Execute(string script, params string[] scriptArgs)
        {
            Guard.AgainstNullArgument("script", script);

            try
            {
                if (script.StartsWith(":"))
                {
                    var tokens = script.Split(' ');
                    if (tokens[0].Length > 1)
                    {
                        var command = Commands.FirstOrDefault(x => x.CommandName == tokens[0].Substring(1));

                        if (command != null)
                        {
                            var argsToPass = new List <object>();
                            foreach (var argument in tokens.Skip(1))
                            {
                                var argumentResult = ScriptEngine.Execute(
                                    argument, _scriptArgs, References, Namespaces, ScriptPackSession);

                                if (argumentResult.CompileExceptionInfo != null)
                                {
                                    throw new Exception(
                                              GetInvalidCommandArgumentMessage(argument),
                                              argumentResult.CompileExceptionInfo.SourceException);
                                }

                                if (argumentResult.ExecuteExceptionInfo != null)
                                {
                                    throw new Exception(
                                              GetInvalidCommandArgumentMessage(argument),
                                              argumentResult.ExecuteExceptionInfo.SourceException);
                                }

                                if (!argumentResult.IsCompleteSubmission)
                                {
                                    throw new Exception(GetInvalidCommandArgumentMessage(argument));
                                }

                                argsToPass.Add(argumentResult.ReturnValue);
                            }

                            var commandResult = command.Execute(this, argsToPass.ToArray());
                            return(ProcessCommandResult(commandResult));
                        }
                    }
                }

                var preProcessResult = FilePreProcessor.ProcessScript(script);

                ImportNamespaces(preProcessResult.Namespaces.ToArray());

                foreach (var reference in preProcessResult.References)
                {
                    var referencePath = FileSystem.GetFullPath(Path.Combine(FileSystem.BinFolder, reference));
                    AddReferences(FileSystem.FileExists(referencePath) ? referencePath : reference);
                }

                Console.ForegroundColor = ConsoleColor.Cyan;

                Buffer = (Buffer == null)
                    ? preProcessResult.Code
                    : Buffer + Environment.NewLine + preProcessResult.Code;

                var result = ScriptEngine.Execute(Buffer, _scriptArgs, References, Namespaces, ScriptPackSession);
                if (result == null)
                {
                    return(ScriptResult.Empty);
                }

                if (result.CompileExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.CompileExceptionInfo.SourceException.Message);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(result.ExecuteExceptionInfo.SourceException.Message);
                }

                if (result.InvalidNamespaces.Any())
                {
                    RemoveNamespaces(result.InvalidNamespaces.ToArray());
                }

                if (!result.IsCompleteSubmission)
                {
                    return(result);
                }

                if (result.ReturnValue != null)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;

                    var serializedResult = _serializer.Serialize(result.ReturnValue);

                    Console.WriteLine(serializedResult);
                }

                Buffer = null;
                return(result);
            }
            catch (FileNotFoundException fileEx)
            {
                RemoveReferences(fileEx.FileName);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(Environment.NewLine + fileEx + Environment.NewLine);

                return(new ScriptResult(compilationException: fileEx));
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(Environment.NewLine + ex + Environment.NewLine);

                return(new ScriptResult(executionException: ex));
            }
            finally
            {
                Console.ResetColor();
            }
        }
Exemple #30
0
        public void AddReferenceByType(Type typeFromReferencedAssembly)
        {
            Guard.AgainstNullArgument("typeFromReferencedAssembly", typeFromReferencedAssembly);

            AddReference(typeFromReferencedAssembly.Assembly.Location);
        }