Skip to content

Commit

Permalink
Merge branch 'ItielBeeri-files-hierarchy'
Browse files Browse the repository at this point in the history
  • Loading branch information
CodySchrank committed Nov 17, 2019
2 parents 78abfaf + e17ba40 commit 7e026bf
Show file tree
Hide file tree
Showing 8 changed files with 113 additions and 18 deletions.
2 changes: 1 addition & 1 deletion Example/Example.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<ItemGroup>
<!-- <PackageReference Include="MTT" Version="0.5.9-*" PrivateAssets="All" /> -->
<PackageReference Include="MTT" Version="0.6.2" />
<PackageReference Include="MTT" Version="0.6.3" />
</ItemGroup>

<Target Name="ConvertMain" BeforeTargets="PrepareForBuild">
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ _ConvertDirectory_ is the output directory of the ts interfaces

_AutoGeneratedTag_ (default true) show "/\* Auto Generated \*/" at the top of every file

_EnumValues_ if set to _Strings_, generates typescript [string enums](https://www.typescriptlang.org/docs/handbook/enums.html#string-enums) instead of the default enums with numeric values which precisely reflect the C# enums
_EnumValues_ (default int) if set to _Strings_, generates typescript [string enums](https://www.typescriptlang.org/docs/handbook/enums.html#string-enums)

_PathStyle_ (default dont change) if set to _Kebeb_, changes the file and directory names to kebeb-case. If it isn't set, the default behaviour applies which leaves the directory names as they are in the working directory and change the file names to camelCase.

## Example

Expand All @@ -34,7 +36,7 @@ _EnumValues_ if set to _Strings_, generates typescript [string enums](https://ww
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MTT" Version="0.6.1"/>
<PackageReference Include="MTT" Version="0.6.3"/>
</ItemGroup>

<Target Name="Convert" BeforeTargets="PrepareForBuild">
Expand Down Expand Up @@ -119,6 +121,7 @@ It correctly converts the following C# types to the equivalent typescript:
* Enumerbale
* IEnumerable
* ICollection
* IList
* Enum
* Optional
* virtual
Expand Down
17 changes: 15 additions & 2 deletions Source/MTT/ConvertMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,21 @@ public class ConvertMain : MSBuildTask
/// </summary>
public string ConvertDirectory { get; set; }

/// <summary>
/// Determines the naming style of the generated files and folders
/// </summary>
public string PathStyle
{
get => _pathStyle.ToString();
set => _pathStyle = (PathStyle)Enum.Parse(typeof(PathStyle), value);
}

/// <summary>
/// Comments at the top of each file that it was auto generated
/// </summary>
public bool AutoGeneratedTag { get; set; } = true; //default value if one is not provided;

private EnumValues _enumValues = MTT.EnumValues.Default;


/// <summary>
/// Determines whether to generate numeric or string values in typescript enums
/// </summary>
Expand All @@ -40,6 +48,10 @@ public string EnumValues

private readonly ConvertService convertService;

private EnumValues _enumValues = MTT.EnumValues.Default;

private PathStyle _pathStyle = MTT.PathStyle.Default;

public ConvertMain()
{
convertService = new ConvertService(Log.LogMessage);
Expand All @@ -53,6 +65,7 @@ public override bool Execute()
convertService.ConvertDirectory = ConvertDirectory;
convertService.WorkingDirectory = WorkingDirectory;
convertService.EnumValues = _enumValues;
convertService.PathStyle = _pathStyle;

var result = convertService.Execute();

Expand Down
82 changes: 73 additions & 9 deletions Source/MTT/ConvertService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

Expand Down Expand Up @@ -34,6 +35,11 @@ public class ConvertService
/// Determines whether to generate numeric or string values in typescript enums
/// </summary>
public EnumValues EnumValues { get; internal set; }

/// <summary>
/// Determines the naming style of the generated files and folders
/// </summary>
public PathStyle PathStyle { get; set; }

private List<ModelFile> Models { get; set; }

Expand Down Expand Up @@ -166,10 +172,22 @@ private void LoadModels(string dirname = "")
}
}

var workingUri = new Uri(EnsureTrailingSlash(LocalWorkingDir));
var dirUri = new Uri(dirname);
var relativePath = workingUri.MakeRelativeUri(dirUri).OriginalString;
foreach (var file in files)
{
AddModel(file, dirname.Replace(LocalWorkingDir, String.Empty));
AddModel(file, relativePath);
}
}

private string EnsureTrailingSlash(string str)
{
if (!str.EndsWith("/") && !str.EndsWith("\\"))
{
str += "\\";
}
return str;
}

private void AddModel(string file, string structure = "")
Expand Down Expand Up @@ -283,13 +301,23 @@ private void BreakDown()
if (line.StrictContains("class") && line.Contains(":"))
{
string inheritance = modLine[modLine.Count - 1];
file.Inherits = inheritance;
file.InheritenceStructure = Find(inheritance, file);

// Ignore interfaces by convention
if (!(inheritance.StartsWith("I") && inheritance.Length > 1 && char.IsUpper(inheritance[1])))
{
var commaIndex = inheritance.IndexOf(',');
if (commaIndex > 0)
{
inheritance = inheritance.Substring(0, commaIndex);
}
file.Inherits = inheritance;
file.InheritenceStructure = Find(inheritance, file);

/** If the class only contains inheritence we need a place holder obj */
LineObject obj = new LineObject() { };
file.Objects.Add(obj);

/** If the class only contains inheritence we need a place holder obj */
LineObject obj = new LineObject() { };
file.Objects.Add(obj);
}
}

// Class property
Expand Down Expand Up @@ -387,7 +415,14 @@ private void Convert()
{
var directoryPath = Path.Combine(LocalConvertDir, file.Structure);

string fileName = ToCamelCase(file.Name + ".ts");
var relativePath = PathStyle == PathStyle.Kebab
? ToKebabCasePath(file.Structure)
: file.Structure;

DirectoryInfo di = Directory.CreateDirectory(Path.Combine(LocalConvertDir, relativePath));
di.Create();

string fileName = (PathStyle == PathStyle.Kebab ? ToKebabCase(file.Name) : ToCamelCase(file.Name)) + ".ts";
log("Creating file {0}", fileName);
string saveDir = Path.Combine(directoryPath, fileName);

Expand Down Expand Up @@ -445,7 +480,9 @@ private void Convert()
if (!String.IsNullOrEmpty(file.Inherits))
{
importing = true;
var import = "import { " + file.Inherits + " } from '" + file.InheritenceStructure + "';";

var import = "import { " + file.Inherits + " } from \""
+ (PathStyle == PathStyle.Kebab ? ToKebabCasePath(file.InheritenceStructure) : file.InheritenceStructure) + "\";";

if (!imports.Contains(import))
{
Expand All @@ -457,7 +494,8 @@ private void Convert()
if (obj.UserDefined)
{
importing = true;
var import = "import { " + obj.Type + " } from '" + obj.UserDefinedImport + "';";
var import = "import { " + obj.Type + " } from \""
+ (PathStyle == PathStyle.Kebab ? ToKebabCasePath(obj.UserDefinedImport) : obj.UserDefinedImport) + "\";";

if (!imports.Contains(import))
{
Expand Down Expand Up @@ -557,6 +595,32 @@ private string ToPascalCase(string str)
return Char.ToUpperInvariant(str[0]) + str.Substring(1);
}

private string ToKebabCase(string str)
{
if (String.IsNullOrEmpty(str))
return str;

var words = new List<string>();
var wordStart = 0;
int i;
for (i = 1; i < str.Length; i++)
{
if (char.IsUpper(str[i]))
{
words.Add(str.Substring(wordStart, i - wordStart));
wordStart = i;
}
}
words.Add(str.Substring(wordStart, i - wordStart));

return string.Join("-", words.Where(w => !string.IsNullOrEmpty(w)).Select(w => w.ToLower()));
}

private string ToKebabCasePath(string path)
{
return string.Join("/", path.Split('/').Select(segment => ToKebabCase(segment)));
}

private bool CheckIsArray(string type)
{
return type.Contains("[]") ||
Expand Down
2 changes: 1 addition & 1 deletion Source/MTT/MTT.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<!-- Change the default location where NuGet will put the build output -->
<BuildOutputTargetFolder>tasks</BuildOutputTargetFolder>
<!-- set the version automatically -->
<VersionPrefix>0.6.2</VersionPrefix>
<VersionPrefix>0.6.3</VersionPrefix>
<!--
The suffix is required because nuget will only update if the package is newer, this tricks it.
note: 0.1.5 has precedence over 0.1.5-build123412341
Expand Down
2 changes: 1 addition & 1 deletion Source/MTT/ModelFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public ModelFile() {

public string PrintBasic() {
return Name.ToString()
+ " : " + Structure.ToString();
+ " : /" + Structure.ToString();
}

public override string ToString() {
Expand Down
15 changes: 15 additions & 0 deletions Source/MTT/PathStyle.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace MTT
{
public enum PathStyle
{
/// <summary>
/// Directories are named as they're named in the source. File names are converted to camelCase.
/// </summary>
Default,

/// <summary>
/// Directory and file names are converted to kebab-case.
/// </summary>
Kebab
}
}
4 changes: 2 additions & 2 deletions Source/MTTRunner.Tests/UnitTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ public void AutoGeneratedExists() {
public void DifferentDirImportStatementExists() {
string[] lines = System.IO.File.ReadAllLines(VehicleFile);

Assert.That(lines[2], Is.EqualTo("import { Entity } from './../entity';"));
Assert.That(lines[2], Is.EqualTo("import { Entity } from \"./../entity\";"));
}

[Test]
public void SameDirImportStatementExists() {
string[] lines = System.IO.File.ReadAllLines(VehicleFile);

Assert.That(lines[3], Is.EqualTo("import { VehicleState } from './vehicleState';"));
Assert.That(lines[3], Is.EqualTo("import { VehicleState } from \"./vehicleState\";"));
}

[Test]
Expand Down

0 comments on commit 7e026bf

Please sign in to comment.