Exemplo n.º 1
0
        /// <summary>
        /// Execute script against the current Context.
        ///
        /// This method is not intended to be called directly.
        /// </summary>
        /// <returns>Script return value</returns>
        public virtual object ExecuteScript()
        {
            //
            CommandLineParameters c = new CommandLineParameters(Parameters, SwitchPrefixes, UnknownSwitches);

            c.ApplyDefaultValues(Context);
            c.CheckRequiredValues(Context);
            return(ReturnValue.Unwrap(base.Execute()));
        }
Exemplo n.º 2
0
        /// Get script usage, not exceeding the given width (-1 = autodetect width)
        public string GetAutoUsage(Script s, int width)
        {
            string id = s.Id;

            if (string.IsNullOrEmpty(id))
            {
                id = Path.GetFileNameWithoutExtension(s.Location).ToUpperInvariant();
            }


            StringWriter sw   = new StringWriter();
            string       desc = null;

            if ((s.Usage.Options & UsageOptions.UseVersionInfo) != 0)
            {
                desc = s.VersionInfo.GenerateInfo(this, true);
            }


            CommandLineParameters c = new CommandLineParameters(s.Parameters, s.SwitchPrefixes, s.UnknownSwitches);

            sw.Write(s.Usage.GetUsage(this, desc, id, width, c));
            return(sw.ToString());
        }
Exemplo n.º 3
0
        // Real main
        static int MainWithContext(XS.ScriptContext context, string[] args)
        {
            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            XS.CommandLineParameter[] param = new XS.CommandLineParameter[] {
                new XS.CommandLineParameter(xs.quiet, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.debug, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.debugc, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.verbose, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.nocolors, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.wait, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.save, XS.CommandLineValueCount.Single, null, "xsharper_save.xsh"),
                new XS.CommandLineParameter(xs.log, XS.CommandLineValueCount.Single, null, "xsharper.log"),
                new XS.CommandLineParameter(xs.requireAdmin, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.last, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.utf8, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.scriptargs, null, XS.CommandLineValueCount.Multiple, null, null)
            };
            param[param.Length - 1].Last = true;
            param[param.Length - 2].Last = true;

            XS.CommandLineParameters xsParams = new XS.CommandLineParameters(param, "//", false);
            foreach (XS.CommandLineParameter a in xsParams)
            {
                if (!string.IsNullOrEmpty(a.Name) && a.Name != xs.scriptargs)
                {
                    a.Switch = a.Name.Replace("xs.", "");
                }
            }


            int exitCode = 0;

            bool utf8 = false;

            foreach (string arg in args)
            {
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                {
                    utf8 = true;
                }
            }
            using (XS.ConsoleWithColors cout = new XS.ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"), utf8))
                using (XS.CtrlCInterceptor ctrl = new XS.CtrlCInterceptor())
                {
                    context.Output += cout.OnOutput;
                    ctrl.Output     = context.Error;
                    ctrl.Abort     += delegate { context.Abort(); };

                    AppDomainLoader.progress("MainWithContext: Console ready --------------------");
                    System.Diagnostics.Stopwatch w = System.Diagnostics.Stopwatch.StartNew();

                    try
                    {
                        AppDomainLoader.progress("MainWithContext: Before parse--------------------");
                        xsParams.Parse(context, args, false);
                        AppDomainLoader.progress("MainWithContext: Before set options--------------------");
                        setOutputOptions(context, cout);

                        AppDomainLoader.progress("MainWithContext: Before load--------------------");
                        $ {
                            GENERATED_CLASS
                        } cl = new $ {
                            GENERATED_CLASS
                        } ();
                        XS.Script s = cl.Script;
                        ctrl.IgnoreCtrlC = s.IgnoreCtrlC;
                        ctrl.AbortDelay  = XS.Utils.ToTimeSpan(s.AbortDelay) ?? ctrl.AbortDelay;
                        ctrl.ExitDelay   = XS.Utils.ToTimeSpan(s.ExitDelay) ?? ctrl.ExitDelay;


                        AppDomainLoader.progress("MainWithContext: After load--------------------");
                        if (context.IsSet(xs.save))
                        {
                            using (XS.ScriptContextScope r = new XS.ScriptContextScope(context))
                                s.Save(context.GetString(xs.save));
                        }
                        else
                        {
                            context.Compiler.AddRequireAdmin(XS.Utils.To <XS.RequireAdminMode>(context.GetStr(xs.requireAdmin, XS.RequireAdminMode.User.ToString())));
                            context.Compiler.AddRequireAdmin(s.RequireAdmin);
                            if (context.Compiler.RequireAdmin != XS.RequireAdminMode.User && !context.IsAdministrator)
                            {
                                return(restartAsAdmin(context, args, context.Compiler.RequireAdmin == XS.RequireAdminMode.Hidden));
                            }

                            AppDomainLoader.progress("MainWithContext: Before initialization --------------------");
                            context.Initialize(s);
                            AppDomainLoader.progress("MainWithContext: After initialization --------------------");
                            string[] parms = null;
                            if (context.IsSet(xs.scriptargs))
                            {
                                parms = context.GetStringArray(xs.scriptargs);
                            }

                            XS.ConsoleRedirector redir = new XS.ConsoleRedirector(context);
                            try
                            {
                                AppDomainLoader.progress("MainWithContext: Before executing --------------------");
                                object r = context.ExecuteScript(s, parms, XS.CallIsolation.High);
                                ctrl.KillAbortTimer();
                                AppDomainLoader.progress("MainWithContext: After executing --------------------");
                                if (r != null)
                                {
                                    int.TryParse(r.ToString(), out exitCode);
                                }
                            }
                            finally
                            {
                                ctrl.KillAbortTimer();
                                redir.Dispose();
                            }
                        }
                    }
                    catch (ThreadAbortException ae)
                    {
                        resetAbort(context);
                        context.WriteException(ae.InnerException);
                        exitCode = -1000;
                    }
                    catch (XS.ScriptTerminateException te)
                    {
                        resetAbort(context);
                        exitCode = te.ExitCode;
                        if (te.InnerException != null)
                        {
                            context.WriteException(te.InnerException);
                        }
                    }
                    catch (Exception e)
                    {
                        resetAbort(context);
                        context.WriteException(e);
                        exitCode = -1;
                    }
                    finally
                    {
                        resetAbort(context);
                    }
                    if (context.GetBool(xs.wait, false))
                    {
                        cout.WriteLine(XS.OutputType.Info, string.Format("Completed in {0} with exit code={1}. Press Enter to close...", w.Elapsed, exitCode));
                        Console.ReadLine();
                    }
                }
            return(exitCode);
        }
Exemplo n.º 4
0
        // Real main
        static int MainWithContext(XS.ScriptContext context, string[] args)
        {
            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            XS.CommandLineParameter[] param = new XS.CommandLineParameter[] {
                new XS.CommandLineParameter(xs.quiet,        XS.CommandLineValueCount.None, null,"true" ),
                new XS.CommandLineParameter(xs.debug,        XS.CommandLineValueCount.None, "false", "true" ) ,
                new XS.CommandLineParameter(xs.debugc,       XS.CommandLineValueCount.None, "false", "true" ) ,
                new XS.CommandLineParameter(xs.verbose,      XS.CommandLineValueCount.None, "false", "true" ) ,
                new XS.CommandLineParameter(xs.nocolors,     XS.CommandLineValueCount.None, "false", "true" ) ,
                new XS.CommandLineParameter(xs.wait,         XS.CommandLineValueCount.None, null,"true" ) ,
                new XS.CommandLineParameter(xs.save,         XS.CommandLineValueCount.Single, null,"xsharper_save.xsh" ) ,
                new XS.CommandLineParameter(xs.log,          XS.CommandLineValueCount.Single, null,"xsharper.log" ) ,
                new XS.CommandLineParameter(xs.requireAdmin, XS.CommandLineValueCount.None, null,"true" ) ,
                new XS.CommandLineParameter(xs.last,         XS.CommandLineValueCount.None, null,"true") ,
                new XS.CommandLineParameter(xs.utf8,         XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.scriptargs,   null, XS.CommandLineValueCount.Multiple, null,null) 
             };
            param[param.Length - 1].Last = true;
            param[param.Length - 2].Last = true;

            XS.CommandLineParameters xsParams = new XS.CommandLineParameters(param,"//",false);
            foreach (XS.CommandLineParameter a in xsParams)
                if (!string.IsNullOrEmpty(a.Name) && a.Name!=xs.scriptargs)
                    a.Switch = a.Name.Replace("xs.", "");
            
            
            int exitCode = 0;

            bool utf8 = false;
            foreach (string arg in args)
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                    utf8 = true;
            using (XS.ConsoleWithColors cout = new XS.ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"),utf8))
            using (XS.CtrlCInterceptor ctrl = new XS.CtrlCInterceptor())
            {
                context.Output += cout.OnOutput;
                ctrl.Output = context.Error;
                ctrl.Abort += delegate { context.Abort(); };

                AppDomainLoader.progress("MainWithContext: Console ready --------------------"); 
                System.Diagnostics.Stopwatch w = System.Diagnostics.Stopwatch.StartNew();

                try
                {
                    AppDomainLoader.progress("MainWithContext: Before parse--------------------"); 
                    xsParams.Parse(context, args, false);
                    AppDomainLoader.progress("MainWithContext: Before set options--------------------"); 
                    setOutputOptions(context, cout);

                    AppDomainLoader.progress("MainWithContext: Before load--------------------"); 
                    ${GENERATED_CLASS} cl = new ${GENERATED_CLASS}();
                    XS.Script s = cl.Script;
                    ctrl.IgnoreCtrlC = s.IgnoreCtrlC;
                    ctrl.AbortDelay = XS.Utils.ToTimeSpan(s.AbortDelay) ?? ctrl.AbortDelay;
                    ctrl.ExitDelay = XS.Utils.ToTimeSpan(s.ExitDelay) ?? ctrl.ExitDelay;
                        
                     
                    AppDomainLoader.progress("MainWithContext: After load--------------------"); 
                    if (context.IsSet(xs.save))
                    {
                        using (XS.ScriptContextScope r=new XS.ScriptContextScope(context))
                            s.Save(context.GetString(xs.save));
                    }
                    else
                    {
                        context.Compiler.AddRequireAdmin(XS.Utils.To<XS.RequireAdminMode>(context.GetStr(xs.requireAdmin, XS.RequireAdminMode.User.ToString())));
                        context.Compiler.AddRequireAdmin(s.RequireAdmin);
                        if (context.Compiler.RequireAdmin!=XS.RequireAdminMode.User && !context.IsAdministrator)
                            return restartAsAdmin(context, args, context.Compiler.RequireAdmin==XS.RequireAdminMode.Hidden);

                        AppDomainLoader.progress("MainWithContext: Before initialization --------------------"); 
                        context.Initialize(s);
                        AppDomainLoader.progress("MainWithContext: After initialization --------------------"); 
                        string[] parms = null;
                        if (context.IsSet(xs.scriptargs))
                            parms = context.GetStringArray(xs.scriptargs);

                        XS.ConsoleRedirector redir = new XS.ConsoleRedirector(context);
                        try
                        {
                            AppDomainLoader.progress("MainWithContext: Before executing --------------------"); 
                            object r = context.ExecuteScript(s, parms, XS.CallIsolation.High);
                            ctrl.KillAbortTimer();
                            AppDomainLoader.progress("MainWithContext: After executing --------------------"); 
                            if (r != null)
                                int.TryParse(r.ToString(), out exitCode);
                        }
                        finally 
                        {
                            ctrl.KillAbortTimer();
                            redir.Dispose();
                        }
                    }
                }
Exemplo n.º 5
0
        /// Parse command line arguments
        public void ParseArguments(IEnumerable <string> args)
        {
            CommandLineParameters c = new CommandLineParameters(Parameters, SwitchPrefixes, UnknownSwitches);

            c.Parse(Context, args, (Usage.Options & UsageOptions.IfHelp) != 0);
        }
Exemplo n.º 6
0
        private string getArgsUsage(ScriptContext context, int width, CommandLineParameters items)
        {
            List <Var> sb = new List <Var>();

            foreach (CommandLineParameter p in items)
            {
                string text     = p.GetTransformedValue(context);
                string vardescr = p.GetDescription(context);

                string name;
                bool   emptyName = (p.Switch ?? string.Empty).Trim().Length == 0;
                if (emptyName && string.IsNullOrEmpty(p.Var))
                {
                    name = p.Switch ?? string.Empty;
                }
                else
                {
                    if (string.IsNullOrEmpty(text))
                    {
                        continue;
                    }
                    if (emptyName)
                    {
                        name = " ";
                    }
                    else
                    {
                        var pp = items.GetSwitchPrefixesArray();
                        name = "  " + ((pp != null && pp.Length > 0) ? pp[0] : string.Empty) + p.Switch;
                    }
                }

                if (p.Count != CommandLineValueCount.None)
                {
                    if (p.Unspecified == null || emptyName)
                    {
                        if (!string.IsNullOrEmpty(vardescr))
                        {
                            name += " " + vardescr;
                        }
                    }
                    else
                    {
                        name += " [" + vardescr + "]";
                    }
                }

                StringBuilder vb = new StringBuilder();
                vb.Append(text);
                if ((Options & UsageOptions.AutoSuffix) != 0)
                {
                    if (p.Required)
                    {
                        vb.Append(" (required)");
                    }
                    else if (p.Default != null && p.Count != CommandLineValueCount.None)
                    {
                        string def = Utils.To <string>(context.Transform(p.Default, p.Transform));
                        vb.Append(" (default: " + def + ")");
                    }
                }
                Var v = new Var(name, vb.ToString());
                sb.Add(v);
            }

            StringWriter sw = new StringWriter();

            Utils.WrapTwoColumns(sw, sb, 30, width);
            return(sw.ToString());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Generate usage text for the script with given ID and descriptions
        /// </summary>
        /// <param name="context">Script context</param>
        /// <param name="description">Script description</param>
        /// <param name="id">Script ID</param>
        /// <param name="width">Console width</param>
        /// <param name="items">Command line parameters</param>
        /// <returns></returns>
        public string GetUsage(ScriptContext context, string description, string id, int width, CommandLineParameters items)
        {
            width = CorrectWidth(width);

            StringWriter sw = new StringWriter();

            // Write description
            if (!string.IsNullOrEmpty(description))
            {
                Utils.Wrap(sw, description, width, string.Empty);
                sw.WriteLine();
            }

            if ((Options & UsageOptions.UsageLine) != 0)
            {
                string prefix = LinePrefix + id;

                StringBuilder line     = new StringBuilder(prefix);
                bool          optional = false;
                foreach (CommandLineParameter p in items)
                {
                    string text     = p.GetTransformedValue(context);
                    string vardescr = p.GetDescription(context);
                    if (p.Required)
                    {
                        if (!string.IsNullOrEmpty(p.Switch))
                        {
                            line.Append(" " + items.GetSwitchPrefixesArray()[0] + p.Switch);
                        }
                        if (p.Count != CommandLineValueCount.None)
                        {
                            line.Append(" " + p.GetDescription(context));
                        }
                    }
                    else if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(p.Switch))
                    {
                        optional = true;
                    }
                    else if (p.Count != CommandLineValueCount.None && string.IsNullOrEmpty(p.Switch) && !string.IsNullOrEmpty(vardescr))
                    {
                        line.Append(" [" + vardescr + "]");
                    }
                }

                if (optional && LineSuffix == null)
                {
                    line.Append(" [parameters]");
                }
                line.Append(LineSuffix);
                Utils.Wrap(sw, line.ToString(), width, new string(' ', prefix.Length + 1));
            }

            foreach (CommandLineParameter p in items)
            {
                string text = p.GetTransformedValue(context);
                if (!string.IsNullOrEmpty(text) &&
                    ((p.Switch ?? string.Empty).Trim().Length != 0 ||
                     (!string.IsNullOrEmpty(p.Var) && !string.IsNullOrEmpty(p.Value))))
                {
                    if ((Options & UsageOptions.UsageLine) != 0)
                    {
                        sw.WriteLine();
                    }
                    break;
                }
            }
            sw.Write(getArgsUsage(context, width, items));
            return(sw.ToString());
        }