Implement wildcards
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -233,12 +234,32 @@ func ParseYAMLFile(filename, workdir string) ([]LinkInstruction, error) {
|
||||
config.Links = instructions
|
||||
}
|
||||
|
||||
toRemove := []int{}
|
||||
for i, link := range config.Links {
|
||||
if strings.Contains(link.Source, "*") {
|
||||
log.Printf("Expanding wildcard source %s%s%s in YAML file %s%s%s", SourceColor, link.Source, DefaultColor, SourceColor, filename, DefaultColor)
|
||||
newlinks, err := ExpandWildcard(link.Source, workdir, link.Target)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error expanding wildcard: %w", err)
|
||||
}
|
||||
log.Printf("Expanded wildcard source %s%s%s in YAML file %s%s%s to %d links", SourceColor, link.Source, DefaultColor, SourceColor, filename, DefaultColor, len(newlinks))
|
||||
config.Links = append(config.Links, newlinks...)
|
||||
toRemove = append(toRemove, i)
|
||||
}
|
||||
}
|
||||
|
||||
for i := len(toRemove) - 1; i >= 0; i-- {
|
||||
config.Links = slices.Delete(config.Links, toRemove[i], 1)
|
||||
}
|
||||
|
||||
for i := range config.Links {
|
||||
config.Links[i].Tidy()
|
||||
config.Links[i].Source, _ = ConvertHome(config.Links[i].Source)
|
||||
config.Links[i].Target, _ = ConvertHome(config.Links[i].Target)
|
||||
config.Links[i].Source = NormalizePath(config.Links[i].Source, workdir)
|
||||
config.Links[i].Target = NormalizePath(config.Links[i].Target, workdir)
|
||||
link := &config.Links[i]
|
||||
|
||||
link.Tidy()
|
||||
link.Source, _ = ConvertHome(link.Source)
|
||||
link.Target, _ = ConvertHome(link.Target)
|
||||
link.Source = NormalizePath(link.Source, workdir)
|
||||
link.Target = NormalizePath(link.Target, workdir)
|
||||
|
||||
// If Delete is true, Force must also be true
|
||||
if config.Links[i].Delete {
|
||||
@@ -249,6 +270,26 @@ func ParseYAMLFile(filename, workdir string) ([]LinkInstruction, error) {
|
||||
return config.Links, nil
|
||||
}
|
||||
|
||||
func ExpandWildcard(source, workdir, target string) (links []LinkInstruction, err error) {
|
||||
dir := filepath.Dir(source)
|
||||
pattern := filepath.Base(source)
|
||||
|
||||
files, err := filepath.Glob(filepath.Join(workdir, dir, pattern))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error expanding wildcard: %w", err)
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
link := LinkInstruction{
|
||||
Source: file,
|
||||
Target: filepath.Join(target, filepath.Base(file)),
|
||||
}
|
||||
links = append(links, link)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func IsYAMLFile(filename string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(filename))
|
||||
return ext == ".yaml" || ext == ".yml"
|
||||
|
Reference in New Issue
Block a user