Class: SwarmMemory::Core::PathNormalizer
- Inherits:
-
Object
- Object
- SwarmMemory::Core::PathNormalizer
- Defined in:
- lib/swarm_memory/core/path_normalizer.rb
Overview
Validates and normalizes memory paths
Ensures paths are safe, hierarchical, and follow conventions.
Constant Summary collapse
- INVALID_PATTERNS =
Invalid path patterns
[ %r{\A/}, # Absolute paths /\.\./, # Parent directory references %r{//}, # Double slashes /\A\s/, # Leading whitespace /\s\z/, # Trailing whitespace /[<>:"|?*]/, # Invalid filesystem characters ].freeze
Class Method Summary collapse
-
.normalize(path) ⇒ String
Normalize and validate a memory path.
-
.valid?(path) ⇒ Boolean
Check if a path is valid without raising an exception.
Class Method Details
.normalize(path) ⇒ String
Normalize and validate a memory path
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/swarm_memory/core/path_normalizer.rb', line 32 def normalize(path) raise ArgumentError, "path is required" if path.nil? || path.to_s.strip.empty? original_path = path.to_s.strip # Check for absolute paths and parent references FIRST (before normalization) if original_path.start_with?("/") raise ArgumentError, "Invalid path: #{original_path}. Paths must be relative, hierarchical, and safe." end if original_path.include?("..") raise ArgumentError, "Invalid path: #{original_path}. Paths must be relative, hierarchical, and safe." end # Normalize (remove leading/trailing slashes, collapse doubles) path = original_path path = path.sub(%r{\A/+}, "") # Remove leading slashes path = path.sub(%r{/+\z}, "") # Remove trailing slashes path = path.gsub(%r{/+}, "/") # Collapse multiple slashes # Check for other invalid characters if path.match?(/[<>:"|?*]/) raise ArgumentError, "Invalid path: #{original_path}. Paths must be relative, hierarchical, and safe." end raise ArgumentError, "Normalized path is empty" if path.empty? path end |
.valid?(path) ⇒ Boolean
Check if a path is valid without raising an exception
66 67 68 69 70 71 |
# File 'lib/swarm_memory/core/path_normalizer.rb', line 66 def valid?(path) normalize(path) true rescue ArgumentError false end |