pathutil

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const WindowsMaxPath = 248 // Leave room for filename

WindowsMaxPath defines the maximum path length for Windows without long path support. This constant accounts for the Windows legacy limitation of 260 characters, with 248 characters reserved for the path to leave room for the filename.

Notes:

  • Applies to standard paths without \\?\ long path prefix
  • Includes the full path, not just the filename
  • Used as a conservative limit to ensure compatibility

Variables

This section is empty.

Functions

func EnsureParentDir

func EnsureParentDir(path string) error

EnsureParentDir creates the parent directory of a given path if it doesn't exist. This function provides safe, robust directory creation with support for various scenarios:

  1. Handles empty path input
  2. Skips creation for current directory or root paths
  3. Special handling for Windows drive root paths
  4. Thread-safe directory creation using os.MkdirAll
  5. Handles race conditions in concurrent environment

Key Features:

  • Idempotent: Multiple calls with same path are safe
  • Uses 0o755 permissions for created directories
  • Verifies that the path is actually a directory

Parameters:

path: The file path whose parent directory should be ensured

Returns:

An error if directory creation fails, nil if parent directory exists or was created successfully

func EnsureParentDirectory

func EnsureParentDirectory(path string) error

EnsureParentDirectory creates the parent directory for a given file path if it doesn't exist. This method is safe for concurrent use and handles various edge cases:

  1. Normalizes the input path
  2. Handles empty paths
  3. Skips creation for root or drive root directories
  4. Gracefully handles concurrent directory creation

If the parent directory already exists, the function returns nil. If the parent path exists but is not a directory, an error is returned.

Parameters:

path: The file path whose parent directory should be ensured

Returns:

An error if directory creation fails, nil otherwise

func IsAbsoluteWindowsPath

func IsAbsoluteWindowsPath(path string) bool

IsAbsoluteWindowsPath determines whether a path is absolute according to Windows path conventions. This function recognizes multiple types of absolute paths:

Absolute Path Types:

  1. Drive-letter paths (C:\path, D:\directory)
  2. UNC network paths (\\server\share)
  3. Windows device paths (\\?\ or \\.\)

On non-Windows platforms, it falls back to standard filepath.IsAbs() behavior.

Validation Criteria:

  • Starts with drive letter followed by :\ or :/
  • Starts with \\server\share format
  • Starts with \\?\ or \\.\

Parameters:

path: The file path to check for absolute status

Returns:

true if the path is absolute on Windows, false otherwise

func IsExtendedLengthPath

func IsExtendedLengthPath(path string) bool

IsExtendedLengthPath determines whether a path uses the \\?\ prefix for Windows extended-length paths. Extended-length paths allow for paths exceeding the standard 260-character limit.

Parameters:

path: The file path to check

Returns:

true if the path starts with \\?\, false otherwise

func IsPathSafe

func IsPathSafe(root, p string) bool

IsPathSafe checks if joining a root directory with a path would be safe without actually performing the join. This method provides a lightweight way to validate a path before using SafeJoin.

The method performs the same safety checks as SafeJoin, including:

  • Rejecting absolute paths
  • Detecting path traversal attempts
  • Ensuring the path remains within the root directory

Parameters:

root: The root directory that serves as a boundary for path resolution
p: The relative path to validate

Returns:

true if the path is safe to join with the root directory, false otherwise

func IsUNCPath

func IsUNCPath(path string) bool

IsUNCPath determines whether a path follows the Universal Naming Convention (UNC) format. UNC paths are network file paths typically used to specify shared resources on Windows.

Examples of valid UNC paths:

  • \\server\share
  • \\computername\sharename
  • \\192.168.1.1\public

The function uses a regex to validate the path structure:

  • Must start with two backslashes
  • Must have a valid server name
  • Must have a valid share name

Parameters:

path: The file path to check

Returns:

true if the path is a valid UNC path, false otherwise

func IsValidWindowsPath

func IsValidWindowsPath(p string) bool

IsValidWindowsPath checks if a given path is valid according to Windows path conventions. This validation includes several checks:

  1. Disallows empty paths
  2. Prevents Windows-reserved characters (< > " | ? *)
  3. Validates drive letter placement and format
  4. Blocks paths with reserved device names (CON, PRN, AUX, etc.)

The function is lenient with relative paths and dot navigation segments. On non-Windows platforms, it always returns true.

Parameters:

p: The path string to validate

Returns:

true if the path is valid on Windows, false otherwise

func IsWindowsBatchFile

func IsWindowsBatchFile(path string) bool

IsWindowsBatchFile determines whether a file is a Windows batch script. It checks the file extension to identify batch and command files.

This function:

  • Returns false on non-Windows platforms
  • Recognizes .bat and .cmd file extensions
  • Performs case-insensitive extension comparison

Parameters:

path: The file path to check

Returns:

true if the file is a Windows batch script, false otherwise

func IsWindowsDevicePath

func IsWindowsDevicePath(path string) bool

IsWindowsDevicePath determines whether a path is a Windows device path. Device paths are special paths used to access Windows system devices and resources.

Valid device path prefixes:

  • \\?\ : Extended-length path prefix, allows paths > 260 characters
  • \\.\ : Direct device access for system devices

These paths have special rules and bypass normal path validation:

  • Can access system devices directly
  • Allow very long file paths
  • Used for low-level system operations

Parameters:

path: The file path to check

Returns:

true if the path is a Windows device path, false otherwise

func MustSafeJoin

func MustSafeJoin(root, p string) string

MustSafeJoin is like SafeJoin but panics if the path is unsafe. Use this method only when you are absolutely certain the path is safe or during development/testing.

Unlike SafeJoin, this method does not return an error. Instead, it will:

  • Return the safe, canonicalized path if valid
  • Panic with a descriptive error message if the path is unsafe

Warning: This method should not be used in production code where error handling is crucial.

Parameters:

root: The root directory that serves as a boundary for path resolution
p: The relative path to join with the root

Returns:

A canonicalized, safe path within the root directory

Panics:

If the path would escape the root directory or is otherwise unsafe

func NormalizeCRLF

func NormalizeCRLF(data []byte) []byte

NormalizeCRLF converts Windows CRLF line endings to Unix LF.

func NormalizePathSeparators

func NormalizePathSeparators(path string) string

NormalizePathSeparators normalizes path separators for the current OS.

func NormalizeUserPath

func NormalizeUserPath(p string) (string, error)

NormalizeUserPath sanitizes and normalizes a user-provided file path. This function performs multiple transformations and security checks:

  1. Converts mixed path separators (/ and \) to canonical form
  2. Handles drive-relative paths (C:temp → C:\temp)
  3. Detects and prevents path traversal attempts
  4. Cleans path by removing redundant segments
  5. Converts to an absolute path
  6. Adds \\?\ prefix for Windows long paths (> 248 characters)

On non-Windows systems, it uses standard filepath cleaning.

Security Features:

  • Prevents directory traversal vulnerabilities
  • Validates path against Windows naming restrictions
  • Handles long path limitations

Parameters:

p: The user-provided path to normalize

Returns:

A normalized, safe, absolute path, or an error if normalization fails

func NormalizeWindowsPath

func NormalizeWindowsPath(p string) (string, error)

NormalizeWindowsPath normalizes a Windows path, resolving multiple platform-specific complexities. It performs the following transformations:

  1. Converts forward slashes to backslashes
  2. Resolves drive-relative paths (e.g., C:foo)
  3. Cleans the path (removes redundant separators and navigation segments)
  4. Converts to an absolute path
  5. Adds \\?\ prefix for Windows long paths (> 248 characters)

On non-Windows platforms, it simply cleans the path using filepath.Clean().

Parameters:

p: The input path to normalize

Returns:

A normalized, cleaned path string and any encountered error

func ResolveDriveRelativePath

func ResolveDriveRelativePath(p string) (string, error)

ResolveDriveRelativePath resolves a drive-relative path to an absolute path on Windows. Drive-relative paths (e.g., C:foo) are resolved relative to the current directory on the specified drive.

On non-Windows platforms, the path is returned as-is without modification.

Parameters:

p: The drive-relative path to resolve

Returns:

The resolved absolute path and any encountered error

func SafeJoin

func SafeJoin(root, p string) (string, error)

SafeJoin safely joins a root directory with a relative path, preventing directory traversal attacks. This function ensures that the resulting path always stays within the specified root directory.

Security Features:

  • Rejects absolute paths
  • Removes null bytes from path
  • Normalizes path using filepath.Clean
  • Validates that the resulting path remains within root directory
  • Compatible with both Windows and Unix-like systems

Parameters:

root: The root directory that serves as a boundary for path resolution
p: The relative path to join with the root

Returns:

A canonicalized, safe path within the root directory, or an error if the path is unsafe

func ValidateWindowsPath

func ValidateWindowsPath(p string) error

ValidateWindowsPath performs comprehensive validation of Windows-specific path characteristics. This method checks for numerous potential issues with paths, including:

  1. Presence of invalid characters
  2. Handling of drive letters
  3. UNC path format validation
  4. Reserved filename detection
  5. Path length restrictions

The function is designed to be strict and catch potential problems early. On non-Windows systems, it always returns nil.

Parameters:

p: The Windows path to validate

Returns:

An error detailing the first validation issue found, or nil if the path is valid

Types

This section is empty.

Jump to

Keyboard shortcuts

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