feat(hosts): Add double ip analyzer

This commit is contained in:
Myzel394 2024-08-25 13:29:26 +02:00
parent 960f365bc9
commit 0ed506f604
No known key found for this signature in database
GPG Key ID: DEC4AAB876F73185
6 changed files with 110 additions and 3 deletions

View File

@ -0,0 +1 @@
package analyzer

View File

@ -0,0 +1,36 @@
package analyzer
import (
"config-lsp/common"
"config-lsp/handlers/hosts/tree"
"net"
)
func ipToString(ip net.IPAddr) string {
return ip.IP.String()
}
func analyzeDoubleIPs(p tree.HostsParser) []common.LSPError {
errors := make([]common.LSPError, 0)
ips := make(map[string]uint32)
for lineNumber, entry := range p.Tree.Entries {
if entry.IPAddress != nil {
key := ipToString(entry.IPAddress.Value)
if foundLine, found := ips[key]; found {
errors = append(errors, common.LSPError{
Range: entry.IPAddress.Location,
Err: DuplicateIPDeclaration{
AlreadyFoundAt: foundLine,
},
})
} else {
ips[key] = lineNumber
}
}
}
return errors
}

View File

@ -0,0 +1,62 @@
package analyzer
import (
"config-lsp/handlers/hosts/tree"
"config-lsp/utils"
"testing"
)
func TestWorksWithNonDoubleIPs(
t *testing.T,
) {
input := utils.Dedent(`
1.2.3.4 hello.com
5.5.5.5 world.com
1.2.3.5 foo.com
1.2.3.6 bar.com
`)
parser := tree.CreateNewHostsParser()
errors := parser.Parse(input)
if len(errors) != 0 {
t.Fatalf("PARER FAILED! Expected no errors, but got %v", errors)
}
errors = analyzeDoubleIPs(parser)
if len(errors) != 0 {
t.Errorf("Expected no errors, but got %v", errors)
}
}
func TestWorksWithDoubleIPs(
t *testing.T,
) {
input := utils.Dedent(`
1.2.3.4 hello.com
5.5.5.5 world.com
1.2.3.4 foo.com
`)
parser := tree.CreateNewHostsParser()
errors := parser.Parse(input)
if len(errors) != 0 {
t.Fatalf("PARER FAILED! Expected no errors, but got %v", errors)
}
errors = analyzeDoubleIPs(parser)
if !(len(errors) == 1) {
t.Errorf("Expected 1 error, but got %v", len(errors))
}
if !(errors[0].Range.Start.Line == 3) {
t.Errorf("Expected error on line 3, but got %v", errors[0].Range.Start.Line)
}
if !(errors[0].Err.(DuplicateIPDeclaration).AlreadyFoundAt == 1) {
t.Errorf("Expected error on line 1, but got %v", errors[0].Err.(DuplicateIPDeclaration).AlreadyFoundAt)
}
}

View File

@ -1,4 +1,4 @@
package handlers
package analyzer
import "fmt"
@ -10,3 +10,11 @@ type DuplicateHostEntry struct {
func (d DuplicateHostEntry) Error() string {
return fmt.Sprintf("'%s' already defined on line %d", d.Hostname, d.AlreadyFoundAt)
}
type DuplicateIPDeclaration struct {
AlreadyFoundAt uint32
}
func (d DuplicateIPDeclaration) Error() string {
return fmt.Sprintf("This IP address is already defined on line %d", d.AlreadyFoundAt)
}

View File

@ -1,4 +1,4 @@
package handlers
package analyzer
import (
"config-lsp/common"

View File

@ -1,4 +1,4 @@
package handlers
package analyzer
import (
"config-lsp/handlers/hosts/tree"