Source Edit

This module contains basic operating system facilities like retrieving environment variables, working with directories, running shell commands, etc.

Example:

  1. import std/os
  2. let myFile = "/path/to/my/file.nim"
  3. assert splitPath(myFile) == (head: "/path/to/my", tail: "file.nim")
  4. when defined(posix):
  5. assert parentDir(myFile) == "/path/to/my"
  6. assert splitFile(myFile) == (dir: "/path/to/my", name: "file", ext: ".nim")
  7. assert myFile.changeFileExt("c") == "/path/to/my/file.c"

See also:

Imports

ospaths2, osfiles, osdirs, ossymlinks, osappdirs, oscommon, since, cmdline, strutils, pathnorm, winlean, times, oserrors, envvars, osseps

Types

  1. DeviceId = int32

Source Edit

  1. FileId = int64

Source Edit

  1. FileInfo = object
  2. id*: tuple[device: DeviceId, file: FileId] ## Device and file id.
  3. kind*: PathComponent ## Kind of file object - directory, symlink, etc.
  4. size*: BiggestInt ## Size of file.
  5. permissions*: set[FilePermission] ## File permissions
  6. linkCount*: BiggestInt ## Number of hard links the file object has.
  7. lastAccessTime*: times.Time ## Time file was last accessed.
  8. lastWriteTime*: times.Time ## Time file was last modified/written to.
  9. creationTime*: times.Time ## Time file was created. Not supported on all systems!
  10. blockSize*: int ## Preferred I/O block size for this object.
  11. ## In some filesystems, this may vary from file to file.
  12. isSpecial*: bool ## Is file special? (on Unix some "files"
  13. ## can be special=non-regular like FIFOs,
  14. ## devices); for directories `isSpecial`
  15. ## is always `false`, for symlinks it is
  16. ## the same as for the link's target.

Contains information associated with a file object.

See also:

Source Edit

Consts

  1. ExeExts = ["exe", "cmd", "bat"]

Platform specific file extension for executables. On Windows [“exe”, “cmd”, “bat”], on Posix [“”]. Source Edit

  1. invalidFilenameChars = {'/', '\\', ':', '*', '?', '\"', '<', '>', '|', '^',
  2. '\x00'}

Characters that may produce invalid filenames across Linux, Windows and Mac. You can check if your filename contains any of these chars and strip them for safety. Mac bans ‘:’, Linux bans ‘/‘, Windows bans all others. Source Edit

  1. invalidFilenames = ["CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", "COM3",
  2. "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0",
  3. "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7",
  4. "LPT8", "LPT9"]

Filenames that may be invalid across Linux, Windows, Mac, etc. You can check if your filename match these and rename it for safety (Currently all invalid filenames are from Windows only). Source Edit

Procs

  1. proc createHardlink(src, dest: string) {....raises: [OSError], tags: [],
  2. forbids: [].}

Create a hard link at dest which points to the item specified by src.

Warning: Some OS’s restrict the creation of hard links to root users (administrators).

See also:

Source Edit

  1. proc exclFilePermissions(filename: string; permissions: set[FilePermission]) {.
  2. ...gcsafe, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect],
  3. raises: [OSError], forbids: [].}

A convenience proc for:

  1. setFilePermissions(filename, getFilePermissions(filename)-permissions)

Source Edit

  1. proc execShellCmd(command: string): int {....gcsafe, extern: "nos$1",
  2. tags: [ExecIOEffect], raises: [], forbids: [].}

Executes a shell command.

Command has the form ‘program args’ where args are the command line arguments given to program. The proc returns the error code of the shell when it has finished (zero if there is no error). The proc does not return until the process has finished.

To execute a program without having a shell involved, use osproc.execProcess proc.

Examples:

  1. discard execShellCmd("ls -la")

Source Edit

  1. proc exitStatusLikeShell(status: cint): cint {....raises: [], tags: [], forbids: [].}

Converts exit code from c_system into a shell exit code. Source Edit

  1. proc expandFilename(filename: string): string {....gcsafe, extern: "nos$1",
  2. tags: [ReadDirEffect], raises: [OSError], forbids: [].}

Returns the full (absolute) path of an existing file filename.

Raises OSError in case of an error. Follows symlinks.

Source Edit

  1. proc expandTilde(path: string): string {....tags: [ReadEnvEffect, ReadIOEffect],
  2. raises: [], forbids: [].}

Expands ~ or a path starting with ~/ to a full path, replacing ~ with appdirs: getHomeDir() (otherwise returns path unmodified).

Windows: this is still supported despite the Windows platform not having this convention; also, both ~/ and ~\ are handled.

See also:

Example:

  1. assert expandTilde("~" / "appname.cfg") == getHomeDir() / "appname.cfg"
  2. assert expandTilde("~/foo/bar") == getHomeDir() / "foo/bar"
  3. assert expandTilde("/foo/bar") == "/foo/bar"

Source Edit

  1. proc fileNewer(a, b: string): bool {....gcsafe, extern: "nos$1", raises: [OSError],
  2. tags: [], forbids: [].}

Returns true if the file a is newer than file b, i.e. if a’s modification time is later than b’s.

See also:

Source Edit

  1. proc findExe(exe: string; followSymlinks: bool = true;
  2. extensions: openArray[string] = ExeExts): string {.
  3. ...tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], raises: [], forbids: [].}

Searches for exe in the current working directory and then in directories listed in the PATH environment variable.

Returns “” if the exe cannot be found. exe is added the ExeExts file extensions if it has none.

If the system supports symlinks it also resolves them until it meets the actual file. This behavior can be disabled if desired by setting followSymlinks = false.

Source Edit

  1. proc getAppDir(): string {....gcsafe, extern: "nos$1", tags: [ReadIOEffect],
  2. raises: [], forbids: [].}

Returns the directory of the application’s executable.

See also:

Source Edit

  1. proc getAppFilename(): string {....gcsafe, extern: "nos$1", tags: [ReadIOEffect],
  2. raises: [], forbids: [].}

Returns the filename of the application’s executable. This proc will resolve symlinks.

Returns empty string when name is unavailable

See also:

Source Edit

  1. proc getCreationTime(file: string): times.Time {....gcsafe, extern: "nos$1",
  2. raises: [OSError], tags: [], forbids: [].}

Returns the file’s creation time.

Note: Under POSIX OS’s, the returned time may actually be the time at which the file’s attribute’s were last modified. See here for details.

See also:

Source Edit

  1. proc getCurrentCompilerExe(): string {.compileTime, ...raises: [], tags: [],
  2. forbids: [].}

This is getAppFilename() at compile time.

Can be used to retrieve the currently executing Nim compiler from a Nim or nimscript program, or the nimble binary inside a nimble program (likewise with other binaries built from compiler API).

Source Edit

  1. proc getCurrentProcessId(): int {....raises: [], tags: [], forbids: [].}

Return current process ID.

See also:

Source Edit

  1. proc getFileInfo(file: File): FileInfo {....raises: [IOError, OSError], tags: [],
  2. forbids: [].}

Retrieves file information for the file object.

See also:

Source Edit

  1. proc getFileInfo(handle: FileHandle): FileInfo {....raises: [OSError], tags: [],
  2. forbids: [].}

Retrieves file information for the file object represented by the given handle.

If the information cannot be retrieved, such as when the file handle is invalid, OSError is raised.

See also:

Source Edit

  1. proc getFileInfo(path: string; followSymlink = true): FileInfo {.
  2. ...raises: [OSError], tags: [], forbids: [].}

Retrieves file information for the file object pointed to by path.

Due to intrinsic differences between operating systems, the information contained by the returned FileInfo object will be slightly different across platforms, and in some cases, incomplete or inaccurate.

When followSymlink is true (default), symlinks are followed and the information retrieved is information related to the symlink’s target. Otherwise, information on the symlink itself is retrieved (however, field isSpecial is still determined from the target on Unix).

If the information cannot be retrieved, such as when the path doesn’t exist, or when permission restrictions prevent the program from retrieving file information, OSError is raised.

See also:

Source Edit

  1. proc getFileSize(file: string): BiggestInt {....gcsafe, extern: "nos$1",
  2. tags: [ReadIOEffect], raises: [OSError], forbids: [].}

Returns the file size of file (in bytes). OSError is raised in case of an error. Source Edit

  1. proc getLastAccessTime(file: string): times.Time {....gcsafe, extern: "nos$1",
  2. raises: [OSError], tags: [], forbids: [].}

Returns the file’s last read or write access time.

See also:

Source Edit

  1. proc getLastModificationTime(file: string): times.Time {....gcsafe,
  2. extern: "nos$1", raises: [OSError], tags: [], forbids: [].}

Returns the file’s last modification time.

See also:

Source Edit

  1. proc inclFilePermissions(filename: string; permissions: set[FilePermission]) {.
  2. ...gcsafe, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect],
  3. raises: [OSError], forbids: [].}

A convenience proc for:

  1. setFilePermissions(filename, getFilePermissions(filename)+permissions)

Source Edit

  1. proc isAdmin(): bool {....raises: [OSError, OSError], tags: [], forbids: [].}

Returns whether the caller’s process is a member of the Administrators local group (on Windows) or a root (on POSIX), via geteuid() == 0. Source Edit

  1. proc isHidden(path: string): bool {....raises: [], tags: [], forbids: [].}

Determines whether path is hidden or not, using this reference.

On Windows: returns true if it exists and its “hidden” attribute is set.

On posix: returns true if lastPathPart(path) starts with . and is not . or …

Note: paths are not normalized to determine isHidden.

Example:

  1. when defined(posix):
  2. assert ".foo".isHidden
  3. assert not ".foo/bar".isHidden
  4. assert not ".".isHidden
  5. assert not "..".isHidden
  6. assert not "".isHidden
  7. assert ".foo/".isHidden

Source Edit

  1. func isValidFilename(filename: string; maxLen = 259.Positive): bool {.
  2. ...raises: [], tags: [], forbids: [].}

Returns true if filename is valid for crossplatform use.

This is useful if you want to copy or save files across Windows, Linux, Mac, etc. It uses invalidFilenameChars, invalidFilenames and maxLen to verify the specified filename.

See also:

Warning: This only checks filenames, not whole paths (because basically you can mount anything as a path on Linux).

Example:

  1. assert not isValidFilename(" foo") # Leading white space
  2. assert not isValidFilename("foo ") # Trailing white space
  3. assert not isValidFilename("foo.") # Ends with dot
  4. assert not isValidFilename("con.txt") # "CON" is invalid (Windows)
  5. assert not isValidFilename("OwO:UwU") # ":" is invalid (Mac)
  6. assert not isValidFilename("aux.bat") # "AUX" is invalid (Windows)
  7. assert not isValidFilename("") # Empty string
  8. assert not isValidFilename("foo/") # Filename is empty

Source Edit

  1. proc quoteShell(s: string): string {.noSideEffect, ...gcsafe, extern: "nosp$1",
  2. raises: [], tags: [], forbids: [].}

Quote s, so it can be safely passed to shell.

When on Windows, it calls quoteShellWindows proc. Otherwise, calls quoteShellPosix proc.

Source Edit

  1. proc quoteShellCommand(args: openArray[string]): string {....raises: [], tags: [],
  2. forbids: [].}

Concatenates and quotes shell arguments args.

Example:

  1. when defined(posix):
  2. assert quoteShellCommand(["aaa", "", "c d"]) == "aaa '' 'c d'"
  3. when defined(windows):
  4. assert quoteShellCommand(["aaa", "", "c d"]) == "aaa \"\" \"c d\""

Source Edit

  1. proc quoteShellPosix(s: string): string {.noSideEffect, ...gcsafe,
  2. extern: "nosp$1", raises: [], tags: [], forbids: [].}

Quote s, so it can be safely passed to POSIX shell. Source Edit

  1. proc quoteShellWindows(s: string): string {.noSideEffect, ...gcsafe,
  2. extern: "nosp$1", raises: [], tags: [], forbids: [].}

Quote s, so it can be safely passed to Windows API.

Based on Python’s subprocess.list2cmdline. See this link for more details.

Source Edit

  1. proc sameFileContent(path1, path2: string): bool {....gcsafe, extern: "nos$1",
  2. tags: [ReadIOEffect], raises: [IOError, OSError], forbids: [].}

Returns true if both pathname arguments refer to files with identical binary content.

See also:

Source Edit

  1. proc setLastModificationTime(file: string; t: times.Time) {....raises: [OSError],
  2. tags: [], forbids: [].}

Sets the file’s last modification time. OSError is raised in case of an error. Source Edit

  1. proc sleep(milsecs: int) {....gcsafe, extern: "nos$1", tags: [TimeEffect],
  2. raises: [], forbids: [].}

Sleeps milsecs milliseconds. Source Edit

Templates

  1. template existsDir(args: varargs[untyped]): untyped {.
  2. ...deprecated: "use dirExists".}

Deprecated: use dirExists

Source Edit

  1. template existsFile(args: varargs[untyped]): untyped {.
  2. ...deprecated: "use fileExists".}

Deprecated: use fileExists

Source Edit

Exports

changeFileExt, /, splitFile, normalizeExe, normalizePath, cmpPaths, WriteDirEffect, ScriptExt, lastPathPart, isRelativeTo, absolutePath, isAbsolute, parentDir, unixToNativePath, /../, DirSep, normalizePathEnd, PathSep, normalizedPath, DynlibFormat, normalizePathEnd, addFileExt, joinPath, extractFilename, relativePath, FileSystemCaseSensitive, sameFile, ReadDirEffect, joinPath, CurDir, ExtSep, splitPath, tailDir, getCurrentDir, searchExtPos, parentDirs, AltSep, doslikeFileSystem, ExeExt, isRootDir, ParDir, tryRemoveFile, removeFile, copyFileToDir, moveFile, fileExists, FilePermission, getFilePermissions, CopyFlag, setFilePermissions, copyFileWithPermissions, copyFile, walkFiles, dirExists, existsOrCreateDir, walkDirRec, removeDir, walkDir, PathComponent, walkDirs, moveDir, createDir, copyDirWithPermissions, copyDir, walkPattern, setCurrentDir, symlinkExists, expandSymlink, createSymlink, getConfigDir, getCacheDir, getDataDir, getTempDir, getHomeDir, getCacheDir, parseCmdLine, paramCount, commandLineParams, paramStr, getCommandLine, $, \==, newOSError, osErrorMsg, raiseOSError, osLastError, OSErrorCode, putEnv, envPairs, delEnv, getEnv, WriteEnvEffect, ReadEnvEffect, existsEnv, ExtSep, FileSystemCaseSensitive, DynlibFormat, DirSep, AltSep, PathSep, ScriptExt, doslikeFileSystem, ExeExt, CurDir, ParDir