wildcard.test.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { test, expect } from "bun:test"
  2. import { Wildcard } from "../../src/util/wildcard"
  3. test("match handles glob tokens", () => {
  4. expect(Wildcard.match("file1.txt", "file?.txt")).toBe(true)
  5. expect(Wildcard.match("file12.txt", "file?.txt")).toBe(false)
  6. expect(Wildcard.match("foo+bar", "foo+bar")).toBe(true)
  7. })
  8. test("all picks the most specific pattern", () => {
  9. const rules = {
  10. "*": "deny",
  11. "git *": "ask",
  12. "git status": "allow",
  13. }
  14. expect(Wildcard.all("git status", rules)).toBe("allow")
  15. expect(Wildcard.all("git log", rules)).toBe("ask")
  16. expect(Wildcard.all("echo hi", rules)).toBe("deny")
  17. })
  18. test("allStructured matches command sequences", () => {
  19. const rules = {
  20. "git *": "ask",
  21. "git status*": "allow",
  22. }
  23. expect(Wildcard.allStructured({ head: "git", tail: ["status", "--short"] }, rules)).toBe("allow")
  24. expect(
  25. Wildcard.allStructured(
  26. { head: "npm", tail: ["run", "build", "--watch"] },
  27. { "npm run *": "allow" },
  28. ),
  29. ).toBe("allow")
  30. expect(Wildcard.allStructured({ head: "ls", tail: ["-la"] }, rules)).toBeUndefined()
  31. })
  32. test("allStructured prioritizes flag-specific patterns", () => {
  33. const rules = {
  34. "find *": "allow",
  35. "find * -delete*": "ask",
  36. "sort*": "allow",
  37. "sort -o *": "ask",
  38. }
  39. expect(Wildcard.allStructured({ head: "find", tail: ["src", "-delete"] }, rules)).toBe("ask")
  40. expect(Wildcard.allStructured({ head: "find", tail: ["src", "-print"] }, rules)).toBe("allow")
  41. expect(Wildcard.allStructured({ head: "sort", tail: ["-o", "out.txt"] }, rules)).toBe("ask")
  42. expect(Wildcard.allStructured({ head: "sort", tail: ["--reverse"] }, rules)).toBe("allow")
  43. })
  44. test("allStructured handles sed flags", () => {
  45. const rules = {
  46. "sed * -i*": "ask",
  47. "sed -n*": "allow",
  48. }
  49. expect(Wildcard.allStructured({ head: "sed", tail: ["-i", "file"] }, rules)).toBe("ask")
  50. expect(Wildcard.allStructured({ head: "sed", tail: ["-i.bak", "file"] }, rules)).toBe("ask")
  51. expect(Wildcard.allStructured({ head: "sed", tail: ["-n", "1p", "file"] }, rules)).toBe("allow")
  52. expect(
  53. Wildcard.allStructured({ head: "sed", tail: ["-i", "-n", "/./p", "myfile.txt"] }, rules),
  54. ).toBe("ask")
  55. })