feat: add file-based pattern support

Allow patterns to be loaded directly from files using explicit path prefixes
(~/, ./, /, or \). This enables easier testing and iteration of patterns
without requiring installation into the fabric config structure.

- Supports relative paths (./pattern.txt, ../pattern.txt)
- Supports home directory expansion (~/patterns/test.txt)
- Supports absolute paths
- Maintains backwards compatibility with named patterns
- Requires explicit path markers to distinguish from pattern names

Example usage:
  fabric --pattern ./draft-pattern.txt
  fabric --pattern ~/patterns/my-pattern.txt
  fabric --pattern ../../shared-patterns/test.txt
This commit is contained in:
Matt Joyce
2024-11-17 13:45:59 +11:00
parent fbd1fbfc67
commit af4752d324
2 changed files with 58 additions and 10 deletions

View File

@@ -66,3 +66,34 @@ type Pattern struct {
Description string
Pattern string
}
// GetFromFile reads a pattern from a file path and applies variables if provided
// this provides an ad-hoc way to use a pattern
func (o *PatternsEntity) GetFromFile(pathStr string, variables map[string]string) (ret *Pattern, err error) {
// Handle home directory expansion
if strings.HasPrefix(pathStr, "~/") {
var homedir string
if homedir, err = os.UserHomeDir(); err != nil {
return nil, fmt.Errorf("could not get home directory: %v", err)
}
pathStr = filepath.Join(homedir, pathStr[2:])
}
var content []byte
if content, err = os.ReadFile(pathStr); err != nil {
return nil, fmt.Errorf("could not read pattern file %s: %v", pathStr, err)
}
ret = &Pattern{
Name: pathStr,
Pattern: string(content),
}
if variables != nil && len(variables) > 0 {
for variableName, value := range variables {
ret.Pattern = strings.ReplaceAll(ret.Pattern, variableName, value)
}
}
return
}