From b966013a2b5c598023d0e74a390c51f03ea54455 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Mon, 17 Apr 2023 08:07:26 +0530 Subject: [PATCH] Make Samefile interface a bit nicer for working with paths --- tools/themes/collection.go | 11 +++------ tools/utils/misc.go | 48 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/tools/themes/collection.go b/tools/themes/collection.go index c0e63d576..12874d75a 100644 --- a/tools/themes/collection.go +++ b/tools/themes/collection.go @@ -830,14 +830,9 @@ func (self *Themes) add_from_dir(dirpath string) error { for _, e := range entries { if !e.IsDir() && strings.HasSuffix(e.Name(), ".conf") { path := filepath.Join(dirpath, e.Name()) - // ignore files if they are the current processes, stdout - // allows using kitten theme --dump-theme > ~/.config/kitty/themes/name.conf - if st, err := os.Stat(path); err == nil { - if st2, err := os.Stdout.Stat(); err == nil && os.SameFile(st, st2) { - continue - } - } - if path == os.Stdout.Name() { + // ignore files if they are the STDOUT of the current processes + // allows using kitten theme --dump-theme name > ~/.config/kitty/themes/name.conf + if utils.Samefile(path, os.Stdout) { continue } if _, err = self.AddFromFile(path); err != nil { diff --git a/tools/utils/misc.go b/tools/utils/misc.go index 0ebb01697..ec57e95a4 100644 --- a/tools/utils/misc.go +++ b/tools/utils/misc.go @@ -4,6 +4,7 @@ package utils import ( "fmt" + "os" "golang.org/x/exp/constraints" "golang.org/x/exp/slices" @@ -153,3 +154,50 @@ func Memset[T any](dest []T, pattern ...T) []T { } return dest } + +type statable interface { + Stat() (os.FileInfo, error) +} + +func Samefile(a, b any) bool { + var sta, stb os.FileInfo + var err error + switch v := a.(type) { + case string: + sta, err = os.Stat(v) + if err != nil { + return false + } + case statable: + sta, err = v.Stat() + if err != nil { + return false + } + case *os.FileInfo: + sta = *v + case os.FileInfo: + sta = v + default: + panic(fmt.Sprintf("a must be a string, os.FileInfo or a stat-able object not %T", v)) + } + switch v := b.(type) { + case string: + stb, err = os.Stat(v) + if err != nil { + return false + } + case statable: + stb, err = v.Stat() + if err != nil { + return false + } + case *os.FileInfo: + stb = *v + case os.FileInfo: + stb = v + default: + panic(fmt.Sprintf("b must be a string, os.FileInfo or a stat-able object not %T", v)) + } + + return os.SameFile(sta, stb) +}