Welcome to mirror list, hosted at ThFree Co, Russian Federation.

generate_page_wrappers.go « page_generate « page « resources - github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: af85cb429a5b114c2ddfdc9f1606fa955bf3d2f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package page_generate

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"
	"reflect"

	"github.com/pkg/errors"

	"github.com/gohugoio/hugo/common/maps"

	"github.com/gohugoio/hugo/codegen"
	"github.com/gohugoio/hugo/resources/page"
	"github.com/gohugoio/hugo/source"
)

const header = `// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file is autogenerated.
`

var (
	fileInterfaceDeprecated = reflect.TypeOf((*source.FileWithoutOverlap)(nil)).Elem()
	pageInterfaceDeprecated = reflect.TypeOf((*page.DeprecatedWarningPageMethods)(nil)).Elem()
	pageInterface           = reflect.TypeOf((*page.Page)(nil)).Elem()

	packageDir = filepath.FromSlash("resources/page")
)

func Generate(c *codegen.Inspector) error {
	if err := generateMarshalJSON(c); err != nil {
		return errors.Wrap(err, "failed to generate JSON marshaler")

	}

	if err := generateDeprecatedWrappers(c); err != nil {
		return errors.Wrap(err, "failed to generate deprecate wrappers")
	}

	return nil
}

func generateMarshalJSON(c *codegen.Inspector) error {
	filename := filepath.Join(c.ProjectRootDir, packageDir, "page_marshaljson.autogen.go")
	f, err := os.Create(filename)

	if err != nil {
		return err
	}
	defer f.Close()

	includes := []reflect.Type{pageInterface}

	// Exclude these methods
	excludes := []reflect.Type{
		// We need to eveluate the deprecated vs JSON in the future,
		// but leave them out for now.
		pageInterfaceDeprecated,

		// Leave this out for now. We need to revisit the author issue.
		reflect.TypeOf((*page.AuthorProvider)(nil)).Elem(),

		// navigation.PageMenus

		// Prevent loops.
		reflect.TypeOf((*page.SitesProvider)(nil)).Elem(),
		reflect.TypeOf((*page.Positioner)(nil)).Elem(),

		reflect.TypeOf((*page.ChildCareProvider)(nil)).Elem(),
		reflect.TypeOf((*page.TreeProvider)(nil)).Elem(),
		reflect.TypeOf((*page.InSectionPositioner)(nil)).Elem(),
		reflect.TypeOf((*page.PaginatorProvider)(nil)).Elem(),
		reflect.TypeOf((*maps.Scratcher)(nil)).Elem(),
	}

	methods := c.MethodsFromTypes(
		includes,
		excludes)

	if len(methods) == 0 {
		return errors.New("no methods found")
	}

	marshalJSON, pkgImports := methods.ToMarshalJSON("Page", "github.com/gohugoio/hugo/resources/page")

	fmt.Fprintf(f, `%s

package page

%s


%s


`, header, importsString(pkgImports), marshalJSON)

	return nil
}

func generateDeprecatedWrappers(c *codegen.Inspector) error {
	filename := filepath.Join(c.ProjectRootDir, packageDir, "page_wrappers.autogen.go")
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	// Generate a wrapper for deprecated page methods

	reasons := map[string]string{
		"IsDraft":        "Use .Draft.",
		"Hugo":           "Use the global hugo function.",
		"LanguagePrefix": "Use .Site.LanguagePrefix.",
		"GetParam":       "Use .Param or .Params.myParam.",
		"RSSLink": `Use the Output Format's link, e.g. something like: 
    {{ with .OutputFormats.Get "RSS" }}{{ . RelPermalink }}{{ end }}`,
		"URL": "Use .Permalink or .RelPermalink. If what you want is the front matter URL value, use .Params.url",
	}

	deprecated := func(name string, tp reflect.Type) string {
		var alternative string
		if tp == fileInterfaceDeprecated {
			alternative = "Use .File." + name
		} else {
			var found bool
			alternative, found = reasons[name]
			if !found {
				panic(fmt.Sprintf("no deprecated reason found for %q", name))
			}
		}

		return fmt.Sprintf("helpers.Deprecated(%q, %q, %q, false)", "Page", "."+name, alternative)
	}

	var buff bytes.Buffer

	methods := c.MethodsFromTypes([]reflect.Type{fileInterfaceDeprecated, pageInterfaceDeprecated}, nil)

	for _, m := range methods {
		fmt.Fprint(&buff, m.Declaration("*pageDeprecated"))
		fmt.Fprintln(&buff, " {")
		fmt.Fprintf(&buff, "\t%s\n", deprecated(m.Name, m.Owner))
		fmt.Fprintf(&buff, "\t%s\n}\n", m.Delegate("p", "p"))

	}

	pkgImports := append(methods.Imports(), "github.com/gohugoio/hugo/helpers")

	fmt.Fprintf(f, `%s

package page

%s
// NewDeprecatedWarningPage adds deprecation warnings to the given implementation.
func NewDeprecatedWarningPage(p DeprecatedWarningPageMethods) DeprecatedWarningPageMethods {
	return &pageDeprecated{p: p}
}

type pageDeprecated struct {
	p DeprecatedWarningPageMethods
}

%s

`, header, importsString(pkgImports), buff.String())

	return nil
}

func importsString(imps []string) string {
	if len(imps) == 0 {
		return ""
	}

	if len(imps) == 1 {
		return fmt.Sprintf("import %q", imps[0])
	}

	impsStr := "import (\n"
	for _, imp := range imps {
		impsStr += fmt.Sprintf("%q\n", imp)
	}

	return impsStr + ")"
}