@@ -4,6 +4,78 @@ import io.unthrottled.doki.build.jvm.models.StringDictionary
44
55// same as functions.ts in doki-build-source
66object BuildFunctions {
7+
8+ fun <T , R > composeTemplateWithCombini (
9+ childTemplate : T ,
10+ templateNameToTemplate : StringDictionary <T >,
11+ attributeResolver : (T ) -> R ,
12+ parentResolver : (T ) -> List <String >? ,
13+ combiniFunction : (R , R ) -> R ,
14+ ): R {
15+ val parentTemplateNames = parentResolver(childTemplate)
16+ return if (parentTemplateNames == null ) {
17+ attributeResolver(childTemplate)
18+ } else {
19+ val fullParentTemplates = parentTemplateNames
20+ .mapNotNull {
21+ parentTemplateName ->
22+ templateNameToTemplate[parentTemplateName]
23+ }
24+
25+ // combine parents first, so that
26+ // we know what will be overidden in the base/grandparent template
27+ val combinedParents = fullParentTemplates
28+ .map {
29+ parentTemplate ->
30+ attributeResolver(parentTemplate)
31+ }
32+ .reduce(combiniFunction)
33+
34+ val grandParentsToFillOut =
35+ fullParentTemplates.flatMap {
36+ fullParentTemplate ->
37+ parentResolver(fullParentTemplate) ? : emptyList()
38+ }
39+
40+ if (grandParentsToFillOut.isEmpty()) {
41+ // no grandparents, so these parents ar the base
42+ // of the template, apply the child overrides
43+ combiniFunction(
44+ combinedParents,
45+ attributeResolver(childTemplate)
46+ )
47+ } else {
48+ val resolvedBaseTemplate =
49+ grandParentsToFillOut
50+ .distinct()
51+ .map {
52+ grandParentToResolve ->
53+ val grandParentTemplate = templateNameToTemplate[grandParentToResolve]
54+ ? : throw IllegalStateException (" Expected template $grandParentToResolve to be present" )
55+ composeTemplateWithCombini(
56+ grandParentTemplate,
57+ templateNameToTemplate,
58+ attributeResolver,
59+ parentResolver,
60+ combiniFunction
61+ )
62+ }.reduce(combiniFunction)
63+
64+ // apply parent overrides to the base template
65+ val fullParentTemplate = combiniFunction(
66+ resolvedBaseTemplate,
67+ combinedParents,
68+ )
69+
70+ // apply child overrides to the parent overrides.
71+ combiniFunction(
72+ fullParentTemplate,
73+ attributeResolver(childTemplate),
74+ )
75+ }
76+ }
77+ }
78+
779 fun <T , R > resolveTemplateWithCombini (
880 childTemplate : T ,
981 templateNameToTemplate : StringDictionary <T >,
0 commit comments