();
+ schemaJsonFiles.forEach(file -> {
+ requests.addAll(parseRequestsFromSchemaFile(file));
+ });
+ return requests;
+ }
+
+ /**
+ * Example JSON file content:
+ *
+ * {
+ * "paths": {
+ * "/apis/api.notification.halo.run/v1alpha1/notifiers/{name}/receiver-config": {
+ * "get": {},
+ * "post": {},
+ * }
+ * }
+ * }
+ *
+ */
+ private List parseRequestsFromSchemaFile(File file) {
+ var node = readFileToJson(file);
+ if (node == null || !node.has("paths")) {
+ return List.of();
+ }
+ var pathsNode = node.get("paths");
+ var requests = new ArrayList();
+ pathsNode.fields().forEachRemaining(pathNode -> {
+ var requestPath = pathNode.getKey();
+ var methodsNode = pathNode.getValue();
+ if (methodsNode == null) {
+ return;
+ }
+ methodsNode.fieldNames().forEachRemaining(requestMethod -> {
+ requests.add(SimpleRequest.builder()
+ .path(requestPath)
+ .method(requestMethod)
+ .build());
+ });
+ });
+ return requests;
+ }
+
+ @Builder
+ record SimpleRequest(String path, String method) {
+ }
+
+ interface ApiResource {
+ boolean isResourceRequest();
+ }
+
+ @Builder
+ record ResourceRequest(String apiGroup, String resource, String name, String subResource,
+ String verb) implements ApiResource, Comparator {
+
+ @Override
+ public boolean isResourceRequest() {
+ return true;
+ }
+
+ @Override
+ public int compare(ResourceRequest o1, ResourceRequest o2) {
+ return Comparator.comparing(ResourceRequest::apiGroup)
+ .thenComparing(ResourceRequest::resource)
+ .compare(o1, o2);
+ }
+ }
+
+ @Builder
+ record NoneResourceRequest(String resourceUrl, String verb)
+ implements ApiResource {
+ @Override
+ public boolean isResourceRequest() {
+ return false;
+ }
+ }
+
+ @Nullable
+ ObjectNode readFileToJson(File file) {
+ if (!file.exists()) {
+ return null;
+ }
+ try {
+ JsonNode jsonNode = JsonUtils.mapper().readTree(file);
+ if (jsonNode.isObject()) {
+ return (ObjectNode) jsonNode;
+ }
+ return null;
+ } catch (IOException e) {
+ // ignore
+ log.warn("Failed to read JSON file: {}", file.getAbsolutePath());
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/run/halo/gradle/utils/JsonUtils.java b/src/main/java/run/halo/gradle/utils/JsonUtils.java
new file mode 100644
index 0000000..0d12cf7
--- /dev/null
+++ b/src/main/java/run/halo/gradle/utils/JsonUtils.java
@@ -0,0 +1,20 @@
+package run.halo.gradle.utils;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+
+public class JsonUtils {
+
+ private static final ObjectMapper mapper;
+
+ static {
+ mapper = new ObjectMapper();
+ mapper.registerModule(new JavaTimeModule());
+ mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
+ }
+
+ public static ObjectMapper mapper() {
+ return mapper;
+ }
+}
diff --git a/src/test/java/run/halo/gradle/role/RoleTemplateGenerateTaskTest.java b/src/test/java/run/halo/gradle/role/RoleTemplateGenerateTaskTest.java
new file mode 100644
index 0000000..07c4619
--- /dev/null
+++ b/src/test/java/run/halo/gradle/role/RoleTemplateGenerateTaskTest.java
@@ -0,0 +1,61 @@
+package run.halo.gradle.role;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests for {@link RoleTemplateGenerateTask}.
+ *
+ * @author guqing
+ * @since 0.3.0
+ */
+class RoleTemplateGenerateTaskTest {
+
+ @Test
+ void writeListAsStringTest() {
+ var role1 = new Role();
+ role1.getRules().add(Role.PolicyRule.builder()
+ .apiGroups(new String[] {"api.console.doc.halo.run"})
+ .resources(new String[] {"docs"})
+ .verbs(new String[] {"create"})
+ .build());
+ var role2 = new Role();
+ role2.getRules().add(Role.PolicyRule.builder()
+ .apiGroups(new String[] {"api.console.content.halo.run"})
+ .resources(new String[] {"posts"})
+ .verbs(new String[] {"get", "list"})
+ .build());
+ var result = RoleTemplateGenerateTask.writeListAsString(List.of(role1, role2));
+ assertThat(result).isEqualToIgnoringNewLines("""
+ ---
+ kind: Role
+ apiVersion: v1alpha1
+ metadata:
+ labels: {}
+ annotations: {}
+ rules:
+ - apiGroups:
+ - api.console.doc.halo.run
+ resources:
+ - docs
+ verbs:
+ - create
+ ---
+ kind: Role
+ apiVersion: v1alpha1
+ metadata:
+ labels: {}
+ annotations: {}
+ rules:
+ - apiGroups:
+ - api.console.content.halo.run
+ resources:
+ - posts
+ verbs:
+ - get
+ - list
+ """);
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/run/halo/gradle/role/RoleTemplateGeneratorTest.java b/src/test/java/run/halo/gradle/role/RoleTemplateGeneratorTest.java
new file mode 100644
index 0000000..b8233d9
--- /dev/null
+++ b/src/test/java/run/halo/gradle/role/RoleTemplateGeneratorTest.java
@@ -0,0 +1,177 @@
+package run.halo.gradle.role;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import org.json.JSONException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.skyscreamer.jsonassert.JSONAssert;
+import run.halo.gradle.utils.JsonUtils;
+
+/**
+ * Tests for {@link RoleTemplateGenerator}.
+ *
+ * @author guqing
+ * @since 0.3.0
+ */
+class RoleTemplateGeneratorTest {
+
+ @Test
+ void createRoles(@TempDir Path tempDir) throws JsonProcessingException, JSONException {
+ var schemaJsonFile = tempDir.resolve("schema.json");
+ var schemaJson = fakeSchemaJson();
+ writeToFile(schemaJsonFile, schemaJson);
+
+ var roleTemplateGenerator = new RoleTemplateGenerator(List.of(schemaJsonFile.toFile()));
+ var roles = roleTemplateGenerator.createRoles()
+ .stream()
+ .peek(role -> role.getMetadata().setName("a-name"))
+ .toList();
+
+ JSONAssert.assertEquals("""
+ [
+ {
+ "kind": "Role",
+ "apiVersion": "v1alpha1",
+ "metadata": {
+ "name": "a-name",
+ "labels": {
+ "halo.run/role-template": "true"
+ },
+ "annotations": {
+ "rbac.authorization.halo.run/ui-permissions": "['{定义 UI 权限}']",
+ "rbac.authorization.halo.run/display-name": "{角色显示名称}",
+ "rbac.authorization.halo.run/module": "{所属模块}"
+ }
+ },
+ "rules": [
+ {
+ "apiGroups": ["api.console.halo.run"],
+ "resources": ["attachments"],
+ "verbs": ["list"]
+ },
+ {
+ "apiGroups": ["api.console.halo.run"],
+ "resources": ["attachments", "attachments/download"],
+ "resourceNames": ["{name}"],
+ "verbs": ["get"]
+ }
+ ]
+ },
+ {
+ "kind": "Role",
+ "apiVersion": "v1alpha1",
+ "metadata": {
+ "name": "a-name",
+ "labels": {
+ "halo.run/role-template": "true"
+ },
+ "annotations": {
+ "rbac.authorization.halo.run/ui-permissions": "['{定义 UI 权限}']",
+ "rbac.authorization.halo.run/display-name": "{角色显示名称}",
+ "rbac.authorization.halo.run/module": "{所属模块}"
+ }
+ },
+ "rules": [
+ {
+ "apiGroups": ["api.content.halo.run"],
+ "resources": ["categories", "posts"],
+ "verbs": ["create", "list"]
+ },
+ {
+ "apiGroups": ["api.content.halo.run"],
+ "resources": ["categories", "categories/posts"],
+ "resourceNames": ["{name}"],
+ "verbs": ["get"]
+ }
+ ]
+ },
+ {
+ "kind": "Role",
+ "apiVersion": "v1alpha1",
+ "metadata": {
+ "name": "a-name",
+ "labels": {
+ "halo.run/role-template": "true"
+ },
+ "annotations": {
+ "rbac.authorization.halo.run/ui-permissions": "['{定义 UI 权限}']",
+ "rbac.authorization.halo.run/display-name": "{角色显示名称}",
+ "rbac.authorization.halo.run/module": "{所属模块}"
+ }
+ },
+ "rules": [{
+ "nonResourceURLs": ["/actuator/info"],
+ "verbs": ["get"]
+ }]
+ },
+ {
+ "kind": "Role",
+ "apiVersion": "v1alpha1",
+ "metadata": {
+ "name": "a-name",
+ "labels": {
+ "halo.run/role-template": "true"
+ },
+ "annotations": {
+ "rbac.authorization.halo.run/ui-permissions": "['{定义 UI 权限}']",
+ "rbac.authorization.halo.run/display-name": "{角色显示名称}",
+ "rbac.authorization.halo.run/module": "{所属模块}"
+ }
+ },
+ "rules": [{
+ "nonResourceURLs": ["/health"],
+ "verbs": ["get"]
+ }]
+ }
+ ]
+ """, JsonUtils.mapper().writeValueAsString(roles), true);
+ }
+
+ private void writeToFile(Path path, String content) {
+ try {
+ Files.writeString(path, content);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ String fakeSchemaJson() {
+ return """
+ {
+ "paths": {
+ "/apis/api.console.halo.run/v1alpha1/attachments": {
+ "get": {}
+ },
+ "/apis/api.console.halo.run/v1alpha1/attachments/{name}": {
+ "get": {}
+ },
+ "/apis/api.console.halo.run/v1alpha1/attachments/{name}/download": {
+ "get": {}
+ },
+ "/apis/api.content.halo.run/v1alpha1/categories": {
+ "get": {}
+ },
+ "/apis/api.content.halo.run/v1alpha1/categories/{name}": {
+ "get": {}
+ },
+ "/apis/api.content.halo.run/v1alpha1/categories/{name}/posts": {
+ "get": {}
+ },
+ "/apis/api.content.halo.run/v1alpha1/posts": {
+ "post": {}
+ },
+ "/health": {
+ "get": {}
+ },
+ "/actuator/info": {
+ "get": {}
+ }
+ }
+ }
+ """;
+ }
+}