Exemple #1
0
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Input))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("input"));

      if (string.IsNullOrEmpty(Command))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("command"));

      // Create the split token array
      var tokens = new List<string>();

      if (SplitOnNewLine)
        tokens.Add("\r\n");

      if (SplitOnTab)
        tokens.Add("\t");

      if (!string.IsNullOrEmpty(SplitSymbol))
        tokens.Add(SplitSymbol);

      // Split the input string
      var elements = Input.Split(tokens.ToArray(), StringSplitOptions.RemoveEmptyEntries);
      var output = new StringBuilder();

      if (Context.EnvironmentVariables.ContainsKey("current"))
        output.AppendLine("WARNING: Environment variable 'current' contains a value. It has been overwritten.");

      // Process command against each string element
      Context.EnvironmentVariables.Remove("current");
      
      foreach(var element in elements)
      {
        Context.EnvironmentVariables.Add("current", element);
        output.Append(Context.ExecuteCommand(Command, Formatter));
        Formatter.PrintLine(string.Empty, output);
        Context.EnvironmentVariables.Remove("current");
      }

      if (!NoStatistics)
        output.Append(string.Format("Processed {0} {1}", elements.Length, (elements.Length == 1 ? "string" : "strings")));

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Exemple #2
0
    public override CommandResult Run()
    {

      if (!Add && !Remove && !Shuffle && !OrderList)
        return new CommandResult(CommandStatus.Failure, "Missing one of -a -r -s -o required flag");

      if (Input == null)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("input"));

      if (string.IsNullOrEmpty(Delimiter))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("delimiter"));

      if (string.IsNullOrEmpty(Element) && !Shuffle && !OrderList)
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("element"));

      if (Shuffle && OrderList)
        return new CommandResult(CommandStatus.Failure, "Cannot use -s and -o together");

      var elements = new List<string>();
      elements.AddRange(Input.Split(new[] { Delimiter }, StringSplitOptions.RemoveEmptyEntries));

      if (Add)
      {
        if (!elements.Contains(Element))
          elements.Add(Element);
      }
      else if (Remove)
      {
        if (elements.Contains(Element))
          elements.Remove(Element);
      }
      else if (Shuffle)
      {
        System.Random random;
        
        if(_randomSeed != null)
          random = new System.Random(_randomSeed.Value);
        else
          random = new System.Random();

        elements = (from element in elements
                    orderby random.Next()
                    select element).ToList();
      }
      else if (OrderList)
      {
        elements = (from element in elements
                    orderby element
                    select element).ToList();
      }
      else
        return new CommandResult(CommandStatus.Failure, "Unknown operation");

      if (ReverseOrder)
        elements.Reverse();

      return new CommandResult(CommandStatus.Success, string.Join(Delimiter, elements.ToArray()));
    }
Exemple #3
0
    public override CommandResult Run()
    {
      var output = new StringBuilder();

      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var item = Context.CurrentItem;

        if (item.HasChildren)
        {
          var children = item.GetChildren(ChildListOptions.None);
          var includeItems = new List<Item>(children.Count);
          var options = RegexOptions.Compiled;
          if (!CaseSensitiveRegex)
            options |= RegexOptions.IgnoreCase;

          var regex = new Regex(Regex, options);

          for (int i = 0; i < children.Count; i++)
          {
            if (Regex != string.Empty)
              if (!regex.IsMatch(children[i].Name))
                continue;

            includeItems.Add(children[i]);
          }

          var items = includeItems.ToArray();

          if (Alphabetical)
            Array.Sort(items, delegate(Item x, Item y)
            {
              return string.Compare(x.Name, y.Name);
            });

          if (ReverseOrder)
            Array.Reverse(items);

          for (int i = 0; i < items.Length; i++)
          {
            if (items[i].HasChildren)
              output.Append("+ ");
            else
              output.Append("  ");

            output.Append(items[i].Name);

            if (i < (items.Length - 1))
              Formatter.PrintLine(string.Empty, output);
          }
        }
        else
        {
          output.Append("zero items found");
        }
      }

      return new CommandResult(CommandStatus.Success, output.ToString());
    }
Exemple #4
0
    /// <summary>
    /// Executes a command
    /// </summary>
    /// <param name="cmd">The command to execute</param>
    /// <param name="args">Arguments to apply to the command</param>
    /// <param name="directive">Directives to execute with</param>
    /// <returns>The outcome of the execution</returns>
    private CommandResult ExecuteCommand(ICommand cmd, string[] args, ExecutionDirective directive)
    {
      cmd.Initialise(_context, _formatter);
      CommandResult result = null;

      var manualParseInterface = CommandInspector.GetManualParseCommand(cmd);
      if (manualParseInterface != null)
      {
        var subArgs = from arg in args
                      select Parser.PerformSubstitution(_context, arg);

        result = manualParseInterface.Run(subArgs.ToArray());
      }
      else
      {
        var properties = cmd.GetType().GetProperties();

        object propValue = null;
        var processingArgs = args;

        // Process multi-word named parameters first
        foreach (var prop in properties)
        {
          propValue = null;

          var namedParameterAttribute = CommandInspector.GetNamedParameter(prop);
          if (namedParameterAttribute != null && namedParameterAttribute.WordCount > 1)
          {
            var words = new List<string>();

            for (var i = 0; i < namedParameterAttribute.WordCount; i++)
            {
              var value = string.Empty;
              ParameterUtil.GetParameter(args, "-" + namedParameterAttribute.Name, i, ref value);
              if (!string.IsNullOrEmpty(value))
                words.Add(value);
            }

            if (words.Count > 0)
            {
              propValue = words.ToArray();
              processingArgs = ParameterUtil.RemoveParameter(processingArgs, "-" + namedParameterAttribute.Name, namedParameterAttribute.WordCount);
            }
          }

          ConvertAndAssignParameter(prop, cmd, propValue);
        }

        // Find flags
        var flags = from prop in properties
                    let attr = CommandInspector.GetFlagParameter(prop)
                    where attr != null
                    select attr.Name;

        // Parse remaining arguments
        StringDictionary named = null;
        string[] numbered = null;
        ParameterUtil.ExtractParameters(out named, out numbered, processingArgs, flags.ToArray());

        // Map the parameters to properties
        foreach (var prop in properties)
        {
          propValue = null;

          var namedParameterAttribute = CommandInspector.GetNamedParameter(prop);
          if (namedParameterAttribute != null)
          {
            if (named.ContainsKey(namedParameterAttribute.Name))
              propValue = named[namedParameterAttribute.Name];
          }

          var numberedParameterAttribute = CommandInspector.GetNumberedParameter(prop);
          if (numberedParameterAttribute != null)
          {
            if (numberedParameterAttribute.Number < numbered.Length)
              propValue = numbered[numberedParameterAttribute.Number];
          }

          var flagParameterAttribute = CommandInspector.GetFlagParameter(prop);
          if (flagParameterAttribute != null)
          {
            if (named.ContainsKey(flagParameterAttribute.Name))
            {
#if NET45
              var origVal = (bool)prop.GetValue(cmd);
#else
              var origVal = (bool)prop.GetValue(cmd, null);
#endif
              propValue = !origVal;
            }
          }

          ConvertAndAssignParameter(prop, cmd, propValue);
        }

        AssignListParameter(cmd, properties, numbered);

        result = cmd.Run();
      }

      if ((bool)(directive.StopOnError ?? false) && (result.Status == CommandStatus.Failure))
        _executionFaulted = true;

      return result;
    }
Exemple #5
0
    /// <summary>
    /// Execute a command or script
    /// </summary>
    /// <param name="command">The command or script name</param>
    /// <param name="args">Arguments to pass to the command</param>
    /// <param name="directive">Execution directives to control how execution should perform</param>
    /// <returns>True if the command was run, otherwise returns false</returns>
    private CommandResult Execute(string command, string[] args, ExecutionDirective directive)
    {
      // update current date and time in environment variable
      Context.EnvironmentVariables["now"] = Sitecore.DateUtil.IsoNow;

      command = Parser.PerformSubstitution(_context, command);

      if (command == string.Empty)
        return new CommandResult(CommandStatus.Success, string.Empty);

      ICommand cmd = null;

      if (_commands.ContainsKey(command))
      {
        cmd = (ICommand)Activator.CreateInstance(_commands[command]);
      }
      else if (_custcommands.ContainsKey(command))
      {
        cmd = (ICommand)Activator.CreateInstance(_custcommands[command]);
      }
      else if(_commandAliases.ContainsKey(command) && _commands.ContainsKey(_commandAliases[command].CommandName))
      {
        var alias = _commandAliases[command];
        cmd = (ICommand)Activator.CreateInstance(_commands[alias.CommandName]);
        
        if(alias.Parameters != null && alias.Parameters.Length > 0)
        {
          var paramsList = new List<string>(alias.Parameters);
          paramsList.AddRange(args);
          args = paramsList.ToArray();
        }
      }

      if (cmd != null)
      {
        return ExecuteCommand(cmd, args, directive);
      }
      else
        return ExecuteScript(command, args, directive);
    }
Exemple #6
0
    /// <summary>
    /// Perform session initialization
    /// </summary>
    /// <returns>The results of session initialization</returns>
    public CommandResult[] Init()
    {
      var buffer = new List<CommandResult>();
      var directive = ExecutionDirective.GetDefault();
      directive.IgnoreUnknownCommands = true;

      var initResult = Execute("init", directive);
      buffer.Add(initResult);

      foreach (var role in Sitecore.Context.User.Roles)
      {
        var localRoleName = role.Name;
        if (localRoleName.StartsWith(role.Domain.Name + "\\"))
          localRoleName = localRoleName.Substring(role.Domain.Name.Length + 1);

        var roleResult = Execute("(init-" + localRoleName.ToLower() + ")", directive);
        buffer.Add(roleResult);
      }

      var userResult = Execute("(init-" + Sitecore.Context.User.LocalName.ToLower() + ")", directive);
      buffer.Add(userResult);

      return buffer.ToArray();
    }