feat: document plain values (#12)

* feat: document plain values

Adds `d.val` to attach type and help information to plain Jsonnet
values, apart from specially treated `fn` and `obj`.

* feat: defaults
This commit is contained in:
sh0rez 2020-07-27 16:59:04 +02:00 committed by GitHub
parent 4c6f532e05
commit 2f9dcb2d21
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 99 additions and 11 deletions

View file

@ -18,6 +18,7 @@ local d = import "github.com/sh0rez/docsonnet/doc-util"
* [`fn fn(help, args)`](#fn-fn)
* [`fn obj(help, fields)`](#fn-obj)
* [`fn pkg(name, url, help)`](#fn-pkg)
* [`fn val(type, help, default)`](#fn-val)
* [`obj argument`](#obj-argument)
* [`fn new(name, type, default)`](#fn-argumentnew)
* [`obj func`](#obj-func)
@ -29,6 +30,8 @@ local d = import "github.com/sh0rez/docsonnet/doc-util"
* [`fn withFields(fields)`](#fn-objectwithfields)
* [`obj package`](#obj-package)
* [`fn new(name, url, help)`](#fn-packagenew)
* [`obj value`](#obj-value)
* [`fn new(type, help, default)`](#fn-valuenew)
## Fields
@ -64,6 +67,14 @@ pkg(name, url, help)
`new` is a shorthand for `package.new`
### fn val
```ts
val(type, help, default)
```
`val` is a shorthand for `value.new`
## obj argument
Utilities for creating function arguments
@ -135,3 +146,15 @@ new(name, url, help)
```
new creates a new package with given `name`, `import` URL and `help` text
## obj value
Utilities for documenting plain Jsonnet values (primitives)
### fn value.new
```ts
new(type, help, default)
```
new creates a new object of given type, optionally with description and default value

View file

@ -73,6 +73,18 @@
'#arg': self.argument['#new'] + self.func.withHelp('`arg` is a shorthand for `argument.new`'),
arg:: self.argument.new,
"#value": d.obj("Utilities for documenting plain Jsonnet values (primitives)"),
value:: {
"#new": d.fn("new creates a new object of given type, optionally with description and default value", [d.arg("type", d.T.string), d.arg("help", d.T.string), d.arg("default", d.T.any)]),
new(type, help='', default=null): { 'value': {
help: help,
type: type,
default: default,
} }
},
'#val': self.value['#new'] + self.func.withHelp('`val` is a shorthand for `value.new`'),
val: self.value.new,
// T contains constants for the Jsonnet types
T:: {
string: 'string',

View file

@ -24,12 +24,13 @@ func main() {
outputJSON := root.Flags().Bool("json", false, "print loaded docsonnet as JSON")
outputRaw := root.Flags().Bool("raw", false, "don't transform, dump raw eval result")
urlPrefix := root.Flags().String("urlPrefix", "/", "url-prefix for frontmatter")
jpath := root.Flags().StringSliceP("jpath", "J", []string{"vendor"}, "Specify an additional library search dir (right-most wins)")
root.Run = func(cmd *cli.Command, args []string) error {
file := args[0]
log.Println("Extracting from Jsonnet")
data, err := docsonnet.Extract(file)
data, err := docsonnet.Extract(file, docsonnet.Opts{JPath: *jpath})
if err != nil {
log.Fatalln("Extracting:", err)
}

View file

@ -94,7 +94,32 @@ func loadField(name string, field map[string]interface{}, parent map[string]inte
return loadObj(name, iobj.(map[string]interface{}), parent)
}
panic(fmt.Sprintf("field %s lacking {function | object}", name))
if vobj, ok := field["value"]; ok {
return loadValue(name, vobj.(map[string]interface{}))
}
panic(fmt.Sprintf("field %s lacking {function | object | value}", name))
}
func loadValue(name string, msi map[string]interface{}) Field {
h, ok := msi["help"].(string)
if !ok {
h = ""
}
t, ok := msi["type"].(string)
if !ok {
panic(fmt.Sprintf("value %s lacking type information", name))
}
v := Value{
Name: name,
Help: h,
Type: Type(t),
Default: msi["default"],
}
return Field{Value: &v}
}
func loadFn(name string, msi map[string]interface{}) Field {

View file

@ -10,10 +10,14 @@ import (
"github.com/markbates/pkger"
)
type Opts struct {
JPath []string
}
// Load extracts and transforms the docsonnet data in `filename`, returning the
// top level docsonnet package.
func Load(filename string) (*Package, error) {
data, err := Extract(filename)
func Load(filename string, opts Opts) (*Package, error) {
data, err := Extract(filename, opts)
if err != nil {
return nil, err
}
@ -25,7 +29,7 @@ func Load(filename string) (*Package, error) {
// information, exactly as they appear in Jsonnet. Keep in mind this
// representation is usually not suitable for any use, use `Transform` to
// convert it to the familiar docsonnet data model.
func Extract(filename string) ([]byte, error) {
func Extract(filename string, opts Opts) ([]byte, error) {
// get load.libsonnet from embedded data
file, err := pkger.Open("/load.libsonnet")
if err != nil {
@ -38,7 +42,7 @@ func Extract(filename string) ([]byte, error) {
// setup Jsonnet vm
vm := jsonnet.MakeVM()
importer, err := newImporter()
importer, err := newImporter(opts.JPath)
if err != nil {
return nil, err
}
@ -74,7 +78,7 @@ type importer struct {
util jsonnet.Contents
}
func newImporter() (*importer, error) {
func newImporter(paths []string) (*importer, error) {
file, err := pkger.Open("/doc-util/main.libsonnet")
if err != nil {
return nil, err
@ -85,7 +89,7 @@ func newImporter() (*importer, error) {
}
return &importer{
fi: jsonnet.FileImporter{},
fi: jsonnet.FileImporter{JPaths: paths},
util: jsonnet.MakeContents(string(load)),
}, nil
}

View file

@ -42,6 +42,7 @@ type Value struct {
Help string `json:"help"`
Type Type `json:"type"`
Default interface{} `json:"default"`
}
// Type is a Jsonnet type

View file

@ -119,6 +119,11 @@ func renderIndex(api docsonnet.Fields, path string, s *slug.Slugger) []md.Elem {
link := "#" + s.Slug("obj "+path+obj.Name)
elems = append(elems, md.Link(md.Code(name), link))
elems = append(elems, md.List(renderIndex(obj.Fields, path+obj.Name+".", s)...))
case v.Value != nil:
val := v.Value
name := md.Text(fmt.Sprintf("%s %s%s", val.Type, path, val.Name))
link := "#" + s.Slug(name.String())
elems = append(elems, md.Link(md.Code(name), link))
}
}
return elems
@ -144,6 +149,23 @@ func renderApi(api docsonnet.Fields, path string) []md.Elem {
md.Text(obj.Help),
)
elems = append(elems, renderApi(obj.Fields, path+obj.Name+".")...)
case v.Value != nil:
val := v.Value
elems = append(elems,
md.Headline(3, fmt.Sprintf("%s %s%s", val.Type, path, val.Name)),
)
if val.Default != nil {
elems = append(elems, md.Paragraph(
md.Italic(md.Text("Default value: ")),
md.Code(md.Text(fmt.Sprint(val.Default))),
))
}
elems = append(elems,
md.Text(val.Help),
)
}
}

File diff suppressed because one or more lines are too long