NIP parser v2 (#17)

This commit is contained in:
Héctor Giménez
2024-05-05 12:15:08 +09:00
committed by GitHub
parent 0d5c108721
commit bb0ec2555d
28 changed files with 56618 additions and 1385 deletions

View File

@@ -6,9 +6,12 @@ import (
"fmt"
"os"
"strings"
"github.com/hectorgimenez/d2go/pkg/data"
"github.com/hectorgimenez/d2go/pkg/data/item"
)
func ReadDir(path string) ([]Rule, error) {
func ReadDir(path string) (Rules, error) {
files, err := os.ReadDir(path)
if err != nil {
return nil, err
@@ -31,7 +34,7 @@ func ReadDir(path string) ([]Rule, error) {
return rules, nil
}
func ParseNIPFile(filePath string) ([]Rule, error) {
func ParseNIPFile(filePath string) (Rules, error) {
fileReader, err := os.Open(filePath)
if err != nil {
return nil, err
@@ -43,18 +46,44 @@ func ParseNIPFile(filePath string) ([]Rule, error) {
rules := make([]Rule, 0)
lineNumber := 0
dummyItem := data.Item{
ID: 516,
Name: "healingpotion",
Quality: item.QualityNormal,
}
for fileScanner.Scan() {
lineNumber++
rule, err := ParseLine(fileScanner.Text(), filePath, lineNumber)
if errors.Is(err, errEmptyLine) {
rule, err := New(fileScanner.Text(), filePath, lineNumber)
if errors.Is(err, ErrEmptyRule) {
continue
}
if err != nil {
return nil, fmt.Errorf("error reading %s file at line %d: %w", filePath, lineNumber, err)
}
// We evaluate all the rules at startup to ensure no format errors, if there is a format error we will throw it now instead of during runtime
_, err = rule.Evaluate(dummyItem)
if err != nil {
return nil, fmt.Errorf("error testing rule on [%s:%d]: %w", filePath, lineNumber, err)
}
rules = append(rules, rule)
}
return rules, nil
}
func sanitizeLine(rawLine string) string {
l := strings.Split(rawLine, "//")
line := strings.TrimSpace(l[0])
line = strings.Join(strings.Fields(line), " ")
line = strings.ReplaceAll(line, "'", "")
// Fix possible wrong formatted lines
line = strings.ReplaceAll(line, "=>", ">=")
line = strings.ReplaceAll(line, "=<", "<=")
line = strings.TrimSpace(strings.Trim(line, "&&"))
return strings.ToLower(line)
}