Skip to content

Effort free video editing!

3.6 KB
Raw Blame
import std/strutils
from std/uri import decodeUrl
when defined(windows):
  from std/os import splitFile

type AbsPath* = distinct string
  ## A filesystem path known to be absolute. `absPath` (in util/abspath) is the
  ## only constructor, so consumers can rely on the invariant (and stay `func`).
func `$`*(path: AbsPath): string {.borrow.}

func pathToUri*(path: AbsPath): string {.raises: [].} =
  ## file:// URL for a path. Bytes outside the RFC 3986 path set (spaces,
  ## '#', '%', non-ASCII, ...) are percent-encoded.
  var p = $path
  when defined(windows):
    p = p.replace('\\', '/')
    result = "file:///"
  else:
    result = "file://"
  for c in p:
    if c in {'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~', '/', ':'}:
      result.add c
    else:
      result.add '%'
      result.add toHex(ord(c), 2)

func uriToPath*(uri: string): string {.raises: [].} =
  ## The path a file:// URL names, decoded; other strings unchanged.
  var path = uri
  if path.startsWith("file://localhost/"):
    # Windows-style: file://localhost/C:/... -> C:/...
    if path.len > 18 and path[18] == ':':
      path = path[17..^1]
    else:
      path = path[16..^1]
  elif path.startsWith("file://"):
    # Windows-style: file:///C:/... -> C:/...
    if path.len > 9 and path[9] == ':':
      path = path[8..^1]
    else:
      # Unix-style: file:///path -> /path
      path = path[7..^1]
  else:
    return uri
  return decodeUrl(path, decodePlus = false)

when defined(posix):
  from std/posix import Stat, stat, S_ISREG, S_ISDIR, S_ISFIFO, S_ISSOCK

proc isDevicePath*(path: string): bool {.raises: [].} =
  ## Whether `path` names something other than a file to create or replace:
  ## a device (/dev/null), a pipe (/dev/stdout, `>(cmd)`), or a socket. Its
  ## name is fixed, so nothing may add an extension or derive siblings from it.
  when defined(windows):
    let (_, name, _) = splitFile(path)
    path.startsWith(r"\\.\") or name.toUpperAscii in ["NUL", "CON", "PRN",
      "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3"]
  elif defined(posix) and not defined(emscripten):
    # An alias of an open descriptor (/dev/stdout redirected to a file)
    # stats as whatever it points at.
    if path in ["/dev/stdout", "/dev/stderr"] or path.startsWith("/dev/fd/") or
        path.startsWith("/proc/") and "/fd/" in path:
      return true
    var st: Stat
    stat(path.cstring, st) == 0 and not S_ISREG(st.st_mode) and
      not S_ISDIR(st.st_mode)
  else:
    false

proc isPipePath*(path: string): bool {.raises: [].} =
  ## Whether writing `path` can't seek back, as a muxer finishing its header
  ## would.
  when defined(posix) and not defined(emscripten):
    var st: Stat
    stat(path.cstring, st) == 0 and (S_ISFIFO(st.st_mode) or S_ISSOCK(st.st_mode))
  else:
    false

func agSplitFile*(path: string): tuple[dir, name, ext: string] =
  ## Platform-independent splitFile. Treats both '/' and '\' as path separators
  ## on every OS, so results don't drift between Linux, macOS, and Windows.
  var namePos = 0
  var dotPos = 0
  for i in countdown(path.len - 1, 0):
    if path[i] == '.' and dotPos == 0:
      dotPos = i
    elif path[i] == '/' or path[i] == '\\':
      if namePos == 0:
        namePos = i + 1
      if dotPos > namePos and dotPos < path.len - 1:
        result.name = substr(path, namePos, dotPos - 1)
        result.ext = substr(path, dotPos)
      else:
        result.name = substr(path, namePos)
      result.dir = substr(path, 0, max(0, namePos - 2))
      return
  if dotPos > 0 and dotPos < path.len - 1:
    result.name = substr(path, 0, dotPos - 1)
    result.ext = substr(path, dotPos)
  else:
    result.name = path