microsoft/healthcare-shared-components

Public

mirrored from https://github.com/microsoft/healthcare-shared-componentsAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
1.0.0-1.0.79

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

tools/Microsoft.Health.Extensions.BuildTimeCodeGenerator/Sql/MemberSorting.cs

51lines · modecode

1// -------------------------------------------------------------------------------------------------
2// Copyright (c) Microsoft Corporation. All rights reserved.
3// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
4// -------------------------------------------------------------------------------------------------
5
6using System;
7using System.Collections.Generic;
8using System.Linq;
9using Microsoft.CodeAnalysis;
10using Microsoft.CodeAnalysis.CSharp.Syntax;
11
12namespace Microsoft.Health.Extensions.BuildTimeCodeGenerator.Sql
13{
14 public static class MemberSorting
15 {
16 private const string SortKey = "SortKey";
17
18 public static readonly Comparer<MemberDeclarationSyntax> Comparer = Comparer<MemberDeclarationSyntax>.Create(CompareMembers);
19
20 private static int CompareMembers(MemberDeclarationSyntax a, MemberDeclarationSyntax b)
21 {
22 string[] GetSortKey(MemberDeclarationSyntax member)
23 {
24 return member.GetAnnotations(SortKey).SingleOrDefault()?.Data.Split(':') ?? throw new InvalidOperationException("Members are required to have a sort key");
25 }
26
27 if (a == b)
28 {
29 return 0;
30 }
31
32 if (a == null)
33 {
34 return -1;
35 }
36
37 if (b == null)
38 {
39 return 1;
40 }
41
42 return GetSortKey(a).Zip(GetSortKey(b), (ta, tb) => (tokenA: ta, tokenB: tb)).Aggregate(0, (acc, curr) => acc != 0 ? acc : string.CompareOrdinal(curr.tokenA, curr.tokenB));
43 }
44
45 public static TMember AddSortingKey<TMember>(this TMember member, SqlVisitor visitor, string name)
46 where TMember : MemberDeclarationSyntax
47 {
48 return member.WithAdditionalAnnotations(new SyntaxAnnotation(SortKey, $"{(member is FieldDeclarationSyntax ? 0 : 1)}:{visitor.ArtifactSortOder}:{name}"));
49 }
50 }
51}
52