public static string GetTokenAtColumn(string line, int column) { Collection <PSParseError> errors; IEnumerable <PSToken> tokens = PSParser.Tokenize(line, out errors); return(tokens.Where(token => token.StartColumn <= column && token.EndColumn >= column).Select(token => token.Content).FirstOrDefault()); }
public bool TestScriptCorrect(out IEnumerable <string> errors) { var psParser = PSParser.Tokenize(_scriptText, out var psErrors); errors = psErrors.Select(e => $"[{e.Token}] {e.Message}"); return(!psErrors.Any()); }
private static string TruncatedCommand2(string command, out string lastToken) { Collection <PSParseError> errors; var tokens = PSParser.Tokenize(command, out errors); var truncatedCommand = string.Empty; lastToken = string.Empty; switch (tokens.Count) { case (0): break; default: var lastPsToken = tokens.Last(); var start = lastPsToken.Start; if ((lastPsToken.Content == "\\" || lastPsToken.Content == "/") && tokens.Count > 1 & tokens[tokens.Count - 2].Type == PSTokenType.String) { start = tokens[tokens.Count - 2].Start; } lastToken = command.Substring(start, lastPsToken.EndColumn - 1 - start); if (lastPsToken.Type == PSTokenType.Operator && lastPsToken.Content != "-") { truncatedCommand = command; lastToken = string.Empty; } else { truncatedCommand = command.Substring(0, command.Length - lastToken.Length); } break; } return(truncatedCommand); }
void WriteTokenized(string text) { Collection <PSParseError> errors; var tokens = PSParser.Tokenize(text, out errors); int index = 0; foreach (var t in tokens) { if (index < t.Start) // whitespace characters in between tokens { QueueInstruction(TerminalInstructionCode.AppendTokenizedText, new { txt = text.Substring(index, t.Start - index) }); index = t.Start; } QueueInstruction(TerminalInstructionCode.AppendTokenizedText, new { txt = text.Substring(index, t.Length), type = t.Type }); index += t.Length; } if (index < text.Length) // whitespace characters at the end { QueueInstruction(TerminalInstructionCode.AppendTokenizedText, new { txt = text.Substring(index, text.Length - index) }); } }
public static IEnumerable <string> GetHelp(ScriptSession session, string command) { Collection <PSParseError> errors; var tokens = PSParser.Tokenize(command, out errors); var lastPsToken = tokens.LastOrDefault(t => t.Type == PSTokenType.Command); if (lastPsToken != null) { session.Output.Clear(); var lastToken = lastPsToken.Content; session.SetVariable("helpFor", lastToken); var platformmodule = ModuleManager.GetModule("Platform"); var scriptItem = Database.GetDatabase(platformmodule.Database) .GetItem(platformmodule.Path + "/Internal/Context Help/Command Help"); if (scriptItem == null) { scriptItem = Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb) .GetItem(ApplicationSettings.ScriptLibraryPath + "Internal/Context Help/Command Help"); } session.ExecuteScriptPart(scriptItem[ScriptItemFieldNames.Script], true, true); var sb = new StringBuilder("<div id=\"HelpClose\">X</div>"); if (session.Output.Count == 0 || session.Output[0].LineType == OutputLineType.Error) { return(new[] { "<div class='ps-help-command-name'> </div><div class='ps-help-header' align='center'>No Command in line or help information found</div><div class='ps-help-parameter' align='center'>Cannot provide help in this context.</div>" }); } session.Output.ForEach(l => sb.Append(l.Text)); session.Output.Clear(); var result = new[] { sb.ToString() }; return(result); } return(new[] { "No Command in line found - cannot provide help in this context." }); }
//_____________________________________________________________________________________________________________________________________________________________ public static void AddText(RichTextBox cTxt, string text, int lineNum, int colNum, string word) { Collection <PSParseError> errors = new Collection <PSParseError>(); currentLine = 1; currentColumn = 1; var tokens = PSParser.Tokenize(text, out errors); // Iterate over the tokens and set the colors appropriately. int position = 0; foreach (PSToken token in tokens) { string block, tokenColor; if (position < token.Start) { block = text.Substring(position, (token.Start - position)); tokenColor = "Unknown"; AppendRtfSpan(cTxt, block, tokenColor, lineNum, colNum, word); } block = text.Substring(token.Start, token.Length); tokenColor = token.Type.ToString(); AppendRtfSpan(cTxt, block, tokenColor, lineNum, colNum, word); position = token.Start + token.Length; } }
//_____________________________________________________________________________________________________________________________________________________________ private static void GetParenthesisTokensFromStringToken(PSToken tknToSearch, string txt, Queue <Token> tokenQueue, Token token) { LogHelper.Add("GetParenthesisTokensFromStringToken"); if (!token.Content.Contains("$(")) { return; } List <Tuple <int, int> > lst = ListOfParenthesis(token.Content); foreach (Tuple <int, int> tpl in lst) { string script = token.Content.Substring(tpl.Item1, tpl.Item2 - tpl.Item1 + 1); Collection <PSParseError> errors = new Collection <PSParseError>(); ScriptBlock scriptBlock = ScriptBlock.Create(script); foreach (PSToken pst in PSParser.Tokenize(new object[] { scriptBlock }, out errors)) { Token t = new Token(pst); t.StartLine += (token.StartLine - 1); t.StartColumn += (token.StartColumn) + tpl.Item1; t.EndColumn += (token.StartColumn) + tpl.Item1; tokenQueue.Enqueue(t); GetTokensFromStringToken(tknToSearch, txt, tokenQueue, t); } } }
public IEnumerable <Token> Tokenize(string[] lines) { Collection <PSParseError> errors; Collection <PSToken> tokens = PSParser.Tokenize(lines, out errors); return(tokens.Select((t) => new Token( MapTokenType(t.Type), t.StartLine, t.EndLine, t.StartColumn, t.EndColumn))); }
/// <summary> /// Gets the error tokens by parsing the text snapshot. /// </summary> /// <param name = "textSnapshot">The text snapshot.</param> /// <returns></returns> protected virtual IEnumerable <PSParseError> GetErrorTokens(ITextSnapshot textSnapshot) { string text = textSnapshot.GetText(); Collection <PSParseError> errors; PSParser.Tokenize(text, out errors); return(errors); }
public IEnumerable <string> GetSuggestions(string guess) { try { if (!_enabled.HasValue) { InitializeEnabled(); } if (!_enabled.GetValueOrDefault()) { return(new string[] {}); } IEnumerable <ErrorRecord> error; Collection <PSParseError> errors; IEnumerable <PSToken> tokens = PSParser.Tokenize(guess, out errors); if (null == tokens || !tokens.Any()) { return(new string[] {}); } var lastToken = tokens.Last(); var lastWord = lastToken.Content; if (PSTokenType.Variable == lastToken.Type) { lastWord = "$" + lastWord; } var arguments = new Dictionary <string, object> { { LineArgumentName, guess }, { LastWordArgumentName, lastWord } }; var results = _executor.ExecuteCommand(TabExpansionFunctionName, arguments, out error, ExecutionOptions.None); if (null == results) { return(new string[] {}); } //var regex = new Regex(Regex.Escape(lastWord) + @"$"); return(results.ToList() .ConvertAll(pso => pso.ToStringValue()) .ConvertAll(s => guess.Remove(lastToken.Start) + s)); } catch { } return(null); }
public void ValidateScript(String script) { Collection <PSParseError> errors; PSParser.Tokenize(script, out errors); if (errors.Count != 0) { throw new ParseException(errors[0].Message); } }
/// <summary> /// Gets the tokens by parsing the text snapshot, optionally including any errors. /// </summary> /// <param name = "textSnapshot">The text snapshot.</param> /// <param name = "includeErrors">if set to <c>true</c> [include errors].</param> /// <returns></returns> protected override IEnumerable <PSToken> GetTokens(ITextSnapshot textSnapshot, bool includeErrors) { string text = textSnapshot.GetText(); Collection <PSParseError> errors; Collection <PSToken> tokens = PSParser.Tokenize(text, out errors); if (includeErrors) { return(tokens.Union(errors.Select(error => error.Token)).ToList()); } return(tokens); }
//_____________________________________________________________________________________________________________________________________________________________ private bool GetReferencesFromScriptTextWithParser(PSToken token, List <cScriptLocation> l, string FullPath, string txt) { LogHelper.Add("GetReferencesFromScriptTextWithParser"); Queue <Token> tokenQueue = new Queue <Token>(); ScriptBlock scriptBlock; try { scriptBlock = ScriptBlock.Create(txt); } catch (Exception ex) { LogHelper.Add($"GetReferencesFromScriptText->Create ERROR: {ex.Message}"); return(false); } string[] ltxt = txt.Replace("\r", "").Split('\n'); foreach (PSToken t in PSParser.Tokenize(new object[] { scriptBlock }, out Collection <PSParseError> errors)) { tokenQueue.Enqueue(new Token(t)); if (token.Type != PSTokenType.String) { Token.GetTokensFromStringToken(token, txt, tokenQueue, t); } } foreach (Token t in tokenQueue) { if (t.Content == null) { continue; } if (!t.Content.iEquals(token.Content)) { continue; } if ((token.Type == PSTokenType.CommandArgument && t.Type == PSTokenType.Command) || (token.Type == PSTokenType.CommandArgument && t.Type == PSTokenType.CommandArgument) || (token.Type == PSTokenType.Command && t.Type == PSTokenType.CommandArgument) || (token.Type == PSTokenType.Command && t.Type == PSTokenType.Command) || (token.Type == PSTokenType.CommandParameter && t.Type == PSTokenType.CommandParameter) || (token.Type == PSTokenType.Comment && t.Type == PSTokenType.Comment) || (token.Type == PSTokenType.Keyword && t.Type == PSTokenType.Keyword) || (token.Type == PSTokenType.Member && t.Type == PSTokenType.Member) || (token.Type == PSTokenType.Member && t.Type == PSTokenType.CommandArgument)) { l.Add(new cScriptLocation(Path.GetFileName(FullPath), t.Type, t.StartLine, t.StartColumn, ltxt, token.Content, mProjects.Project.Functions.GetFunctionsByLine(FullPath, t.StartLine)?.Name)); } else if (token.Type == PSTokenType.Variable && t.Type == PSTokenType.Variable) { l.Add(new cScriptLocation(Path.GetFileName(FullPath), t.Type, t.StartLine, t.StartColumn, ltxt, $"${token.Content}", mProjects.Project.Functions.GetFunctionsByLine(FullPath, t.StartLine)?.Name)); } else if (token.Type == PSTokenType.String && t.Type == PSTokenType.String) { l.Add(new cScriptLocation(Path.GetFileName(FullPath), t.Type, t.StartLine, t.StartColumn, ltxt, $"\"{token.Content}\"", mProjects.Project.Functions.GetFunctionsByLine(FullPath, t.StartLine)?.Name)); } } return(true); }
public static bool CheckScript(string scriptPath, out IEnumerable <string> errors) { if (string.IsNullOrEmpty(scriptPath) || !File.Exists(scriptPath)) { errors = new [] { "The specified file does not exist." }; return(false); } string content = File.ReadAllText(scriptPath); Collection <PSParseError> parserErrors; var tokens = PSParser.Tokenize(content, out parserErrors); errors = new List <string>(parserErrors.Select(e => e.Message)); if (parserErrors.Any()) { return(false); } int index = 0; foreach (PSToken token in tokens) { if (token.Type == PSTokenType.NewLine) { continue; } if (sequence[index].Invoke(token)) { index++; } else { index = 0; } if (index == sequence.Length) { return(true); } } ((List <string>)errors).Add("Function \"MetricProcessor ([LogMonitor.FileChange] change)\" not found in script."); return(false); }
public static IDictionary <IPackageFile, ICollection <PSToken> > get_chocolatey_scripts_tokens(IPackage package) { var scriptsAsTokens = new Dictionary <IPackageFile, ICollection <PSToken> >(); var scripts = get_chocolatey_automation_scripts(package); foreach (var script in scripts.or_empty_list_if_null()) { Collection <PSParseError> errors = null; ICollection <PSToken> tokens = PSParser.Tokenize(script.Value, out errors); scriptsAsTokens.Add(script.Key, tokens); } return(scriptsAsTokens); }
public override void ExecuteCmdlet() { if (ShouldProcess(Name, "Create Container Group")) { var creationParameter = new ContainerGroupCreationParameters { Name = Name, ResourceGroupName = ResourceGroupName, Location = Location ?? GetResourceGroupLocation(ResourceGroupName), Tags = TagsConversionHelper.CreateTagDictionary(Tag, validate: true), OsType = OsType ?? ContainerGroupCreationParameters.DefaultOsType, RestartPolicy = RestartPolicy ?? ContainerGroupRestartPolicy.Always, IpAddressType = IpAddressType, DnsNameLabel = DnsNameLabel, Ports = Port ?? ContainerGroupCreationParameters.DefaultPorts, ContainerImage = Image, EnvironmentVariables = ConvertHashtableToDictionary(EnvironmentVariable), Cpu = Cpu ?? ContainerGroupCreationParameters.DefaultCpu, MemoryInGb = MemoryInGB ?? ContainerGroupCreationParameters.DefaultMemory, RegistryServer = RegistryServerDomain, RegistryUsername = RegistryCredential?.UserName, RegistryPassword = ContainerGroupCreationParameters.ConvertToString(RegistryCredential?.Password), AzureFileVolumeShareName = AzureFileVolumeShareName, AzureFileVolumeAccountName = AzureFileVolumeAccountCredential?.UserName, AzureFileVolumeAccountKey = ContainerGroupCreationParameters.ConvertToString(AzureFileVolumeAccountCredential?.Password), AzureFileVolumeMountPath = AzureFileVolumeMountPath }; // TODO: Remove IfDef code #if !NETSTANDARD if (!string.IsNullOrWhiteSpace(this.Command)) { Collection <PSParseError> errors; var commandTokens = PSParser.Tokenize(this.Command, out errors); if (errors.Any()) { throw new ArgumentException($"Invalid 'Command' parameter: {string.Join("; ", errors.Select(err => err.Message))}"); } creationParameter.ContainerCommand = commandTokens.Select(token => token.Content).ToList(); } #endif creationParameter.Validate(); var psContainerGroup = PSContainerGroup.FromContainerGroup( CreateContainerGroup(creationParameter)); WriteObject(psContainerGroup); } }
private Boolean IsValid(String data) { Debug.WriteLine("[DEBUG] In IsValid"); Collection <PSParseError> errors = new Collection <PSParseError>(); Collection <PSToken> tokens = PSParser.Tokenize(data, out errors); if (errors.Count > 0) { return(false); } return(true); }
public bool GoToDefinition() { try { var editor = this.hostObject.CurrentPowerShellTab.Files.SelectedFile.Editor; var currentLine = editor.CaretLineText; System.Collections.ObjectModel.Collection <PSParseError> errors = new System.Collections.ObjectModel.Collection <PSParseError>(); var tokens = PSParser.Tokenize(currentLine, out errors).Where(t => t.Type == PSTokenType.Command && t.StartColumn <editor.CaretColumn && t.EndColumn> editor.CaretColumn).ToList(); var function = functions.GetFunctionByName(tokens[0].Content); if (function == null) { UpdateStatusBarMessage(string.Format("Function '{0}' not found", tokens[0].Content)); return(false); } var iseFile = this.hostObject.CurrentPowerShellTab.Files.Where(file => file.FullPath == function.FullPath).FirstOrDefault(); if (iseFile != null) { this.hostObject.CurrentPowerShellTab.Files.SetSelectedFile(iseFile); } else { try { this.hostObject.CurrentPowerShellTab.Files.Add(function.FullPath); UpdateStatusBarMessage(string.Format("Opened file '{0}'", System.IO.Path.GetFileName(function.FullPath))); } catch { return(false); } } this.hostObject.CurrentPowerShellTab.Files.SelectedFile.Editor.SetCaretPosition(function.LineNumber, 1); return(true); } catch { return(false); } }
public void WriteAllText(string path, string contents) { File.WriteAllText(path, contents); if (new FileInfo(path).Extension != ".ps1") { return; } Collection <PSParseError> errors; PSParser.Tokenize(contents, out errors); if (errors.Any()) { throw new ScriptGeneratorException( "The script that was generated at path {path} contains syntax errors. This is likely an application bug.", errors.ToDictionary(error => error.Token)); } }
protected override void ExecuteCmdletInternal() { if (this.ShouldProcess(this.Name, "Create Container Group")) { var creationParameter = new ContainerGroupCreationParameters() { Name = this.Name, ResourceGroupName = this.ResourceGroupName, Location = this.Location ?? this.GetResourceGroupLocation(this.ResourceGroupName), Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true), OsType = this.OsType ?? ContainerGroupCreationParameters.DefaultOsType, IpAddressType = this.IpAddressType, Port = this.Port ?? ContainerGroupCreationParameters.DefaultPort, ContainerImage = this.Image, EnvironmentVariables = this.ConvertHashtableToDictionary(this.EnvironmentVariable), Cpu = this.Cpu ?? ContainerGroupCreationParameters.DefaultCpu, MemoryInGb = this.MemoryInGB ?? ContainerGroupCreationParameters.DefaultMemory, RegistryServer = this.RegistryServerDomain, RegistryUsername = this.RegistryCredential?.UserName, RegistryPassword = ContainerGroupCreationParameters.ConvertToString(this.RegistryCredential?.Password) }; if (!string.IsNullOrWhiteSpace(this.Command)) { Collection <PSParseError> errors; var commandTokens = PSParser.Tokenize(this.Command, out errors); if (errors.Any()) { throw new ArgumentException($"Invalid 'Command' parameter: {string.Join("; ", errors.Select(err => err.Message))}"); } creationParameter.ContainerCommand = commandTokens.Select(token => token.Content).ToList(); } creationParameter.Validate(); var psContainerGroup = PSContainerGroup.FromContainerGroup( this.CreateContainerGroup(creationParameter)); this.WriteObject(psContainerGroup); } }
/// <summary> /// Validates the syntax of the script text for this activity. /// </summary> /// <param name="metadata">Activity metadata for this activity</param> protected override void CacheMetadata(NativeActivityMetadata metadata) { base.CacheMetadata(metadata); if (!string.IsNullOrWhiteSpace(Expression)) { var errors = new Collection <PSParseError>(); PSParser.Tokenize(Expression, out errors); if (errors != null && errors.Count > 0) { string compositeErrorString = ""; foreach (var e in errors) { // Format and add each error message... compositeErrorString += string.Format(CultureInfo.InvariantCulture, "[{0}, {1}]: {2}\n", e.Token.StartLine, e.Token.StartColumn, e.Message); } metadata.AddValidationError(compositeErrorString); } } }
//_____________________________________________________________________________________________________________________________________________________________ private static void GetVariableTokensFromStringToken(PSToken tknToSearch, string txt, Queue <Token> tokenQueue, Token token) { LogHelper.Add("GetVariableTokensFromStringToken"); if (!token.Content.Contains("$")) { return; } string newStr = Regex.Replace(token.Content, "[^$_:0-9a-zA-Z]", " "); newStr = newStr.Replace("$ ", " "); string pat = @"(\$\w+[:\w]+)\s+"; Regex r = new Regex(pat, RegexOptions.IgnoreCase); Match m = r.Match(newStr); Collection <PSParseError> errors = new Collection <PSParseError>(); while (m.Success) { Group g = m.Groups[1]; CaptureCollection cc = g.Captures; for (int j = 0; j < cc.Count; j++) { Capture c = cc[j]; //System.Console.WriteLine("Capture" + j + "='" + c + "', Position=" + c.Index); ScriptBlock scriptBlock = ScriptBlock.Create(g.ToString()); foreach (PSToken pst in PSParser.Tokenize(new object[] { scriptBlock }, out errors)) { if (pst.Type != PSTokenType.Variable) { continue; } Token t = new Token(pst); t.StartLine += (token.StartLine - 1); t.StartColumn += (token.StartColumn) + c.Index; t.EndColumn += (token.StartColumn) + c.Index; tokenQueue.Enqueue(t); } } m = m.NextMatch(); } }
private void ParseScript() { if (string.IsNullOrEmpty(Script)) { throw new Exception("Script is null or empty."); } Collection <PSParseError> parseErrors; var tokens = PSParser.Tokenize(Script, out parseErrors); var apiFunction = tokens.FirstOrDefault( t => t.Type.Equals(PSTokenType.CommandArgument) && (t.Content.Equals("spooler_init") || t.Content.Equals("spooler_open") || t.Content.Equals("spooler_process") || t.Content.Equals("spooler_close") || t.Content.Equals("spooler_on_success") || t.Content.Equals("spooler_on_error") || t.Content.Equals("spooler_exit"))); isShellMode = apiFunction == null; }
private static IEnumerable <string> ExtractVariablesInternal(string script) { var tokens = PSParser.Tokenize(script, out var errors); if (tokens == null) { return(Enumerable.Empty <string>()); } var vars = tokens .Where(v => v.Type == PSTokenType.Variable) .Select(v => v.Content) .ToHashSet(StringComparer.OrdinalIgnoreCase); var strings = tokens .Where(t => t.Type == PSTokenType.String) .Select(t => t.Content); foreach (var s in strings) { var matches = VariableRegex.Matches(s); if (matches.Count > 0) { foreach (Match match in matches) { if (match.Groups[1].Success) { vars.Add(match.Groups[1].Value); } else if (match.Groups[2].Success) { vars.Add(match.Groups[2].Value); } } } } return(vars); }
//_____________________________________________________________________________________________________________________________________________________________ public bool GoToDefinition() { LogHelper.Add("GoToDefinition"); try { ISEEditor editor = hostObject.CurrentPowerShellTab.Files.SelectedFile.Editor; string currentFile = hostObject.CurrentPowerShellTab.Files.SelectedFile.FullPath; string caretLineText = editor.CaretLineText; Tuple <string, int, int> pos = new Tuple <string, int, int>(currentFile, editor.CaretLine, editor.CaretColumn); List <PSToken> list = PSParser.Tokenize(caretLineText, out Collection <PSParseError> errors).Where(t => (t.Type == PSTokenType.Command || t.Type == PSTokenType.Member) && t.StartColumn <= editor.CaretColumn && t.EndColumn >= editor.CaretColumn).ToList(); List <cFunction> functions = mProjects.Project.Functions.GetFunctionByFileAndName(currentFile, list[0].Content); if (functions.Count == 0) { functions = mProjects.Project.Functions.GetFunctionByName(list[0].Content); } if (functions.Count == 0) { return(false); } cFunction function = GetSelectedFileName(functions, currentFile, editor); ISEFile file = hostObject.CurrentPowerShellTab.Files.Where(x => x.FullPath.iEquals(function.FullName)).FirstOrDefault(); if (file != null) { hostObject.CurrentPowerShellTab.Files.SetSelectedFile(file); } else { try { hostObject.CurrentPowerShellTab.Files.Add(function.FullName); } catch (Exception ex) { LogHelper.AddException(ex, "GoToDefinition", null); return(false); } } hostObject.CurrentPowerShellTab.Files.SelectedFile.Editor.SetCaretPosition(functions[0].Line, 1); hostObject.CurrentPowerShellTab.Files.SelectedFile.Editor.Select(function.Line, function.Position, function.Line, function.Position + function.Name.Length); BackList.Push(pos); return(true); } catch (Exception ex) { LogHelper.AddException(ex, "GoToDefinition", null); return(false); } }
protected string[] BreakIntoWords(string guess) { Collection <PSParseError> errors; var tokens = PSParser.Tokenize(guess, out errors); var parts = from token in tokens select token.Content; if (parts.Any()) { return(parts.ToArray()); } guess = guess.Trim(); Regex re = new Regex(@"('[^']+(?:'|$))|(""[^""]+(?:""|$))|([^\s'""]+)"); var matches = re.Matches(guess); return((from Match match in matches let value = String.IsNullOrEmpty(match.Groups[1].Value) ? match.Groups[0].Value : match.Groups[1].Value select value).ToArray()); //return Regex.Split(guess, @"\s+"); /*char[] quotes = new char[] {'\'', '"'}; * * if( (-1) != guess.IndexOfAny( quotes )) * { * List<string> quotedParts = new List<string>(); * Regex reQuotes = new Regex( @"['""]" ); * parts.ToList().ForEach( * part => * { * * } * ); * } * return parts;*/ }
/// <summary> /// Determines which <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s should be part of the specified <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession" />. /// </summary> /// <param name = "session">The session for which completions are to be computed.</param> /// <param name = "completionSets">The set of the completionSets to be added to the session.</param> /// <remarks> /// Each applicable <see cref = "M:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource.AugmentCompletionSession(Microsoft.VisualStudio.Language.Intellisense.ICompletionSession,System.Collections.Generic.IList{Microsoft.VisualStudio.Language.Intellisense.CompletionSet})" /> instance will be called in-order to /// (re)calculate a <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSession" />. <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s can be added to the session by adding /// them to the completionSets collection passed-in as a parameter. In addition, by removing items from the collection, a /// source may filter <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.CompletionSet" />s provided by <see cref = "T:Microsoft.VisualStudio.Language.Intellisense.ICompletionSource" />s earlier in the calculation /// chain. /// </remarks> public override void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets) { // TODO: This declaration set is a quick impl. It does not take scope or order in file into consideration string text = Buffer.CurrentSnapshot.GetText(); Collection <PSParseError> errors; Collection <PSToken> tokens = PSParser.Tokenize(text, out errors); bool nextIsMethodName = false; var completionsToAdd = new List <string>(); foreach (PSToken psToken in tokens) { if (nextIsMethodName) { nextIsMethodName = false; completionsToAdd.Add(psToken.Content); continue; } if (psToken.Type == PSTokenType.Keyword && string.Equals(psToken.Content, "function")) { nextIsMethodName = true; } if (psToken.Type == PSTokenType.Variable) { completionsToAdd.Add("$" + psToken.Content); } } completionsToAdd = completionsToAdd.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); completionsToAdd.Sort(); List <Microsoft.VisualStudio.Language.Intellisense.Completion> completions = completionsToAdd.Select(CreateCompletion) .ToList(); UpdateDefaultCompletionSet(session, completionSets, completions); }
protected override void ProcessRecord() { base.ProcessRecord(); if (String.IsNullOrEmpty(StorageAccount) || String.IsNullOrEmpty(StorageKey)) { return; } #region WhereBlockTranslation this.WriteVerbose(this.ParameterSetName); if (this.ParameterSetName == "WhereBlock") { StringCollection filterList = new StringCollection(); foreach (ScriptBlock whereBlock in Where) { this.WriteVerbose(String.Format("Processing Where Clause {0}", whereBlock.ToString())); string whereString = whereBlock.ToString(); if (whereString.Length > 512) { WriteError( new ErrorRecord(new Exception("Will not tokenize filters longer than 512 characters"), "SearchAzureTable.WhereBlockTooLong", ErrorCategory.InvalidArgument, whereBlock)); continue; } Collection <PSParseError> error = new Collection <PSParseError>();; Collection <PSToken> tokens = PSParser.Tokenize(whereString, out error); this.WriteVerbose(String.Format("Tokens Count {0}", tokens.Count.ToString())); bool ok = true; string adoFilter = String.Empty; IEnumerator <PSToken> enumerator = tokens.GetEnumerator(); enumerator.MoveNext(); while (enumerator.Current != null) { this.WriteVerbose(String.Format("Processing {0}", enumerator.Current.ToString())); if (enumerator.Current.Type != PSTokenType.Variable || enumerator.Current.Content != "_") { WriteError( new ErrorRecord(new Exception("The first item in the filter script must $_"), "SearchAzureTable.FilterScriptMustStartWithDollarUnderbar", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } if (!enumerator.MoveNext()) { ok = false; break; } if (enumerator.Current.Type != PSTokenType.Operator && enumerator.Current.Content != ".") { WriteError( new ErrorRecord(new Exception("$_ must be followed by the . operator"), "SearchAzureTable.FilterScriptDollarUnderBarMustBeFollowedByDot", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } if (!enumerator.MoveNext()) { ok = false; break; } if (enumerator.Current.Type != PSTokenType.Member) { WriteError( new ErrorRecord(new Exception("The . operator must be followed by a property name"), "SearchAzureTable.FilterScriptDotMustBeFollowedByPropertyName", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } adoFilter += enumerator.Current.Content; if (!enumerator.MoveNext()) { ok = false; break; } if (enumerator.Current.Type != PSTokenType.Operator) { WriteError( new ErrorRecord(new Exception("The filter item must be followed by an operator"), "SearchAzureTable.FilterScriptItemMustBeFollowedByOperator", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } string[] validOperators = new string[] { "-gt", "-lt", "-ge", "-le", "-ne", "-eq" }; bool isValidOperator = false; foreach (string validOp in validOperators) { if (enumerator.Current.Content == validOp) { isValidOperator = true; break; } } if (!isValidOperator) { WriteError( new ErrorRecord(new Exception(enumerator.Current.Content + @" is not a valid operator. Please use ""-gt"", ""-lt"", ""-ge"", ""-le"", ""-ne"", ""-eq"""), "SearchAzureTable.FilterScriptUsesInvalidOperator", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } adoFilter += enumerator.Current.Content.Replace("-", " "); if (!enumerator.MoveNext()) { ok = false; break; } this.WriteVerbose(String.Format("Comparing Tokens {0}", enumerator.Current.Type.ToString())); if (!(enumerator.Current.Type == PSTokenType.Number || enumerator.Current.Type == PSTokenType.String)) { WriteError( new ErrorRecord(new Exception("The operator must be followed by a string or a number"), "SearchAzureTable.FilterScriptOperatorMustBeFollowedByStringOrNumber", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } if (enumerator.Current.Type == PSTokenType.String && enumerator.Current.Content.Contains("$(")) { WriteError( new ErrorRecord(new Exception("Variables expansion not allowed in filter script"), "SearchAzureTable.FilterScriptCannotContainVariables", ErrorCategory.InvalidArgument, enumerator.Current)); ok = false; break; } adoFilter += " '" + this.SessionState.InvokeCommand.ExpandString(enumerator.Current.Content) + "'"; enumerator.MoveNext(); } if (ok) { filterList.Add(adoFilter); } else { return; } } if (filterList.Count >= 1) { if (filterList.Count > 1) { StringBuilder filterBuilder = new StringBuilder(); foreach (string f in filterList) { filterBuilder.Append("("); filterBuilder.Append(f); filterBuilder.Append(")"); if (Or) { filterBuilder.Append("or"); } else { filterBuilder.Append("and"); } } } else { Filter = filterList[0]; } } } #endregion string selectString = String.Empty; if (this.MyInvocation.BoundParameters.ContainsKey("Select")) { for (int i = 0; i < Select.Length; i++) { selectString += Select[i]; if (i != (Select.Length - 1)) { selectString += ","; } } } string sortString = String.Empty; if (this.MyInvocation.BoundParameters.ContainsKey("Sort")) { for (int i = 0; i < Sort.Length; i++) { sortString += Sort[i]; if (i != (Sort.Length - 1)) { sortString += ","; } } } if (!this.MyInvocation.BoundParameters.ContainsKey("BatchSize")) { BatchSize = 640; } bool thereIsMore = false; nextRow = String.Empty; if (this.MyInvocation.BoundParameters.ContainsKey("NextRowKey")) { nextRow = NextRowKey; } nextPart = String.Empty; if (this.MyInvocation.BoundParameters.ContainsKey("NextPartition")) { nextPart = NextPartition; } int collectedSoFar = 0; if (this.MyInvocation.BoundParameters.ContainsKey("Next")) { First = Next; } if (this.MyInvocation.BoundParameters.ContainsKey("First") && First < BatchSize) { BatchSize = First; } do { if (this.MyInvocation.BoundParameters.ContainsKey("First") || this.MyInvocation.BoundParameters.ContainsKey("Next")) { if (collectedSoFar >= First) { break; } } string result = QueryEntities( this.TableName, null, null, this.Filter, sortString, selectString, BatchSize); if (!String.IsNullOrEmpty(result)) { if (this.MyInvocation.BoundParameters.ContainsKey("First") || this.MyInvocation.BoundParameters.ContainsKey("Next")) { foreach (PSObject resultObj in ExpandObject(result, !ExcludeTableInfo, this.TableName)) { collectedSoFar++; if (collectedSoFar >= First) { if (!(String.IsNullOrEmpty(nextRow) && String.IsNullOrEmpty(nextPart))) { PSNoteProperty nextRowKey = new PSNoteProperty("NextRowKey", nextRow); resultObj.Properties.Add(nextRowKey); PSNoteProperty nextPartition = new PSNoteProperty("NextPartition", nextPart); resultObj.Properties.Add(nextPartition); } WriteObject(resultObj); break; } else { WriteObject(resultObj); } } } else { WriteObject( ExpandObject(result, !ExcludeTableInfo, this.TableName), true); } } if (!(String.IsNullOrEmpty(nextRow) && String.IsNullOrEmpty(nextPart))) { thereIsMore = true; } else { thereIsMore = false; } } while (thereIsMore); }
public static PowerShellScriptInfo Parse(TextReader scriptText) { if (scriptText == null) { throw new ArgumentNullException(nameof(scriptText)); } Collection <PSParseError> errors; var tokens = PSParser.Tokenize(scriptText.ReadToEnd(), out errors); int paramIndex = tokens .TakeWhile(t => t.Type != PSTokenType.Keyword || !string.Equals(t.Content, "param", StringComparison.OrdinalIgnoreCase)) .Count(); var parameters = ScrapeParameters(tokens.Skip(paramIndex + 1)).ToList(); var documentationToken = tokens .Take(paramIndex) .Where(t => t.Type == PSTokenType.Comment && t.Content != null && t.Content.StartsWith("<#") && t.Content.EndsWith("#>")) .LastOrDefault(); if (documentationToken != null) { var documentation = documentationToken.Content; if (documentation.StartsWith("<#") && documentation.EndsWith("#>")) { documentation = documentation.Substring(2, documentation.Length - 4); } var docBlocks = DocumentationRegex .Value .Matches(documentation) .Cast <Match>() .Select(m => new { Name = m.Groups[1].Value, Arg = !string.IsNullOrWhiteSpace(m.Groups[2].Value) ? m.Groups[2].Value.Trim() : null, Value = !string.IsNullOrWhiteSpace(m.Groups[3].Value) ? SpaceCollapseRegex.Value.Replace(m.Groups[3].Value.Trim(), " ") : null }) .Where(d => d.Value != null) .ToLookup( d => d.Name, d => new { d.Arg, d.Value }, StringComparer.OrdinalIgnoreCase); return(new PowerShellScriptInfo( description: docBlocks["SYNOPSIS"].Concat(docBlocks["DESCRIPTION"]).Select(d => d.Value).FirstOrDefault(), parameters: parameters.GroupJoin( docBlocks["PARAMETER"], p => p.Name, d => d.Arg, (p, d) => new PowerShellParameterInfo( name: p.Name, description: d.Select(t => t.Value).FirstOrDefault(), defaultValue: p.DefaultValue, isBooleanOrSwitch: p.IsBooleanOrSwitch, isOutput: p.IsOutput ), StringComparer.OrdinalIgnoreCase) )); } return(new PowerShellScriptInfo( parameters: parameters.Select(p => new PowerShellParameterInfo( name: p.Name, defaultValue: p.DefaultValue, isBooleanOrSwitch: p.IsBooleanOrSwitch, isOutput: p.IsOutput )) )); }
protected override void ProcessRecord() { base.ProcessRecord(); if (ParameterSetName.Equals("File")) { if (File.Exists(ScriptFile)) { Body = File.ReadAllText(ScriptFile); } } Collection <PSParseError> parseErrors = new Collection <PSParseError>(); PSParser.Tokenize(Body, out parseErrors); if (parseErrors.Count > 0) { var exception = new Exception("Script parse error"); ErrorRecord error = new ErrorRecord(exception, "1", ErrorCategory.InvalidData, null); WriteError(error); return; } string url = automationHelper.GetUrl(); url = url + "/api/Script"; WriteVerbose($"Using URL: {url}"); //does it already exist? List <VMScript> result = automationHelper.GetWebCall <List <VMScript> >(url + $"?Name={Name}"); bool exists = result.Any(r => r.Name.Equals(Name)); string scriptID = null; if (!exists) { //create new ScriptPostParameters postParams = new ScriptPostParameters(); postParams.Description = Description; postParams.Name = Name; scriptID = automationHelper.PostWebCall(url, postParams); } else { scriptID = result.Select(r => r.ScriptId).FirstOrDefault().ToString(); } //create version if (!string.IsNullOrEmpty(Body) && scriptID != null) { url = automationHelper.GetUrl() + $"/api/Script/{scriptID}/Version"; ScriptVersionPostParameters verPostParms = new ScriptVersionPostParameters(); verPostParms.ScriptBody = Body; short lang = 0; switch (Language) { case "PowerShellCore": lang = (short)ScriptLanguageEnum.PowerShellCore; break; } verPostParms.ScriptLanguageId = lang; string versionID = automationHelper.PostWebCall(url, verPostParms); } //return script object url = automationHelper.GetUrl() + $"/api/Script/{scriptID}"; WriteObject(automationHelper.GetWebCall <VMScript>(url)); }