Skip to content

Commit

Permalink
refactor: use new system pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
jdkato committed Jan 16, 2025
1 parent c4193a9 commit 3c31b3f
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 78 deletions.
2 changes: 1 addition & 1 deletion internal/core/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func FindAsset(cfg *Config, path string) string {
return p
}

p := determinePath(cfg.Flags.Path, path)
p := system.DeterminePath(cfg.Flags.Path, path)
if system.FileExists(p) {
return p
}
Expand Down
2 changes: 1 addition & 1 deletion internal/core/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func NewFile(src string, config *Config) (*File, error) {
}
filepaths := []string{src}

normed := ReplaceExt(src, config.Formats)
normed := system.ReplaceFileExt(src, config.Formats)
if normed != src {
// NOTE: In retrospect, this was a mistake: we should NOT normalize
// the extension with respect to the `.vale.ini` file.
Expand Down
28 changes: 6 additions & 22 deletions internal/core/ini.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,6 @@ import (

var coreError = "'%s' is a core option; it should be defined above any syntax-specific options (`[...]`)."

func determinePath(configPath string, keyPath string) string {
// expand tilde at this point as this is where user-provided paths are provided
keyPath = normalizePath(keyPath)
if !system.IsDir(configPath) {
configPath = filepath.Dir(configPath)
}
sep := string(filepath.Separator)
abs, _ := filepath.Abs(keyPath)
rel := strings.TrimRight(keyPath, sep)
if abs != rel || !strings.Contains(keyPath, sep) {
// The path was relative
return filepath.Join(configPath, keyPath)
}
return abs
}

func mergeValues(shadows []string) []string {
values := []string{}
for _, v := range shadows {
Expand Down Expand Up @@ -130,7 +114,7 @@ var syntaxOpts = map[string]func(string, *ini.Section, *Config) error{
},
"Transform": func(label string, sec *ini.Section, cfg *Config) error { //nolint:unparam
candidate := sec.Key("Transform").String()
cfg.Stylesheets[label] = determinePath(cfg.Flags.Path, candidate)
cfg.Stylesheets[label] = system.DeterminePath(cfg.Flags.Path, candidate)
return nil

},
Expand Down Expand Up @@ -188,21 +172,21 @@ var coreOpts = map[string]func(*ini.Section, *Config) error{
// In such a case, there are three options: (1) both files define a
// `StylesPath`, (2) only one file defines a `StylesPath`, or (3)
// neither file defines a `StylesPath`.
basePath := determinePath(files[0], filepath.FromSlash(paths[0]))
mockPath := determinePath(files[1], filepath.FromSlash(paths[0]))
basePath := system.DeterminePath(files[0], filepath.FromSlash(paths[0]))
mockPath := system.DeterminePath(files[1], filepath.FromSlash(paths[0]))
// ^ This case handles the situation where both configs define the
// same StylesPath (e.g., `StylesPath = styles`).
if len(paths) == 2 {
basePath = determinePath(files[0], filepath.FromSlash(paths[0]))
mockPath = determinePath(files[1], filepath.FromSlash(paths[1]))
basePath = system.DeterminePath(files[0], filepath.FromSlash(paths[0]))
mockPath = system.DeterminePath(files[1], filepath.FromSlash(paths[1]))
}
cfg.AddStylesPath(basePath)
cfg.AddStylesPath(mockPath)
} else if len(paths) > 0 {
// In this case, we have a local configuration file (no default)
// that defines a `StylesPath`.
candidate := filepath.FromSlash(paths[len(paths)-1])
path := determinePath(cfg.ConfigFile(), candidate)
path := system.DeterminePath(cfg.ConfigFile(), candidate)

cfg.AddStylesPath(path)
if !system.FileExists(path) {
Expand Down
45 changes: 0 additions & 45 deletions internal/core/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ package core
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"unicode"
Expand Down Expand Up @@ -119,17 +116,6 @@ func InRange(n int, r []int) bool {
return len(r) == 2 && (r[0] <= n && n <= r[1])
}

// Which checks for the existence of any command in `cmds`.
func Which(cmds []string) string {
for _, cmd := range cmds {
path, err := exec.LookPath(cmd)
if err == nil {
return path
}
}
return ""
}

// CondSprintf is sprintf, ignores extra arguments.
func CondSprintf(format string, v ...interface{}) string {
v = append(v, "")
Expand Down Expand Up @@ -233,20 +219,6 @@ func SplitLines(data []byte, atEOF bool) (adv int, token []byte, err error) { //
return 0, nil, nil
}

func normalizePath(path string) string {
// expand tilde
homedir, err := os.UserHomeDir()
if err != nil {
return path
}
if path == "~" {
return homedir
} else if strings.HasPrefix(path, filepath.FromSlash("~/")) {
path = filepath.Join(homedir, path[2:])
}
return path
}

func TextToContext(text string, meta *nlp.Info) []nlp.TaggedWord {
context := []nlp.TaggedWord{}

Expand Down Expand Up @@ -304,23 +276,6 @@ func HasAnySuffix(s string, suffixes []string) bool {
return false
}

// ReplaceExt replaces the extension of `fp` with `ext` if the extension of
// `fp` is in `formats`.
//
// This is used in places where we need to normalize file extensions (e.g.,
// `foo.mdx` -> `foo.md`) in order to respect format associations.
func ReplaceExt(fp string, formats map[string]string) string {
var ext string

old := filepath.Ext(fp)
if normed, found := formats[strings.Trim(old, ".")]; found {
ext = "." + normed
fp = fp[0:len(fp)-len(old)] + ext
}

return fp
}

// UniqueStrings returns a new slice with all duplicate strings removed.
func UniqueStrings(slice []string) []string {
keys := make(map[string]bool)
Expand Down
8 changes: 5 additions & 3 deletions internal/core/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"os"
"path/filepath"
"testing"

"github.com/errata-ai/vale/v3/internal/system"
)

func TestFormatFromExt(t *testing.T) {
Expand Down Expand Up @@ -61,7 +63,7 @@ func TestNormalizePath(t *testing.T) {
}
stylesPathInput := filepath.FromSlash("~/.vale")
expectedOutput := filepath.Join(homedir, ".vale")
result := normalizePath(stylesPathInput)
result := system.NormalizePath(stylesPathInput)
if result != expectedOutput {
t.Errorf("expected = %v, got = %v", expectedOutput, result)
}
Expand All @@ -71,7 +73,7 @@ func TestNormalizePath(t *testing.T) {
return
}
expectedOutput = stylesPathInput
result = normalizePath(stylesPathInput)
result = system.NormalizePath(stylesPathInput)
if result != expectedOutput {
t.Errorf("expected = %v, got = %v", expectedOutput, result)
}
Expand All @@ -81,7 +83,7 @@ func TestNormalizePath(t *testing.T) {
return
}
expectedOutput = stylesPathInput
result = normalizePath(stylesPathInput)
result = system.NormalizePath(stylesPathInput)
if result != expectedOutput {
t.Errorf("expected = %v, got = %v", expectedOutput, result)
}
Expand Down
3 changes: 2 additions & 1 deletion internal/lint/adoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/errata-ai/vale/v3/internal/core"
"github.com/errata-ai/vale/v3/internal/nlp"
"github.com/errata-ai/vale/v3/internal/system"
)

// NOTE: Asciidoctor converts "'" to "’".
Expand All @@ -31,7 +32,7 @@ func (l *Linter) lintADoc(f *core.File) error {
var html string
var err error

exe := core.Which([]string{"asciidoctor"})
exe := system.Which([]string{"asciidoctor"})
if exe == "" {
return core.NewE100("lintAdoc", errors.New("asciidoctor not found"))
}
Expand Down
3 changes: 2 additions & 1 deletion internal/lint/dita.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import (
"strings"

"github.com/errata-ai/vale/v3/internal/core"
"github.com/errata-ai/vale/v3/internal/system"
)

func (l Linter) lintDITA(file *core.File) error {
var out bytes.Buffer
var htmlFile string

dita := core.Which([]string{"dita", "dita.bat"})
dita := system.Which([]string{"dita", "dita.bat"})
if dita == "" {
return core.NewE100("lintDITA", errors.New("dita not found"))
}
Expand Down
2 changes: 1 addition & 1 deletion internal/lint/lint.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ func (l *Linter) match(s string) bool {
}

func (l *Linter) skip(old string) bool {
ref := filepath.ToSlash(core.ReplaceExt(old, l.Manager.Config.Formats))
ref := filepath.ToSlash(system.ReplaceFileExt(old, l.Manager.Config.Formats))

if !l.match(old) && !l.match(ref) {
return true
Expand Down
5 changes: 3 additions & 2 deletions internal/lint/rst.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/errata-ai/vale/v3/internal/core"
"github.com/errata-ai/vale/v3/internal/system"
)

// reStructuredText configuration.
Expand All @@ -34,9 +35,9 @@ var rstArgs = []string{
func (l *Linter) lintRST(f *core.File) error {
var html string

rst2html := core.Which([]string{
rst2html := system.Which([]string{
"rst2html", "rst2html.py", "rst2html-3", "rst2html-3.py"})
python := core.Which([]string{
python := system.Which([]string{
"python", "py", "python.exe", "python3", "python3.exe", "py3"})

if rst2html == "" || python == "" {
Expand Down
3 changes: 2 additions & 1 deletion internal/lint/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"

"github.com/errata-ai/vale/v3/internal/core"
"github.com/errata-ai/vale/v3/internal/system"
)

// XML configuration.
Expand All @@ -23,7 +24,7 @@ func (l Linter) lintXML(file *core.File) error {
var out bytes.Buffer
var eut bytes.Buffer

xsltproc := core.Which([]string{"xsltproc", "xsltproc.exe"})
xsltproc := system.Which([]string{"xsltproc", "xsltproc.exe"})
if xsltproc == "" {
return core.NewE100("lintXML", errors.New("xsltproc not found"))
} else if file.Transform == "" {
Expand Down
17 changes: 17 additions & 0 deletions internal/system/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,20 @@ func FileNameWithoutExt(fileName string) string {
base := filepath.Base(fileName)
return strings.TrimSuffix(base, filepath.Ext(base))
}

// ReplaceExt replaces the extension of `fp` with `ext` if the extension of
// `fp` is in `formats`.
//
// This is used in places where we need to normalize file extensions (e.g.,
// `foo.mdx` -> `foo.md`) in order to respect format associations.
func ReplaceFileExt(fp string, formats map[string]string) string {
var ext string

old := filepath.Ext(fp)
if normed, found := formats[strings.Trim(old, ".")]; found {
ext = "." + normed
fp = fp[0:len(fp)-len(old)] + ext
}

return fp
}
62 changes: 62 additions & 0 deletions internal/system/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package system

import (
"os"
"os/exec"
"path/filepath"
"strings"
)

// Which checks for the existence of any command in `cmds`.
func Which(cmds []string) string {
for _, cmd := range cmds {
path, err := exec.LookPath(cmd)
if err == nil {
return path
}
}
return ""
}

// NormalizePath expands a tilde and returns the absolute path of `path`.
func NormalizePath(path string) string {
homedir, err := os.UserHomeDir()
if err != nil {
return path
}

if path == "~" {
return homedir
} else if strings.HasPrefix(path, filepath.FromSlash("~/")) {
path = filepath.Join(homedir, path[2:])
}

return path
}

// DeterminePath determines the path of `keyPath` based on `configPath`.
//
// If `keyPath` is an absolute path, it is returned as is.
//
// If `keyPath` is a relative path, it is joined with `configPath`.
//
// If `configPath` is not a directory, the directory part of `configPath`
// is used.
func DeterminePath(configPath string, keyPath string) string {
// expand tilde at this point as this is where user-provided paths are provided
keyPath = NormalizePath(keyPath)
if !IsDir(configPath) {
configPath = filepath.Dir(configPath)
}

sep := string(filepath.Separator)
abs := AbsPath(keyPath)

rel := strings.TrimRight(keyPath, sep)
if abs != rel || !strings.Contains(keyPath, sep) {
// The path was relative
return filepath.Join(configPath, keyPath)
}

return abs
}

0 comments on commit 3c31b3f

Please sign in to comment.