Add Version method to NFT interface and implementation

Include `RunWithOutput` support in the command package and introduce version parsing logic, enabling retrieval of the nftables version and options.
This commit is contained in:
2025-10-20 22:44:40 +05:00
parent c3a513f92c
commit 9210448f16
3 changed files with 83 additions and 0 deletions

49
nft.go
View File

@@ -2,7 +2,10 @@ package nft
import (
"errors"
"regexp"
"strings"
"git.kor-elf.net/kor-elf-shield/go-nftables-client/internal/chain"
"git.kor-elf.net/kor-elf-shield/go-nftables-client/internal/command"
"git.kor-elf.net/kor-elf-shield/go-nftables-client/internal/table"
)
@@ -15,6 +18,12 @@ type NFT interface {
// nft flush ruleset
Clear() error
// Version returns the version of nftables.
//
// This command is equivalent to:
// nft -V
Version() (Version, error)
// Table returns an API for working with tables.
Table() table.API
}
@@ -22,6 +31,7 @@ type NFT interface {
type nft struct {
command command.NFT
table table.API
chain chain.API
}
// New Returns a client for working with nftables.
@@ -48,6 +58,7 @@ func NewWithPath(path string) (NFT, error) {
return &nft{
command: nftCommand,
table: table.New(nftCommand),
chain: chain.New(nftCommand),
}, nil
}
@@ -56,6 +67,44 @@ func (n *nft) Clear() error {
return n.command.Run(args...)
}
func (n *nft) Version() (Version, error) {
args := []string{"-V"}
out, err := n.command.RunWithOutput(args...)
if err != nil {
return nil, err
}
vers := ""
opts := make(map[string]string)
lines := regexp.MustCompile("\r?\n").Split(strings.TrimSpace(string(out)), -1)
for index, line := range lines {
line = strings.TrimSpace(line)
if index == 0 {
vers = line
continue
}
values := strings.Split(line, ":")
if len(values) != 2 {
continue
}
name := strings.TrimSpace(values[0])
value := strings.TrimSpace(values[1])
opts[name] = value
}
return &version{
version: vers,
opts: opts,
}, nil
}
func (n *nft) Table() table.API {
return n.table
}
func (n *nft) Chain() chain.API {
return n.chain
}