Skip to content

Commit

Permalink
feat: use charm/log (#158)
Browse files Browse the repository at this point in the history
* feat: use charm/log

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

* chore: fmt

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

* chore: lint

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>

---------

Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 authored Mar 9, 2023
1 parent 9c93fe8 commit e4bf3a4
Show file tree
Hide file tree
Showing 17 changed files with 85 additions and 53 deletions.
2 changes: 1 addition & 1 deletion _example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package main

import (
"fmt"
"log"
"path/filepath"

"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/keygen"
"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/activeterm"
Expand Down
12 changes: 6 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import (
"errors"
"fmt"
"io"
"log"
"os"

tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/log"
"github.com/muesli/termenv"
"golang.org/x/crypto/ssh"
gossh "golang.org/x/crypto/ssh"
Expand Down Expand Up @@ -54,19 +54,19 @@ func createSession(conf *gossh.ClientConfig, e *Endpoint, abort <-chan os.Signal
if err := session.Setenv(k, v); err != nil {
return session, conn, cl, fmt.Errorf("could not set env: %s=%s: %w", k, v, err)
}
log.Printf("setting env %s = %q", k, v)
log.Info("setting env", "key", k, "value", v)
}
return session, conn, cl, nil
}

func shellAndWait(session *gossh.Session) error {
log.Println("requesting shell")
log.Info("requesting shell")
if err := session.Shell(); err != nil {
return fmt.Errorf("failed to start shell: %w", err)
}
if err := session.Wait(); err != nil {
if errors.Is(err, &ssh.ExitMissingError{}) {
log.Println("exit was missing, assuming exit 0")
log.Info("exit was missing, assuming exit 0")
return nil
}
return fmt.Errorf("session failed: %w", err)
Expand All @@ -75,7 +75,7 @@ func shellAndWait(session *gossh.Session) error {
}

func runAndWait(session *gossh.Session, cmd string) error {
log.Printf("running %q", cmd)
log.Info("running", "command", cmd)
if err := session.Run(cmd); err != nil {
return fmt.Errorf("failed to run %q: %w", cmd, err)
}
Expand All @@ -91,7 +91,7 @@ func (c closers) close() {
// do not print EOF errors... not a big deal anyway
continue
}
log.Println("failed to close:", err)
log.Warn("failed to close", "err", err)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions client_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package wishlist

import (
"fmt"
"log"

"github.com/charmbracelet/log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)

func forwardAgent(agt agent.Agent, session *ssh.Session, client *ssh.Client) error {
if agt == nil {
log.Println("requested ForwardAgent, but no agent is available")
log.Info("requested ForwardAgent, but no agent is available")
return nil
}
if err := agent.RequestAgentForwarding(session); err != nil {
Expand Down
28 changes: 23 additions & 5 deletions client_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package wishlist
import (
"errors"
"fmt"
"log"
"net"
"os"
"path/filepath"

"github.com/charmbracelet/keygen"
"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wishlist/home"
Expand Down Expand Up @@ -73,7 +73,11 @@ func agentAuthMethod(agt agent.Agent) gossh.AuthMethod {

signers, _ := agt.Signers()
for _, signer := range signers {
log.Printf("offering public key via ssh agent: %s %s", signer.PublicKey().Type(), gossh.FingerprintSHA256(signer.PublicKey()))
log.Info(
"offering public key via ssh agent",
"key.type", signer.PublicKey().Type(),
"key.fingerprint", gossh.FingerprintSHA256(signer.PublicKey()),
)
}
return gossh.PublicKeysCallback(agt.Signers)
}
Expand Down Expand Up @@ -128,7 +132,11 @@ func tryRemoteAuthAgent(s ssh.Session) (gossh.AuthMethod, agent.Agent, closers,

signers, _ := agent.Signers()
for _, signer := range signers {
log.Printf("offering public key via ssh agent: %s %s", signer.PublicKey().Type(), gossh.FingerprintSHA256(signer.PublicKey()))
log.Info(
"offering public key via ssh agent",
"key.type", signer.PublicKey().Type(),
"key.fingerprint", gossh.FingerprintSHA256(signer.PublicKey()),
)
}
return gossh.PublicKeysCallback(agent.Signers), agent, closers, nil
}
Expand All @@ -151,7 +159,12 @@ func tryNewKey() (gossh.AuthMethod, error) {
return nil, err //nolint:wrapcheck
}

log.Printf("offering public key: %s %s %s", path, signer.PublicKey().Type(), gossh.FingerprintSHA256(signer.PublicKey()))
log.Info(
"offering public key",
"key.path", path,
"key.type", signer.PublicKey().Type(),
"key.fingerprint", gossh.FingerprintSHA256(signer.PublicKey()),
)

if key.KeyPairExists() {
return gossh.PublicKeys(signer), nil
Expand Down Expand Up @@ -246,7 +259,12 @@ func parsePrivateKey(path string, password []byte) (gossh.AuthMethod, error) {
return nil, fmt.Errorf("failed to parse private key: %q: %w", path, err)
}

log.Printf("offering public key: %s %s %s", path, signer.PublicKey().Type(), gossh.FingerprintSHA256(signer.PublicKey()))
log.Info(
"offering public key",
"key.path", path,
"key.type", signer.PublicKey().Type(),
"key.fingerprint", gossh.FingerprintSHA256(signer.PublicKey()),
)
return gossh.PublicKeys(signer), nil
}

Expand Down
8 changes: 4 additions & 4 deletions client_local.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"os/user"
"path/filepath"

tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/log"
"github.com/muesli/cancelreader"
"golang.org/x/crypto/ssh"
"golang.org/x/term"
Expand Down Expand Up @@ -116,15 +116,15 @@ func (s *localSession) Run() error {
return fmt.Errorf("requested a TTY, but current session is not TTY, aborting")
}

log.Println("requesting tty")
log.Info("requesting tty")
originalState, err := term.MakeRaw(fd)
if err != nil {
return fmt.Errorf("failed get terminal state: %w", err)
}

defer func() {
if err := term.Restore(fd, originalState); err != nil {
log.Println("couldn't restore terminal state:", err)
log.Warn("couldn't restore terminal state", "err", err)
}
}()

Expand All @@ -141,7 +141,7 @@ func (s *localSession) Run() error {
defer cancel()
go s.notifyWindowChanges(ctx, session)
} else {
log.Println("did not request a tty")
log.Info("did not request a tty")
}

if s.endpoint.RemoteCommand == "" {
Expand Down
13 changes: 9 additions & 4 deletions client_remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package wishlist
import (
"fmt"
"io"
"log"

tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wishlist/blocking"
gossh "golang.org/x/crypto/ssh"
Expand Down Expand Up @@ -70,7 +70,12 @@ func (s *remoteSession) Run() error {
return fmt.Errorf("failed to create session: %w", err)
}

log.Printf("%s connect to %q, %s", s.parentSession.User(), s.endpoint.Name, s.parentSession.RemoteAddr().String())
log.Info(
"connect",
"user", s.parentSession.User(),
"endpoint", s.endpoint.Name,
"remote.addr", s.parentSession.RemoteAddr().String(),
)

session.Stdout = s.parentSession
session.Stderr = s.parentSession.Stderr()
Expand All @@ -83,7 +88,7 @@ func (s *remoteSession) Run() error {
}

if s.endpoint.RemoteCommand == "" || s.endpoint.RequestTTY {
log.Println("requesting tty")
log.Info("requesting tty")
pty, winch, ok := s.parentSession.Pty()
if !ok {
return fmt.Errorf("requested a tty, but current session doesn't allow one")
Expand Down Expand Up @@ -115,7 +120,7 @@ func (s *remoteSession) notifyWindowChanges(session *gossh.Session, done <-chan
return
}
if err := session.WindowChange(w.Height, w.Width); err != nil {
log.Println("failed to notify window change:", err)
log.Warn("failed to notify window change", "err", err)
return
}
}
Expand Down
6 changes: 3 additions & 3 deletions client_signals_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ package wishlist

import (
"context"
"log"
"os"
"os/signal"
"syscall"

"github.com/charmbracelet/log"
"golang.org/x/crypto/ssh"
"golang.org/x/term"
)
Expand All @@ -28,10 +28,10 @@ func (s *localSession) notifyWindowChanges(ctx context.Context, session *ssh.Ses
case <-sig:
w, h, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
log.Println(err)
log.Info("could not get term size", "err", err)
}
if err := session.WindowChange(h, w); err != nil {
log.Println(err)
log.Info("could not notify term size change", "err", err)
}
}
}
Expand Down
18 changes: 10 additions & 8 deletions cmd/wishlist/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"runtime/debug"
Expand All @@ -13,6 +12,7 @@ import (

tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/keygen"
"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/activeterm"
Expand Down Expand Up @@ -100,13 +100,13 @@ var serverCmd = &cobra.Command{
}

if refreshInterval > 0 {
log.Println("Will refresh endpoints every", refreshInterval)
log.Info("endpoints", "refresh.interval", refreshInterval)
config.EndpointChan = make(chan []*wishlist.Endpoint)
ticker := time.NewTicker(refreshInterval)
defer ticker.Stop()
go func() {
for range ticker.C {
log.Println("Refreshing endpoints...")
log.Info("refreshing endpoints...")
reloaded, err := getConfigFile(path, seed)
if err != nil {
continue
Expand Down Expand Up @@ -173,7 +173,7 @@ func main() {
Version = fmt.Sprintf("%s (%s)", info.Main.Version, CommitSHA)
}
if err := rootCmd.Execute(); err != nil {
log.Fatalln(err)
log.Fatal("command failed", "err", err)
}
}

Expand Down Expand Up @@ -209,15 +209,15 @@ func getConfig(configFile string, seed []*wishlist.Endpoint) (wishlist.Config, s

cfg, err := getConfigFile(path, seed)
if err != nil {
log.Println("Not using", path, ":", err)
log.Info("Not using", "path", path, "err", err)
if errors.Is(err, os.ErrNotExist) {
allErrs = multierror.Append(allErrs, fmt.Errorf("%q: %w", path, err))
continue
}
return wishlist.Config{}, "", err
}

log.Println("Using config from", path)
log.Info("Using configuration file", "path", path)
return cfg, path, nil
}
return wishlist.Config{}, "", fmt.Errorf("no valid config files found: %w", allErrs)
Expand Down Expand Up @@ -281,13 +281,15 @@ func getSSHConfig(path string, seed []*wishlist.Endpoint) (wishlist.Config, erro
}

func workLocally(config wishlist.Config, args []string) error {
f, err := tea.LogToFile("wishlist.log", "")
f, err := os.OpenFile("wishlist.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) //nolint:gomnd
if err != nil {
return err //nolint: wrapcheck
}
log.SetOutput(f)
log.SetLevel(log.DebugLevel)
defer func() {
if err := f.Close(); err != nil {
log.Println(err)
log.Info("failes to close wishlist.log", "err", err)
}
}()

Expand Down
4 changes: 2 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ package wishlist

import (
"fmt"
"log"
"strings"
"time"

"github.com/charmbracelet/log"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/gobwas/glob"
Expand Down Expand Up @@ -64,7 +64,7 @@ func (e Endpoint) Environment(hostenv ...string) map[string]string {
if e.shouldSend(k) {
env[k] = v
} else {
log.Printf("ignored env %s", k)
log.Debug("ignored", "env", k)
}
}

Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/charmbracelet/bubbletea v0.23.2
github.com/charmbracelet/keygen v0.3.0
github.com/charmbracelet/lipgloss v0.6.0
github.com/charmbracelet/log v0.1.2
github.com/charmbracelet/promwish v0.5.0
github.com/charmbracelet/ssh v0.0.0-20221117183211-483d43d97103
github.com/charmbracelet/wish v1.0.0
Expand Down Expand Up @@ -36,6 +37,7 @@ require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/containerd/console v1.0.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ github.com/charmbracelet/keygen v0.3.0 h1:mXpsQcH7DDlST5TddmXNXjS0L7ECk4/kLQYyBc
github.com/charmbracelet/keygen v0.3.0/go.mod h1:1ukgO8806O25lUZ5s0IrNur+RlwTBERlezdgW71F5rM=
github.com/charmbracelet/lipgloss v0.6.0 h1:1StyZB9vBSOyuZxQUcUwGr17JmojPNm87inij9N3wJY=
github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk=
github.com/charmbracelet/log v0.1.2 h1:xmKMxo0T/lcftgggQOhUkS32exku2/ID55FGYbr4nKQ=
github.com/charmbracelet/log v0.1.2/go.mod h1:86XdIdmrubqtL/6u0z+jGFol1bQejBGG/qPSTwGZuQQ=
github.com/charmbracelet/promwish v0.5.0 h1:Oh08pKC/LNQlnXdNu+jDUgrjQvmCd+WzorgB+PYK00g=
github.com/charmbracelet/promwish v0.5.0/go.mod h1:R3mSvCiHlyzu5uK73rNvwz7pP0S3vqRe01EEk2VKPZ8=
github.com/charmbracelet/ssh v0.0.0-20221117183211-483d43d97103 h1:wpHMERIN0pQZE635jWwT1dISgfjbpUcEma+fbPKSMCU=
Expand All @@ -37,6 +39,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
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/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
Expand Down
Loading

0 comments on commit e4bf3a4

Please sign in to comment.