feat: add log command (#449)

* feat: add log command

* fix: lint

* refactor: remove switch

* fix: use one level style embed

* fix(log): lint

* Update log/command.go

Co-authored-by: Ayman Bagabas <ayman.bagabas@gmail.com>

---------

Co-authored-by: Maas Lalani <maas@lalani.dev>
This commit is contained in:
Ayman Bagabas 2023-11-08 07:43:50 -08:00 committed by GitHub
parent 46328de806
commit 7d51fd8b73
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 189 additions and 20 deletions

View file

@ -14,7 +14,7 @@ jobs:
- name: Install Go
uses: actions/setup-go@v4
with:
go-version: ~1.18
go-version: ~1.19
- name: Checkout code
uses: actions/checkout@v4
@ -31,4 +31,4 @@ jobs:
snapshot:
uses: charmbracelet/meta/.github/workflows/snapshot.yml@main
secrets:
goreleaser_key: ${{ secrets.GORELEASER_KEY }}
goreleaser_key: ${{ secrets.GORELEASER_KEY }}

View file

@ -36,10 +36,10 @@ func (o Options) Run() error {
os.Exit(exit.StatusAborted)
} else if m.(model).confirmation {
os.Exit(0)
} else {
os.Exit(1)
}
os.Exit(1)
return nil
}

10
go.mod
View file

@ -1,6 +1,6 @@
module github.com/charmbracelet/gum
go 1.18
go 1.19
require (
github.com/alecthomas/kong v0.8.1
@ -8,7 +8,8 @@ require (
github.com/charmbracelet/bubbles v0.16.1
github.com/charmbracelet/bubbletea v0.24.2
github.com/charmbracelet/glamour v0.6.1-0.20230531150759-6d5b52861a9d
github.com/charmbracelet/lipgloss v0.9.0
github.com/charmbracelet/lipgloss v0.9.1
github.com/charmbracelet/log v0.3.0
github.com/mattn/go-isatty v0.0.20
github.com/muesli/reflow v0.3.0
github.com/muesli/roff v0.1.0
@ -24,6 +25,7 @@ require (
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
github.com/dlclark/regexp2 v1.8.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
@ -36,10 +38,10 @@ require (
github.com/rivo/uniseg v0.4.4 // indirect
github.com/yuin/goldmark v1.5.4 // indirect
github.com/yuin/goldmark-emoji v1.0.1 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
golang.org/x/net v0.8.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/term v0.6.0 // indirect
golang.org/x/text v0.8.0 // indirect
)

20
go.sum
View file

@ -18,14 +18,19 @@ github.com/charmbracelet/bubbletea v0.24.2 h1:uaQIKx9Ai6Gdh5zpTbGiWpytMU+CfsPp06
github.com/charmbracelet/bubbletea v0.24.2/go.mod h1:XdrNrV4J8GiyshTtx3DNuYkR1FDaJmO3l2nejekbsgg=
github.com/charmbracelet/glamour v0.6.1-0.20230531150759-6d5b52861a9d h1:S4Ejl/M2VrryIgDrDbiuvkwMUDa67/t/H3Wz3i2/vUw=
github.com/charmbracelet/glamour v0.6.1-0.20230531150759-6d5b52861a9d/go.mod h1:swCB3CXFsh22H1ESDYdY1tirLiNqCziulDyJ1B6Nt7Q=
github.com/charmbracelet/lipgloss v0.9.0 h1:BHIM7U4vX77xGEld8GrTKspBMtSv7j0wxPCH73nrdxE=
github.com/charmbracelet/lipgloss v0.9.0/go.mod h1:h8KDyaivONasw1Bhb4nWiKlk4P1wHPly+3+3v6EFMmA=
github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg=
github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I=
github.com/charmbracelet/log v0.3.0 h1:u5aB2KJDgNZo4WOfOC8C+KvGIkJ2rCFNlPWDu6xhnqI=
github.com/charmbracelet/log v0.3.0/go.mod h1:OR4E1hutLsax3ZKpXbgUqPtTjQfrh1pG3zwHGWuuq8g=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/dlclark/regexp2 v1.8.1 h1:6Lcdwya6GjPUNsBct8Lg/yRPwMhABj269AAzdGSiR+0=
github.com/dlclark/regexp2 v1.8.1/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
@ -56,28 +61,31 @@ github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo
github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f h1:MvTmaQdww/z0Q4wrYjDSCcZ78NoftLQyHBSLW/Cx79Y=
github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.5.4 h1:2uY/xC0roWy8IBEGLgB1ywIoEJFGmRrX21YQcvGZzjU=
github.com/yuin/goldmark v1.5.4/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os=
github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

10
gum.go
View file

@ -11,6 +11,7 @@ import (
"github.com/charmbracelet/gum/format"
"github.com/charmbracelet/gum/input"
"github.com/charmbracelet/gum/join"
"github.com/charmbracelet/gum/log"
"github.com/charmbracelet/gum/man"
"github.com/charmbracelet/gum/pager"
"github.com/charmbracelet/gum/spin"
@ -204,4 +205,13 @@ type Gum struct {
// $ gum write > output.text
//
Write write.Options `cmd:"" help:"Prompt for long-form text"`
// Log provides a shell script interface for logging using Log.
// https://github.com/charmbracelet/log
//
// It can be used to log messages to output.
//
// $ gum log --level info "Hello, world!"
//
Log log.Options `cmd:"" help:"Log messages to output"`
}

120
log/command.go Normal file
View file

@ -0,0 +1,120 @@
package log
import (
"errors"
"math"
"os"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
)
// Run is the command-line interface for logging text.
func (o Options) Run() error {
l := log.New(os.Stderr)
if o.File != "" {
f, err := os.OpenFile(o.File, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
if err != nil {
return fmt.Errorf("error opening file: %w", err)
}
defer f.Close() //nolint:errcheck
l.SetOutput(f)
}
l.SetPrefix(o.Prefix)
l.SetLevel(-math.MaxInt32) // log all levels
l.SetReportTimestamp(o.Time)
l.SetTimeFormat(o.TimeFormat)
st := log.DefaultStyles()
defaultColors := map[log.Level]lipgloss.Color{
log.DebugLevel: lipgloss.Color("63"),
log.InfoLevel: lipgloss.Color("83"),
log.WarnLevel: lipgloss.Color("192"),
log.ErrorLevel: lipgloss.Color("204"),
log.FatalLevel: lipgloss.Color("134"),
}
lvlStyle := o.LevelStyle.ToLipgloss()
if lvlStyle.GetForeground() == lipgloss.Color("") {
lvlStyle = lvlStyle.Foreground(defaultColors[levelToLog[o.Level]])
}
lvl := levelToLog[o.Level]
st.Levels[lvl] = lvlStyle.
SetString(strings.ToUpper(lvl.String())).
Inline(true)
st.Timestamp = o.TimeStyle.ToLipgloss().
Inline(true)
st.Prefix = o.PrefixStyle.ToLipgloss().
Inline(true)
st.Message = o.MessageStyle.ToLipgloss().
Inline(true)
st.Key = o.KeyStyle.ToLipgloss().
Inline(true)
st.Value = o.ValueStyle.ToLipgloss().
Inline(true)
st.Separator = o.SeparatorStyle.ToLipgloss().
Inline(true)
l.SetStyles(st)
switch o.Formatter {
case "json":
l.SetFormatter(log.JSONFormatter)
case "logfmt":
l.SetFormatter(log.LogfmtFormatter)
case "text":
l.SetFormatter(log.TextFormatter)
}
var arg0 string
var args []interface{}
if len(o.Text) > 0 {
arg0 = o.Text[0]
}
if len(o.Text) > 1 {
args = make([]interface{}, len(o.Text[1:]))
for i, arg := range o.Text[1:] {
args[i] = arg
}
}
logger := map[string]logger{
"none": {printf: l.Printf, print: l.Print},
"debug": {printf: l.Debugf, print: l.Debug},
"info": {printf: l.Infof, print: l.Info},
"warn": {printf: l.Warnf, print: l.Warn},
"error": {printf: l.Errorf, print: l.Error},
"fatal": {printf: l.Fatalf, print: l.Fatal},
}[o.Level]
if o.Format {
logger.printf(arg0, args...)
} else if o.Structured {
logger.print(arg0, args...)
} else {
logger.print(strings.Join(o.Text, " "))
}
return nil
}
type logger struct {
printf func(string, ...interface{})
print func(interface{}, ...interface{})
}
var levelToLog = map[string]log.Level{
"none": log.Level(math.MaxInt32),
"debug": log.DebugLevel,
"info": log.InfoLevel,
"warn": log.WarnLevel,
"error": log.ErrorLevel,
"fatal": log.FatalLevel,
}

34
log/options.go Normal file
View file

@ -0,0 +1,34 @@
package log
import (
"github.com/alecthomas/kong"
"github.com/charmbracelet/gum/style"
)
// Options is the set of options that can configure a join.
type Options struct {
Text []string `arg:"" help:"Text to log"`
File string `short:"o" help:"Log to file"`
Format bool `short:"f" help:"Format message using printf" xor:"format,structured"`
Formatter string `help:"The log formatter to use" enum:"json,logfmt,text" default:"text"`
Level string `help:"The log level to use" enum:"none,debug,info,warn,error,fatal" default:"none"`
Prefix string `help:"Prefix to print before the message"`
Structured bool `short:"s" help:"Use structured logging" xor:"format,structured"`
Time bool `help:"Whether to print the time"`
TimeFormat string `help:"The time format to use" default:"2006/01/02 15:04:05"`
LevelStyle style.Styles `embed:"" prefix:"level." help:"The style of the level being used" set:"defaultBold=true" envprefix:"GUM_LOG_LEVEL_"` //nolint:staticcheck
TimeStyle style.Styles `embed:"" prefix:"time." help:"The style of the time" envprefix:"GUM_LOG_TIME_"`
PrefixStyle style.Styles `embed:"" prefix:"prefix." help:"The style of the prefix" set:"defaultBold=true" set:"defaultFaint=true" envprefix:"GUM_LOG_PREFIX_"` //nolint:staticcheck
MessageStyle style.Styles `embed:"" prefix:"message." help:"The style of the message" envprefix:"GUM_LOG_MESSAGE_"`
KeyStyle style.Styles `embed:"" prefix:"key." help:"The style of the key" set:"defaultFaint=true" envprefix:"GUM_LOG_KEY_"`
ValueStyle style.Styles `embed:"" prefix:"value." help:"The style of the value" envprefix:"GUM_LOG_VALUE_"`
SeparatorStyle style.Styles `embed:"" prefix:"separator." help:"The style of the separator" set:"defaultFaint=true" envprefix:"GUM_LOG_SEPARATOR_"`
}
// BeforeReset hook. Used to unclutter style flags.
func (o Options) BeforeReset(ctx *kong.Context) error {
style.HideFlags(ctx)
return nil
}

View file

@ -87,13 +87,8 @@ func (o Options) Run() error {
}
if o.Print {
headers := make([]any, 0, len(columnNames))
for _, name := range columnNames {
headers = append(headers, name)
}
table := ltable.New().
Headers(headers...).
Headers(columnNames...).
Rows(data...).
BorderStyle(o.BorderStyle.ToLipgloss()).
Border(style.Border[o.Border]).