Skip to content

Commit a2e74c3

Browse files
authored
Merge pull request #3 from myunitytools/feature/template-preview
[Feature] Add namespace module and preview
2 parents f6e765c + dd4c56d commit a2e74c3

36 files changed

+788
-162
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ Change Log
33

44
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
55

6+
## [3.0.0] - 2022-10-03
7+
- Added: Namespace settings module.
8+
- Added: Live preview of namespace and signature changes.
9+
- Changed: Cached data is now a single entry instead of multiple entries in EditorPrefs.
10+
611
## [2.2.0] - 2022-09-13
712
- Added: Support for ISO date format by default.
813

@@ -42,6 +47,7 @@ All notable changes to this project will be documented in this file. This projec
4247
## [1.0.0] - 2019-07-27
4348
- Initial Asset Store release.
4449

50+
[3.0.0]: https://github.com/myunitytools/script-template/compare/2.2.0...3.0.0
4551
[2.2.0]: https://github.com/myunitytools/script-template/compare/2.1.0...2.2.0
4652
[2.1.0]: https://github.com/myunitytools/script-template/compare/2.0.1...2.1.0
4753
[2.0.1]: https://github.com/myunitytools/script-template/compare/2.0.0...2.0.1

Editor/IndentPattern.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* IndentPattern.cs
3+
* Created by: João Borks [[email protected]]
4+
* Created on: 2021-10-02
5+
*/
6+
7+
namespace MyUnityTools.ScriptTemplates
8+
{
9+
public enum IndentPattern
10+
{
11+
Spaces,
12+
Tabs
13+
};
14+
}

Editor/IndentPattern.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"name": "MyUnityTools.ScriptTemplates",
3+
"rootNamespace": "",
4+
"references": [
5+
"GUID:2fa312fb52fb6b547b332c9fb4cb6d79"
6+
],
7+
"includePlatforms": [
8+
"Editor"
9+
],
10+
"excludePlatforms": [],
11+
"allowUnsafeCode": false,
12+
"overrideReferences": false,
13+
"precompiledReferences": [],
14+
"autoReferenced": true,
15+
"defineConstraints": [],
16+
"versionDefines": [],
17+
"noEngineReferences": false
18+
}

Editor/NamespaceSettings.cs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* NamespaceSettings.cs
3+
* Created by: João Borks [[email protected]]
4+
* Created on: 2021-10-02
5+
*/
6+
7+
using System;
8+
9+
namespace MyUnityTools.ScriptTemplates
10+
{
11+
[Serializable]
12+
public struct NamespaceSettings
13+
{
14+
public bool Enabled;
15+
public bool UseAssemblyDefinition;
16+
public string DefaultNamespace;
17+
public IndentPattern IndentPattern;
18+
public int IndentMultiplier;
19+
20+
public override bool Equals(object obj)
21+
{
22+
return obj is NamespaceSettings settings &&
23+
Enabled == settings.Enabled &&
24+
UseAssemblyDefinition == settings.UseAssemblyDefinition &&
25+
DefaultNamespace == settings.DefaultNamespace &&
26+
IndentPattern == settings.IndentPattern &&
27+
IndentMultiplier == settings.IndentMultiplier;
28+
}
29+
30+
public override int GetHashCode()
31+
{
32+
return HashCode.Combine(Enabled, UseAssemblyDefinition, DefaultNamespace, IndentPattern, IndentMultiplier);
33+
}
34+
35+
public bool IsValid() => !Enabled || !string.IsNullOrWhiteSpace(DefaultNamespace);
36+
37+
public bool IsEmpty() => this == new NamespaceSettings();
38+
39+
public static bool operator ==(NamespaceSettings left, NamespaceSettings right)
40+
{
41+
return left.Equals(right);
42+
}
43+
44+
public static bool operator !=(NamespaceSettings left, NamespaceSettings right)
45+
{
46+
return !(left == right);
47+
}
48+
}
49+
}

Editor/NamespaceSettings.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Editor/ScriptKeywordProcessor.cs renamed to Editor/ScriptAssetProcessor.cs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,46 @@
11
/**
2-
* ScriptKeywordProcessor.cs
2+
* ScriptAssetProcessor.cs
33
* Created by: João Borks [[email protected]]
44
* Created on: 2019-02-19
55
* Tips from https://forum.unity3d.com/threads/c-script-template-how-to-make-custom-changes.273191/
66
*/
77

8-
using UnityEngine;
8+
using System.IO;
99
using UnityEditor;
10-
using System.Globalization;
10+
using UnityEngine;
1111

1212
namespace MyUnityTools.ScriptTemplates
1313
{
1414
/// <summary>
1515
/// This class listens to <see cref="AssetModificationProcessor"/>'s <see cref="OnWillCreateAsset(string)"/> event that executes whenever a new asset is created
1616
/// and replaces the keywords on scripts to what we defined on our <see cref="ScriptTemplatesEditor"/>
1717
/// </summary>
18-
public class ScriptKeywordProcessor : AssetModificationProcessor
18+
public class ScriptAssetProcessor : AssetModificationProcessor
1919
{
2020
public static void OnWillCreateAsset(string path)
2121
{
2222
path = path.Replace(".meta", "");
23-
int index = path.LastIndexOf(".");
23+
var assetPath = path;
24+
var index = path.LastIndexOf(".");
2425
if (index < 0)
2526
return;
2627

27-
string file = path.Substring(index);
28+
var file = path.Substring(index);
2829
if (file != ".cs")
2930
return;
3031

3132
index = Application.dataPath.LastIndexOf("Assets");
3233
path = Application.dataPath.Substring(0, index) + path;
33-
if (!System.IO.File.Exists(path))
34+
if (!File.Exists(path))
3435
return;
3536

36-
string fileContent = System.IO.File.ReadAllText(path);
37-
fileContent = fileContent.Replace("#AUTHOR#", $"{EditorPrefs.GetString(ScriptTemplatesEditor.AuthorNameKey)}{(EditorPrefs.HasKey(ScriptTemplatesEditor.AuthorEmailKey) ? $" [{EditorPrefs.GetString(ScriptTemplatesEditor.AuthorEmailKey)}]" : string.Empty)}");
38-
fileContent = fileContent.Replace("#CREATIONDATE#", EditorPrefs.GetBool(ScriptTemplatesEditor.UseLocalDateKey, false) ? $"{System.DateTime.Now.ToString("d", CultureInfo.CurrentCulture)} ({CultureInfo.CurrentCulture.Name})" : System.DateTime.Now.ToString("yyyy-MM-dd"));
37+
var keywordReplacer = new ScriptKeywordReplacer(ScriptTemplateSettings.FromEditorPrefs());
38+
39+
var fileContent = File.ReadAllText(path);
40+
41+
fileContent = keywordReplacer.ProcessScriptTemplate(fileContent, assetPath);
3942

40-
System.IO.File.WriteAllText(path, fileContent);
43+
File.WriteAllText(path, fileContent);
4144
AssetDatabase.Refresh();
4245
}
4346
}

Editor/ScriptKeywordReplacer.cs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
* ScriptKeywordReplacer.cs
3+
* Created by: João Borks [[email protected]]
4+
* Created on: 2022-09-21
5+
*/
6+
7+
using System;
8+
using System.Globalization;
9+
using System.Text;
10+
using System.Text.RegularExpressions;
11+
using UnityEditor.Compilation;
12+
13+
namespace MyUnityTools.ScriptTemplates
14+
{
15+
public class ScriptKeywordReplacer
16+
{
17+
const string _scriptNameKeyword = "#SCRIPTNAME#";
18+
const string _namespaceKeyword = "#NAMESPACE#";
19+
const string _signatureKeyword = "#SIGNATURE#";
20+
const string _authorKeyword = "#AUTHOR#";
21+
const string _dateKeyword = "#CREATIONDATE#";
22+
23+
static readonly string _signatureTemplate =
24+
"/**\n" +
25+
" * " + _scriptNameKeyword + ".cs\n" +
26+
" * Created by: " + _authorKeyword + "\n" +
27+
" * Created on: " + _dateKeyword + "\n" +
28+
" */\n\n";
29+
30+
public string AuthorString => $"{_templateSettings.Signature.AuthorName}{(!string.IsNullOrWhiteSpace(_templateSettings.Signature.AuthorEmail) ? $" [{_templateSettings.Signature.AuthorEmail}]" : string.Empty)}";
31+
public string DateString => _templateSettings.Signature.UseLocalDateFormat ? $"{DateTime.Now.ToString("d", CultureInfo.CurrentCulture)} ({CultureInfo.CurrentCulture.Name})" : DateTime.Now.ToString("yyyy-MM-dd");
32+
33+
readonly ScriptTemplateSettings _templateSettings;
34+
35+
public ScriptKeywordReplacer(ScriptTemplateSettings templateSettings)
36+
{
37+
_templateSettings = templateSettings;
38+
}
39+
40+
public string ProcessScriptTemplate(string scriptContent, string path)
41+
{
42+
Regex regex;
43+
if (_templateSettings.Namespace.Enabled)
44+
{
45+
var namespaceString = string.Empty;
46+
if (_templateSettings.Namespace.UseAssemblyDefinition)
47+
{
48+
namespaceString = CompilationPipeline.GetAssemblyRootNamespaceFromScriptPath(path);
49+
if (string.IsNullOrWhiteSpace(namespaceString))
50+
namespaceString = CompilationPipeline.GetAssemblyNameFromScriptPath(path).Replace(".dll", string.Empty);
51+
}
52+
if (string.IsNullOrWhiteSpace(namespaceString) || namespaceString.StartsWith("Assembly-CSharp"))
53+
namespaceString = _templateSettings.Namespace.DefaultNamespace;
54+
55+
regex = new Regex(@"(?<=#NAMESPACE#)([\s\S]*?(\n|\r|\r\n)}(\n|\r|\r\n)?)");
56+
if (regex.IsMatch(scriptContent))
57+
{
58+
var match = regex.Match(scriptContent);
59+
var indentString = GetIndentReplacement();
60+
var indentedMatch = match.Value.Replace("\n", indentString);
61+
scriptContent = scriptContent
62+
.Replace(match.Value, indentedMatch)
63+
.Replace(_namespaceKeyword, "namespace " + namespaceString + "\n{" + indentString);
64+
65+
scriptContent = scriptContent.Insert(scriptContent.Length, "\n}");
66+
}
67+
}
68+
69+
scriptContent = scriptContent.Replace(_namespaceKeyword, string.Empty);
70+
71+
var stringBuilder = new StringBuilder(scriptContent);
72+
stringBuilder
73+
.Replace(_signatureKeyword, _templateSettings.Signature.Enabled ? _signatureTemplate.Replace(_authorKeyword, AuthorString).Replace(_dateKeyword, DateString) : string.Empty)
74+
.Replace(_scriptNameKeyword, System.IO.Path.GetFileNameWithoutExtension(path));
75+
return Regex.Replace(stringBuilder.ToString(), @"\r\n|\n\r|\n|\r", Environment.NewLine);
76+
}
77+
78+
string GetIndentReplacement()
79+
{
80+
string indentValue = _templateSettings.Namespace.IndentPattern == IndentPattern.Spaces ? " " : "\t";
81+
var stringBuilder = new StringBuilder("\n");
82+
83+
for (int i = 0; i < _templateSettings.Namespace.IndentMultiplier; i++)
84+
stringBuilder.Append(indentValue);
85+
return stringBuilder.ToString();
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)