Exemplo n.º 1
0
        ///////////////////////////////////////////////////////////////////////

        public static bool WriteText(
            IInteractiveHost interactiveHost
            )
        {
            return((interactiveHost != null) ?
                   interactiveHost.WriteLine(Text) : false);
        }
Exemplo n.º 2
0
        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
#if EAGLE
        public static bool WriteSummary(
            IInteractiveHost interactiveHost
            )
        {
            return((interactiveHost != null) ?
                   interactiveHost.WriteLine(Summary) : false);
        }
Exemplo n.º 3
0
        ///////////////////////////////////////////////////////////////////////

        #region Public Methods
        public ReturnCode ArgumentCallback(
            Interpreter interpreter,
            IInteractiveHost interactiveHost,
            IClientData clientData,
            int count,
            string arg,
            ref IList <string> argv,
            ref Result result
            )
        {
            if (callback == null)
            {
                result = "invalid shell callback";
                return(ReturnCode.Error);
            }

            return(callback.ProcessArgument(
                       interpreter, interactiveHost, clientData, count, arg,
                       ref argv, ref result));
        }
Exemplo n.º 4
0
        ///////////////////////////////////////////////////////////////////////

        #region Application Entry Point
        /// <summary>
        /// This is the main entry point for this assembly.
        /// </summary>
        /// <param name="args">
        /// The command line arguments received from the calling assembly.
        /// </param>
        /// <returns>
        /// Zero for success, non-zero on error.
        /// </returns>
        private static int Main(
            string[] args /* in */
            )
        {
            //
            // NOTE: The integer exit code to return to the caller (parent
            //       process, etc).
            //
            ExitCode exitCode = Utility.SuccessExitCode();

            //
            // NOTE: Save the command line arguments for use by the
            //       interpreter via the linked variable (optional).
            //
            mainArgs = args;

            //
            // NOTE: The "interpreter result" that is passed to various
            //       methods.
            //
            Result result = null;

            //
            // NOTE: First, we create a new interpreter (with the default
            //       options).
            //
            using (Interpreter interpreter = Interpreter.Create(
                       args, ref result))
            {
                if (interpreter != null)
                {
                    ReturnCode code = interpreter.SetVariableLink(
                        VariableFlags.None, fieldName, typeof(Program).
                        GetField(fieldName), null, ref result);

                    if (code != ReturnCode.Ok)
                    {
                        //
                        // NOTE: Handle variable linking error.
                        //
                        exitCode = Utility.ReturnCodeToExitCode(code);
                    }

                    //
                    // NOTE: Create an instance of the example custom command.
                    //
                    Class0 class0 = new Class0(new CommandData("class0", null,
                                                               null, ClientData.Empty, typeof(Class0).FullName,
                                                               CommandFlags.None, null, 0));

                    //
                    // NOTE: The token that will represent the custom command
                    //       we add.
                    //
                    long commandToken = 0;

                    //
                    // NOTE: Next, we can optionally add one or more custom
                    //       commands.
                    //
                    if (code == ReturnCode.Ok)
                    {
                        code = interpreter.AddCommand(
                            class0, null, ref commandToken, ref result);
                    }

                    //
                    // NOTE: The token that will represent the custom command
                    //       policy we add.
                    //
                    long policyToken = 0;

                    //
                    // NOTE: Next, add our custom command execution policy (for
                    //       use in "safe" mode).
                    //
                    if (code == ReturnCode.Ok)
                    {
                        code = interpreter.AddPolicy(
                            Class0PolicyCallback, null, null, ref policyToken,
                            ref result);
                    }

                    //
                    // NOTE: The error line number that is passed to various
                    //       script evaluation methods.
                    //
                    int errorLine = 0;

                    //
                    // NOTE: Check for a successful return code.
                    //
                    if (code == ReturnCode.Ok) // OR: Utility.IsSuccess(code, true)
                    {
#if SHELL
                        result = null;

                        code = Interpreter.InteractiveLoop(
                            interpreter, args, ref result);
#else
                        //
                        // NOTE: Next, evaluate one or more scripts of your
                        //       choosing (which may or may not reference any
                        //       custom commands you may have added in the
                        //       previous step).
                        //
                        code = Engine.EvaluateScript(
                            interpreter, "class0 test; # <-- script text",
                            ref result, ref errorLine);
#endif

                        //
                        // NOTE: Check for an unsuccessful return code.
                        //
                        if (code != ReturnCode.Ok) // OR: !Utility.IsSuccess(code, true)
                        {
                            //
                            // NOTE: Handle script error.
                            //
                            exitCode = Utility.ReturnCodeToExitCode(code);
                        }

                        //
                        // NOTE: Next, we can optionally remove one or more of
                        //       the custom command policies we added earlier.
                        //
                        code = interpreter.RemovePolicy(policyToken, null,
                                                        ref result);

                        //
                        // NOTE: Check for an unsuccessful return code.
                        //
                        if (code != ReturnCode.Ok)
                        {
                            //
                            // NOTE: Handle policy removal error.
                            //
                            exitCode = Utility.ReturnCodeToExitCode(code);
                        }

                        //
                        // NOTE: Next, we can optionally remove one or more of
                        //       the custom commands we added earlier.
                        //
                        code = interpreter.RemoveCommand(commandToken, null,
                                                         ref result);

                        //
                        // NOTE: Check for an unsuccessful return code.
                        //
                        if (code != ReturnCode.Ok)
                        {
                            //
                            // NOTE: Handle command removal error.
                            //
                            exitCode = Utility.ReturnCodeToExitCode(code);
                        }

                        code = interpreter.UnsetVariable(VariableFlags.None,
                                                         fieldName, ref result);

                        if (code != ReturnCode.Ok)
                        {
                            //
                            // NOTE: Handle variable unlinking error.
                            //
                            exitCode = Utility.ReturnCodeToExitCode(code);
                        }
                    }
                    else
                    {
                        //
                        // NOTE: Handle failure to add the custom command
                        //       or policy.
                        //
                        exitCode = Utility.ReturnCodeToExitCode(code);
                    }

                    //
                    // NOTE: Always check for a valid interpreter hosting
                    //       environment before using it as it is not
                    //       guaranteed to always be available.
                    //
                    IInteractiveHost interactiveHost = interpreter.Host;

                    if (interactiveHost != null)
                    {
                        interactiveHost.WriteResultLine(
                            code, result, errorLine);
                    }
                    else
                    {
                        Console.WriteLine(Utility.FormatResult(
                                              code, result, errorLine));
                    }
                }
                else
                {
                    //
                    // NOTE: Creation of the interpreter failed.
                    //
                    Console.WriteLine(Utility.FormatResult(
                                          ReturnCode.Error, result));

                    exitCode = Utility.FailureExitCode();
                }
            }

            return((int)exitCode);
        }
Exemplo n.º 5
0
        [STAThread()] /* WinForms */
        private static int Main(string[] args)
        {
            ReturnCode code;
            Result     result = null;

            using (interpreter = Interpreter.Create(
                       args, CreateFlags.ShellUse, ref result))
            {
                if (interpreter != null)
                {
                    code = interpreter.Initialize(false, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        Assembly     assembly     = Assembly.GetExecutingAssembly();
                        AssemblyName assemblyName = assembly.GetName();
                        string       fileName     = assembly.Location;
                        string       typeName     = typeof(_Plugins.Toolkit).FullName;
                        Uri          uri          = Utility.GetAssemblyUri(assembly);

                        IPlugin plugin = new _Plugins.Toolkit(new PluginData(
                                                                  Utility.FormatPluginName(assemblyName.FullName,
                                                                                           typeName), null, null, ClientData.Empty,
                                                                  PluginFlags.None, assemblyName.Version, uri,
                                                                  interpreter.GetAppDomain(), assembly, assemblyName,
                                                                  fileName, typeName, null, null, null, null, null,
                                                                  null, null, null, 0));

                        code = Utility.PrepareStaticPlugin(plugin, ref result);

                        if (code == ReturnCode.Ok)
                        {
                            code = interpreter.AddPlugin(plugin, null,
                                                         ref toolkitPluginToken, ref result);
                        }
                    }

                    if (code == ReturnCode.Ok)
                    {
                        Thread thread = Engine.CreateThread(
                            interpreter, InteractiveLoopThreadStart, 0, true,
                            false);

                        if (thread != null)
                        {
                            thread.Name = String.Format(
                                "interactiveLoopThread: {0}", interpreter);

                            thread.Start(args);

                            Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);

                            Toplevel toplevel = new Toplevel(interpreter, ".");

                            Application.Run(toplevel);

                            if (thread != null)
                            {
                                thread.Join();
                            }

                            exitCode = interpreter.ExitCode;
                        }
                        else
                        {
                            result = "could not create interactive loop thread";
                            code   = ReturnCode.Error;
                        }
                    }

                    if (code != ReturnCode.Ok)
                    {
                        IInteractiveHost interactiveHost = interpreter.Host;

                        if (interactiveHost != null)
                        {
                            interactiveHost.WriteResultLine(
                                code, result, interpreter.ErrorLine);
                        }

                        exitCode = Utility.ReturnCodeToExitCode(code, true);
                    }
                }
                else
                {
#if CONSOLE
                    //
                    // NOTE: Creation of the interpreter failed.
                    //
                    Console.WriteLine(Utility.FormatResult(
                                          ReturnCode.Error, result));
#endif

                    exitCode = Utility.FailureExitCode();
                }
            }

            return((int)exitCode);
        }
Exemplo n.º 6
0
        ///////////////////////////////////////////////////////////////////////

        #region INotify Members (Required)
        /// <summary>
        /// Receives notifications when an event occurs that the plugin has
        /// declared it wants to be notified about.
        /// </summary>
        /// <param name="interpreter">
        /// The interpreter context we are executing in.
        /// </param>
        /// <param name="eventArgs">
        /// Contains data related to the event.  The exact data depends on the
        /// type of event being processed.
        /// </param>
        /// <param name="clientData">
        /// The extra data supplied for this event, if any.
        /// </param>
        /// <param name="result">
        /// Upon success, this may contain an informational message.
        /// Upon failure, this must contain an appropriate error message.
        /// </param>
        /// <returns>
        /// ReturnCode.Ok on success, ReturnCode.Error on failure.
        /// </returns>
        public override ReturnCode Notify(
            Interpreter interpreter,    /* in */
            IScriptEventArgs eventArgs, /* in */
            IClientData clientData,     /* in */
            ArgumentList arguments,     /* in */
            ref Result result           /* out */
            )
        {
            ReturnCode code = ReturnCode.Ok;

            //
            // NOTE: If there is no data associated with this event, just
            //       return.  We do not know how to handle these types of
            //       events and nothing else should be done.  The best advice
            //       when implementing this interface is "when in doubt, just
            //       do nothing".
            //
            if (eventArgs == null)
            {
                return(code);
            }

            //
            // NOTE: Make sure that notification matches the types and flags
            //       that we care about.  In theory, this should be handled
            //       by the core library before we get called; however, it
            //       cannot really hurt to double check.
            //
            if (!Utility.HasFlags(
                    eventArgs.NotifyTypes, NotifyType.Script, true) ||
                !Utility.HasFlags(
                    eventArgs.NotifyFlags, NotifyFlags.Completed, true))
            {
                return(code);
            }

#if false
            //
            // NOTE: This is the interpreter involved in the event, which may
            //       be different from the interpreter context we are executing
            //       in.  This example does not make use of this interpreter;
            //       therefore, this code block is commented out.
            //
            /* NOT USED */
            Interpreter eventInterpreter = eventArgs.Interpreter;

            if (eventInterpreter == null)
            {
                return(code);
            }
#endif

            //
            // NOTE: Grab the extra data associated with this "event" now.  The
            //       exact contents will vary depending on the event type being
            //       serviced.  The source code associated with the event type
            //       in question should be consulted to determine the necessary
            //       type conversion(s).
            //
            IClientData eventClientData = eventArgs.ClientData;

            if (eventClientData == null)
            {
                return(code);
            }

            //
            // NOTE: In this case, the data associated with the event is an
            //       "object list".  If the data does not conform to that type,
            //       bail out now.
            //
            IList <object> list = eventClientData.Data as IList <object>;

            if (list == null)
            {
                return(code);
            }

            //
            // NOTE: Attempt to fetch the text of the script that was just
            //       completed.
            //
            string text;

            try
            {
                //
                // NOTE: The third element should contain the full text of the
                //       completed script.
                //
                text = list[2] as string;

                if (text != null)
                {
                    //
                    // NOTE: The third and fourth elements should contain the
                    //       offset and number of characters for the completed
                    //       script, respectively.
                    //
                    text = text.Substring((int)list[3], (int)list[4]);
                }
            }
            catch
            {
                //
                // NOTE: Somehow, the data does not conform to expectations for
                //       this event type.  Gracefully ignore it.
                //
                text = null;
            }

            //
            // NOTE: To display the text of the completed script, both the
            //       interpreter and the text itself is required.
            //
            if ((interpreter != null) && (text != null))
            {
                //
                // NOTE: Grab the host from the interpreter context we are
                //       executing in.
                //
                IInteractiveHost interactiveHost = interpreter.Host;

                if (interactiveHost != null)
                {
                    //
                    // NOTE: Emit a message to the interpreter host that
                    //       includes the full text of the completed script.
                    //
                    interactiveHost.WriteLine(String.Format(
                                                  "{0}: script completed{1}{2}", GetType().FullName,
                                                  Environment.NewLine, text));
                }
            }

            return(code);
        }
Exemplo n.º 7
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == 2)
                    {
                        if (!interpreter.HasNoBackgroundError())
                        {
                            IInteractiveHost interactiveHost = interpreter.Host;

                            if (interactiveHost != null)
                            {
                                string message = arguments[1];

                                message = !String.IsNullOrEmpty(message) ?
                                          String.Format("{0}: {1}", this.Name, message) :
                                          this.Name;

                                interactiveHost.WriteResultLine(ReturnCode.Error,
                                                                message, Interpreter.GetErrorLine(interpreter));

                                result = String.Empty;
                            }
                            else
                            {
                                result = "interpreter host not available";
                                code   = ReturnCode.Error;
                            }
                        }
                        else
                        {
                            result = "background error handling disabled";
                            code   = ReturnCode.Error;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"bgerror message\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Exemplo n.º 8
0
        public static ReturnCode PolicyCallback( /* POLICY */
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            IPolicyContext policyContext = null;
            bool           match         = false;

            if (Utility.ExtractPolicyContextAndCommand(
                    interpreter, clientData, null, 0, ref policyContext,
                    ref match, ref result) == ReturnCode.Ok)
            {
                if (match)
                {
                    //
                    // NOTE: Fetch the reference to the Cmdlet itself that we
                    //       smuggled in via the named opaque object handle
                    //       that was prearranged with the base cmdlet itself.
                    //
                    _Cmdlets.Script script = null;

                    if (GetCmdlet(interpreter,
                                  ref script, ref result) == ReturnCode.Ok)
                    {
                        //
                        // NOTE: Grab the interpreter host, if any.
                        //
                        IInteractiveHost interactiveHost = interpreter.Host;

                        //
                        // NOTE: If the interpreter host is available, use the
                        //       title as the caption; otherwise, we will use
                        //       the hard-coded default.
                        //
                        string processCaption = (interactiveHost != null) ?
                                                interactiveHost.Title : null;

                        //
                        // NOTE: If the caption is null or empty, use the
                        //       hard-coded default.
                        //
                        if (String.IsNullOrEmpty(processCaption))
                        {
                            processCaption = _Constants.Policy.ProcessCaption;
                        }

                        //
                        // NOTE: Build the description of the operation for
                        //       "What-If" and "Verbose" modes.
                        //
                        string verboseDescription = String.Format(
                            _Constants.Policy.VerboseDescription, arguments);

                        //
                        // NOTE: Grab the command name from the argument list
                        //       because we need to present it to the user in
                        //       the confirmation query.
                        //
                        string commandName = (arguments.Count > 0) ?
                                             arguments[0] : null;

                        //
                        // NOTE: Build the confirmation query to present to
                        //       the user.
                        //
                        string verboseWarning = String.Format(
                            _Constants.Policy.VerboseWarning, commandName,
                            arguments);

                        //
                        // TODO: *TEST* Verify that this works correctly and
                        //       has the expected semantics.
                        //
                        if (ShouldProcess(script, verboseDescription,
                                          verboseWarning, processCaption))
                        {
                            //
                            // NOTE: If the interpreter host is available, use
                            //       the title as the caption; otherwise, we
                            //       will use the hard-coded default.
                            //
                            string continueCaption = (interactiveHost != null) ?
                                                     interactiveHost.Title : null;

                            //
                            // NOTE: If the caption is null or empty, use the
                            //       hard-coded default.
                            //
                            if (String.IsNullOrEmpty(continueCaption))
                            {
                                continueCaption = _Constants.Policy.ContinueCaption;
                            }

                            //
                            // NOTE: Build the re-confirmation query to present
                            //       to the user.
                            //
                            string query = String.Format(
                                _Constants.Policy.Query, verboseWarning);

                            //
                            // NOTE: If we are in "force" mode or the user
                            //       allows us to continue then do so;
                            //       otherwise, do nothing and the command will
                            //       be allowed/denied based on the other
                            //       policies, if any.  In the event that there
                            //       are no other policies present, the command
                            //       will not be allowed to execute.
                            //
                            // BUGFIX: Cannot ask user when not interactive.
                            //
                            if (script.Force ||
                                ShouldContinue(script, query, continueCaption,
                                               ref yesToAll, ref noToAll))
                            {
                                //
                                // NOTE: The user has explicitly approved the
                                //       command execution.
                                //
                                policyContext.Approved();
                            }
                            else if (script.Deny)
                            {
                                //
                                // BUGFIX: Must explicitly deny to override the
                                //         built-in policies (e.g. for [info],
                                //         [object], etc).
                                //
                                policyContext.Denied();
                            }
                        }
                        else if (script.Deny)
                        {
                            //
                            // BUGFIX: Must explicitly deny to override the
                            //         built-in policies (e.g. for [info],
                            //         [object], etc).
                            //
                            policyContext.Denied();
                        }

                        //
                        // NOTE: The policy checking has been successful;
                        //       however, this does not necessarily mean
                        //       that we allow the command to be executed.
                        //
                        return(ReturnCode.Ok);
                    }
                }
                else
                {
                    result = "policyContext does not contain a command object";
                }
            }

            return(ReturnCode.Error);
        }
Exemplo n.º 9
0
        ///////////////////////////////////////////////////////////////////////

        public static HeaderFlags GetHeaderFlags(
            IInteractiveHost interactiveHost,
            HeaderFlags headerFlags,
            bool debug,
            bool show,
            bool empty,
            bool @default
            )
        {
            //
            // NOTE: If we are in debug mode and no header display flags have
            //       been explicitly set for the interpreter, initialize them
            //       to the default value.
            //
            if (@default && FlagOps.HasFlags(
                    headerFlags, HeaderFlags.Invalid, true))
            {
                //
                // NOTE: Remove the "these flags have not been setup before"
                //       indicator flag.
                //
                headerFlags &= ~HeaderFlags.Invalid;

                //
                // NOTE: Add the default header flags for the interactive
                //       host.  If the interactive host is not available,
                //       fallback on the system default header flags.
                //
                HeaderFlags defaultHeaderFlags = HeaderFlags.Default;

                if (interactiveHost != null)
                {
                    headerFlags |= HostOps.GetHeaderFlags(
                        interactiveHost, defaultHeaderFlags);
                }
                else
                {
                    headerFlags |= defaultHeaderFlags;
                }
            }

            //
            // NOTE: Only modify (set or unset) the active debugger flag if we
            //       have been told to do so; otherwise, the active debugger
            //       flag may have been manually changed and should be left
            //       alone.
            //
            if (show)
            {
                //
                // NOTE: Is there an active debugger?
                //
                if (debug)
                {
                    //
                    // NOTE: Set the active debugger flag.
                    //
                    headerFlags |= HeaderFlags.Debug;
                }
                else
                {
                    //
                    // NOTE: Unset the active debugger flag.
                    //
                    headerFlags &= ~HeaderFlags.Debug;
                }
            }

            //
            // NOTE: Show empty content?
            //
            if (empty)
            {
                headerFlags |= HeaderFlags.EmptyContent;
            }

            return(headerFlags);
        }