Skip to content

Commit

Permalink
Update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
fakefeik committed Jun 22, 2020
1 parent 06b4b02 commit 6535ea1
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 79 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## v2.0.xx - 2020.06.xx
- Remove deprecated options (See [MIGRATION](MIGRATION.md))
- Use abstractions instead of reflection types in public api (See [MIGRATION](MIGRATION.md))
- Fix nullability issues with Nullable Reference Types
- Add Roslyn support
- Add dotnet tool

## v1.10.3 - 2020.05.28
- Fix eslint-ignore comment
- Add public modifier to function definition
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<Target Name="SetNuSpecProperties" BeforeTargets="GenerateNuspec" DependsOnTargets="GetBuildVersion">
<PropertyGroup>
<Authors>Eugene Tihonov</Authors>
<Authors>Eugene Tihonov, Pavel Vostretsov</Authors>
<PackageDescription>A tool that can generate TypeScript types from C# classes</PackageDescription>
<PackageTags>TypeScript CodeGenerator</PackageTags>
<RepositoryType>git</RepositoryType>
Expand Down
10 changes: 9 additions & 1 deletion MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,12 @@ public static class TypeScriptGeneratorHelpers
+ return typeGenerator.ResolveType(type).ReferenceFrom(type, typeScriptUnit, typeGenerator);
+ }
}
```
```

## Roslyn

When using Roslyn to generate TypeScript, Customization code is preprocessed, replacing `TypeInfo.From<T>()` and `TypeInfo.From(typeof(T))` invocations with `RoslynTypeInfo` instances and then compiled to in-memory assembly. Therefore, several changes to customization code are required to use Roslyn:

- There should be no `typeof(T)` invocations not wrapped with `TypeInfo.From()`
- All customization-related code should be in the same namespace
- Customization-related code should not depend on any third party packages
80 changes: 35 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# TypeScript.ContractGenerator

A tool that can generate TypeScript or Flow types from C# classes
A tool that can generate TypeScript types from C# classes

| | Build Status
|--------------|:--------------:
Expand Down Expand Up @@ -35,7 +35,7 @@ Then generate TypeScript files with:

```csharp
var generator = new TypeScriptGenerator(TypeScriptGenerationOptions.Default, CustomTypeGenerator.Null, new RootTypesProvider(typeof(SecondType)));
generator.GenerateFiles("./output", JavaScriptTypeChecker.TypeScript);
generator.GenerateFiles("./output");
```

By default, this will generate file with name `.ts` with following content:
Expand All @@ -58,36 +58,9 @@ If you want generated files to have different name or to generate some typings d

## Generation options

### EnumGenerationMode
### LinterDisableMode

This options is set to `FixedStringsAndDictionary` by default.

```csharp
public enum EnumGenerationMode
{
FixedStringsAndDictionary = 0,
TypeScriptEnum = 1,
}
```

Setting option value equal to `FixedStringsAndDictionary` produces following output:

```ts
export type SomeEnum = 'A' | 'B';
export const SomeEnums = {
['A']: ('A') as SomeEnum,
['B']: ('B') as SomeEnum,
};
```

Option value `TypeScriptEnum` produces following:

```ts
export enum SomeEnum {
A = 'A',
B = 'B',
}
```
Use `/* eslint-disable */` or `// tslint:disable` comment in generated files. `EsLint` is default option.

### EnableOptionalProperties

Expand All @@ -102,27 +75,44 @@ export type SomeType = {
```
When **disabled**, all properties produced as required.

### EnableExplicitNullability

This option is **enabled** by default. When **enabled** produces nullable types for members which may contain nulls.

```ts
export type SomeType = {
nullablePropertyDefinition: null | string;
nonNullablePropertyDefinition: string;
};
```

When **disabled** produces all types as-is.

### UseGlobalNullable

This option is **disabled** by default. When **enabled**, global `Nullable<T>` is used instead of union `null | T`

### NullabilityMode

This option is set to `Pessimistic` by default. When set to `Pessimistic`, generates `Nullable` property for properties that have no nullability attributes. When set to `Optimistic`, generates not null property for properties that have no nullability attributes.
NullabilityMode has 4 options:
- None - all generated properties are not null
- Pessimistic (default) - generates `Nullable` property for properties that have no JetBrains nullability attributes
- Optimistic - generates not null property for properties that have no JetBrains nullability attributes
- NullableReference - generates not null properties based on C# 8 Nullable Reference Type attributes

Options `Pessimistic` or `Optimistic` can be combined with `NullableReference` option, this way generator first looks for C# 8 Nullable Reference Type attributes, then JetBrains nullability attributes

## Attributes

There is `ContractGeneratorIgnore` attribute that can be applied to properties and makes generator skip current property.

## Roslyn usage

To use Roslyn you should get a `Compilation` object of your project. It can be done with helper method `AdhocProject.GetCompilation(string[] directories, string[] assemblies)`.
You can then get customization info from this compilation by calling extension method `compilation.GetCustomization()` and call `TypeScriptGenerator` with this customization:
```csharp
var (customTypeGenerator, typesProvider) = AdhocProject.GetCompilation(directories, assemblies).GetCustomization();
var typeGenerator = new TypeScriptGenerator(options, customTypeGenerator, typesProvider);
typeGenerator.GenerateFiles(outputDirectory);
```

## dotnet tool usage

Install tool with command:

`dotnet tool install -g SkbKontur.TypeScript.ContractGenerator.Cli`

Use tool with command:

`dotnet ts-gen --assembly ./Api/bin/Api.dll --outputDir ./src/Api`

dotnet tool also supports Roslyn:

`dotnet ts-gen --directory ./Api;./Core --assembly ./External/Dependency.dll --outputDir ./src/Api`
2 changes: 1 addition & 1 deletion TypeScript.ContractGenerator.Cli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ private static void GenerateByOptions(Options o)

if (o.Assembly.Count() != 1 || o.Directory.Any())
{
var (customTypeGenerator, typesProvider) = RoslynCustomizationProvider.GetCustomization(o.Directory.ToArray(), o.Assembly.ToArray());
var (customTypeGenerator, typesProvider) = AdhocProject.GetCompilation(o.Directory.ToArray(), o.Assembly.ToArray()).GetCustomization();
var typeGenerator = new TypeScriptGenerator(o.ToTypeScriptGenerationOptions(), customTypeGenerator, typesProvider);
typeGenerator.GenerateFiles(o.OutputDirectory);
return;
Expand Down
5 changes: 3 additions & 2 deletions TypeScript.ContractGenerator.Roslyn/AdhocProject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ public static Project FromDirectory(params string[] directories)
return project;
}

public static Compilation GetCompilation(params string[] directories)
public static Compilation GetCompilation(string[] directories, string[] assemblies)
{
var project = FromDirectory(directories);
var compilation = project.GetCompilationAsync().GetAwaiter().GetResult()!;
return compilation.AddReferences(GetMetadataReferences());
return compilation.AddReferences(GetMetadataReferences())
.AddReferences(assemblies.Select(x => MetadataReference.CreateFromFile(x)));
}

public static Assembly CompileAssembly(SyntaxTree[] tree)
Expand Down
23 changes: 0 additions & 23 deletions TypeScript.ContractGenerator.Roslyn/RoslynCustomizationProvider.cs

This file was deleted.

17 changes: 14 additions & 3 deletions TypeScript.ContractGenerator.Roslyn/RoslynTypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@ public static IAttributeInfo[] GetAttributesInfo(this ISymbol symbol)
return symbol.GetAttributes().Select(x => (IAttributeInfo)new RoslynAttributeInfo(x)).ToArray();
}

public static SyntaxTree[] GetCustomGenerationTypes(this Compilation compilation)
public static (ICustomTypeGenerator, IRootTypesProvider) GetCustomization(this Compilation compilation)
{
return GetNamespaceTypes(compilation, x => !x.IsEqualTo<RootTypesProvider>() &&
x.Interfaces.Any(i => i.IsEqualTo<IRootTypesProvider>()));
var customGenerationTypes = GetCustomGenerationTypes(compilation);
var assembly = AdhocProject.CompileAssembly(customGenerationTypes);

var customTypeGenerator = assembly.GetImplementations<ICustomTypeGenerator>().Single();
var typesProvider = assembly.GetImplementations<IRootTypesProvider>().Single();

return (customTypeGenerator, typesProvider);
}

public static bool IsEqualTo<T>(this ITypeSymbol typeSymbol)
Expand Down Expand Up @@ -53,5 +58,11 @@ private static IEnumerable<INamedTypeSymbol> GetNestedTypes(INamedTypeSymbol typ
foreach (var nestedType in type.GetTypeMembers().SelectMany(GetNestedTypes))
yield return nestedType;
}

private static SyntaxTree[] GetCustomGenerationTypes(Compilation compilation)
{
return GetNamespaceTypes(compilation, x => !x.IsEqualTo<RootTypesProvider>() &&
x.Interfaces.Any(i => i.IsEqualTo<IRootTypesProvider>()));
}
}
}
2 changes: 1 addition & 1 deletion TypeScript.ContractGenerator.Tests/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected static (ICustomTypeGenerator, IRootTypesProvider) GetCustomization<TTy
IRootTypesProvider rootTypesProvider;
if (typeof(TTypesProvider) == typeof(RoslynTypesProvider))
{
var compilation = AdhocProject.GetCompilation($"{projectDir}/Types", $"{projectDir}/CustomTypeGenerators");
var compilation = AdhocProject.GetCompilation(new[] {$"{projectDir}/Types", $"{projectDir}/CustomTypeGenerators"}, new string[0]);
rootTypesProvider = (IRootTypesProvider)Activator.CreateInstance(typeof(TTypesProvider), compilation, rootTypes)!;
customTypeGenerator = customGeneratorType == null ? CustomTypeGenerator.Null : RoslynCustomTypeGenerator.GetCustomTypeGenerator(compilation, customGeneratorType);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="DiffPlex" Version="1.6.2" />
<PackageReference Include="DiffPlex" Version="1.6.3" />
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.6.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
Expand Down
2 changes: 1 addition & 1 deletion version.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "2.0-pre10",
"version": "2.0",
"assemblyVersion": {
"precision": "build"
},
Expand Down

0 comments on commit 6535ea1

Please sign in to comment.