コード例 #1
0
ファイル: DeleteVersions.cs プロジェクト: KerwinMa/revolver
    public override CommandResult Run()
    {
      using (var cs = new ContextSwitcher(Context, Path))
      {
        if (cs.Result.Status != CommandStatus.Success)
          return cs.Result;

        var languages = new List<Language>();
        languages.Add(Context.CurrentItem.Language);

        if (AllLanguages)
        {
          languages.Clear();
          languages.AddRange(Context.CurrentItem.Languages);
        }

        var versions = new List<int>();
        versions.Add(Context.CurrentItem.Version.Number);

        if (OtherVersions)
        {
          versions.Clear();
          versions.AddRange(Context.CurrentItem.Versions.GetVersionNumbers().Select(x => x.Number));
          versions.Remove(Context.CurrentItem.Version.Number);

          if (AllLanguages)
          {
            // Other languages may have different version numbers. Need to add those extras
            foreach (var language in Context.CurrentItem.Languages)
            {
              var langItem = Context.CurrentItem.Database.GetItem(Context.CurrentItem.ID, language);
              foreach (var version in langItem.Versions.GetVersionNumbers())
              {
                if (!versions.Contains(version.Number) && version.Number != Context.CurrentItem.Version.Number)
                  versions.Add(version.Number);
              }
            }
          }
        }

        var count = 0;

        foreach (var language in languages)
        {
          foreach (var version in versions)
          {
            var versionItem = Context.CurrentItem.Database.GetItem(Context.CurrentItem.ID, language, new Version(version));
            if (versionItem != null)
            {
              versionItem.Versions.RemoveVersion();
              count++;
            }
          }
        }

        return new CommandResult(CommandStatus.Success, "Deleted {0} version{1}".FormatWith(count, count == 1 ? string.Empty : "s"));
      }
    }
コード例 #2
0
ファイル: Grep.cs プロジェクト: KerwinMa/revolver
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Regex))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("regex"));

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

      var options = RegexOptions.Compiled;
      if (!CaseSensitive)
        options |= RegexOptions.IgnoreCase;

      var regex = new Regex(Regex, options);

      var lines = Formatter.SplitLines(Input);
      var outputLines = new List<string>();

      foreach (var line in lines)
      {
        var isMatch = regex.IsMatch(line);
        if (isMatch ^ NotMatching)
          outputLines.Add(line);
      }

      var output = new StringBuilder();
      outputLines.ForEach(x => Formatter.PrintLine(x, output));
      return new CommandResult(CommandStatus.Success, output.ToString());
    }
コード例 #3
0
ファイル: SplitString.cs プロジェクト: KerwinMa/revolver
    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());
    }
コード例 #4
0
ファイル: XPathMatch.cs プロジェクト: KerwinMa/revolver
    public override CommandResult Run()
    {
      if (string.IsNullOrEmpty(Input))
        return new CommandResult(CommandStatus.Failure, Constants.Messages.MissingRequiredParameter.FormatWith("input"));

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

      XPathNavigator nav = null;

      if (HAPRequired)
      {
        var doc = new HtmlDocument();
        try
        {
          doc.LoadHtml(Input);
        }
        catch (Exception ex)
        {
          return new CommandResult(CommandStatus.Success, "Failed to parse input: " + ex.Message);
        }

        nav = doc.CreateNavigator();
      }
      else
      {
        var doc = new XmlDocument();

        try
        {
          doc.LoadXml(Input);
        }
        catch (Exception ex)
        {
          return new CommandResult(CommandStatus.Success, "Failed to parse input: " + ex.Message);
        }

        nav = doc.CreateNavigator();
      }

      if (nav == null)
        return new CommandResult(CommandStatus.Failure, "Failed to create XPath navigator");

      // Process XML and extract any namespaces it contains. Allows using the namespaces in queries
      var namespaceManager = new XmlNamespaceManager(nav.NameTable);

      var allNodes = nav.Select("//*");
      while (allNodes.MoveNext())
      {
        var namespaces = allNodes.Current.GetNamespacesInScope(XmlNamespaceScope.Local);
        foreach (var ns in namespaces)
        {
          namespaceManager.AddNamespace(ns.Key, ns.Value);
        }
      }

      var nodes = nav.Select(XPath, namespaceManager);

      var lines = new List<string>();
      while (nodes.MoveNext())
      {
        if (ValueOutput)
          lines.Add(nodes.Current.Value);
        else
          lines.Add(nodes.Current.OuterXml);
      }

      var buffer = new StringBuilder(Formatter.JoinLines(lines));

      if (!NoStats)
      {
        Formatter.PrintLine(string.Empty, buffer);
        buffer.Append(string.Format("Matched {0} {1}", nodes.Count, (nodes.Count == 1 ? "node" : "nodes")));
      }

      return new CommandResult(CommandStatus.Success, buffer.ToString());
    }
コード例 #5
0
ファイル: ListManipulator.cs プロジェクト: KerwinMa/revolver
    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()));
    }
コード例 #6
0
ファイル: List.cs プロジェクト: KerwinMa/revolver
    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());
    }
コード例 #7
0
ファイル: CommandHandler.cs プロジェクト: KerwinMa/revolver
    /// <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;
    }
コード例 #8
0
ファイル: CommandHandler.cs プロジェクト: KerwinMa/revolver
    /// <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();
    }