• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package main
6
7import (
8	"flag"
9	"fmt"
10	"io/ioutil"
11	"log"
12	"path"
13	"strings"
14
15	"go.chromium.org/luci/lucicfg/docgen"
16)
17
18// Returns a func which returns the contents of a Starlark module relative to
19// starlarkRoot.
20//
21// Some modules are skipped, e.g. "@stdlib" modules.
22func getSourceFn(starlarkRoot string) func(string) (string, error) {
23	return func(module string) (string, error) {
24		if strings.HasPrefix(module, "@stdlib") || strings.HasPrefix(module, "@proto") {
25			log.Printf("Skipping module %v", module)
26			return "", nil
27		}
28
29		if !strings.HasPrefix(module, "//") {
30			return "", fmt.Errorf("Expected module to start with '//', actual %v", module)
31		}
32
33		log.Printf("Reading module %v\n", module)
34
35		fileBytes, err := ioutil.ReadFile(
36			path.Join(
37				starlarkRoot,
38				strings.TrimLeft(module, "/"),
39			),
40		)
41
42		if err != nil {
43			return "", err
44		}
45
46		return string(fileBytes), nil
47	}
48}
49
50func main() {
51	template := flag.String("template", "", "Path to a markdown template file. Required.")
52	output := flag.String("output", "", "Path to output a markdown file to. Required.")
53	starlarkRoot := flag.String(
54		"starlarkRoot",
55		"",
56		"Path to the root of the Starlark package. This is the directory "+
57			"load statements are relative to, i.e. if //config/util/liba.star "+
58			"is pointing to ~/chromiumos/src/config/util/liba.star, "+
59			"starlarkRoot is ~/chromiumos/src. Required.",
60	)
61
62	flag.Parse()
63
64	if len(*template) == 0 {
65		log.Fatalln("template must be specified.")
66	}
67
68	if len(*output) == 0 {
69		log.Fatalln("output must be specified.")
70	}
71
72	if len(*starlarkRoot) == 0 {
73		log.Fatalln("starlarkRoot must be specified.")
74	}
75
76	templateBytes, err := ioutil.ReadFile(*template)
77	if err != nil {
78		log.Fatalln(err)
79	}
80
81	generator := &docgen.Generator{Starlark: getSourceFn(*starlarkRoot)}
82
83	outputBytes, err := generator.Render(string(templateBytes))
84	if err != nil {
85		log.Fatalln(err)
86	}
87
88	if err = ioutil.WriteFile(*output, outputBytes, 0640); err != nil {
89		log.Fatalln(err)
90	}
91
92	log.Printf("Wrote output to %v\n", *output)
93}
94