Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.path

    Path.toString

    Returns the text representation of this path.

    toString() -> string
    Модуль
    std.path →
    Получатель
    Path
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.path in language mode 5.21.

    The current compiler selects std/path.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    Path

    Ограничения параметров

    Path.from(text) is the constructor for normalized relative paths and returns Result<Path, string>.

    Path.from normalizes path separators and removes empty and dot components. Parent components must stay within the relative root. A path reduced to no components is represented by a dot.

    Empty text, NUL, absolute paths, and parent traversal beyond the relative root return Err. These input failures are values that a caller can handle.

    A leading slash or backslash returns Err. Text that starts with one ASCII character followed immediately by a colon returns Err.

    Path.cwdRelative and Path.project are absent. A Path value already satisfies normalization and has no normalize member.

    Path operations inspect text without accessing the filesystem. Constructing a Path does not establish that its target exists or is accessible.

    A Path is immutable normalized relative text. Every member evaluates its receiver and arguments once in ordinary call order. Members perform no host access and leave the receiver unchanged on success and failure.

    toString returns the exact normalized representation. Separators are forward slashes and the relative root is a dot. Constructing a Path from that text returns the same representation.

    join accepts nonempty relative child text. It rejects NUL, a leading separator, and a colon immediately after one ASCII character before combining the child with the receiver. Both slash forms are separators. Parent components remove preceding components from the combined path and return Err when none remain to remove.

    Joining a child may reach the relative root but may not cross it. A dot child preserves the receiver. Invalid child text returns Err containing an error string without producing a Path. Error text identifies Path.join and the invalid condition.

    parent removes the final component. For a one component path it returns Some containing the dot root. The relative root has no parent and returns None().

    fileName returns the final component without any preceding separator. The relative root returns None(). These results describe text and do not establish whether the path identifies a file or directory.

    extension returns the text after the final dot in the file name, provided that dot is not its first character. A leading dot alone does not introduce an extension. A final dot returns Some(""). A name without such a dot and the relative root return None().

    withExtension replaces the final extension or appends one when it is absent. The argument supplies the suffix without a leading dot. An empty argument removes an existing suffix and its separating dot. A leading dot, either separator, or NUL in the argument returns Err.

    withExtension preserves a leading dot that belongs to the file name. It returns Err when the receiver is the relative root because that path has no file name. A successful replacement is normalized with the same rules as Path.from.

    Path validation describes lexical text. Host operations may reject an otherwise valid Path because of platform naming rules, permissions, or capability restrictions. A Path does not establish filesystem existence or prevent a symbolic link from resolving elsewhere.

    Результат

    The declared result type is string.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Return the normalized relative representation with forward slash separators and a dot for the root.

    Related entries

    Ссылка

    std.path →

    Construct normalized paths with Path.from

    Ссылка
    Правилоtopaz.stdlib.contract.path-from.rule

    Construct normalized paths with Path.from

    Path.from(text) is the constructor for normalized relative paths and returns Result<Path, string>.

    Path.from normalizes path separators and removes empty and dot components. Parent components must stay within the relative root. A path reduced to no components is represented by a dot.

    Empty text, NUL, absolute paths, and parent traversal beyond the relative root return Err. These input failures are values that a caller can handle.

    A leading slash or backslash returns Err. Text that starts with one ASCII character followed immediately by a colon returns Err.

    Path.cwdRelative and Path.project are absent. A Path value already satisfies normalization and has no normalize member.

    Path operations inspect text without accessing the filesystem. Constructing a Path does not establish that its target exists or is accessible.

    Причина

    One constructor gives relative path text one interpretation. Normalization is a Path invariant, so a separate identity operation gives the same value a second spelling.

    Construct a normalized path

    Ссылка
    main.tpzConstruct a normalized pathОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let chapter = test.assertOk(Path.from("chapters/./draft/../main.tpz"))
    5. io.writeLine(chapter.toString())
    Ожидаемый выводКод завершения 0
    chapters/main.tpz
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. chapters/main.tpz

    Reject a path that escapes its relative root

    Ссылка
    main.tpzReject a path that escapes its relative rootОткрыть песочницу →
    1. import std.path { Path }
    2. import std.io
    3. match (Path.from("../chapter.tpz")) {
    4. case Err(_) => io.writeLine("outside root rejected")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Ожидаемый выводКод завершения 0
    outside root rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. outside root rejected

    Reject Path.cwdRelative

    Ссылка
    main.tpzReject Path.cwdRelativeОткрыть песочницу →
    1. import std.path { Path }
    2. let value = Path.cwdRelative("chapter.tpz")
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения check. Ненулевой код завершения.

    Reject Path.project

    Ссылка
    main.tpzReject Path.projectОткрыть песочницу →
    1. import std.path { Path }
    2. let value = Path.project("chapter.tpz")
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения check. Ненулевой код завершения.

    Reject Path.normalize

    Ссылка
    main.tpzReject Path.normalizeОткрыть песочницу →
    1. import std.path { Path }
    2. function inspect(path: Path) -> () {
    3. let value = path.normalize()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения check. Ненулевой код завершения.

    Distinguish rejected ASCII prefixes from relative path text

    Ссылка
    main.tpzDistinguish rejected ASCII prefixes from relative path textОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. test.assertErr(Path.from("a:"))
    5. test.assertErr(Path.from("1:"))
    6. test.assertErr(Path.from("!:"))
    7. io.writeLine(test.assertOk(Path.from("aa:")).toString())
    8. io.writeLine(test.assertOk(Path.from("é:")).toString())
    9. io.writeLine(test.assertOk(Path.from("가:")).toString())
    Ожидаемый выводКод завершения 0
    aa:
    é:
    가:
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. aa:
    2. é:
    3. 가:

    Diagnostics

    Ссылка

    Unknown member or field →

    Inspect and transform normalized paths

    Ссылка
    Правилоtopaz.stdlib.contract.path-operations.rule

    Inspect and transform normalized paths

    A Path is immutable normalized relative text. Every member evaluates its receiver and arguments once in ordinary call order. Members perform no host access and leave the receiver unchanged on success and failure.

    toString returns the exact normalized representation. Separators are forward slashes and the relative root is a dot. Constructing a Path from that text returns the same representation.

    join accepts nonempty relative child text. It rejects NUL, a leading separator, and a colon immediately after one ASCII character before combining the child with the receiver. Both slash forms are separators. Parent components remove preceding components from the combined path and return Err when none remain to remove.

    Joining a child may reach the relative root but may not cross it. A dot child preserves the receiver. Invalid child text returns Err containing an error string without producing a Path. Error text identifies Path.join and the invalid condition.

    parent removes the final component. For a one component path it returns Some containing the dot root. The relative root has no parent and returns None().

    fileName returns the final component without any preceding separator. The relative root returns None(). These results describe text and do not establish whether the path identifies a file or directory.

    extension returns the text after the final dot in the file name, provided that dot is not its first character. A leading dot alone does not introduce an extension. A final dot returns Some(""). A name without such a dot and the relative root return None().

    withExtension replaces the final extension or appends one when it is absent. The argument supplies the suffix without a leading dot. An empty argument removes an existing suffix and its separating dot. A leading dot, either separator, or NUL in the argument returns Err.

    withExtension preserves a leading dot that belongs to the file name. It returns Err when the receiver is the relative root because that path has no file name. A successful replacement is normalized with the same rules as Path.from.

    Path validation describes lexical text. Host operations may reject an otherwise valid Path because of platform naming rules, permissions, or capability restrictions. A Path does not establish filesystem existence or prevent a symbolic link from resolving elsewhere.

    Причина

    One normalized representation makes composition predictable. Parent and extension queries describe components without consulting host state. A suffix has one accepted spelling, and joining validates the child before its leading separator can disappear inside the combined text.

    Join relative components without changing the receiver

    Ссылка
    main.tpzJoin relative components without changing the receiverОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let base = test.assertOk(Path.from("chapters/draft"))
    5. let child = test.assertOk(base.join("../final/./main.tpz"))
    6. io.writeLine(base.toString())
    7. io.writeLine(child.toString())
    8. io.writeLine(test.assertOk(base.join("../..")).toString())
    9. io.writeLine(test.assertOk(base.join(".")).toString())
    Ожидаемый выводКод завершения 0
    chapters/draft
    chapters/final/main.tpz
    .
    chapters/draft
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. chapters/draft
    2. chapters/final/main.tpz
    3. .
    4. chapters/draft

    Reject invalid child text before joining

    Ссылка
    main.tpzReject invalid child text before joiningОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let base = test.assertOk(Path.from("chapters"))
    5. for child in (["", "/outside", "C:/outside", "../../outside"]) {
    6. match (base.join(child)) {
    7. case Err(_) => io.writeLine("rejected")
    8. case Ok(_) => io.writeLine("accepted")
    9. }
    10. }
    11. io.writeLine(base.toString())
    Ожидаемый выводКод завершения 0
    rejected
    rejected
    rejected
    rejected
    chapters
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. rejected
    2. rejected
    3. rejected
    4. rejected
    5. chapters

    Inspect the final component and the relative root

    Ссылка
    main.tpzInspect the final component and the relative rootОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let file = test.assertOk(Path.from("chapters/main.tpz"))
    5. io.writeLine(test.assertSome(file.parent()).toString())
    6. io.writeLine(test.assertSome(file.fileName()))
    7. io.writeLine(test.assertSome(file.extension()))
    8. let root = test.assertOk(Path.from("."))
    9. test.assertNone(root.parent())
    10. test.assertNone(root.fileName())
    11. test.assertNone(root.extension())
    12. io.writeLine(root.toString())
    Ожидаемый выводКод завершения 0
    chapters
    main.tpz
    tpz
    .
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. chapters
    2. main.tpz
    3. tpz
    4. .

    Keep the relative root as the parent of one component

    Ссылка
    main.tpzKeep the relative root as the parent of one componentОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let file = test.assertOk(Path.from("main.tpz"))
    5. match (file.parent()) {
    6. case Some(parent) => io.writeLine(parent.toString())
    7. case None() => io.writeLine("missing")
    8. }
    Ожидаемый выводКод завершения 0
    .
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. .

    Distinguish an absent extension from an empty extension

    Ссылка
    main.tpzDistinguish an absent extension from an empty extensionОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. for name in (["README", ".env", ".env.local", "archive.tar.gz", "trailing."]) {
    5. let file = test.assertOk(Path.from(name))
    6. match (file.extension()) {
    7. case Some(extension) => io.writeLine("present [{extension}]")
    8. case None() => io.writeLine("absent")
    9. }
    10. }
    Ожидаемый выводКод завершения 0
    absent
    absent
    present [local]
    present [gz]
    present []
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. absent
    2. absent
    3. present [local]
    4. present [gz]
    5. present []

    Replace and remove a final extension

    Ссылка
    main.tpzReplace and remove a final extensionОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let file = test.assertOk(Path.from("chapters/main.tpz"))
    5. io.writeLine(test.assertOk(file.withExtension("pdf")).toString())
    6. io.writeLine(test.assertOk(file.withExtension("")).toString())
    7. io.writeLine(file.toString())
    Ожидаемый выводКод завершения 0
    chapters/main.pdf
    chapters/main
    chapters/main.tpz
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. chapters/main.pdf
    2. chapters/main
    3. chapters/main.tpz

    Preserve the name of a file that starts with a dot

    Ссылка
    main.tpzPreserve the name of a file that starts with a dotОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let file = test.assertOk(Path.from(".env"))
    5. io.writeLine(test.assertOk(file.withExtension("local")).toString())
    6. io.writeLine(test.assertOk(file.withExtension("")).toString())
    Ожидаемый выводКод завершения 0
    .env.local
    .env
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. .env.local
    2. .env

    Reject a second suffix spelling and a path without a file name

    Ссылка
    main.tpzReject a second suffix spelling and a path without a file nameОткрыть песочницу →
    1. import std.path { Path }
    2. import std.test
    3. import std.io
    4. let file = test.assertOk(Path.from("chapter.txt"))
    5. for extension in ([".pdf", "pdf/extra", "pdf\\extra"]) {
    6. match (file.withExtension(extension)) {
    7. case Err(_) => io.writeLine("rejected")
    8. case Ok(_) => io.writeLine("accepted")
    9. }
    10. }
    11. let root = test.assertOk(Path.from("."))
    12. match (root.withExtension("pdf")) {
    13. case Err(_) => io.writeLine("root rejected")
    14. case Ok(_) => io.writeLine("root accepted")
    15. }
    Ожидаемый выводКод завершения 0
    rejected
    rejected
    rejected
    root rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. rejected
    2. rejected
    3. rejected
    4. root rejected

    Меню

    Загрузка →