Skip to content

Commit

Permalink
Update docs, port bash script to Go, add example (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
mszostok committed May 6, 2023
1 parent e9da3c1 commit a69cf43
Show file tree
Hide file tree
Showing 11 changed files with 228 additions and 122 deletions.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 1 addition & 5 deletions docs/customization/pretty/format.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,10 @@ Check the [`style.Formatting`](https://github.com/mszostok/version/blob/main/sty

## Config file

!!! coming-soon "Coming soon"

See the [mszostok/version#13](https://github.com/mszostok/version/issues/13) issue for reference. If you'd like to see it included in a future release, add 👍 under the issue.

To load the config file, you can:

- Enable loading your custom style from an environment variable via `printer.WithPrettyStyleFromEnv("ENV_NAME_FOR_FILE_PATH")`
- Use the `printer.WithPrettyStyleFile` function directly
- Use the `printer.WithPrettyStyleFile("file_path")` function directly

=== "YAML"

Expand Down
6 changes: 1 addition & 5 deletions docs/customization/pretty/layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,10 @@ func main() {

## Config file

!!! coming-soon "Coming soon"

See the [mszostok/version#13](https://github.com/mszostok/version/issues/13) issue for reference. If you'd like to see it included in a future release, add 👍 under the issue.

To load the config file, you can:

- Enable loading your custom style from an environment variable via `printer.WithPrettyStyleFromEnv("ENV_NAME_FOR_FILE_PATH")`
- Use `printer.WithPrettyStyleFile` function directly
- Use `printer.WithPrettyStyleFile("file_path")` function directly

=== "YAML"

Expand Down
15 changes: 15 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,21 @@
./example
```

## [Custom Style from environment variable](https://github.com/mszostok/version/tree/main/examples/custom-layout/main.go)

![](assets/examples/screen-custom-layout--env-style.png)

!!! run-example "Run in terminal"

```bash
# Build
export CLI_STYLE="${PWD}/style.yaml"
go build -ldflags "-X 'go.szostok.io/version.buildDate=`date`'" -o example ./custom-layout

# Try out
./example
```

## [Custom Renderer](https://github.com/mszostok/version/tree/main/examples/custom-renderer/main.go)

![](assets/examples/screen-custom-renderer-.png)
Expand Down
21 changes: 15 additions & 6 deletions examples/custom-layout/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ import (
)

func main() {
opts := []printer.ContainerOption{
styleFromEnv, err := printer.WithPrettyStyleFromEnv("CLI_STYLE")
exitOnErr(err)

p := printer.New(
printer.WithPrettyPostRenderHook(SprintInBox),
printer.WithPrettyLayout(&style.Layout{
GoTemplate: layoutGoTpl,
}),
}
p := printer.New(opts...)
if err := p.Print(os.Stdout); err != nil {
log.Fatal(err)
}
styleFromEnv,
)

err = p.Print(os.Stdout)
exitOnErr(err)
}

var layoutGoTpl = heredoc.Doc(`
Expand All @@ -50,3 +53,9 @@ func SprintInBox(body string, isSmartTerminal bool) (string, error) {
}
return "\n" + body, nil
}

func exitOnErr(err error) {
if err != nil {
log.Fatal(err)
}
}
31 changes: 31 additions & 0 deletions examples/style.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
formatting:
header:
prefix: '-> '
color: Magenta
background: ""
options: []
key:
color: Yellow
background: ""
options:
- Bold
val:
color: Green
background: ""
options: []
date:
enableHumanizedSuffix: true

layout:
goTemplate: |
{{ AdjustKeyWidth .ExtraFields }}
{{ Header .Meta.CLIName }}
{{ Key "Version" }} {{ .Version | Val }}
{{ Key "Dirty Build" }} {{ .DirtyBuild | FmtBool | Val }}
{{ Key "Go version" }} {{ .GoVersion | trimPrefix "go"| Val }}
{{ Key "Compiler" }} {{ .Compiler | Val }}
{{ Key "Platform" }} {{ .Platform | Val }}
{{- range $item := (.ExtraFields | Extra) }}
{{ $item.Key | Key }} {{ $item.Value | Val }}
{{- end}}
93 changes: 0 additions & 93 deletions magefiles/hack/gallery.sh

This file was deleted.

4 changes: 1 addition & 3 deletions magefiles/magefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,5 @@ func (Gen) Preview() {
}

func (Gen) Gallery() {
lo.Must0(
shx.MustCmdf("./magefiles/hack/gallery.sh").RunV(),
)
target.Gallery()
}
144 changes: 144 additions & 0 deletions magefiles/target/gallery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package target

import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"

"github.com/mattn/go-shellwords"
"github.com/samber/lo"
)

const (
yellow = "\033[1;33m"
nc = "\033[0m" // No Color
screenshotCommand = "screencapture -x -R0,25,1285,650 %s"
)

var (
repoRootDir = lo.Must(os.Getwd())
currentDir = filepath.Join(repoRootDir, "magefiles", "hack")
assetExamplesDir = fmt.Sprintf("%s/docs/assets/examples", repoRootDir)
)

var (
bigScreenCapture = []Program{
{Name: "plain"},
{Name: "cobra", Args: Args{"version"}},
{Name: "printer", Args: Args{"", "-oyaml", "-ojson", "-oshort"}},
{Name: "custom-formatting"},
}

mediumScreenCapture = []Program{
{Name: "upgrade-notice-sub-cmd", Args: Args{"version check"}},
{Name: "upgrade-notice-custom", Args: Args{"version"}},
{Name: "upgrade-notice-standalone"},
{Name: "printer-post-hook"},
{Name: "upgrade-notice-cobra", Args: Args{"version", "version -ojson"}},
{Name: "custom-layout"},
{Name: "custom-layout",
Suffix: "-env-style",
Envs: fmt.Sprintf("CLI_STYLE=%s", filepath.Join(repoRootDir, "examples/style.yaml"))},
{Name: "custom-renderer"},
{Name: "custom-fields"},
}
smallScreenCapture = []Program{
{Name: "cobra", Args: Args{"version -h"}},
{Name: "cobra-alias", Args: Args{"version -h"}},
}
)

type Program struct {
Name string
Args Args
Suffix string
Envs string
}
type Args []string

func (p *Program) Run() {
if p == nil {
return
}
if p.Args == nil {
capture(p.Name, "", p.Envs, p.Suffix)
return
}
for _, arg := range p.Args {
capture(p.Name, arg, p.Envs, p.Suffix)
}
}

func Gallery() {
remove(assetExamplesDir)
lo.Must0(os.MkdirAll(assetExamplesDir, os.ModePerm))

// Big
setup("version-cmd")
for _, program := range bigScreenCapture {
program.Run()
}

// Medium
setup("custom-pretty-cmd")
for _, program := range mediumScreenCapture {
program.Run()
}

// Small
setup("help-cmd")
for _, program := range smallScreenCapture {
program.Run()
}

}

func setup(profile string) {
lo.Must0(os.Chdir(currentDir))
fmt.Printf("\033]50;SetProfile=%s\a", profile)
run("osascript resize_window.scpt")
run("clear")
time.Sleep(500 * time.Millisecond) // wait for the setup to establish
}

func remove(path string) {
if _, err := os.Stat(path); !os.IsNotExist(err) {
lo.Must0(os.RemoveAll(path))
}
}

func capture(program string, arg string, env string, suffix string) {
run("clear")

lo.Must0(os.Chdir(filepath.Join(repoRootDir, "examples")))
run(`go install -ldflags "-X 'go.szostok.io/version.buildDate=%s' -X 'go.szostok.io/version.version=v0.6.1'" ./%s`, time.Now(), program)
lo.Must0(os.Chdir(os.Getenv("HOME")))
fmt.Printf("▲ %s%s%s %s\n", yellow, program, nc, arg)

toRun := fmt.Sprintf("%s %s", program, arg)
if env != "" {
toRun = fmt.Sprintf("%s %s", env, toRun)
}

run(toRun)

fileName := fmt.Sprintf("%s/screen-%s-%s%s.png", assetExamplesDir, program, strings.ReplaceAll(arg, " ", "_"), suffix)
remove(fileName)
run(screenshotCommand, fileName)
}

func run(format string, a ...interface{}) {
rawCmd := fmt.Sprintf(format, a...)

envs, args := lo.Must2(shellwords.ParseWithEnvs(rawCmd))

c := exec.Command(args[0], args[1:]...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Env = append(os.Environ(), envs...)

lo.Must0(c.Run())
}

0 comments on commit a69cf43

Please sign in to comment.