Skip to content

Commit

Permalink
feat: document plain values (#12)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
sh0rez authored Jul 27, 2020
1 parent 4c6f532 commit 2f9dcb2
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 11 deletions.
25 changes: 24 additions & 1 deletion doc-util/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -134,4 +145,16 @@ The `withFields` modifier overrides the fields property of an already created ob
new(name, url, help)
```

new creates a new package with given `name`, `import` URL and `help` text
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
12 changes: 12 additions & 0 deletions doc-util/main.libsonnet
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
27 changes: 26 additions & 1 deletion pkg/docsonnet/fast.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
16 changes: 10 additions & 6 deletions pkg/docsonnet/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 {
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand All @@ -85,7 +89,7 @@ func newImporter() (*importer, error) {
}

return &importer{
fi: jsonnet.FileImporter{},
fi: jsonnet.FileImporter{JPaths: paths},
util: jsonnet.MakeContents(string(load)),
}, nil
}
Expand Down
3 changes: 2 additions & 1 deletion pkg/docsonnet/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ type Value struct {
Name string `json:"-"`
Help string `json:"help"`

Type Type `json:"type"`
Type Type `json:"type"`
Default interface{} `json:"default"`
}

// Type is a Jsonnet type
Expand Down
22 changes: 22 additions & 0 deletions pkg/render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
)
}
}

Expand Down
2 changes: 1 addition & 1 deletion pkged.go

Large diffs are not rendered by default.

0 comments on commit 2f9dcb2

Please sign in to comment.