Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[go] logrus to slog #16

Merged
merged 7 commits into from
Sep 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Main target audience is private golang projects or anyone, who wants to keep doc

`go build go2md.go` will produce you go2md binary.

Imports: 5
Imports: 8

## Index
- [Variables](variables)
Expand Down
1 change: 1 addition & 0 deletions cmd/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ Default is to generate markdown from current directory.
--

Generated by [github.com/jylitalo/go2md](https://github.com/jylitalo/go2md/) v0.5.1

2 changes: 2 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ func NewCommand(writer io.WriteCloser, version string) *cobra.Command {
}
cmd.Flags().StringP("directory", "d", ".", "root directory")
cmd.Flags().StringP("output", "o", "", "write output to file")
cmd.Flags().Bool("debug", false, "debug level logging")
cmd.Flags().Bool("ignore-main", false, "ignore directory, if its main package")
cmd.Flags().Bool("no-color", false, "don't use ANSI colors in logging")
cmd.Flags().BoolP("recursive", "r", false, "go directories recursively")
cmd.Flags().BoolP("version", "v", false, "print go2md version")
return cmd
Expand Down
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ module github.com/jylitalo/go2md
go 1.21.1

require (
github.com/sirupsen/logrus v1.9.3
github.com/jylitalo/tint v1.0.3
github.com/mattn/go-isatty v0.0.19
github.com/spf13/cobra v1.7.0
)

require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
golang.org/x/sys v0.12.0 // indirect
)
21 changes: 7 additions & 14 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/jylitalo/tint v1.0.3 h1:+7p85lCc825nArtkbd5LBFH7PaUOWNQx0K4O/640zSw=
github.com/jylitalo/tint v1.0.3/go.mod h1:/0YpWWwwl9EEMDcMH5G3HZpR4gTEZ3Y451hlxmDSBdM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/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=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
30 changes: 27 additions & 3 deletions go2md.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package main
import (
_ "embed"
"io"
"log/slog"
"os"
"slices"

"github.com/jylitalo/go2md/cmd"

log "github.com/sirupsen/logrus"
"github.com/jylitalo/tint"
"github.com/mattn/go-isatty"
)

//go:embed version.txt
Expand All @@ -17,8 +19,30 @@ func execute(writer io.WriteCloser) error {
return cmd.NewCommand(writer, Version).Execute()
}

func setupLogging(debug bool, color bool) {
logLevel := slog.LevelInfo
if debug {
logLevel = slog.LevelDebug
}
w := os.Stderr
log := slog.New(tint.NewHandler(w, &tint.Options{
Level: logLevel,
NoColor: !isatty.IsTerminal(w.Fd()) || !color,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
},
}))
slog.SetDefault(log)
slog.Debug("go2md started")
}

func main() {
setupLogging(slices.Contains(os.Args, "--debug"), !slices.Contains(os.Args, "--no-color"))
if err := execute(os.Stdout); err != nil {
log.Fatal(err)
slog.Error(err.Error())
os.Exit(1)
}
}
8 changes: 4 additions & 4 deletions pkg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var ErrNoPackageFound = errors.New("couldn't find package from ")

## Functions

### func [RunDirTree](./run.go#L131)
### func [RunDirTree](./run.go#L130)

<pre>
func RunDirTree(out <a href="#type-outputsettings">OutputSettings</a>, version string, includeMain bool) error
Expand All @@ -43,7 +43,7 @@ RunDirTree checks given directory and its subdirectories with RunDirectory().
Ignores all ErrNoPackageFound errors from RunDirectory.


### func [RunDirectory](./run.go#L121)
### func [RunDirectory](./run.go#L120)

<pre>
func RunDirectory(out <a href="#type-outputsettings">OutputSettings</a>, version string, includeMain bool) error
Expand All @@ -53,7 +53,7 @@ Returns ErrNoPackagesFound if includeMain=true and current directory has only ma


## Types
### type [OutputSettings](./run.go#L22)
### type [OutputSettings](./run.go#L21)

<pre>
type OutputSettings struct {
Expand All @@ -62,7 +62,7 @@ type OutputSettings struct {
Filename string
}
</pre>
### func (output *OutputSettings) [Writer](./run.go#L107)
### func (output *OutputSettings) [Writer](./run.go#L106)
<pre>
func (output *OutputSettings) Writer() (<a href="https://pkg.go.dev/io#WriteCloser">io.WriteCloser</a>, error)
</pre>
Expand Down
38 changes: 22 additions & 16 deletions pkg/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import (
"fmt"
"go/ast"
"go/doc"
"log/slog"
"path/filepath"
"regexp"
"strings"
"text/template"

log "github.com/sirupsen/logrus"
)

var (
Expand Down Expand Up @@ -52,7 +51,7 @@ func intoImportLink(text string, imports map[string]string) string {
if exportedType.MatchString(text) {
return fmt.Sprintf(`<a href="#%s">%s</a>`, intoLink("type "+text), text)
}
log.Warningf("Internal type: %s", text)
slog.Warn(fmt.Sprintf("Internal type: %s", text))
return text
}
fields := strings.SplitN(text, ".", 2)
Expand All @@ -63,7 +62,10 @@ func intoImportLink(text string, imports map[string]string) string {
if strings.Join(modFields[0:3], "/") == mainPath {
relPath, err := filepath.Rel(imports["main"], modPath)
if err != nil {
log.WithFields(log.Fields{"imports['main']": imports["main"], "modPath": modPath}).Fatal("Unable to establish relative path")
panic(fmt.Errorf(
"Unable to establish relative path imports['main']=%#v, modPath=%s",
imports["main"], modPath,
))
}
return fmt.Sprintf(`<a href="%s/README.md#%s">%s</a>`, relPath, intoLink("type "+fields[1]), text)
}
Expand Down Expand Up @@ -170,9 +172,10 @@ func funcHeading(lineNumbers map[string]lineNumber) func(doc.Func) string {
if value, ok := lineNumbers[key]; ok {
return fmt.Sprintf("func %s[%s](./%s#L%d)", recv, funcObj.Name, value.filename, value.line)
}
log.WithFields(log.Fields{
"key": key, "lineNumbers": fmt.Sprintf("%#v", lineNumbers),
}).Error("Failed to find line number in funcHeading")
slog.Error(
"Failed to find line number in funcHeading",
"key", key, "lineNumbers", fmt.Sprintf("%#v", lineNumbers),
)
return fmt.Sprintf("func %s%s", recv, funcObj.Name)
}
}
Expand Down Expand Up @@ -207,9 +210,10 @@ func typeElem(typeObj doc.Type) string {
lines = append(lines, " "+funcElem(*funcObj))
}
default:
log.WithFields(log.Fields{
"spec.(*ast.TypeSpec).Type": fmt.Sprintf("%#v", spec.(*ast.TypeSpec).Type)},
).Fatalf("unknown parameter type %#v", t)
panic(fmt.Errorf(
"unknown parameter type %#v spec.(*ast.TypeSpec).Type=%#v",
t, spec.(*ast.TypeSpec).Type,
))
}
}
fields := ""
Expand All @@ -225,9 +229,10 @@ func typeHeading(lineNumbers map[string]lineNumber) func(string) string {
if value, ok := lineNumbers[key]; ok {
return fmt.Sprintf("type [%s](./%s#L%d)", name, value.filename, value.line)
}
log.WithFields(log.Fields{
"key": key, "lineNumbers": fmt.Sprintf("%#v", lineNumbers),
}).Error("Failed to find line number in typeHeading")
slog.Error(
"Failed to find line number in typeHeading",
"key", key, "lineNumbers", fmt.Sprintf("%#v", lineNumbers),
)
return "type " + name
}
}
Expand Down Expand Up @@ -279,9 +284,10 @@ func typeSection(imports map[string]string) func(doc.Type) string {
lines = append(lines, "")
}
default:
log.WithFields(log.Fields{
"spec.(*ast.TypeSpec).Type": fmt.Sprintf("%#v", spec.(*ast.TypeSpec).Type)},
).Fatalf("unknown parameter type %#v", t)
panic(fmt.Errorf(
"unknown parameter type %#v spec.(*ast.TypeSpec).Type=%#v",
t, spec.(*ast.TypeSpec).Type,
))
}
}
fields := ""
Expand Down
8 changes: 3 additions & 5 deletions pkg/mod.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import (
"bufio"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"

log "github.com/sirupsen/logrus"
)

var (
Expand All @@ -17,7 +16,6 @@ var (
)

func hasGoMod(dir string) bool {
// log.Info("Checking " + dir)
_, err := os.Stat(dir + "/go.mod")
return !os.IsNotExist(err)
}
Expand All @@ -26,7 +24,7 @@ func moduleName(dir string) (string, error) {
f, err := os.Open(filepath.Clean(dir + "/go.mod"))
if err != nil {
err = fmt.Errorf("moduleName failed: %w", err)
log.WithFields(log.Fields{"dir": dir}).Error(err)
slog.Error(err.Error(), "dir", dir)
return "", err
}
defer f.Close()
Expand All @@ -39,7 +37,7 @@ func moduleName(dir string) (string, error) {
if len(words) > 1 {
return words[1], nil
}
log.WithFields(log.Fields{"line": line}).Error("module name missing from line")
slog.Error("module name missing from line", "line", line)
}
}
return "", fmt.Errorf("%w from %s/go.mod", ErrModuleNameMissing, dir)
Expand Down
Loading