Skip to content

Commit

Permalink
bind: refactor osFileFlag to FileFlag
Browse files Browse the repository at this point in the history
Change constructor and export so that ad-hoc anyflag initialization is not needed.
  • Loading branch information
mmatczuk committed Jul 9, 2024
1 parent df60e31 commit 1019036
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
16 changes: 10 additions & 6 deletions bind/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,29 @@ package bind
import (
"os"

"github.com/mmatczuk/anyflag"
"github.com/spf13/pflag"
)

// osFileFlag allows to print the file name instead of the file descriptor.
type osFileFlag struct {
pflag.Value
// FileFlag wraps anyflag.NewValue[*os.File] to fix the String() method.
// When the file is nil, it returns an empty string.
type FileFlag struct {
anyflag.Value[*os.File]
f **os.File
}

func (f *osFileFlag) String() string {
func (f *FileFlag) String() string {
if *f.f == nil {
return ""
}
return (*f.f).Name()
}

func newOSFileFlag(v pflag.Value, f **os.File) pflag.Value {
func NewFileFlag(f **os.File, p func(val string) (*os.File, error)) pflag.Value {
if f == nil {
panic("nil pointer")
}
return &osFileFlag{v, f}

v := anyflag.NewValue[*os.File](*f, f, p)
return &FileFlag{*v, f}
}
4 changes: 1 addition & 3 deletions bind/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"fmt"
"net/netip"
"net/url"
"os"
"strings"

"github.com/mmatczuk/anyflag"
Expand Down Expand Up @@ -382,8 +381,7 @@ func TLSServerConfig(fs *pflag.FlagSet, cfg *forwarder.TLSServerConfig, namePref
}

func LogConfig(fs *pflag.FlagSet, cfg *log.Config) {
fs.VarP(newOSFileFlag(anyflag.NewValue[*os.File](nil, &cfg.File,
forwarder.OpenFileParser(log.DefaultFileFlags, log.DefaultFileMode, log.DefaultDirMode)), &cfg.File),
fs.VarP(NewFileFlag(&cfg.File, forwarder.OpenFileParser(log.DefaultFileFlags, log.DefaultFileMode, log.DefaultDirMode)),
"log-file", "", "<path>"+
"Path to the log file, if empty, logs to stdout. "+
"The file is reopened on SIGHUP to allow log rotation using external tools. ")
Expand Down

0 comments on commit 1019036

Please sign in to comment.