Skip to content

Commit

Permalink
feat: return error
Browse files Browse the repository at this point in the history
  • Loading branch information
op committed May 10, 2024
1 parent 7db4c88 commit 0388514
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,19 @@ slog.SetDefault(slog.New(log.Default()))
It is possible to request a specific theme.

```go
log.SetStyles(redlog.Theme("catppuccin"))
styles, _ := redlog.Theme("catppuccin")
logger := log.New(os.Stderr)
logger.SetStyles(styles)
```

And with a specific variation of the theme.

```go
log.SetStyles(redlog.Theme("catppuccin", redlog.WithVariant("mocha")))
styles, err := redlog.Theme("catppuccin", redlog.WithVariant("mocha"))
if err != nil {
log.Fatal(err)
}
log.SetStyles(styles)
```

## Specific theme
Expand Down
19 changes: 13 additions & 6 deletions redlog.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package redlog

import (
"errors"

"github.com/charmbracelet/log"
"github.com/op/redlog/internal/themes"
)

var (
ErrUnknownTheme = errors.New("unknown theme")
ErrUnknownVariant = errors.New("unknown variant")
)

// Default is the default theme style.
var Default = themes.Default.Default.Styles

Expand All @@ -15,23 +22,23 @@ func WithVariant(name string) func(*option) {

// Theme returns the most suitable theme given the provided arguments.
//
// This function will fallback to the default theme or the found themes
// variant, if the requested was not found.
func Theme(name string, opts ...Option) *log.Styles {
// This function will always return a usable style, together with an error if
// the requested theme or variant was not found.
func Theme(name string, opts ...Option) (*log.Styles, error) {
o := option{name: name}
for _, opt := range opts {
opt(&o)
}

t, ok := themes.ByName(o.name)
if !ok {
return Default
return Default, ErrUnknownTheme
}
v, ok := themes.VariantByName(t, o.variant)
if !ok {
return t.Default.Styles
return t.Default.Styles, ErrUnknownVariant
}
return v.Styles
return v.Styles, nil
}

type Option func(*option)
Expand Down

0 comments on commit 0388514

Please sign in to comment.