Make Samefile interface a bit nicer for working with paths

This commit is contained in:
Kovid Goyal 2023-04-17 08:07:26 +05:30
parent 046fbb860b
commit b966013a2b
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 51 additions and 8 deletions

View File

@ -830,14 +830,9 @@ func (self *Themes) add_from_dir(dirpath string) error {
for _, e := range entries { for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".conf") { if !e.IsDir() && strings.HasSuffix(e.Name(), ".conf") {
path := filepath.Join(dirpath, e.Name()) path := filepath.Join(dirpath, e.Name())
// ignore files if they are the current processes, stdout // ignore files if they are the STDOUT of the current processes
// allows using kitten theme --dump-theme > ~/.config/kitty/themes/name.conf // allows using kitten theme --dump-theme name > ~/.config/kitty/themes/name.conf
if st, err := os.Stat(path); err == nil { if utils.Samefile(path, os.Stdout) {
if st2, err := os.Stdout.Stat(); err == nil && os.SameFile(st, st2) {
continue
}
}
if path == os.Stdout.Name() {
continue continue
} }
if _, err = self.AddFromFile(path); err != nil { if _, err = self.AddFromFile(path); err != nil {

View File

@ -4,6 +4,7 @@ package utils
import ( import (
"fmt" "fmt"
"os"
"golang.org/x/exp/constraints" "golang.org/x/exp/constraints"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
@ -153,3 +154,50 @@ func Memset[T any](dest []T, pattern ...T) []T {
} }
return dest 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)
}