protected static MatchResult HandleDeclaration(SyntaxNodeAnalysisContext context, string firstTextPart, string secondTextPart, DiagnosticDescriptor diagnosticDescriptor)
        {
            var declarationSyntax      = (BaseMethodDeclarationSyntax)context.Node;
            var documentationStructure = declarationSyntax.GetDocumentationCommentTriviaSyntax();

            if (documentationStructure == null)
            {
                return(MatchResult.Unknown);
            }

            Location diagnosticLocation;
            ImmutableDictionary <string, string> diagnosticProperties;

            if (documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.IncludeXmlTag) is XmlEmptyElementSyntax includeElement)
            {
                diagnosticLocation   = includeElement.GetLocation();
                diagnosticProperties = NoCodeFixProperties;

                var declaration = context.SemanticModel.GetDeclaredSymbol(declarationSyntax, context.CancellationToken);
                if (declaration == null)
                {
                    return(MatchResult.Unknown);
                }

                var rawDocumentation      = declaration.GetDocumentationCommentXml(expandIncludes: true, cancellationToken: context.CancellationToken);
                var completeDocumentation = XElement.Parse(rawDocumentation, LoadOptions.None);

                var summaryElement = completeDocumentation.Nodes().OfType <XElement>().FirstOrDefault(element => element.Name == XmlCommentHelper.SummaryXmlTag);
                if (summaryElement == null)
                {
                    return(MatchResult.Unknown);
                }

                var summaryNodes = summaryElement.Nodes().ToList();
                if (summaryNodes.Count >= 3)
                {
                    if (summaryNodes[0] is XText firstTextPartNode &&
                        summaryNodes[1] is XElement classReferencePart &&
                        summaryNodes[2] is XText secondTextPartNode)
                    {
                        if (TextPartsMatch(firstTextPart, secondTextPart, firstTextPartNode, secondTextPartNode))
                        {
                            if (SeeTagIsCorrect(context, classReferencePart, declarationSyntax))
                            {
                                // We found a correct standard text
                                return(MatchResult.FoundMatch);
                            }
                        }
                    }
                }
            }
            else
            {
                if (!(documentationStructure.Content.GetFirstXmlElement(XmlCommentHelper.SummaryXmlTag) is XmlElementSyntax summaryElement))
                {
                    return(MatchResult.Unknown);
                }

                diagnosticLocation   = summaryElement.GetLocation();
                diagnosticProperties = ImmutableDictionary.Create <string, string>();

                // Check if the summary content could be a correct standard text
                if (summaryElement.Content.Count >= 3)
                {
                    // Standard text has the form <part1><see><part2>
                    if (summaryElement.Content[0] is XmlTextSyntax firstTextPartSyntax &&
                        summaryElement.Content[1] is XmlEmptyElementSyntax classReferencePart &&
                        summaryElement.Content[2] is XmlTextSyntax secondTextPartSyntax)
                    {
                        if (TextPartsMatch(firstTextPart, secondTextPart, firstTextPartSyntax, secondTextPartSyntax))
                        {
                            if (SeeTagIsCorrect(context, classReferencePart, declarationSyntax))
                            {
                                // We found a correct standard text
                                return(MatchResult.FoundMatch);
                            }

                            diagnosticLocation = classReferencePart.GetLocation();
                        }
                    }
                }
            }

            if (diagnosticDescriptor != null)
            {
                context.ReportDiagnostic(Diagnostic.Create(diagnosticDescriptor, diagnosticLocation, diagnosticProperties));
            }

            // TODO: be more specific about the type of error when possible
            return(MatchResult.None);
        }
        // Given the ordered list of all pragma warning and nullable directives in the syntax tree, return a list of mapping entries,
        // containing the cumulative set of warnings that are disabled for that point in the source.
        // This mapping also contains a global warning option, accumulated of all #pragma up to the current line position.
        private static WarningStateMapEntry[] CreatePragmaWarningStateEntries(ArrayBuilder <DirectiveTriviaSyntax> directiveList)
        {
            var entries = new WarningStateMapEntry[directiveList.Count + 1];
            var current = new WarningStateMapEntry(0, PragmaWarningState.Default, null);
            var index   = 0;

            entries[index] = current;

            // Captures the general reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedGeneralWarningState = PragmaWarningState.Default;

            // Captures the mapping of a warning number to the reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedSpecificWarningState = ImmutableDictionary.Create <string, PragmaWarningState>();

            while (index < directiveList.Count)
            {
                var currentDirective = directiveList[index];

                if (currentDirective.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia))
                {
                    var currentPragmaDirective = (PragmaWarningDirectiveTriviaSyntax)currentDirective;

                    // Compute the directive state (either Disable or Restore)
                    var directiveState = currentPragmaDirective.DisableOrRestoreKeyword.Kind() == SyntaxKind.DisableKeyword ? PragmaWarningState.Disabled : PragmaWarningState.Default;

                    // Check if this directive applies for all (e.g., #pragma warning disable)
                    if (currentPragmaDirective.ErrorCodes.Count == 0)
                    {
                        // Update the warning state and reset the specific one
                        accumulatedGeneralWarningState  = directiveState;
                        accumulatedSpecificWarningState = ImmutableDictionary.Create <string, PragmaWarningState>();
                    }
                    else
                    {
                        // Compute warning numbers from the current directive's codes
                        for (int x = 0; x < currentPragmaDirective.ErrorCodes.Count; x++)
                        {
                            var currentErrorCode = currentPragmaDirective.ErrorCodes[x];
                            if (currentErrorCode.IsMissing || currentErrorCode.ContainsDiagnostics)
                            {
                                continue;
                            }

                            var errorId = string.Empty;
                            if (currentErrorCode.Kind() == SyntaxKind.NumericLiteralExpression)
                            {
                                var token = ((LiteralExpressionSyntax)currentErrorCode).Token;
                                errorId = MessageProvider.Instance.GetIdForErrorCode((int)token.Value);
                            }
                            else if (currentErrorCode.Kind() == SyntaxKind.IdentifierName)
                            {
                                errorId = ((IdentifierNameSyntax)currentErrorCode).Identifier.ValueText;
                            }

                            if (!string.IsNullOrWhiteSpace(errorId))
                            {
                                // Update the state of this error code with the current directive state
                                accumulatedSpecificWarningState = accumulatedSpecificWarningState.SetItem(errorId, directiveState);
                            }
                        }
                    }
                }
                else
                {
                    var currentNullableDirective = (NullableDirectiveTriviaSyntax)currentDirective;
                    PragmaWarningState directiveState;

                    switch (currentNullableDirective.SettingToken.Kind())
                    {
                    case SyntaxKind.DisableKeyword:
                        directiveState = PragmaWarningState.Disabled;
                        break;

                    case SyntaxKind.EnableKeyword:
                        directiveState = PragmaWarningState.Enabled;
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(currentNullableDirective.SettingToken.Kind());
                    }

                    // Update the state of this error code with the current directive state
                    var builder = ArrayBuilder <KeyValuePair <string, PragmaWarningState> > .GetInstance(ErrorFacts.NullableFlowAnalysisWarnings.Count);

                    foreach (string id in ErrorFacts.NullableFlowAnalysisWarnings)
                    {
                        builder.Add(new KeyValuePair <string, PragmaWarningState>(id, directiveState));
                    }

                    accumulatedSpecificWarningState = accumulatedSpecificWarningState.SetItems(builder);
                    builder.Free();
                }

                current = new WarningStateMapEntry(currentDirective.Location.SourceSpan.End, accumulatedGeneralWarningState, accumulatedSpecificWarningState);
                ++index;
                entries[index] = current;
            }

#if DEBUG
            // Make sure the entries array is correctly sorted.
            for (int i = 1; i < entries.Length - 1; ++i)
            {
                Debug.Assert(entries[i].CompareTo(entries[i + 1]) < 0);
            }
#endif

            return(entries);
        }
 internal WorkspaceOptionSet(IOptionService service)
 {
     _service = service;
     _values  = ImmutableDictionary.Create <OptionKey, object>();
 }
示例#4
0
 public Scope(Env env)
 {
     Env     = env;
     Aliases = ImmutableDictionary.Create <string, string[]>(Naming.Comparer);
     Ctes    = ImmutableDictionary.Create <string, Table>(Naming.Comparer);
 }
示例#5
0
        protected override void InitializeWorker(ApiControllerAnalyzerContext analyzerContext)
        {
            analyzerContext.Context.RegisterSyntaxNodeAction(context =>
            {
                var methodSyntax = (MethodDeclarationSyntax)context.Node;
                if (methodSyntax.Body == null)
                {
                    // Ignore expression bodied methods.
                }

                var method = context.SemanticModel.GetDeclaredSymbol(methodSyntax, context.CancellationToken);
                if (!analyzerContext.IsApiAction(method))
                {
                    return;
                }

                if (method.ReturnsVoid || method.ReturnType.Kind != SymbolKind.NamedType)
                {
                    return;
                }

                var declaredReturnType  = method.ReturnType;
                var namedReturnType     = (INamedTypeSymbol)method.ReturnType;
                var isTaskOActionResult = false;
                if (namedReturnType.ConstructedFrom?.IsAssignableFrom(analyzerContext.SystemThreadingTaskOfT) ?? false)
                {
                    // Unwrap Task<T>.
                    isTaskOActionResult = true;
                    declaredReturnType  = namedReturnType.TypeArguments[0];
                }

                if (!declaredReturnType.IsAssignableFrom(analyzerContext.IActionResult))
                {
                    // Method signature does not look like IActionResult MyAction or SomeAwaitable<IActionResult>.
                    // Nothing to do here.
                    return;
                }

                // Method returns an IActionResult. Determine if the method block returns an ObjectResult
                foreach (var returnStatement in methodSyntax.DescendantNodes().OfType <ReturnStatementSyntax>())
                {
                    var returnType = context.SemanticModel.GetTypeInfo(returnStatement.Expression, context.CancellationToken);
                    if (returnType.Type == null || returnType.Type.Kind == SymbolKind.ErrorType)
                    {
                        continue;
                    }

                    ImmutableDictionary <string, string> properties = null;
                    if (returnType.Type.IsAssignableFrom(analyzerContext.ObjectResult))
                    {
                        // Check if the method signature looks like "return Ok(userModelInstance)". If so, we can infer the type of userModelInstance
                        if (returnStatement.Expression is InvocationExpressionSyntax invocation &&
                            invocation.ArgumentList.Arguments.Count == 1)
                        {
                            var typeInfo          = context.SemanticModel.GetTypeInfo(invocation.ArgumentList.Arguments[0].Expression);
                            var desiredReturnType = analyzerContext.ActionResultOfT.Construct(typeInfo.Type);
                            if (isTaskOActionResult)
                            {
                                desiredReturnType = analyzerContext.SystemThreadingTaskOfT.Construct(desiredReturnType);
                            }

                            var desiredReturnTypeString = desiredReturnType.ToMinimalDisplayString(
                                context.SemanticModel,
                                methodSyntax.ReturnType.SpanStart);

                            properties = ImmutableDictionary.Create <string, string>(StringComparer.Ordinal)
                                         .Add(ReturnTypeKey, desiredReturnTypeString);
                        }

                        context.ReportDiagnostic(Diagnostic.Create(
                                                     SupportedDiagnostic,
                                                     methodSyntax.ReturnType.GetLocation(),
                                                     properties: properties));
                    }
                }
            }, SyntaxKind.MethodDeclaration);
        }
 protected TemplateContextBase(Type template)
 {
     m_dictionary = ImmutableDictionary.Create <object, object> ();
     m_template   = template;
 }
示例#7
0
        private static void CheckToken(SyntaxNodeAnalysisContext context, SyntaxToken token, bool withLeadingWhitespace, bool allowAtEndOfLine, bool withTrailingWhitespace, string tokenText = null)
        {
            tokenText = tokenText ?? token.Text;

            var precedingToken      = token.GetPreviousToken();
            var precedingTriviaList = TriviaHelper.MergeTriviaLists(precedingToken.TrailingTrivia, token.LeadingTrivia);

            var followingToken      = token.GetNextToken();
            var followingTriviaList = TriviaHelper.MergeTriviaLists(token.TrailingTrivia, followingToken.LeadingTrivia);

            if (withLeadingWhitespace)
            {
                // Don't report missing leading whitespace when the token is the first token on a text line.
                if (!token.IsFirstInLine() &&
                    ((precedingTriviaList.Count == 0) || !precedingTriviaList.Last().IsKind(SyntaxKind.WhitespaceTrivia)))
                {
                    var properties = ImmutableDictionary.Create <string, string>()
                                     .Add(CodeFixAction, InsertBeforeTag);
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorPrecededByWhitespace, token.GetLocation(), properties, tokenText));
                }
            }
            else
            {
                // don't report leading whitespace when the token is the first token on a text line
                if (!token.IsOnlyPrecededByWhitespaceInLine() &&
                    ((precedingTriviaList.Count > 0) && precedingTriviaList.Last().IsKind(SyntaxKind.WhitespaceTrivia)))
                {
                    var properties = ImmutableDictionary.Create <string, string>()
                                     .Add(CodeFixAction, RemoveBeforeTag);
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorNotPrecededByWhitespace, token.GetLocation(), properties, tokenText));
                }
            }

            if (!allowAtEndOfLine && token.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia))
            {
                var properties = ImmutableDictionary.Create <string, string>();

                // Do not register a code fix action if there are non whitespace or end of line tokens present.
                if (followingTriviaList.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia) || t.IsKind(SyntaxKind.EndOfLineTrivia)))
                {
                    properties = properties.Add(CodeFixAction, withTrailingWhitespace ? RemoveEndOfLineWithTrailingSpaceTag : RemoveEndOfLineTag);
                }

                context.ReportDiagnostic(Diagnostic.Create(DescriptorNotAtEndOfLine, token.GetLocation(), properties, tokenText));
                return;
            }

            if (withTrailingWhitespace)
            {
                if ((followingTriviaList.Count == 0) || !(followingTriviaList.First().IsKind(SyntaxKind.WhitespaceTrivia) || followingTriviaList.First().IsKind(SyntaxKind.EndOfLineTrivia)))
                {
                    var properties = ImmutableDictionary.Create <string, string>()
                                     .Add(CodeFixAction, InsertAfterTag);
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorFollowedByWhitespace, token.GetLocation(), properties, tokenText));
                }
            }
            else
            {
                if ((followingTriviaList.Count > 0) && followingTriviaList.First().IsKind(SyntaxKind.WhitespaceTrivia))
                {
                    var properties = ImmutableDictionary.Create <string, string>()
                                     .Add(CodeFixAction, RemoveAfterTag);
                    context.ReportDiagnostic(Diagnostic.Create(DescriptorNotFollowedByWhitespace, token.GetLocation(), properties, tokenText));
                }
            }
        }
 public WarningStateMapEntry(int position)
 {
     this.Position              = position;
     this.GeneralWarningOption  = default;
     this.SpecificWarningOption = ImmutableDictionary.Create <string, TWarningState>();
 }
示例#9
0
        private static Generic.IParser <char, object> GerJsonParserCore(int maxDepth = Infinity)
        {
            if (Infinity == maxDepth)
            {
                var value_p = default(Generic.IParser <char, object>);

                var element_p =
                    from _ in WhitespaceSequenceNillableIgnored
                    from value in value_p
                    from __ in WhitespaceSequenceNillableIgnored
                    select value;

                var member_p =
                    from _ in WhitespaceSequenceNillableIgnored
                    from key in string_p
                    from __ in WhitespaceSequenceNillableIgnored
                    from ___ in ':'.ToParserInvariant()
                    from value in element_p
                    select KeyValuePair.Create(key, value);

                var object_p =
                    from _ in '{'.ToParserInvariant()
                    from v in (
                        from hd in member_p
                        from tl in (
                            from _ in ','.ToParserInvariant()
                            from te in member_p
                            select te
                            ).Times(ImmutableDictionary.Create <string, object>(), (x, y) => x.Add(y.Key, y.Value))
                        select tl.Add(hd.Key, hd.Value)
                        ).OrElseUntagged(
                        from __ in WhitespaceSequenceNillableIgnored
                        select ImmutableDictionary.Create <string, object>()
                        )
                    from __ in '}'.ToParserInvariant()
                    select v;

                var array_p =
                    from _ in '['.ToParserInvariant()
                    from v in (
                        from hd in element_p
                        from tl in (
                            from _ in ','.ToParserInvariant()
                            from te in element_p
                            select te
                            ).Times()
                        select tl.Insert(0, hd)
                        ).OrElseUntagged(
                        from __ in WhitespaceSequenceNillableIgnored
                        select ImmutableList.Create <object>()
                        )
                    from __ in ']'.ToParserInvariant()
                    select v;

                value_p =
                    object_p.Or(
                        null_p
                        , x => (object)x, x => (object)x).Or(
                        array_p.Or(
                            string_p
                            , x => (object)x, x => (object)x)
                        , x => (object)x, x => (object)x).Or(
                        number_p.Or(
                            boolean_p
                            , x => (object)x, x => (object)x)
                        , x => (object)x, x => (object)x);
                // Or(string_p, number_p, object_p, array_p, boolean_p, );

                return(value_p);
            }
            if (0 == maxDepth)
            {
                return(string_p.Or(
                           null_p
                           , x => (object)x, x => (object)x).Or(
                           number_p.Or(
                               boolean_p
                               , x => (object)x, x => (object)x)
                           , x => (object)x, x => (object)x));
            }
            else
            {
                var element_p =
                    from _ in WhitespaceSequenceNillableIgnored
                    from value in GerJsonParserCore(maxDepth - 1)
                    from __ in WhitespaceSequenceNillableIgnored
                    select value;

                var member_p =
                    from _ in WhitespaceSequenceNillableIgnored
                    from key in string_p
                    from __ in WhitespaceSequenceNillableIgnored
                    from ___ in ':'.ToParserInvariant()
                    from value in element_p
                    select KeyValuePair.Create(key, value);

                var object_p =
                    from _ in '{'.ToParserInvariant()
                    from v in (
                        from hd in member_p
                        from tl in (
                            from _ in ','.ToParserInvariant()
                            from te in member_p
                            select te
                            ).Times(ImmutableDictionary.Create <string, object>(), (x, y) => x.Add(y.Key, y.Value))
                        select tl.Add(hd.Key, hd.Value)
                        ).OrElseUntagged(
                        from __ in WhitespaceSequenceNillableIgnored
                        select ImmutableDictionary.Create <string, object>()
                        )
                    from __ in '}'.ToParserInvariant()
                    select v;

                var array_p =
                    from _ in '['.ToParserInvariant()
                    from v in (
                        from hd in element_p
                        from tl in (
                            from _ in ','.ToParserInvariant()
                            from te in element_p
                            select te
                            ).Times()
                        select tl.Insert(0, hd)
                        ).OrElseUntagged(
                        from __ in WhitespaceSequenceNillableIgnored
                        select ImmutableList.Create <object>()
                        )
                    from __ in ']'.ToParserInvariant()
                    select v;

                return
                    (object_p.Or(
                         null_p
                         , x => (object)x, x => (object)x).Or(
                         array_p.Or(
                             string_p
                             , x => (object)x, x => (object)x)
                         , x => (object)x, x => (object)x).Or(
                         number_p.Or(
                             boolean_p
                             , x => (object)x, x => (object)x)
                         , x => (object)x, x => (object)x));
            }
        }
示例#10
0
 public ValueTask <ImmutableDictionary <string, JsonElement> > GetPropertiesAsync(Client application, CancellationToken cancellationToken)
 {
     return(ValueTask.FromResult(ImmutableDictionary.Create <string, JsonElement>()));
 }
示例#11
0
        /// <summary>
        /// Implements the 'add-subscription' operation
        /// </summary>
        /// <param name="options"></param>
        public override async Task <int> ExecuteAsync()
        {
            IRemote remote = RemoteFactory.GetBarOnlyRemote(_options, Logger);

            if (_options.IgnoreChecks.Count() > 0 && !_options.AllChecksSuccessfulMergePolicy)
            {
                Console.WriteLine($"--ignore-checks must be combined with --all-checks-passed");
                return(Constants.ErrorCode);
            }

            // Parse the merge policies
            List <MergePolicy> mergePolicies = new List <MergePolicy>();

            if (_options.NoExtraCommitsMergePolicy)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name = Constants.NoExtraCommitsMergePolicyName
                });
            }

            if (_options.AllChecksSuccessfulMergePolicy)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = Constants.AllCheckSuccessfulMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                                 .Add(Constants.IgnoreChecksMergePolicyPropertyName, JToken.FromObject(_options.IgnoreChecks))
                });
            }

            if (_options.NoRequestedChangesMergePolicy)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = Constants.NoRequestedChangesMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                });
            }

            if (_options.StandardAutoMergePolicies)
            {
                mergePolicies.Add(
                    new MergePolicy
                {
                    Name       = Constants.StandardMergePolicyName,
                    Properties = ImmutableDictionary.Create <string, JToken>()
                });
            }

            if (_options.Batchable && mergePolicies.Count > 0)
            {
                Console.WriteLine("Batchable subscriptions cannot be combined with merge policies. " +
                                  "Merge policies are specified at a repository+branch level.");
                return(Constants.ErrorCode);
            }

            string channel          = _options.Channel;
            string sourceRepository = _options.SourceRepository;
            string targetRepository = _options.TargetRepository;
            string targetBranch     = _options.TargetBranch;
            string updateFrequency  = _options.UpdateFrequency;
            bool   batchable        = _options.Batchable;

            // If in quiet (non-interactive mode), ensure that all options were passed, then
            // just call the remote API
            if (_options.Quiet && !_options.ReadStandardIn)
            {
                if (string.IsNullOrEmpty(channel) ||
                    string.IsNullOrEmpty(sourceRepository) ||
                    string.IsNullOrEmpty(targetRepository) ||
                    string.IsNullOrEmpty(targetBranch) ||
                    string.IsNullOrEmpty(updateFrequency) ||
                    !Constants.AvailableFrequencies.Contains(updateFrequency, StringComparer.OrdinalIgnoreCase))
                {
                    Logger.LogError($"Missing input parameters for the subscription. Please see command help or remove --quiet/-q for interactive mode");
                    return(Constants.ErrorCode);
                }
            }
            else
            {
                // Grab existing subscriptions to get suggested values.
                // TODO: When this becomes paged, set a max number of results to avoid
                // pulling too much.
                var suggestedRepos    = remote.GetSubscriptionsAsync();
                var suggestedChannels = remote.GetChannelsAsync();

                // Help the user along with a form.  We'll use the API to gather suggested values
                // from existing subscriptions based on the input parameters.
                AddSubscriptionPopUp addSubscriptionPopup =
                    new AddSubscriptionPopUp("add-subscription/add-subscription-todo",
                                             Logger,
                                             channel,
                                             sourceRepository,
                                             targetRepository,
                                             targetBranch,
                                             updateFrequency,
                                             batchable,
                                             mergePolicies,
                                             (await suggestedChannels).Select(suggestedChannel => suggestedChannel.Name),
                                             (await suggestedRepos).SelectMany(subscription => new List <string> {
                    subscription.SourceRepository, subscription.TargetRepository
                }).ToHashSet(),
                                             Constants.AvailableFrequencies,
                                             Constants.AvailableMergePolicyYamlHelp);

                UxManager uxManager = new UxManager(_options.GitLocation, Logger);
                int       exitCode  = _options.ReadStandardIn ? uxManager.ReadFromStdIn(addSubscriptionPopup) : uxManager.PopUp(addSubscriptionPopup);
                if (exitCode != Constants.SuccessCode)
                {
                    return(exitCode);
                }
                channel          = addSubscriptionPopup.Channel;
                sourceRepository = addSubscriptionPopup.SourceRepository;
                targetRepository = addSubscriptionPopup.TargetRepository;
                targetBranch     = addSubscriptionPopup.TargetBranch;
                updateFrequency  = addSubscriptionPopup.UpdateFrequency;
                mergePolicies    = addSubscriptionPopup.MergePolicies;
                batchable        = addSubscriptionPopup.Batchable;
            }

            try
            {
                // If we are about to add a batchable subscription and the merge policies are empty for the
                // target repo/branch, warn the user.
                if (batchable)
                {
                    var existingMergePolicies = await remote.GetRepositoryMergePoliciesAsync(targetRepository, targetBranch);

                    if (!existingMergePolicies.Any())
                    {
                        Console.WriteLine("Warning: Batchable subscription doesn't have any repository merge policies. " +
                                          "PRs will not be auto-merged.");
                        Console.WriteLine($"Please use 'darc set-repository-policies --repo {targetRepository} --branch {targetBranch}' " +
                                          $"to set policies.{Environment.NewLine}");
                    }
                }

                // Verify the target
                IRemote targetVerifyRemote = RemoteFactory.GetRemote(_options, targetRepository, Logger);
                if (!(await UxHelpers.VerifyAndConfirmBranchExistsAsync(targetVerifyRemote, targetRepository, targetBranch, !_options.Quiet)))
                {
                    Console.WriteLine("Aborting subscription creation.");
                    return(Constants.ErrorCode);
                }

                // Verify the source.
                IRemote sourceVerifyRemote = RemoteFactory.GetRemote(_options, sourceRepository, Logger);
                if (!(await UxHelpers.VerifyAndConfirmRepositoryExistsAsync(sourceVerifyRemote, sourceRepository, !_options.Quiet)))
                {
                    Console.WriteLine("Aborting subscription creation.");
                    return(Constants.ErrorCode);
                }

                var newSubscription = await remote.CreateSubscriptionAsync(channel,
                                                                           sourceRepository,
                                                                           targetRepository,
                                                                           targetBranch,
                                                                           updateFrequency,
                                                                           batchable,
                                                                           mergePolicies);

                Console.WriteLine($"Successfully created new subscription with id '{newSubscription.Id}'.");

                // Prompt the user to trigger the subscription unless they have explicitly disallowed it
                if (!_options.NoTriggerOnCreate)
                {
                    bool triggerAutomatically = _options.TriggerOnCreate || UxHelpers.PromptForYesNo("Trigger this subscription immediately?");
                    if (triggerAutomatically)
                    {
                        await remote.TriggerSubscriptionAsync(newSubscription.Id.ToString());

                        Console.WriteLine($"Subscription '{newSubscription.Id}' triggered.");
                    }
                }

                return(Constants.SuccessCode);
            }
            catch (RestApiException e) when(e.Response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                // Could have been some kind of validation error (e.g. channel doesn't exist)
                Logger.LogError($"Failed to create subscription: {e.Response.Content}");
                return(Constants.ErrorCode);
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"Failed to create subscription.");
                return(Constants.ErrorCode);
            }
        }
示例#12
0
        public BuiltinType(string name)
            :
            this(name, ImmutableDictionary.Create <string, string>())

        {
        }
 public BindTypeBuilder()
 {
     Map = ImmutableDictionary.Create <string, string>();
 }
示例#14
0
 private static ImmutableDictionary <string, string> CreateProperties(OptimizeLinqUsageData data)
 {
     return(ImmutableDictionary.Create <string, string>().Add("Data", data.ToString()));
 }
 protected override IImmutableDictionary <TKey, TValue> GetEmptyImmutableDictionary <TKey, TValue>()
 {
     return(ImmutableDictionary.Create <TKey, TValue>());
 }
 private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Location location, string kind, params string[] messageArgs)
 {
     return(Diagnostic.Create(descriptor, location, ImmutableDictionary.Create <string, string>().Add(DiagnosticKindText, kind), messageArgs));
 }
 protected override IImmutableDictionary <string, TValue> Empty <TValue>(StringComparer comparer)
 {
     return(ImmutableDictionary.Create <string, TValue>(comparer));
 }
 public WarningStateMapEntry(int position, TWarningState general, ImmutableDictionary <string, TWarningState> specific)
 {
     this.Position              = position;
     this.GeneralWarningOption  = general;
     this.SpecificWarningOption = specific ?? ImmutableDictionary.Create <string, TWarningState>();
 }
示例#19
0
        // Given the ordered list of all pragma warning directives in the syntax tree, return a list of mapping entries,
        // containing the cumulative set of warnings that are disabled for that point in the source.
        // This mapping also contains a global warning option, accumulated of all #pragma up to the current line position.
        private static WarningStateMapEntry[] CreatePragmaWarningStateEntries(ImmutableArray <PragmaWarningDirectiveTriviaSyntax> directiveList)
        {
            var entries = new WarningStateMapEntry[directiveList.Length + 1];
            var current = new WarningStateMapEntry(0, ReportDiagnostic.Default, null);
            var index   = 0;

            entries[index] = current;

            // Captures the general reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedGeneralWarningState = ReportDiagnostic.Default;

            // Captures the mapping of a warning number to the reporting option, accumulated of all #pragma up to the current directive.
            var accumulatedSpecificWarningState = ImmutableDictionary.Create <string, ReportDiagnostic>();

            while (index < directiveList.Length)
            {
                var currentDirective = directiveList[index];

                // Compute the directive state (either Disable or Restore)
                var directiveState = currentDirective.DisableOrRestoreKeyword.Kind() == SyntaxKind.DisableKeyword ? ReportDiagnostic.Suppress : ReportDiagnostic.Default;

                // Check if this directive applies for all (e.g., #pragma warning disable)
                if (currentDirective.ErrorCodes.Count == 0)
                {
                    // Update the warning state and reset the specific one
                    accumulatedGeneralWarningState  = directiveState;
                    accumulatedSpecificWarningState = ImmutableDictionary.Create <string, ReportDiagnostic>();
                }
                else
                {
                    // Compute warning numbers from the current directive's codes
                    for (int x = 0; x < currentDirective.ErrorCodes.Count; x++)
                    {
                        var currentErrorCode = currentDirective.ErrorCodes[x];
                        if (currentErrorCode.IsMissing || currentErrorCode.ContainsDiagnostics)
                        {
                            continue;
                        }

                        var errorId = string.Empty;
                        if (currentErrorCode.Kind() == SyntaxKind.NumericLiteralExpression)
                        {
                            var token = (currentErrorCode as LiteralExpressionSyntax).Token;
                            errorId = MessageProvider.Instance.GetIdForErrorCode((int)token.Value);
                        }
                        else if (currentErrorCode.Kind() == SyntaxKind.IdentifierName)
                        {
                            errorId = (currentErrorCode as IdentifierNameSyntax).Identifier.ValueText;
                        }

                        if (!string.IsNullOrWhiteSpace(errorId))
                        {
                            // Update the state of this error code with the current directive state
                            accumulatedSpecificWarningState = accumulatedSpecificWarningState.SetItem(errorId, directiveState);
                        }
                    }
                }

                current = new WarningStateMapEntry(currentDirective.Location.SourceSpan.End, accumulatedGeneralWarningState, accumulatedSpecificWarningState);
                ++index;
                entries[index] = current;
            }

#if DEBUG
            // Make sure the entries array is correctly sorted.
            for (int i = 1; i < entries.Length - 1; ++i)
            {
                Debug.Assert(entries[i].CompareTo(entries[i + 1]) < 0);
            }
#endif

            return(entries);
        }
示例#20
0
 /// <summary>
 /// Removes all registered listeners.
 /// </summary>
 /// <returns>a reference to this object.</returns>
 public Emitter Off()
 {
     callbacks      = ImmutableDictionary.Create <string, ImmutableList <IListener> >();
     _onceCallbacks = ImmutableDictionary.Create <IListener, IListener>();
     return(this);
 }
示例#21
0
 public WarningStateMapEntry(int position)
 {
     this.Position              = position;
     this.GeneralWarningOption  = ReportDiagnostic.Default;
     this.SpecificWarningOption = ImmutableDictionary.Create <string, ReportDiagnostic>();
 }
示例#22
0
 public NullFlowState(SemanticModel model)
     : this(model, ImmutableDictionary.Create <object, NullState>(new VariableComparer(model)))
 {
 }
示例#23
0
 public WarningStateMapEntry(int position, ReportDiagnostic general, ImmutableDictionary <string, ReportDiagnostic> specific)
 {
     this.Position              = position;
     this.GeneralWarningOption  = general;
     this.SpecificWarningOption = specific ?? ImmutableDictionary.Create <string, ReportDiagnostic>();
 }
示例#24
0
        public void ProcessMarkdownResultWithEncodedUrlShouldSucceed()
        {
            var markdownResult = new MarkupResult
            {
                Html = @"<p><a href=""%7E/docs/csharp/language-reference/keywords/select-clause.md""></p>"
            };

            markdownResult = MarkupUtility.Parse(markdownResult, "docs/framework/data/wcf/how-to-project-query-results-wcf-data-services.md", ImmutableDictionary.Create <string, FileAndType>());
            Assert.Equal("~/docs/csharp/language-reference/keywords/select-clause.md", markdownResult.LinkToFiles.First());
        }
        public void ProcessMarkdownResultWithEncodedUrlShouldSucceed(string htmlContent, string expectedFileLink)
        {
            var markdownResult = new MarkupResult
            {
                Html = htmlContent
            };

            markdownResult = MarkupUtility.Parse(markdownResult, "docs/framework/data/wcf/how-to-project-query-results-wcf-data-services.md", ImmutableDictionary.Create <string, FileAndType>());
            Assert.Equal(expectedFileLink, markdownResult.LinkToFiles.First());
        }