Beispiel #1
0
        internal static IList <string> GetCommandTree(this CliCommand command, List <string> list = null)
        {
            if (list == null)
            {
                list = new List <string>();
            }

            if (command.Parent == null)
            {
                var name = !command.AppSettings.CustomName
                    ? $"{command.AppSettings.Name}.exe"
                    : command.AppSettings.Name;
                list.Insert(0, _isWindows && !command.AppSettings.CustomName
                    ? $"{command.AppSettings.Name}.exe"
                    : command.AppSettings.Name);
                return(list);
            }

            var matchingCommand = command.Parent.CommandProperties
                                  .First(prop => prop.PropertyType == command.Type);

            var commandName = matchingCommand.Name.KebabConvert().ToLower();

            list.Insert(0, commandName);
            return(GetCommandTree(command.Parent, list));
        }
        private bool ReadUserInput()
        {
            string commandText = Console.ReadLine();

            if (commandText == null)
            {
                RequestClose();
                return(false);
            }

            if (commandText.Length == 0)
            {
                return(false);
            }

            CliCommand newCommand = CliCommand.Parse(commandText);

            if (newCommand.IsEmpty)
            {
                return(false);
            }

            LastCommand = newCommand;

            return(true);
        }
        public OpenTelemetryLogsFolderCommand() : base("OpenTelemetryLogsFolder", "opens the folder that contains the telemetry log files")
        {
            var telLogFolderPath = this.Option("-p|--path", $"opens the folder that contains the telemetry log files. Default value: '{KnownStrings.TelemetryLogFolder}'", CommandOptionType.SingleOrNoValue);

            this.OnExecute(async() => {
                var folderFullpath = telLogFolderPath.HasValue()
                    ? new PathHelper().GetFullPath(telLogFolderPath.Value())
                    : new PathHelper().GetFullPath(KnownStrings.TelemetryLogFolder);

                var openCommand = new CliCommand {
                    Command   = "open",
                    Arguments = folderFullpath
                };

                if (VerboseOption.HasValue())
                {
                    Console.WriteLine($"Opening telemetry log folder {folderFullpath}");
                }

                var cmdresult = await openCommand.RunCommand();
                if (!string.IsNullOrEmpty(cmdresult.StandardError))
                {
                    Console.WriteLine($"Error: {cmdresult.StandardError}");
                }
            });
        }
Beispiel #4
0
        public static string ReadFile(string remote)
        {
            var cmd = CliCommand.Create(CliScope.AdbShell, "cat {0}", remote);
            var res = CliResult.Run(cmd, CliDataType.String);

            return(res.String);
        }
Beispiel #5
0
        public RestartTouchbarCommand() : base(
                "rt",
                "restart-touchbar",
                "Restarts macOS touchbar")
        {
            this.OnExecute(async() => {
                // pkill "Touch Bar agent";
                // killall "ControlStrip";

                ICliCommand pkillCmd = new CliCommand {
                    Command   = "pkill",
                    Arguments = @"Touch Bar agent",
                    SupressExceptionOnNonZeroExitCode = true
                };

                var res1 = await pkillCmd.RunCommand();

                var res2 = await new CliCommand {
                    Command   = "killall",
                    Arguments = @"ControlStrip",
                    SupressExceptionOnNonZeroExitCode = true
                }.RunCommand();

                return(0);
            });
        }
Beispiel #6
0
        private static CCRecord ReadRecord(CCArguments args)
        {
            string ddCmdStr = args.Compile();

            ddCmdStr = String.Format("\"{0}\"", ddCmdStr);

            var ddCmd = CliCommand.Create(CliScope.AdbExecOut, ddCmdStr);


            var ddRes = CliResult.Run(ddCmd, CliDataType.ByteArray);

            var ccRec = new CCRecord();

            lock (ccRec) {
                ccRec.BinaryRaw = ddRes.ByteArray;
                //ccRec.StatsRaw = Android.Value.ReadFile(args.StatsRedirect);
            }

            //ddRes.CommandProcess.Close();
            //ddRes.CommandProcess.WaitForExit();
            //ddRes.CommandProcess.Kill();


            return(ccRec);
        }
Beispiel #7
0
        public static bool ResolveCommand(List <CliCommand> commands, CliCommand command)
        {
            var retValue = true;

            if (!commands.Any(c => c.Module == command.Module))
            {
                Logging.LogFatal("Module {0} doesn't exist", command.Module);
                retValue = false;
            }
            else
            {
                if (!commands.Any(c => c.Module == command.Module && c.Command == command.Command))
                {
                    Logging.LogFatal("Module {0} has no command {1}", command.Module, command.Command);
                    retValue = false;
                }
            }
            if (retValue)
            {
                var resolvedCommand = commands.Single(c => c.Module == command.Module && c.Command == command.Command);
                command.Type   = resolvedCommand.Type;
                command.Method = resolvedCommand.Method;
            }
            return(retValue);
        }
Beispiel #8
0
        public TailLogFileCommand() : base(
                "TailLog",
                "Tails the IDE log")
        {
            // options
            var optionIdeVersion
                = this.Option <string>(
                      "-v|--ideversion",
                      $"Version of VSmac - default is {KnownStrings.DefaultVsmacVersion}",
                      CommandOptionType.SingleValue);

            var optionFilePath = this.Option <string>(
                "-f|--filepath",
                $"File path to the log file - default is {KnownStrings.VsMacLogFilePath}",
                CommandOptionType.SingleValue);

            this.OnExecute(async() => {
                var ideVersion = optionIdeVersion.HasValue()
                                    ? optionIdeVersion.ParsedValue
                                    : KnownStrings.DefaultVsmacVersion;

                var logfilePath = optionFilePath.HasValue()
                                ? optionFilePath.ParsedValue
                                : KnownStrings.VsMacLogFilePath;
                // tail -f /Users/sayedhashimi/Library/Logs/VisualStudio/8.0/Ide.log
                var tailCommand = new CliCommand {
                    Command   = "tail",
                    Arguments = $"-f {logfilePath}"
                };

                await tailCommand.RunCommand(captureStdOutput: false, captureStdError: false);
            });
        }
Beispiel #9
0
        public bool Execute(CLIBase parent, CliCommand Input)
        {
            switch (Input.Command)
            {
            case "t1":
                Example1();
                break;

            case "t2":
                Example2();
                break;

            case "t3":
                Example3();
                break;

            case "t4":
                Example4();
                break;

            case "t5":
                Example5();
                break;

            case "t6":
                Example6();
                break;

            case "pool":
                ExamplePool();
                break;
            }
            return(true);
        }
Beispiel #10
0
        public bool Execute(CLIBase parent, CliCommand Input)
        {
            string res = null;

            switch (Input.Command)
            {
            case "scheld":
                if (Input.Count > 0)
                {
                    res = $"{Input[0]} is een dik varken, een onozelaar en een lapzwans!";
                }
                else
                {
                    res = "Pipo, kieken, varken en alles wat lelijk is";
                }
                break;

            default:
                return(false);
            }
            if (res?.Length > 0)
            {
                parent.ShowInColor(res, ConsoleColor.DarkRed, ConsoleColor.Green);
                return(true);
            }
            return(false);
        }
Beispiel #11
0
 /// <summary>
 /// Parse and run a command that is in the form as a string. Intended for use when the application is reading input from the console/terminal.
 /// </summary>
 /// <param name="commandString">The command string to parse</param>
 public void Run(string commandString)
 {
     try
     {
         ParseResult result = Parse(commandString);
         CliCommand  cmd    = null;
         if (!string.IsNullOrWhiteSpace(result.Error))
         {
             cmd = Build(result);
         }
         else
         {
             cmd = GenerateErrorCommand(result.Error);
         }
         cmd.Invoke(cmd.Parameters);
     }
     catch (Exception ex)
     {
         if (HandleExceptionCommand == null)
         {
             throw;
         }
         HandleExceptionCommand(ex);
     }
 }
Beispiel #12
0
        public static string GetFileSha1Hash(string remote)
        {
            var cmd  = CliCommand.Create(CliScope.AdbShell, "sha1sum \"{0}\"", remote);
            var res  = CliResult.Run(cmd, CliDataType.String);
            var hash = res.String.Split(" ")[0];

            return(hash.ToUpper());
        }
Beispiel #13
0
        public static void Reset()
        {
            // adb shell "rm /data/local/tmp/busybox"

            CliCommand rmCmd = CliCommand.Create(CliScope.AdbShell, "rm {0}", REMOTE_BUSYBOX_EXE);

            var rmResult = CliResult.Run(rmCmd);
        }
        public static string GetMethodInvokeHelpText(this MethodInfo info)
        {
            CliCommand commandAttribute = info.GetCustomAttribute <CliCommand>();
            string     name             = commandAttribute.Name;
            string     description      = commandAttribute.Description;

            return(name + " " + GetParams(info) + " : " + description);
        }
Beispiel #15
0
 public bool Execute(CLIBase parent, CliCommand Input)
 {
     if (Input.Command == "ola")
     {
         Console.WriteLine("Ola Pola");
         return(true);
     }
     return(false);
 }
Beispiel #16
0
 public bool Execute(CLIBase parent, CliCommand Input)
 {
     if (Input.Command == "hallo")
     {
         Console.WriteLine("Hallo iedereen !!");
         return(true);
     }
     return(false);
 }
 public bool Execute(CLIBase parent, CliCommand Input)
 {
     switch (Input.Command)
     {
     case "singleton":
         Console.WriteLine(SingletonDemo.Instance.Talk());
         return(true);
     }
     return(false);
 }
Beispiel #18
0
        private void ParseArguments(Request request, Type type, CliCommand command)
        {
            var hasHelpArg = false;
            var usedProps  = new List <PropertyInfo>();
            var cmdProps   = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                             .Select(x => (propInfo: x, attrib: x.GetCustomAttribute <CliArgAttribute>()))
                             .ToArray();

            foreach (var arg in request.Args.Where(x => x.HasContent()))
            {
                var key = "";
                try
                {
                    // todo: ugly, refactor!
                    // implement simple tokenizer and parser

                    var parts = arg.Split(_separators, StringSplitOptions.RemoveEmptyEntries);
                    key = parts[0].TrimStart('-');

                    if (key.Equals("help", StringComparison.OrdinalIgnoreCase))
                    {
                        hasHelpArg = true;
                    }

                    var cmdProp = cmdProps.FirstOrDefault(x => x.propInfo.Name.Equals(key, StringComparison.OrdinalIgnoreCase));

                    if (cmdProp.propInfo != null)
                    {
                        if (cmdProp.attrib?.Skip == true)
                        {
                            continue;
                        }

                        var value = ExtractValue(parts, cmdProp.propInfo);

                        cmdProp.propInfo.SetValue(command, Convert.ChangeType(value, cmdProp.propInfo.PropertyType), null);
                        usedProps.Add(cmdProp.propInfo);
                    }
                    else
                    {
                        _logger.LogTrace($"Field [{key}] not found on type [{type.Name}]");
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, $"Error mapping value of key [{key}] to [{type.Name}]");
                }
            }

            if (!hasHelpArg)
            {
                CheckRequiredArguments(cmdProps, usedProps);
            }
        }
 public void Execute(CliCommand cliCommand)
 {
     if (cliCommand.Parameters.Count > 0)
     {
         prompter.Text = cliCommand.Parameters[0].Value;
     }
     else
     {
         ChangePrompter();
     }
 }
Beispiel #20
0
        public async Task TestInvalidArgsCommand()
        {
            var cmd = new CliCommand {
                Command   = "dotnet",
                Arguments = "invalidargshere"
            };
            var result = await cmd.RunCommand();

            Assert.NotNull(result);
            Assert.NotNull(result.StandardError);
            Assert.NotEqual(0, result.ExitCode);
        }
Beispiel #21
0
        public static void SetParams(object target, CliCommand command)
        {
            var props = target.GetType().GetProperties();

            foreach (var prop in props)
            {
                var propName   = prop.Name.ToLower();
                var propInfo   = target.GetType().GetProperty(propName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                var paramValue = command.Parameters.ContainsKey(propName) ? command.Parameters[propName] : GetDefault(propInfo.PropertyType);
                propInfo.SetValue(target, Convert.ChangeType(paramValue, propInfo.PropertyType), null);
            }
        }
Beispiel #22
0
 private void Execute(CliCommand cliCommand, Cmd cmd)
 {
     try
     {
         cliCommand.Execute(cmd);
     }
     catch (ArgumentError e)
     {
         clti.WriteError(e.Message);
         clti.WriteError(cliCommand.Help);
     }
 }
Beispiel #23
0
        public async Task TestMissingCommand()
        {
            CliCommand cmd = new CliCommand {
                Command   = "doesntexistsayedha",
                Arguments = "something here"
            };

            var result = await cmd.RunCommand();

            Assert.NotNull(result);
            Assert.NotNull(result.Exception);
        }
Beispiel #24
0
        public static long GetFileSize(string s)
        {
            // sprintf(buf, "wc -c < \"%s\"", remoteFile);

            var cmd = CliCommand.Create(CliScope.AdbShell, "\"wc -c < \"{0}\"\"", s);
            var res = CliResult.Run(cmd, CliDataType.String);

            //Console.WriteLine(res.Data);
            var n = long.Parse((string)res.Data);


            return(n);
        }
Beispiel #25
0
    /// <summary>
    /// Parses command-line arguments and performs the indicated action. Performs error handling.
    /// </summary>
    /// <param name="exeName">The name of the executable to use as a reference in help messages and self-invocation.</param>
    /// <param name="args">The arguments to be processed.</param>
    /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param>
    /// <returns>The exit status code to end the process with. Cast to <see cref="int"/> to return from a Main method.</returns>
    public static ExitCode Run(string exeName, string[] args, ICommandHandler handler)
    {
        #region Sanity checks
        if (string.IsNullOrEmpty(exeName))
        {
            throw new ArgumentNullException(nameof(exeName));
        }
        if (args == null)
        {
            throw new ArgumentNullException(nameof(args));
        }
        if (handler == null)
        {
            throw new ArgumentNullException(nameof(handler));
        }
        #endregion

        try
        {
            var command = CliCommand.CreateAndParse(
                args.FirstOrDefault() == AsAdminIndicatorArg
                    ? args.Skip(1).ToList()
                    : args,
                handler);
            return(command.Execute());
        }
        #region Error handling
        catch (OperationCanceledException)
        {
            return(ExitCode.UserCanceled);
        }
        catch (NeedsGuiException) when(GuiStartInfo(args) is {} startInfo)
        {
            Log.Info("Switching to GUI");
            handler.DisableUI();
            try
            {
                return((ExitCode)startInfo.Run());
            }
            catch (IOException ex2)
            {
                handler.Error(ex2);
                return(ExitCode.IOError);
            }
            catch (NotAdminException ex2)
            {
                handler.Error(ex2);
                return(ExitCode.AccessDenied);
            }
        }
        static void Main(string[] args)
        {
            if (args == null ||
                args.Length == 0)
            {
                return;
            }

            string     typeName   = string.Format("ConcurrentProgramming.CLI.{0}CliCommand", args[0]);
            CliCommand cliCommand = (CliCommand)Activator.CreateInstance(Type.GetType(typeName));

            cliCommand.Execute(args);

            Console.Read();
        }
Beispiel #27
0
        public async Task TestBasicPassingCommand()
        {
            CliCommand cmd = new CliCommand {
                Command   = "dotnet",
                Arguments = "--version"
            };


            var result = await cmd.RunCommand();

            Assert.NotNull(result);
            Assert.Equal(0, result.ExitCode);
            Assert.NotEmpty(result.StandardOutput);
            Assert.Empty(result.StandardError);
        }
 public void OnStep(IApplication application, string step)
 {
     if (step == ExecutionLifeCycleSteps.AfterCommitChanges)
     {
         var outputTarget = CliCommand.GetFrontEndOutputTarget(application);
         if (outputTarget == null)
         {
             Logging.Log.Warning("Could not find a location where the Angular application is installed. Ensure that a Web Client package has been created.");
             return;
         }
         if (!Directory.Exists(Path.Combine(outputTarget.Location, "node_modules", "oidc-client")))
         {
             CliCommand.Run(outputTarget.Location, $@"npm i oidc-client");
         }
     }
 }
Beispiel #29
0
        private static string?GetSerial()
        {
            var devices       = CliCommand.Create(CliScope.Adb, "devices");
            var devicesResult = CliResult.Run(devices, CliDataType.StringArray);

            var resultLines = devicesResult.StringArray;


            var hasDevice = resultLines?.Length >= 2 && resultLines[1] != null;

            Debug.Assert(resultLines != null);

            var device = hasDevice ? resultLines[1].SubstringBefore("device").Trim() : null;

            return(device);
        }
Beispiel #30
0
 public string BestandsNaam(CliCommand input)
 {
     if (input.Parameters?.Count >= 1)
     {
         _bestand = input.Parameters[0];
     }
     else if (_bestand.IsEmpty())
     {
         _bestand = $@"{Directory.GetCurrentDirectory().TrimEnd('\\')}\{Path.GetRandomFileName()}";
     }
     if (Path.GetExtension(_bestand)?.ToLower() != ".json")
     {
         _bestand += ".json";
     }
     return(_bestand);
 }