Debian Codegraph @

commands/import.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package commands
15
16 import (
17 "bytes"
18 "context"
19 "errors"
20 "fmt"
21 "io"
22 "log"
23 "os"
24 "path/filepath"
25 "regexp"
26 "strconv"
27 "strings"
28 "time"
29 "unicode"
30
31 "github.com/bep/simplecobra"
32 "github.com/gohugoio/hugo/common/hmaps"
33 "github.com/gohugoio/hugo/common/htime"
34 "github.com/gohugoio/hugo/common/hugio"
35 "github.com/gohugoio/hugo/helpers"
36 "github.com/gohugoio/hugo/hugofs"
37 "github.com/gohugoio/hugo/parser"
38 "github.com/gohugoio/hugo/parser/metadecoders"
39 "github.com/gohugoio/hugo/parser/pageparser"
40 "github.com/spf13/afero"
41 "github.com/spf13/cobra"
42 )
43
44 func newImportCommand() *importCommand {
45 var c *importCommand
46 c = &importCommand{
47 commands: []simplecobra.Commander{
48 &simpleCommand{
49 name: "jekyll",
50 short: "hugo import from Jekyll",
51 long: `hugo import from Jekyll.
52
53 Import from Jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.",
54 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
55 if len(args) < 2 {
56 return newUserError(`import from jekyll requires two paths, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`.")
57 }
58 return c.importFromJekyll(args)
59 },
60 withc: func(cmd *cobra.Command, r *rootCommand) {
61 cmd.ValidArgsFunction = cobra.NoFileCompletions
62 cmd.Flags().BoolVar(&c.force, "force", false, "allow import into non-empty target directory")
63 },
64 },
65 },
66 }
67
68 return c
69 }
70
71 type importCommand struct {
72 r *rootCommand
73
74 force bool
75
76 commands []simplecobra.Commander
77 }
78
79 func (c *importCommand) Commands() []simplecobra.Commander {
80 return c.commands
81 }
82
83 func (c *importCommand) Name() string {
84 return "import"
85 }
86
87 func (c *importCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
88 return nil
89 }
90
91 func (c *importCommand) Init(cd *simplecobra.Commandeer) error {
92 cmd := cd.CobraCommand
93 cmd.Short = "Import a project from another system"
94 cmd.Long = `Import a project from another system.
95
96 Import requires a subcommand, e.g. ` + "`hugo import jekyll jekyll_root_path target_path`."
97
98 cmd.RunE = nil
99 return nil
100 }
101
102 func (c *importCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
103 c.r = cd.Root.Command.(*rootCommand)
104 return nil
105 }
106
107 func (i *importCommand) createConfigFromJekyll(fs afero.Fs, inpath string, kind metadecoders.Format, jekyllConfig map[string]any) (err error) {
108 title := "My New Hugo Project"
109 baseURL := "http://example.org/"
110
111 for key, value := range jekyllConfig {
112 lowerKey := strings.ToLower(key)
113
114 switch lowerKey {
115 case "title":
116 if str, ok := value.(string); ok {
117 title = str
118 }
119
120 case "url":
121 if str, ok := value.(string); ok {
122 baseURL = str
123 }
124 }
125 }
126
127 in := map[string]any{
128 "baseURL": baseURL,
129 "title": title,
130 "locale": "en-us",
131 "disablePathToLower": true,
132 }
133
134 var buf bytes.Buffer
135 err = parser.InterfaceToConfig(in, kind, &buf)
136 if err != nil {
137 return err
138 }
139
140 return helpers.WriteToDisk(filepath.Join(inpath, "hugo."+string(kind)), &buf, fs)
141 }
142
143 func (c *importCommand) getJekyllDirInfo(fs afero.Fs, jekyllRoot string) (map[string]bool, bool) {
144 postDirs := make(map[string]bool)
145 hasAnyPost := false
146 if entries, err := os.ReadDir(jekyllRoot); err == nil {
147 for _, entry := range entries {
148 if entry.IsDir() {
149 subDir := filepath.Join(jekyllRoot, entry.Name())
150 if isPostDir, hasAnyPostInDir := c.retrieveJekyllPostDir(fs, subDir); isPostDir {
151 postDirs[entry.Name()] = hasAnyPostInDir
152 if hasAnyPostInDir {
153 hasAnyPost = true
154 }
155 }
156 }
157 }
158 }
159 return postDirs, hasAnyPost
160 }
161
162 func (c *importCommand) createProjectFromJekyll(jekyllRoot, targetDir string, jekyllPostDirs map[string]bool) error {
163 fs := &afero.OsFs{}
164 if exists, _ := helpers.Exists(targetDir, fs); exists {
165 if isDir, _ := helpers.IsDir(targetDir, fs); !isDir {
166 return errors.New("target path \"" + targetDir + "\" exists but is not a directory")
167 }
168
169 isEmpty, _ := helpers.IsEmpty(targetDir, fs)
170
171 if !isEmpty && !c.force {
172 return errors.New("target path \"" + targetDir + "\" exists and is not empty")
173 }
174 }
175
176 jekyllConfig := c.loadJekyllConfig(fs, jekyllRoot)
177
178 mkdir(targetDir, "layouts")
179 mkdir(targetDir, "content")
180 mkdir(targetDir, "archetypes")
181 mkdir(targetDir, "static")
182 mkdir(targetDir, "data")
183 mkdir(targetDir, "themes")
184
185 c.createConfigFromJekyll(fs, targetDir, "yaml", jekyllConfig)
186
187 c.copyJekyllFilesAndFolders(jekyllRoot, filepath.Join(targetDir, "static"), jekyllPostDirs)
188
189 return nil
190 }
191
192 func (c *importCommand) convertJekyllContent(m any, content string) (string, error) {
193 metadata, _ := hmaps.ToStringMapE(m)
194
195 lines := strings.Split(content, "\n")
196 var resultLines []string
197 for _, line := range lines {
198 resultLines = append(resultLines, strings.Trim(line, "\r\n"))
199 }
200
201 content = strings.Join(resultLines, "\n")
202
203 excerptSep := "<!--more-->"
204 if value, ok := metadata["excerpt_separator"]; ok {
205 if str, strOk := value.(string); strOk {
206 content = strings.Replace(content, strings.TrimSpace(str), excerptSep, -1)
207 }
208 }
209
210 replaceList := []struct {
211 re *regexp.Regexp
212 replace string
213 }{
214 {regexp.MustCompile("(?i)<!-- more -->"), "<!--more-->"},
215 {regexp.MustCompile(`\{%\s*raw\s*%\}\s*(.*?)\s*\{%\s*endraw\s*%\}`), "$1"},
216 {regexp.MustCompile(`{%\s*endhighlight\s*%}`), "{{< / highlight >}}"},
217 }
218
219 for _, replace := range replaceList {
220 content = replace.re.ReplaceAllString(content, replace.replace)
221 }
222
223 replaceListFunc := []struct {
224 re *regexp.Regexp
225 replace func(string) string
226 }{
227 // Octopress image tag: http://octopress.org/docs/plugins/image-tag/
228 {regexp.MustCompile(`{%\s+img\s*(.*?)\s*%}`), c.replaceImageTag},
229 {regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`), c.replaceHighlightTag},
230 }
231
232 for _, replace := range replaceListFunc {
233 content = replace.re.ReplaceAllStringFunc(content, replace.replace)
234 }
235
236 var buf bytes.Buffer
237 if len(metadata) != 0 {
238 err := parser.InterfaceToFrontMatter(m, metadecoders.YAML, &buf)
239 if err != nil {
240 return "", err
241 }
242 }
243 buf.WriteString(content)
244
245 return buf.String(), nil
246 }
247
248 func (c *importCommand) convertJekyllMetaData(m any, postName string, postDate time.Time, draft bool) (any, error) {
249 metadata, err := hmaps.ToStringMapE(m)
250 if err != nil {
251 return nil, err
252 }
253
254 if draft {
255 metadata["draft"] = true
256 }
257
258 for key, value := range metadata {
259 lowerKey := strings.ToLower(key)
260
261 switch lowerKey {
262 case "layout":
263 delete(metadata, key)
264 case "permalink":
265 if str, ok := value.(string); ok {
266 metadata["url"] = str
267 }
268 delete(metadata, key)
269 case "category":
270 if str, ok := value.(string); ok {
271 metadata["categories"] = []string{str}
272 }
273 delete(metadata, key)
274 case "excerpt_separator":
275 if key != lowerKey {
276 delete(metadata, key)
277 metadata[lowerKey] = value
278 }
279 case "date":
280 if str, ok := value.(string); ok {
281 re := regexp.MustCompile(`(\d+):(\d+):(\d+)`)
282 r := re.FindAllStringSubmatch(str, -1)
283 if len(r) > 0 {
284 hour, _ := strconv.Atoi(r[0][1])
285 minute, _ := strconv.Atoi(r[0][2])
286 second, _ := strconv.Atoi(r[0][3])
287 postDate = time.Date(postDate.Year(), postDate.Month(), postDate.Day(), hour, minute, second, 0, time.UTC)
288 }
289 }
290 delete(metadata, key)
291 }
292
293 }
294
295 metadata["date"] = postDate.Format(time.RFC3339)
296
297 return metadata, nil
298 }
299
300 func (c *importCommand) convertJekyllPost(path, relPath, targetDir string, draft bool) error {
301 log.Println("Converting", path)
302
303 filename := filepath.Base(path)
304 postDate, postName, err := c.parseJekyllFilename(filename)
305 if err != nil {
306 c.r.Printf("Failed to parse filename '%s': %s. Skipping.", filename, err)
307 return nil
308 }
309
310 log.Println(filename, postDate, postName)
311
312 targetFile := filepath.Join(targetDir, relPath)
313 targetParentDir := filepath.Dir(targetFile)
314 os.MkdirAll(targetParentDir, 0o777)
315
316 contentBytes, err := os.ReadFile(path)
317 if err != nil {
318 c.r.logger.Errorln("Read file error:", path)
319 return err
320 }
321 pf, err := pageparser.ParseFrontMatterAndContent(bytes.NewReader(contentBytes))
322 if err != nil {
323 return fmt.Errorf("failed to parse file %q: %s", filename, err)
324 }
325 newmetadata, err := c.convertJekyllMetaData(pf.FrontMatter, postName, postDate, draft)
326 if err != nil {
327 return fmt.Errorf("failed to convert metadata for file %q: %s", filename, err)
328 }
329
330 content, err := c.convertJekyllContent(newmetadata, string(pf.Content))
331 if err != nil {
332 return fmt.Errorf("failed to convert content for file %q: %s", filename, err)
333 }
334
335 fs := hugofs.Os
336 if err := helpers.WriteToDisk(targetFile, strings.NewReader(content), fs); err != nil {
337 return fmt.Errorf("failed to save file %q: %s", filename, err)
338 }
339 return nil
340 }
341
342 func (c *importCommand) copyJekyllFilesAndFolders(jekyllRoot, dest string, jekyllPostDirs map[string]bool) (err error) {
343 fs := hugofs.Os
344
345 fi, err := fs.Stat(jekyllRoot)
346 if err != nil {
347 return err
348 }
349 if !fi.IsDir() {
350 return errors.New(jekyllRoot + " is not a directory")
351 }
352 err = os.MkdirAll(dest, fi.Mode())
353 if err != nil {
354 return err
355 }
356 entries, err := os.ReadDir(jekyllRoot)
357 if err != nil {
358 return err
359 }
360
361 for _, entry := range entries {
362 sfp := filepath.Join(jekyllRoot, entry.Name())
363 dfp := filepath.Join(dest, entry.Name())
364 if entry.IsDir() {
365 if entry.Name()[0] != '_' && entry.Name()[0] != '.' {
366 if _, ok := jekyllPostDirs[entry.Name()]; !ok {
367 err = hugio.CopyDir(fs, sfp, dfp, nil)
368 if err != nil {
369 c.r.logger.Errorln(err)
370 }
371 }
372 }
373 } else {
374 lowerEntryName := strings.ToLower(entry.Name())
375 exceptSuffix := []string{
376 ".md", ".markdown", ".html", ".htm",
377 ".xml", ".textile", "rakefile", "gemfile", ".lock",
378 }
379 isExcept := false
380 for _, suffix := range exceptSuffix {
381 if strings.HasSuffix(lowerEntryName, suffix) {
382 isExcept = true
383 break
384 }
385 }
386
387 if !isExcept && entry.Name()[0] != '.' && entry.Name()[0] != '_' {
388 err = hugio.CopyFile(fs, sfp, dfp)
389 if err != nil {
390 c.r.logger.Errorln(err)
391 }
392 }
393 }
394
395 }
396 return nil
397 }
398
399 func (c *importCommand) importFromJekyll(args []string) error {
400 jekyllRoot, err := filepath.Abs(filepath.Clean(args[0]))
401 if err != nil {
402 return newUserError("path error:", args[0])
403 }
404
405 targetDir, err := filepath.Abs(filepath.Clean(args[1]))
406 if err != nil {
407 return newUserError("path error:", args[1])
408 }
409
410 c.r.Println("Import Jekyll from:", jekyllRoot, "to:", targetDir)
411
412 if strings.HasPrefix(filepath.Dir(targetDir), jekyllRoot) {
413 return newUserError("abort: target path should not be inside the Jekyll root")
414 }
415
416 fs := afero.NewOsFs()
417 jekyllPostDirs, hasAnyPost := c.getJekyllDirInfo(fs, jekyllRoot)
418 if !hasAnyPost {
419 return errors.New("abort: jekyll root contains neither posts nor drafts")
420 }
421
422 err = c.createProjectFromJekyll(jekyllRoot, targetDir, jekyllPostDirs)
423 if err != nil {
424 return newUserError(err)
425 }
426
427 c.r.Println("Importing...")
428
429 fileCount := 0
430 callback := func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error {
431 if fi.IsDir() {
432 return nil
433 }
434
435 relPath, err := filepath.Rel(jekyllRoot, path)
436 if err != nil {
437 return newUserError("get rel path error:", path)
438 }
439
440 relPath = filepath.ToSlash(relPath)
441 draft := false
442
443 switch {
444 case strings.Contains(relPath, "_posts/"):
445 relPath = filepath.Join("content/post", strings.Replace(relPath, "_posts/", "", -1))
446 case strings.Contains(relPath, "_drafts/"):
447 relPath = filepath.Join("content/draft", strings.Replace(relPath, "_drafts/", "", -1))
448 draft = true
449 default:
450 return nil
451 }
452
453 fileCount++
454 return c.convertJekyllPost(path, relPath, targetDir, draft)
455 }
456
457 for jekyllPostDir, hasAnyPostInDir := range jekyllPostDirs {
458 if hasAnyPostInDir {
459 if err = helpers.Walk(hugofs.Os, filepath.Join(jekyllRoot, jekyllPostDir), callback); err != nil {
460 return err
461 }
462 }
463 }
464
465 c.r.Println("Congratulations!", fileCount, "post(s) imported!")
466 c.r.Println("Now, start Hugo by yourself:")
467 c.r.Println("cd " + args[1])
468 c.r.Println("git init")
469 c.r.Println("git submodule add https://github.com/gohugo-ananke/ananke themes/ananke")
470 c.r.Println("echo \"theme: ananke\" >> hugo.yaml")
471 c.r.Println("hugo server")
472
473 return nil
474 }
475
476 func (c *importCommand) loadJekyllConfig(fs afero.Fs, jekyllRoot string) map[string]any {
477 for _, candidate := range []struct {
478 filename string
479 format metadecoders.Format
480 }{
481 {"_config.yml", metadecoders.YAML},
482 {"_config.yaml", metadecoders.YAML},
483 {"_config.toml", metadecoders.TOML},
484 } {
485 path := filepath.Join(jekyllRoot, candidate.filename)
486 exists, err := helpers.Exists(path, fs)
487 if err != nil || !exists {
488 continue
489 }
490
491 f, err := fs.Open(path)
492 if err != nil {
493 continue
494 }
495 b, err := io.ReadAll(f)
496 f.Close()
497 if err != nil {
498 continue
499 }
500
501 m, err := metadecoders.Default.UnmarshalToMap(b, candidate.format)
502 if err != nil {
503 continue
504 }
505
506 return m
507 }
508
509 c.r.Println("no config file (_config.yml, _config.yaml, or _config.toml) found: is the specified Jekyll root correct?")
510 return nil
511 }
512
513 func (c *importCommand) parseJekyllFilename(filename string) (time.Time, string, error) {
514 re := regexp.MustCompile(`(\d+-\d+-\d+)-(.+)\..*`)
515 r := re.FindAllStringSubmatch(filename, -1)
516 if len(r) == 0 {
517 return htime.Now(), "", errors.New("filename not match")
518 }
519
520 postDate, err := time.Parse("2006-1-2", r[0][1])
521 if err != nil {
522 return htime.Now(), "", err
523 }
524
525 postName := r[0][2]
526
527 return postDate, postName, nil
528 }
529
530 func (c *importCommand) replaceHighlightTag(match string) string {
531 r := regexp.MustCompile(`{%\s*highlight\s*(.*?)\s*%}`)
532 parts := r.FindStringSubmatch(match)
533 lastQuote := rune(0)
534 f := func(c rune) bool {
535 switch {
536 case c == lastQuote:
537 lastQuote = rune(0)
538 return false
539 case lastQuote != rune(0):
540 return false
541 case unicode.In(c, unicode.Quotation_Mark):
542 lastQuote = c
543 return false
544 default:
545 return unicode.IsSpace(c)
546 }
547 }
548 // splitting string by space but considering quoted section
549 items := strings.FieldsFunc(parts[1], f)
550
551 result := bytes.NewBufferString("{{< highlight ")
552 result.WriteString(items[0]) // language
553 options := items[1:]
554 for i, opt := range options {
555 opt = strings.Replace(opt, "\"", "", -1)
556 if opt == "linenos" {
557 opt = "linenos=table"
558 }
559 if i == 0 {
560 opt = " \"" + opt
561 }
562 if i < len(options)-1 {
563 opt += ","
564 } else if i == len(options)-1 {
565 opt += "\""
566 }
567 result.WriteString(opt)
568 }
569
570 result.WriteString(" >}}")
571 return result.String()
572 }
573
574 func (c *importCommand) replaceImageTag(match string) string {
575 r := regexp.MustCompile(`{%\s+img\s*(\p{L}*)\s+([\S]*/[\S]+)\s+(\d*)\s*(\d*)\s*(.*?)\s*%}`)
576 result := bytes.NewBufferString("{{< figure ")
577 parts := r.FindStringSubmatch(match)
578 // Index 0 is the entire string, ignore
579 c.replaceOptionalPart(result, "class", parts[1])
580 c.replaceOptionalPart(result, "src", parts[2])
581 c.replaceOptionalPart(result, "width", parts[3])
582 c.replaceOptionalPart(result, "height", parts[4])
583 // title + alt
584 part := parts[5]
585 if len(part) > 0 {
586 splits := strings.Split(part, "'")
587 lenSplits := len(splits)
588 if lenSplits == 1 {
589 c.replaceOptionalPart(result, "title", splits[0])
590 } else if lenSplits == 3 {
591 c.replaceOptionalPart(result, "title", splits[1])
592 } else if lenSplits == 5 {
593 c.replaceOptionalPart(result, "title", splits[1])
594 c.replaceOptionalPart(result, "alt", splits[3])
595 }
596 }
597 result.WriteString(">}}")
598 return result.String()
599 }
600
601 func (c *importCommand) replaceOptionalPart(buffer *bytes.Buffer, partName string, part string) {
602 if len(part) > 0 {
603 buffer.WriteString(partName + "=\"" + part + "\" ")
604 }
605 }
606
607 func (c *importCommand) retrieveJekyllPostDir(fs afero.Fs, dir string) (bool, bool) {
608 if strings.HasSuffix(dir, "_posts") || strings.HasSuffix(dir, "_drafts") {
609 isEmpty, _ := helpers.IsEmpty(dir, fs)
610 return true, !isEmpty
611 }
612
613 if entries, err := os.ReadDir(dir); err == nil {
614 for _, entry := range entries {
615 if entry.IsDir() {
616 subDir := filepath.Join(dir, entry.Name())
617 if isPostDir, hasAnyPost := c.retrieveJekyllPostDir(fs, subDir); isPostDir {
618 return isPostDir, hasAnyPost
619 }
620 }
621 }
622 }
623
624 return false, true
625 }