Skip to content

Commit 945b49b

Browse files
committed
Legacy reference files
1 parent cbf316c commit 945b49b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+852
-172
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
using System;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
using System.IO;
5+
using System.Linq;
6+
#if UNITY_EDITOR
7+
using UnityEditor;
8+
#endif
9+
using UnityEngine;
10+
using UnityOpenApi;
11+
using UnityOpenApi.ApiModels.OpenApi;
12+
13+
14+
public class ApiAssetsGenerator
15+
{
16+
public void GenerateOrUpdateApiAssets(string basePath, OpenApi3 openApi3, bool considerOptionHttpWord = false)
17+
{
18+
19+
string apiConfigAssetFilename = openApi3.info.title;
20+
string localApiDirectory = CreateDirectoryIfNotExists(basePath, openApi3.info.title);
21+
22+
// create paths subdirectory
23+
string resDirectoryPath = CreateDirectoryIfNotExists(localApiDirectory, "resources");
24+
25+
// create data model directory
26+
string dataModelsDirectory = CreateDirectoryIfNotExists(localApiDirectory, "data_model");
27+
28+
29+
// Create/update api config
30+
ApiConfig apiConfig = GetOrCreateAsset<ApiConfig>(localApiDirectory, apiConfigAssetFilename);
31+
32+
apiConfig.rawData = openApi3;
33+
34+
//apiConfig.baseUri = openApi3.servers[0].url.Replace(
35+
// "/{basePath}"
36+
// , openApi3.servers[0].variables.basePath._default);
37+
38+
// for now consider only first server
39+
apiConfig.serverVariableValues = new List<ApiConfig.ServerVariableValue>();
40+
foreach (var sv in openApi3.servers[0].variables)
41+
{
42+
apiConfig.serverVariableValues.Add(new ApiConfig.ServerVariableValue()
43+
{
44+
varName = sv.Key,
45+
varValue = sv.Value.@default
46+
});
47+
}
48+
49+
// Authorization resources
50+
apiConfig.authorizers = new List<ApiAuthorizer>();
51+
if (openApi3.components.securitySchemes != null)
52+
{
53+
foreach (var s in openApi3.components.securitySchemes)
54+
{
55+
switch (s.Value.@in)
56+
{
57+
case OpenApi3ParameterIn.query:
58+
break;
59+
case OpenApi3ParameterIn.path:
60+
break;
61+
case OpenApi3ParameterIn.header:
62+
string fName = apiConfigAssetFilename + "_auth_" + s.Key;
63+
ApiHeaderAuthorizer hAuth = GetOrCreateAsset<ApiHeaderAuthorizer>(localApiDirectory, fName);
64+
hAuth.authName = s.Key;
65+
hAuth.securityScheme = s.Value;
66+
apiConfig.authorizers.Add(hAuth);
67+
break;
68+
case OpenApi3ParameterIn.cookie:
69+
break;
70+
default:
71+
break;
72+
}
73+
}
74+
}
75+
76+
// create/update individual api resources
77+
foreach (var openApiPath in openApi3.paths)
78+
{
79+
80+
string resSubdirectory = CreateDirectoryIfNotExists(resDirectoryPath, openApiPath.Key);
81+
82+
//string resUri = apiConfig.baseUri;
83+
//if (openApiPath.Key != "/") resUri += openApiPath.Key;
84+
85+
foreach (var res in openApiPath.Value)
86+
{
87+
string fName = apiConfig.name
88+
+ openApiPath.Key.Replace("/", "_")
89+
+ "_"
90+
+ res.Key.ToString().ToUpper();
91+
92+
if (considerOptionHttpWord == false && res.Key == OpenApi3HttpWords.options)
93+
{
94+
Debug.Log("Skipping OPTION http resource for " + fName);
95+
continue;
96+
}
97+
98+
ApiResource apiResource = GetOrCreateAsset<ApiResource>(resSubdirectory, fName);
99+
100+
101+
apiResource.apiConfig = apiConfig;
102+
apiResource.httpWord = res.Key;
103+
apiResource.path = openApiPath.Key;
104+
apiResource.method = res.Value;
105+
apiResource.ResetParametersValues();
106+
107+
if (res.Value.security != null && res.Value.security.Count > 0)
108+
{
109+
string authName = res.Value.security[0].First().Key;
110+
apiResource.apiAuthorizer = apiConfig.GetAuthorizer(authName);
111+
if (apiResource.apiAuthorizer == null)
112+
{
113+
Debug.LogError("Can't find authorizer " + authName + " for " + apiResource.name);
114+
}
115+
}
116+
117+
EditorUtility.SetDirty(apiResource);
118+
}
119+
}
120+
121+
AssetDatabase.Refresh();
122+
AssetDatabase.SaveAssets();
123+
124+
}
125+
126+
private T GetOrCreateAsset<T>(string path, string subpath, string ext = ".asset", bool setDirty = true) where T : ScriptableObject
127+
{
128+
if (path[path.Length - 1] != '/') path += "/";
129+
if (subpath[0] == '/') subpath = subpath.Substring(1);
130+
string assetFullPath = path + subpath + ext;
131+
T asset = AssetDatabase.LoadAssetAtPath<T>(assetFullPath);
132+
if (asset == null)
133+
{
134+
asset = ScriptableObject.CreateInstance<T>();
135+
Debug.Log("Creating new asset at: " + assetFullPath);
136+
AssetDatabase.CreateAsset(asset, assetFullPath);
137+
}
138+
if (setDirty)
139+
{
140+
EditorUtility.SetDirty(asset);
141+
}
142+
return asset;
143+
}
144+
145+
private string CreateDirectoryIfNotExists(params string[] paths)
146+
{
147+
string path = string.Empty;
148+
foreach (var p in paths)
149+
{
150+
if (string.IsNullOrEmpty(p))
151+
{
152+
continue;
153+
}
154+
string pathPart = p;
155+
char separator = '/';
156+
if (pathPart[0] != separator)
157+
{
158+
pathPart = separator + pathPart;
159+
}
160+
if (pathPart[pathPart.Length - 1] == separator)
161+
{
162+
pathPart = pathPart.Remove(pathPart.Length - 1);
163+
}
164+
path += pathPart;
165+
}
166+
// remove the initial slash
167+
path = path.Substring(1);
168+
if (Directory.Exists(path) == false)
169+
{
170+
Debug.Log("Creating directory: " + path);
171+
Directory.CreateDirectory(path);
172+
}
173+
return path;
174+
}
175+
}

Assets/Editor/ApiAssetsGenerator.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.

Assets/Editor/AssetsHelper.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
using System.Collections;
2+
using System.Collections.Generic;
3+
using UnityEngine;
4+
using UnityEditor;
5+
6+
public class AssetsHelper
7+
{
8+
public static T GetOrCreateScriptableObject<T>(string path, string subpath, string ext = ".asset", bool setDirty = true) where T : ScriptableObject
9+
{
10+
if (path[path.Length - 1] != '/') path += "/";
11+
if (subpath[0] == '/') subpath = subpath.Substring(1);
12+
string assetFullPath = path + subpath + ext;
13+
T asset = AssetDatabase.LoadAssetAtPath<T>(assetFullPath);
14+
if (asset == null)
15+
{
16+
asset = ScriptableObject.CreateInstance<T>();
17+
Debug.Log("Creating new asset at: " + assetFullPath);
18+
AssetDatabase.CreateAsset(asset, assetFullPath);
19+
} else
20+
{
21+
Debug.Log("Getting reference to the existing asset at: " + assetFullPath);
22+
}
23+
if (setDirty)
24+
{
25+
EditorUtility.SetDirty(asset);
26+
}
27+
return asset;
28+
}
29+
}

Assets/Editor/AssetsHelper.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.
File renamed without changes.
File renamed without changes.

Assets/Editor/OpenApiParser.cs

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
using UnityEngine;
2+
using UnityEditor;
3+
using Microsoft.OpenApi.Readers;
4+
using System.IO;
5+
using Microsoft.OpenApi.Validations;
6+
using HttpMono;
7+
using Microsoft.OpenApi.Models;
8+
using UnityOpenApi;
9+
10+
[CreateAssetMenu(menuName = "Unity Open API/Parser")]
11+
public class OpenApiParser : ScriptableObject
12+
{
13+
[Header("Dependencies")]
14+
[SerializeField] private HttpAsset http = null;
15+
16+
private string _lastAssetPath = "Assets";
17+
18+
public void Parse(string json)
19+
{
20+
var stream = CreateStream(json);
21+
var parsed = new OpenApiStreamReader(new OpenApiReaderSettings
22+
{
23+
ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
24+
RuleSet = ValidationRuleSet.GetDefaultRuleSet()
25+
}).Read(stream, out var openApiDiagnostic);
26+
Debug.Log("Successfully parsed API Description: " + parsed.Info.Title);
27+
GenerateAssets(parsed);
28+
}
29+
30+
public void ParseFromUrl(string url)
31+
{
32+
http.HttpMono.Get(url, null, result =>
33+
{
34+
if (result.Ok)
35+
{
36+
Parse(result.Text);
37+
}
38+
else
39+
{
40+
Debug.Log(result.Error.Message);
41+
}
42+
});
43+
}
44+
45+
private MemoryStream CreateStream(string text)
46+
{
47+
var stream = new MemoryStream();
48+
var writer = new StreamWriter(stream);
49+
50+
writer.Write(text);
51+
writer.Flush();
52+
stream.Position = 0;
53+
54+
return stream;
55+
}
56+
57+
public void GenerateAssets(OpenApiDocument openApiDocument)
58+
{
59+
string assetsPath = EditorUtility.OpenFolderPanel("Select assets folder", _lastAssetPath, "");
60+
_lastAssetPath = assetsPath;
61+
assetsPath = assetsPath.Substring(assetsPath.IndexOf("Assets"));
62+
ApiAsset apiAsset = AssetsHelper.GetOrCreateScriptableObject<ApiAsset>(assetsPath, openApiDocument.Info.Title);
63+
apiAsset.openApiDocument = openApiDocument;
64+
AssetDatabase.SaveAssets();
65+
}
66+
67+
}
68+
69+
[CustomEditor(typeof(OpenApiParser))]
70+
public class OpenApiParserEditor : Editor
71+
{
72+
string url = "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/uspto.yaml";
73+
TextAsset textAsset;
74+
public override void OnInspectorGUI()
75+
{
76+
base.OnInspectorGUI();
77+
78+
GUILayout.Space(10);
79+
80+
var t = (OpenApiParser)target;
81+
82+
GUILayout.BeginVertical();
83+
textAsset = (TextAsset)EditorGUILayout.ObjectField("API Asset", textAsset, typeof(TextAsset), false);
84+
if (GUILayout.Button("Parse From Asset"))
85+
{
86+
t.Parse(textAsset.text);
87+
}
88+
GUILayout.EndVertical();
89+
90+
GUILayout.Space(10);
91+
92+
GUILayout.BeginVertical();
93+
url = EditorGUILayout.TextField(new GUIContent("URL"), url);
94+
if (GUILayout.Button("Parse From Url"))
95+
{
96+
t.ParseFromUrl(url);
97+
}
98+
GUILayout.EndVertical();
99+
100+
}
101+
}

0 commit comments

Comments
 (0)