Files
helder/Sources/HelderCore/Files/PathUtils.swift
T

64 lines
2.7 KiB
Swift

import Foundation
public enum PathUtils {
public static func basename(_ path: String) -> String {
path.split(separator: "/").last.map(String.init) ?? ""
}
/// Everything before the last segment; "" for a top-level entry.
public static func dirname(_ path: String) -> String {
guard let slash = path.lastIndex(of: "/") else { return "" }
return String(path[..<slash])
}
/// `dir/name`, or just `name` when `dir` is the root.
public static func join(_ dir: String, _ name: String) -> String {
dir.isEmpty ? name : dir + "/" + name
}
/// Every ancestor folder of a path, outermost first: `a/b/c.txt` → [a, a/b].
public static func ancestors(_ path: String) -> [String] {
let parts = path.split(separator: "/").map(String.init)
guard parts.count > 1 else { return [] }
return (1..<parts.count).map { parts[0..<$0].joined(separator: "/") }
}
/// True when any segment is a dotfile or dot-folder.
public static func isHidden(_ path: String) -> Bool {
path.split(separator: "/").contains { $0.hasPrefix(".") }
}
/// True for `path` itself and, when it is a folder, for everything under it.
public static func isInside(_ candidate: String, _ path: String, isDirectory: Bool) -> Bool {
candidate == path || (isDirectory && candidate.hasPrefix(path + "/"))
}
/// Carries a path over a rename of `from` to `to`; folders move everything under them.
public static func remap(_ candidate: String, from: String, to: String, isDirectory: Bool) -> String {
if candidate == from { return to }
if isDirectory && candidate.hasPrefix(from + "/") { return to + candidate.dropFirst(from.count) }
return candidate
}
/// A cleaned basename for a rename, or nil when it is empty, has a slash, or is `.`/`..`.
public static func validatedName(_ name: String) -> String? {
var clean = name.trimmingCharacters(in: .whitespacesAndNewlines)
while clean.hasSuffix("/") { clean.removeLast() }
if clean.isEmpty || clean.contains("/") || clean == "." || clean == ".." { return nil }
return clean
}
/// The relative path a create-in-folder action targets; leading and trailing slashes are dropped.
public static func newEntryPath(inDirectory dir: String, name: String) -> String {
var clean = Substring(name)
while clean.hasPrefix("/") { clean = clean.dropFirst() }
while clean.hasSuffix("/") { clean = clean.dropLast() }
return join(dir, String(clean))
}
/// A reference to a project entry: folders end in a slash.
public static func reference(_ path: String, isDirectory: Bool) -> String {
isDirectory ? path + "/" : path
}
}