Help us shape the future of Go! Take the 2026 Go Developer Survey

pathx

package
v0.20.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package pathx 提供文件路径匹配与清洗工具。

MatchesPath 支持标准 glob 模式和 /** 目录前缀匹配, 适用于 .gitignore 风格的路径过滤场景(代码审查忽略路径、构建排除等)。

SanitizeRel / SanitizeRelStrict 提供仓库相对路径的清洗与 traversal 拒绝: 路径来自外部输入(webhook 载荷)时,清洗逻辑每次都要重写且各处口径容易 漂移(实测同一仓内三档:宽松 / 严格 / 只看 Clean 后的结果)——本包给基线, 严格档额外拒绝显式 ".." 段。

用法:

pathx.MatchesPath([]string{"vendor/**", "*.test"}, "vendor/foo/bar.go") // true
pathx.MatchesPath([]string{"*.go"}, "main.go")                          // true

cleaned, ok := pathx.SanitizeRel("src/./main.go")   // "src/main.go", true
cleaned, ok := pathx.SanitizeRel("../../etc/passwd") // "", false

Package pathx 提供文件路径匹配工具。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MatchesPath

func MatchesPath(patterns []string, path string) bool

MatchesPath 检查路径是否匹配任意一个 glob 模式。 支持标准 filepath.Match 模式以及 /** 目录前缀匹配。

模式示例:

  • "*.go" → 匹配根目录下的 .go 文件
  • "vendor/*" → 匹配 vendor 目录下的直接子项
  • "node_modules/**" → 匹配 node_modules 下所有层级的文件
  • "test/*.txt" → 匹配 test 目录下的 .txt 文件

用法:

pathx.MatchesPath([]string{"vendor/**", "*.test"}, "vendor/foo/bar.go") // true
pathx.MatchesPath([]string{"*.go"}, "main.go")                          // true

func SanitizeRel added in v0.20.0

func SanitizeRel(p string) (cleaned string, ok bool)

SanitizeRel 清洗仓库相对路径:统一分隔符为 "/"、消除 "." 与 ".." 段, 绝对路径或越出根目录("..")时 ok=false。

定位:仓库相对路径常来自外部输入(webhook 载荷里的文件路径), 清洗与 traversal 拒绝是同一件事的两面——消费方各写各的清洗逻辑时, 口径会漂移(实测同一仓内三档:宽松 / 严格 / 只看 Clean 后的结果)。 本原语给基线,调用方在基线上选严格档。

分隔符口径:**"/" 与 "\" 都当作分隔符**。仓库路径来自外部载荷时 Windows 风格分隔符同样是路径的一部分;若按运行平台解释(Linux 上 "\" 只是普通字符),同一段载荷在 Linux 与 Windows 上会得到不同结论—— 而 Linux 才是绝大多数服务端环境,那正是 "..\..\" 形绕过最容易漏掉的地方。

判定口径:

  • 绝对路径("/foo"、UNC "//host/share"、Windows 盘符 "C:\foo")→ ok=false;
  • 越出根目录("../x"、"/../x"、"a/../../x")→ ok=false;
  • 清洗后为空("."、"a/.." —— 指向仓库根目录本身,非具体条目)→ ok=false;
  • 空串 / 纯空白 → ok=false。

".." 段的处理:宽松档下 ".." 抵消前一段("a/../b" → "b"),但抵消后 仍要留在根目录内("a/../../b" 越界 → ok=false)。

用法:

cleaned, ok := pathx.SanitizeRel("src/./main.go")   // "src/main.go", true
cleaned, ok := pathx.SanitizeRel("../../etc/passwd") // "", false

func SanitizeRelStrict added in v0.20.0

func SanitizeRelStrict(p string) (cleaned string, ok bool)

SanitizeRelStrict 是 SanitizeRel 的严格档:除 SanitizeRel 的全部判定外, **输入中显式出现的 ".." 段一律拒绝**,即使它能被 Clean 抵消掉 ("a/../b" 在宽松档得到 "b",在严格档直接 ok=false)。

为什么需要这一档:宽松档的 ".." 抵消是纯文本语义,看不见符号链接。 路径先过一层符号链接再按相对路径解析时,文本上合法的 "a/../b" 可能 指向预期之外的位置——安全档宁可拒绝,也不做这层推断。

用法:

cleaned, ok := pathx.SanitizeRelStrict("a/../b") // "", false(宽松档是 "b")

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL