Skip to content

Commit

Permalink
Merge pull request #1102 from TelegramBots/develop
Browse files Browse the repository at this point in the history
Release v18
  • Loading branch information
tuscen committed Jun 16, 2022
2 parents 72f6278 + 52294a1 commit ad9dfc2
Show file tree
Hide file tree
Showing 66 changed files with 1,703 additions and 820 deletions.
2 changes: 1 addition & 1 deletion .azure-pipelines/variables.yml
Expand Up @@ -3,7 +3,7 @@ variables:
- name: versionPrefix
value: 18.0.0
- name: versionSuffix
value: 'alpha.3'
value: ''
- name: ciVersionSuffix
value: ci.$(Build.BuildId)+git.commit.$(Build.SourceVersion)
- name: isPreRelease
Expand Down
4 changes: 2 additions & 2 deletions .devcontainer/Dockerfile
@@ -1,5 +1,5 @@
ARG DOTNET_VERSION=5.0
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-buster-slim
ARG DOTNET_VERSION=6.0
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION}-bullseye-slim
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=${USER_UID}
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -23,6 +23,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

> [Bot API 6.0](https://core.telegram.org/bots/api#april-16-2022) (April 16, 2022)
### Added

- Package `Telegram.Bot.Extensions.Polling` is merged in the main package
Expand All @@ -45,6 +47,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
- Renamed properties `ChatMemberAdministrator.CanManageVoiceChats`, `PromoteChatMemberRequest.CanManageVoiceChats` to
`ChatMemberAdministrator.CanManageVideoChats ` and `PromoteChatMemberRequest.CanManageVideoChats`
- Removed `baseUrl` parameter from constructor in `TelegramBotClient` that accepts a token
- Type of property `FileBase.FileSize` changed from `int?` to `long?`

### Fixed
- Argument `protectContent` in method `TelegramBotClientExtensions.ForwardMessageAsync` is passed to the
Expand Down
73 changes: 73 additions & 0 deletions THIRD_PARTY_NOTICES
@@ -0,0 +1,73 @@
Telegram.Bot

THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize

This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Camunda received such components are set forth below.

1. Newtonsoft.Json (https://github.com/JamesNK/Newtonsoft.Json)
2. Scriban (https://github.com/scriban/scriban)
3. Nullable (https://github.com/manuelroemer/Nullable)


Newtonsoft.Json NOTICES AND INFORMATION BEGIN HERE
==========================================
The MIT License (MIT)

Copyright (c) 2007 James Newton-King

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Scriban NOTICES AND INFORMATION BEGIN HERE
==========================================
Copyright (c) 2016-2020, Alexandre Mutel
All rights reserved.

Redistribution and use in source and binary forms, with or without modification
, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Nullable NOTICES AND INFORMATION BEGIN HERE
==========================================
MIT License

Copyright (c) Manuel Römer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 9 additions & 2 deletions Telegram.Bot.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.16
# Visual Studio Version 17
VisualStudioVersion = 17.2.32422.2
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{838231A4-B081-44B0-AC16-DC4C2FABAE86}"
EndProject
Expand Down Expand Up @@ -44,6 +44,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".devcontainer", ".devcontai
.devcontainer\Dockerfile = .devcontainer\Dockerfile
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnumSerializer.Generator", "src\EnumSerializer.Generator\EnumSerializer.Generator.csproj", "{C246B54F-018B-4589-B26D-C38D7846FFF2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -62,6 +64,10 @@ Global
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Release|Any CPU.Build.0 = Release|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -73,6 +79,7 @@ Global
{71662597-40F2-4192-AC4D-5FB9A1F12642} = {C45387C6-C93F-4FD2-84A8-A69CCE93B7EE}
{C20A563E-603B-49E8-A954-DB90D4F351DE} = {71662597-40F2-4192-AC4D-5FB9A1F12642}
{4897F36C-2F57-48A7-B425-D8F695E0AC0D} = {C45387C6-C93F-4FD2-84A8-A69CCE93B7EE}
{C246B54F-018B-4589-B26D-C38D7846FFF2} = {838231A4-B081-44B0-AC16-DC4C2FABAE86}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F6A9C4CA-DF26-4772-9119-627935D70E7C}
Expand Down
179 changes: 179 additions & 0 deletions src/EnumSerializer.Generator/EnumConverterGenerator.cs
@@ -0,0 +1,179 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Scriban;
using System.Collections.Immutable;
using System.Text;

namespace EnumSerializer.Generator;

[Generator]
public class EnumConverterGenerator : IIncrementalGenerator
{
const string JsonConverterAttribute = "Newtonsoft.Json.JsonConverterAttribute";

public void Initialize(IncrementalGeneratorInitializationContext context)
{
IncrementalValuesProvider<EnumDeclarationSyntax> enumDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
transform: static (ctx, _) => GetSemanticTargetForGeneration(ctx))
.Where(static m => m is not null)!;

IncrementalValueProvider<(Compilation, ImmutableArray<EnumDeclarationSyntax>)> compilationAndEnums
= context.CompilationProvider.Combine(enumDeclarations.Collect());

context.RegisterSourceOutput(compilationAndEnums,
static (spc, source) => Execute(source.Item1, source.Item2, spc));
}

static bool IsSyntaxTargetForGeneration(SyntaxNode node)
=> node is EnumDeclarationSyntax { AttributeLists.Count: > 0 };

static EnumDeclarationSyntax? GetSemanticTargetForGeneration(GeneratorSyntaxContext context)
{
// we know the node is a EnumDeclarationSyntax thanks to IsSyntaxTargetForGeneration
var enumDeclarationSyntax = (EnumDeclarationSyntax)context.Node;

// loop through all the attributes on the method
foreach (AttributeListSyntax attributeListSyntax in enumDeclarationSyntax.AttributeLists)
{
foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes)
{
if (context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol
is not IMethodSymbol attributeSymbol)
{
// weird, we couldn't get the symbol, ignore it
continue;
}

INamedTypeSymbol attributeContainingTypeSymbol = attributeSymbol.ContainingType;
string fullName = attributeContainingTypeSymbol.ToDisplayString();

// Is the attribute the [JsonConverterAttribute] attribute?
if (fullName == JsonConverterAttribute)
{
// return the enum
return enumDeclarationSyntax;
}
}
}

// we didn't find the attribute we were looking for
return null;
}

static void Execute(
Compilation compilation,
ImmutableArray<EnumDeclarationSyntax> enums,
SourceProductionContext context)
{
if (enums.IsDefaultOrEmpty)
{
// nothing to do yet
return;
}

IEnumerable<EnumDeclarationSyntax> distinctEnums = enums.Distinct();

List<EnumInfo> enumsToProcess = GetTypesToGenerate(compilation, distinctEnums, context.CancellationToken);
if (enumsToProcess.Count == 0)
{
return;
}

Template template = Template.Parse(SourceGenerationHelper.ConverterTemplate);
foreach (var enumToProcess in enumsToProcess)
{
var result = SourceGenerationHelper.GenerateConverterClass(template, enumToProcess);
context.AddSource(
hintName: $"{enumToProcess.Name}Converter.g.cs",
sourceText: SourceText.From(result, Encoding.UTF8)
);
}
}

static List<EnumInfo> GetTypesToGenerate(
Compilation compilation,
IEnumerable<EnumDeclarationSyntax> enums, CancellationToken ct)
{
var enumsToProcess = new List<EnumInfo>();
INamedTypeSymbol? enumAttribute = compilation.GetTypeByMetadataName(JsonConverterAttribute);
if (enumAttribute is null)
{
// nothing to do if this type isn't available
return enumsToProcess;
}

foreach (var enumDeclarationSyntax in enums)
{
// stop if we're asked to
ct.ThrowIfCancellationRequested();

SemanticModel semanticModel = compilation.GetSemanticModel(enumDeclarationSyntax.SyntaxTree);
if (semanticModel.GetDeclaredSymbol(enumDeclarationSyntax, cancellationToken: ct)
is not INamedTypeSymbol enumSymbol)
{
// report diagnostic, something went wrong
continue;
}

string name = enumSymbol.Name;
string nameSpace = enumSymbol.ContainingNamespace.IsGlobalNamespace
? string.Empty
: enumSymbol.ContainingNamespace.ToString();

string fullyQualifiedName = enumSymbol.ToString();

var enumMembers = enumSymbol.GetMembers();
var members = new List<KeyValuePair<string, string>>(enumMembers.Length);

foreach (var member in enumMembers)
{
if (member is not IFieldSymbol field
|| field.ConstantValue is null)
{
continue;
}

string? displayName = null;
foreach (var attribute in member.GetAttributes())
{
if (attribute.AttributeClass is null
|| attribute.AttributeClass.Name != "DisplayAttribute")
{
continue;
}

foreach (var namedArgument in attribute.NamedArguments)
{
if (namedArgument.Key == "Name" && namedArgument.Value.Value?.ToString() is { } dn)
{
displayName = dn;
break;
}
}
}

members.Add(new(
member.Name,
displayName ?? ToSnakeCase(member.Name)
));
}

enumsToProcess.Add(new(
name: name,
ns: nameSpace,
fullyQualifiedName: fullyQualifiedName,
members: members
));
}
return enumsToProcess;
}

static string ToSnakeCase(string name) =>
string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x)
? $"_{x}"
: x.ToString())
).ToLower();
}
25 changes: 25 additions & 0 deletions src/EnumSerializer.Generator/EnumInfo.cs
@@ -0,0 +1,25 @@
namespace EnumSerializer.Generator;

public readonly struct EnumInfo
{
public readonly string Name;
public readonly string FullyQualifiedName;
public readonly string Namespace;

/// <summary>
/// Key is the enum name.
/// </summary>
public readonly List<KeyValuePair<string, string>> Members;

public EnumInfo(
string name,
string ns,
string fullyQualifiedName,
List<KeyValuePair<string, string>> members)
{
Name = name;
Namespace = ns;
Members = members;
FullyQualifiedName = fullyQualifiedName;
}
}
25 changes: 25 additions & 0 deletions src/EnumSerializer.Generator/EnumSerializer.Generator.csproj
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>10</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IncludeBuildOutput>false</IncludeBuildOutput>
<IsRoslynComponent>true</IsRoslynComponent>
<EnableNETAnalyzers>True</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
</PropertyGroup>

<!-- The following libraries include the source generator interfaces and types we need -->
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" />
<PackageReference Include="Scriban" Version="5.4.4" GeneratePathProperty="true" PrivateAssets="all" />

<!-- This ensures the library will be packaged as a source generator when we use `dotnet pack` -->
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />

<TargetPathWithTargetPlatformMoniker Include="$(PKGScriban)\lib\netstandard2.0\*.dll" IncludeRuntimeDependency="false" />
</ItemGroup>
</Project>
19 changes: 19 additions & 0 deletions src/EnumSerializer.Generator/README.md
@@ -0,0 +1,19 @@
# Enum Converter Generator

## Background

Telegram.Bot library relies on [Json.NET converters](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm)
to map JSON input to various enums and vice versa.

It's rather tedious and repeating task. So that's where C# source generators come to help.

`EnumSerializer.Generator` looks for enums
annotated with `[JsonConverter(typeof(TEnumConverter))]` attribute and generates a converter that handles all possible enum values for us.

## Credits

This project is heavily inspired by the series of posts by Andrew Lock [Creating an incremental generator](https://andrewlock.net/creating-a-source-generator-part-1-creating-an-incremental-source-generator/) and [NetEscapades.EnumGenerators
](https://github.com/andrewlock/NetEscapades.EnumGenerators) project.

We use Alexandre Mutel's [Scriban](https://github.com/scriban/scriban) templating engine to generate
converter class output.

0 comments on commit ad9dfc2

Please sign in to comment.