File: generate.go

package info (click to toggle)
docker.io 27.5.1%2Bdfsg4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 67,384 kB
  • sloc: sh: 5,847; makefile: 1,146; ansic: 664; python: 162; asm: 133
file content (76 lines) | stat: -rw-r--r-- 1,493 bytes parent folder | download | duplicates (5)
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
package main

import (
	"bytes"
	"fmt"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"

	"github.com/pkg/errors"
)

func main() {
	re := regexp.MustCompile("(?s)<!---GENERATE_START (.*?)-->(.*?)<!---GENERATE_END-->\n")

	err := filepath.Walk("./docs", func(path string, stat fs.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if stat.IsDir() {
			return nil
		}
		if filepath.Ext(path) != ".md" {
			return nil
		}

		data, err := os.ReadFile(path)
		if err != nil {
			return err
		}

		dataNew := re.ReplaceAllFunc(data, func(match []byte) []byte {
			groups := re.FindStringSubmatch(string(match))
			stdout := bytes.NewBuffer(nil)
			fmt.Fprintf(stdout, "<!---GENERATE_START %s-->\n", groups[1])
			fmt.Fprintf(stdout, "```\n")
			cmd := exec.Cmd{
				Path:   "/bin/sh",
				Args:   []string{"sh", "-c", groups[1]},
				Stdout: stdout,
			}
			err = cmd.Start()
			if err != nil {
				err = errors.Wrapf(err, "could not start command %s", groups[1])
				return nil
			}
			err = cmd.Wait()
			if err != nil {
				err = errors.Wrapf(err, "could not run command %s", groups[1])
				return nil
			}
			fmt.Fprintf(stdout, "```\n")
			fmt.Fprintf(stdout, "<!---GENERATE_END-->\n")

			return stdout.Bytes()
		})
		if err != nil {
			return err
		}

		if !bytes.Equal(data, dataNew) {
			fmt.Println(path)
			if err := os.WriteFile(path, dataNew, stat.Mode()); err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}