restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
import Foundation
|
||||
|
||||
/// What was right-clicked.
|
||||
public enum ContextTarget: Sendable, Equatable {
|
||||
/// A line or selection in the editor; `code` is the selected text, if any.
|
||||
case editor(reference: AgentReference, code: String?)
|
||||
case file(path: String)
|
||||
case directory(path: String)
|
||||
/// A git row; the row carries its own half, since one file can have two rows.
|
||||
case gitRow(path: String, staged: Bool)
|
||||
/// The empty space under the tree: the project folder itself.
|
||||
case projectRoot
|
||||
case terminal(TerminalKind, hasSelection: Bool)
|
||||
|
||||
public var path: String {
|
||||
switch self {
|
||||
case let .editor(reference, _): reference.path
|
||||
case let .file(path), let .directory(path), let .gitRow(path, _): path
|
||||
case .projectRoot, .terminal: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum ContextAction: Sendable, Equatable {
|
||||
/// Opens the pass-on prompt; with code for an editor selection.
|
||||
case passOnReference(String, code: String?)
|
||||
case copyReference(String)
|
||||
case passOnFileName(String)
|
||||
case copyFileName(String)
|
||||
case newFile(inDirectory: String)
|
||||
case newFolder(inDirectory: String)
|
||||
case stage(String)
|
||||
case unstage(String)
|
||||
case openDiff(String)
|
||||
case discard(String)
|
||||
case rename(String, isDirectory: Bool)
|
||||
case revealInFinder(String)
|
||||
case delete(String, isDirectory: Bool)
|
||||
case copyTerminalSelection(TerminalKind)
|
||||
case pasteIntoTerminal(TerminalKind)
|
||||
|
||||
/// Destructive items read in amber-deep.
|
||||
public var isDestructive: Bool {
|
||||
switch self {
|
||||
case .discard, .delete: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A menu entry, or a separator between groups.
|
||||
public enum ContextMenuEntry: Sendable, Equatable {
|
||||
case action(ContextAction, label: String)
|
||||
case separator
|
||||
}
|
||||
|
||||
public enum ContextActions {
|
||||
/// The header line of the menu: the reference, or `project/` for the root.
|
||||
public static func header(for target: ContextTarget, projectName: String) -> String {
|
||||
switch target {
|
||||
case let .editor(reference, _): reference.description
|
||||
case let .directory(path): path + "/"
|
||||
case let .file(path), let .gitRow(path, _): path
|
||||
case .projectRoot: projectName + "/"
|
||||
case .terminal: ""
|
||||
}
|
||||
}
|
||||
|
||||
/// Menu entries: every "Pass on …" item has its "Copy …" twin directly below.
|
||||
public static func entries(for target: ContextTarget) -> [ContextMenuEntry] {
|
||||
switch target {
|
||||
case let .editor(reference, code):
|
||||
let ref = reference.description
|
||||
let hasCode = !(code ?? "").isEmpty
|
||||
return [
|
||||
.action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"),
|
||||
.action(.copyReference(ref), label: "Copy reference"),
|
||||
]
|
||||
case .projectRoot:
|
||||
return [
|
||||
.action(.newFile(inDirectory: ""), label: "New file"),
|
||||
.action(.revealInFinder(""), label: "Show in Finder"),
|
||||
]
|
||||
case let .file(path):
|
||||
return fileHead(path) + [
|
||||
.separator,
|
||||
.action(.rename(path, isDirectory: false), label: "Rename file"),
|
||||
.action(.revealInFinder(path), label: "Show in Finder"),
|
||||
.action(.delete(path, isDirectory: false), label: "Delete file"),
|
||||
]
|
||||
case let .directory(path):
|
||||
let ref = path + "/"
|
||||
return [
|
||||
.action(.passOnReference(ref, code: nil), label: "Pass on reference"),
|
||||
.action(.copyReference(ref), label: "Copy reference"),
|
||||
.separator,
|
||||
.action(.newFile(inDirectory: path), label: "New file"),
|
||||
.action(.newFolder(inDirectory: path), label: "New folder"),
|
||||
.separator,
|
||||
.action(.rename(path, isDirectory: true), label: "Rename folder"),
|
||||
.action(.revealInFinder(path), label: "Show in Finder"),
|
||||
.action(.delete(path, isDirectory: true), label: "Delete folder"),
|
||||
]
|
||||
case let .terminal(kind, hasSelection):
|
||||
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
|
||||
+ [.action(.pasteIntoTerminal(kind), label: "Paste")]
|
||||
case let .gitRow(path, staged):
|
||||
return fileHead(path) + [
|
||||
.separator,
|
||||
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
|
||||
.action(.openDiff(path), label: "Open diff"),
|
||||
.action(.discard(path), label: "Discard changes"),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
private static func fileHead(_ path: String) -> [ContextMenuEntry] {
|
||||
let name = PathUtils.basename(path)
|
||||
return [
|
||||
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
|
||||
.action(.copyReference(path), label: "Copy reference"),
|
||||
.action(.passOnFileName(name), label: "Pass on file name"),
|
||||
.action(.copyFileName(name), label: "Copy file name"),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import Foundation
|
||||
|
||||
public enum FileLimits {
|
||||
/// Files above this size are left out of the content index.
|
||||
public static let maxIndexedFileBytes = 300_000
|
||||
public static let maxIndexedFiles = 6000
|
||||
public static let maxImageBytes = 25_000_000
|
||||
/// Git reads a file above this size as having no text, so one dump or lock file cannot stall the column.
|
||||
public static let maxDiffFileBytes = 1_000_000
|
||||
/// How deep the fallback directory walk goes.
|
||||
public static let maxWalkDepth = 12
|
||||
|
||||
/// A NUL byte in the first 8000 bytes marks a file as binary, like git does.
|
||||
public static func looksBinary(_ data: Data) -> Bool {
|
||||
data.prefix(8000).contains(0)
|
||||
}
|
||||
|
||||
public static let imageMimeTypes: [String: String] = [
|
||||
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg",
|
||||
"gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml", "bmp": "image/bmp",
|
||||
"ico": "image/x-icon", "avif": "image/avif", "apng": "image/apng",
|
||||
]
|
||||
}
|
||||
|
||||
public enum IgnoreRules {
|
||||
/// Folders the fallback walk and the watcher never enter.
|
||||
public static let walkIgnoredNames: Set<String> = [
|
||||
"node_modules", ".git", "out", "dist", "build", ".next", ".nuxt",
|
||||
".cache", "coverage", "vendor", ".idea", ".vscode", ".helder", ".turbo",
|
||||
]
|
||||
|
||||
/// Always passed to ripgrep as `!glob`, on top of gitignore and `files.exclude`.
|
||||
/// `.DS_Store` is here because `followGitignore` defaults to false (rg runs with --no-ignore).
|
||||
public static let ripgrepBaseIgnore = [
|
||||
"node_modules", ".git", "out", "dist", "build", ".cache",
|
||||
"vendor", "coverage", ".helder", ".next", ".nuxt", ".turbo", ".idea", ".vscode",
|
||||
".DS_Store",
|
||||
]
|
||||
|
||||
/// Declarations are indexed inside `vendor/` too, so framework classes stay clickable.
|
||||
public static let symbolDeclarationIgnore = ripgrepBaseIgnore.filter { $0 != "vendor" && $0 != ".DS_Store" }
|
||||
/// References skip `vendor/`: nobody wants to read how a framework uses a class.
|
||||
public static let symbolReferenceIgnore = ripgrepBaseIgnore.filter { $0 != ".DS_Store" }
|
||||
|
||||
/// True for a name the fallback walk skips.
|
||||
public static func isWalkIgnored(_ name: String) -> Bool {
|
||||
walkIgnoredNames.contains(name) || name == ".DS_Store"
|
||||
}
|
||||
|
||||
/// True when any segment of a relative path is an ignored folder; the watcher drops such events.
|
||||
public static func isWatchIgnored(_ relativePath: String) -> Bool {
|
||||
relativePath.split(separator: "/").contains { walkIgnoredNames.contains(String($0)) }
|
||||
}
|
||||
|
||||
/// Framework caches rewritten on every request or test run; watching them refreshes the project in a loop.
|
||||
public static let watchIgnoredPrefixes = [
|
||||
"storage/framework/", "bootstrap/cache/", ".phpunit.result.cache", ".phpunit.cache/",
|
||||
]
|
||||
|
||||
/// `isWatchIgnored`, plus the framework caches and the project's `files.exclude` globs.
|
||||
public static func isWatchIgnored(_ relativePath: String, exclude: [String]) -> Bool {
|
||||
if isWatchIgnored(relativePath) { return true }
|
||||
if watchIgnoredPrefixes.contains(where: { relativePath == $0 || relativePath.hasPrefix($0) || $0 == relativePath + "/" }) {
|
||||
return true
|
||||
}
|
||||
return exclude.contains { !$0.isEmpty && globMatches($0, path: relativePath) }
|
||||
}
|
||||
|
||||
/// The `--glob !x` pairs plus `--no-ignore` that make ripgrep honour the project's file settings.
|
||||
public static func ripgrepArguments(files: HelderConfig.Files, base: [String] = ripgrepBaseIgnore) -> [String] {
|
||||
var args: [String] = []
|
||||
for glob in base { args += ["--glob", "!" + glob] }
|
||||
for glob in files.exclude where !glob.isEmpty { args += ["--glob", "!" + glob] }
|
||||
if !files.followGitignore { args.append("--no-ignore") }
|
||||
return args
|
||||
}
|
||||
|
||||
/// Gitignore-style glob match of a relative path, with ripgrep's `--glob` semantics.
|
||||
///
|
||||
/// A pattern without a slash matches a basename at any depth; `**` crosses folders, `*` and `?`
|
||||
/// stop at a slash. A matching folder matches everything under it, as in ripgrep.
|
||||
public static func globMatches(_ glob: String, path: String) -> Bool {
|
||||
var pattern = Substring(glob)
|
||||
while pattern.hasSuffix("/") { pattern = pattern.dropLast() }
|
||||
let rooted = pattern.hasPrefix("/")
|
||||
if rooted { pattern = pattern.dropFirst() }
|
||||
guard !pattern.isEmpty else { return false }
|
||||
let anchored = rooted || pattern.contains("/")
|
||||
let candidates = PathUtils.ancestors(path) + [path]
|
||||
for alternative in expandBraces(String(pattern)) {
|
||||
let chars = Array(alternative)
|
||||
for candidate in candidates {
|
||||
let subject = Array(anchored ? candidate : PathUtils.basename(candidate))
|
||||
var matcher = WildcardMatcher(pattern: chars, subject: subject)
|
||||
if matcher.matches() { return true }
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// `{a,b}` alternation expanded into plain patterns; nested braces expand recursively.
|
||||
static func expandBraces(_ pattern: String) -> [String] {
|
||||
let chars = Array(pattern)
|
||||
guard let open = chars.firstIndex(of: "{") else { return [pattern] }
|
||||
var depth = 0
|
||||
var parts: [String] = []
|
||||
var current = ""
|
||||
for k in (open + 1)..<chars.count {
|
||||
let c = chars[k]
|
||||
if c == "{" { depth += 1 }
|
||||
if c == "}" {
|
||||
if depth == 0 {
|
||||
parts.append(current)
|
||||
let head = String(chars[..<open]), rest = String(chars[(k + 1)...])
|
||||
return parts.flatMap { expandBraces(head + $0 + rest) }
|
||||
}
|
||||
depth -= 1
|
||||
}
|
||||
if c == "," && depth == 0 {
|
||||
parts.append(current)
|
||||
current = ""
|
||||
} else {
|
||||
current.append(c)
|
||||
}
|
||||
}
|
||||
return [pattern]
|
||||
}
|
||||
}
|
||||
|
||||
/// Glob matcher: `**` crosses folders, `*` and `?` stop at a slash, `[...]` is a character class.
|
||||
private struct WildcardMatcher {
|
||||
let pattern: [Character]
|
||||
let subject: [Character]
|
||||
private var memo: [Bool?]
|
||||
|
||||
init(pattern: [Character], subject: [Character]) {
|
||||
self.pattern = pattern
|
||||
self.subject = subject
|
||||
memo = Array(repeating: nil, count: (pattern.count + 1) * (subject.count + 1))
|
||||
}
|
||||
|
||||
mutating func matches() -> Bool { match(0, 0) }
|
||||
|
||||
private mutating func match(_ p: Int, _ s: Int) -> Bool {
|
||||
let key = p * (subject.count + 1) + s
|
||||
if let known = memo[key] { return known }
|
||||
let result = compute(p, s)
|
||||
memo[key] = result
|
||||
return result
|
||||
}
|
||||
|
||||
private mutating func compute(_ p: Int, _ s: Int) -> Bool {
|
||||
guard p < pattern.count else { return s == subject.count }
|
||||
switch pattern[p] {
|
||||
case "*":
|
||||
if p + 1 < pattern.count && pattern[p + 1] == "*" {
|
||||
let afterStars = p + 2
|
||||
if afterStars < pattern.count && pattern[afterStars] == "/" && match(afterStars + 1, s) { return true }
|
||||
for k in s...subject.count where match(afterStars, k) { return true }
|
||||
return false
|
||||
}
|
||||
var k = s
|
||||
while true {
|
||||
if match(p + 1, k) { return true }
|
||||
if k == subject.count || subject[k] == "/" { return false }
|
||||
k += 1
|
||||
}
|
||||
case "?":
|
||||
return s < subject.count && subject[s] != "/" && match(p + 1, s + 1)
|
||||
case "[":
|
||||
guard s < subject.count, subject[s] != "/", let (hit, next) = classMatch(p, subject[s]) else {
|
||||
return s < subject.count && subject[s] == "[" && match(p + 1, s + 1)
|
||||
}
|
||||
return hit && match(next, s + 1)
|
||||
case "\\" where p + 1 < pattern.count:
|
||||
return s < subject.count && subject[s] == pattern[p + 1] && match(p + 2, s + 1)
|
||||
default:
|
||||
return s < subject.count && subject[s] == pattern[p] && match(p + 1, s + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `c` is in the class opening at `p`, and the index after it; nil for an unclosed `[`.
|
||||
private func classMatch(_ p: Int, _ c: Character) -> (Bool, Int)? {
|
||||
var k = p + 1
|
||||
let negated = k < pattern.count && (pattern[k] == "!" || pattern[k] == "^")
|
||||
if negated { k += 1 }
|
||||
var hit = false
|
||||
var first = true
|
||||
while k < pattern.count {
|
||||
if pattern[k] == "]" && !first { return (hit != negated, k + 1) }
|
||||
first = false
|
||||
if k + 2 < pattern.count && pattern[k + 1] == "-" && pattern[k + 2] != "]" {
|
||||
if pattern[k] <= c && c <= pattern[k + 2] { hit = true }
|
||||
k += 3
|
||||
} else {
|
||||
if pattern[k] == c { hit = true }
|
||||
k += 1
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import Foundation
|
||||
|
||||
public struct FileNode: Sendable, Equatable, Identifiable {
|
||||
public enum Kind: String, Sendable, Equatable {
|
||||
case directory
|
||||
case file
|
||||
}
|
||||
|
||||
public var name: String
|
||||
public var kind: Kind
|
||||
/// Project-relative, "/"-separated; "" is the project root.
|
||||
public var path: String
|
||||
/// nil for files; an empty array for an empty folder.
|
||||
public var children: [FileNode]?
|
||||
|
||||
public var id: String { path }
|
||||
public var isDirectory: Bool { kind == .directory }
|
||||
public var isHidden: Bool { name.hasPrefix(".") }
|
||||
|
||||
public init(name: String, kind: Kind, path: String, children: [FileNode]? = nil) {
|
||||
self.name = name
|
||||
self.kind = kind
|
||||
self.path = path
|
||||
self.children = kind == .directory ? (children ?? []) : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// One visible row of the Explorer, in render order.
|
||||
public struct TreeRow: Sendable, Equatable {
|
||||
public var path: String
|
||||
public var kind: FileNode.Kind
|
||||
/// 0 for a top-level entry; the Explorer indents 16px per level.
|
||||
public var depth: Int
|
||||
|
||||
public init(path: String, kind: FileNode.Kind, depth: Int) {
|
||||
self.path = path
|
||||
self.kind = kind
|
||||
self.depth = depth
|
||||
}
|
||||
}
|
||||
|
||||
public enum FileTree {
|
||||
/// Nested tree from relative file paths: folders first, then files, each sorted by name.
|
||||
///
|
||||
/// `emptyDirs` adds the folders that hold no file, which `rg --files` never lists.
|
||||
/// Names sort case-insensitively, not in byte order.
|
||||
public static func build(rootName: String, paths: [String], emptyDirs: [String] = []) -> FileNode {
|
||||
var folders: [String: Set<String>] = ["": []]
|
||||
var files: [String: Set<String>] = [:]
|
||||
|
||||
func ensureFolder(_ parts: ArraySlice<Substring>) -> String {
|
||||
var parent = ""
|
||||
for part in parts {
|
||||
let path = PathUtils.join(parent, String(part))
|
||||
if folders[path] == nil {
|
||||
folders[path] = []
|
||||
folders[parent, default: []].insert(path)
|
||||
}
|
||||
parent = path
|
||||
}
|
||||
return parent
|
||||
}
|
||||
|
||||
for path in paths {
|
||||
let parts = path.split(separator: "/")
|
||||
guard let name = parts.last else { continue }
|
||||
let parent = ensureFolder(parts.dropLast())
|
||||
files[parent, default: []].insert(PathUtils.join(parent, String(name)))
|
||||
}
|
||||
for dir in emptyDirs {
|
||||
_ = ensureFolder(dir.split(separator: "/")[...])
|
||||
}
|
||||
|
||||
func node(folder path: String, name: String) -> FileNode {
|
||||
let subfolders = (folders[path] ?? []).map { node(folder: $0, name: PathUtils.basename($0)) }
|
||||
let leaves = (files[path] ?? []).map { FileNode(name: PathUtils.basename($0), kind: .file, path: $0) }
|
||||
return FileNode(name: name, kind: .directory, path: path, children: sortedByName(subfolders) + sortedByName(leaves))
|
||||
}
|
||||
return node(folder: "", name: rootName)
|
||||
}
|
||||
|
||||
/// Case-insensitive, locale-aware order.
|
||||
static func sortedByName(_ nodes: [FileNode]) -> [FileNode] {
|
||||
nodes.sorted { $0.name.compare($1.name, locale: sortLocale) == .orderedAscending }
|
||||
}
|
||||
|
||||
private static let sortLocale = Locale(identifier: "en_US")
|
||||
|
||||
/// The node at a relative path ("" is the root), or nil.
|
||||
public static func find(_ path: String, in tree: FileNode) -> FileNode? {
|
||||
if path.isEmpty { return tree }
|
||||
var node = tree
|
||||
for part in path.split(separator: "/") {
|
||||
guard let next = node.children?.first(where: { $0.name == part }) else { return nil }
|
||||
node = next
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
/// A copy of the tree with the children of the node at `path` replaced; unchanged when the path is absent.
|
||||
public static func replacingChildren(of path: String, with children: [FileNode], in tree: FileNode) -> FileNode {
|
||||
if tree.path == path {
|
||||
var copy = tree
|
||||
copy.children = children
|
||||
return copy
|
||||
}
|
||||
guard let kids = tree.children, path.hasPrefix(tree.path) else { return tree }
|
||||
var copy = tree
|
||||
copy.children = kids.map { replacingChildren(of: path, with: children, in: $0) }
|
||||
return copy
|
||||
}
|
||||
|
||||
/// The visible rows under the root, honouring expanded folders and the hidden-files toggle.
|
||||
public static func visibleRows(_ tree: FileNode, expanded: Set<String>, showHidden: Bool) -> [TreeRow] {
|
||||
var rows: [TreeRow] = []
|
||||
func walk(_ node: FileNode, depth: Int) {
|
||||
for child in node.children ?? [] where showHidden || !child.isHidden {
|
||||
rows.append(TreeRow(path: child.path, kind: child.kind, depth: depth))
|
||||
if child.isDirectory && expanded.contains(child.path) { walk(child, depth: depth + 1) }
|
||||
}
|
||||
}
|
||||
walk(tree, depth: 0)
|
||||
return rows
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import Foundation
|
||||
|
||||
/// A highlighter grammar.
|
||||
public enum Language: String, Sendable, CaseIterable {
|
||||
case php, javascript, jsx, typescript, tsx, python, markup, css, json, markdown, bash, yaml
|
||||
}
|
||||
|
||||
/// One of the four badge fills; the UI maps each to a Palette colour.
|
||||
public enum BadgeTint: String, Sendable {
|
||||
case purple
|
||||
case amber
|
||||
case teal
|
||||
case grey
|
||||
}
|
||||
|
||||
/// The small extension chip in rows and headers: ink text on a tinted fill.
|
||||
public struct FileBadge: Sendable, Equatable {
|
||||
public var text: String
|
||||
public var tint: BadgeTint
|
||||
|
||||
public init(_ text: String, _ tint: BadgeTint) {
|
||||
self.text = text
|
||||
self.tint = tint
|
||||
}
|
||||
}
|
||||
|
||||
public enum FileType {
|
||||
/// Lowercased extension; any `.env*` file reads as `env`.
|
||||
public static func ext(_ path: String) -> String {
|
||||
let base = PathUtils.basename(path)
|
||||
if base.hasPrefix(".env") { return "env" }
|
||||
guard let dot = base.lastIndex(of: ".") else { return "" }
|
||||
return base[base.index(after: dot)...].lowercased()
|
||||
}
|
||||
|
||||
private static let languages: [String: Language] = [
|
||||
"php": .php, "js": .javascript, "mjs": .javascript, "cjs": .javascript,
|
||||
"jsx": .jsx, "ts": .typescript, "tsx": .tsx, "py": .python,
|
||||
"html": .markup, "xml": .markup, "svg": .markup, "vue": .markup,
|
||||
"css": .css, "scss": .css, "json": .json, "md": .markdown,
|
||||
"sh": .bash, "bash": .bash, "yml": .yaml, "yaml": .yaml, "env": .bash,
|
||||
]
|
||||
|
||||
public static func language(for path: String) -> Language? {
|
||||
languages[ext(path)]
|
||||
}
|
||||
|
||||
public static func isMarkdown(_ path: String) -> Bool {
|
||||
language(for: path) == .markdown
|
||||
}
|
||||
|
||||
private static let labels: [String: String] = [
|
||||
"php": "PHP", "js": "JavaScript", "mjs": "JavaScript", "ts": "TypeScript",
|
||||
"tsx": "TypeScript", "jsx": "JavaScript", "py": "Python", "html": "HTML",
|
||||
"css": "CSS", "json": "JSON", "md": "Markdown", "sh": "Shell", "env": "Dotenv",
|
||||
"yml": "YAML", "yaml": "YAML",
|
||||
]
|
||||
|
||||
/// The status-bar language name.
|
||||
public static func languageLabel(for path: String) -> String {
|
||||
let e = ext(path)
|
||||
return labels[e] ?? (e.isEmpty ? "Plain Text" : e.uppercased())
|
||||
}
|
||||
|
||||
public static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "apng", "jfif"]
|
||||
|
||||
/// Files the viewer shows as a picture instead of text.
|
||||
public static func isImage(_ path: String) -> Bool {
|
||||
imageExtensions.contains(ext(path))
|
||||
}
|
||||
|
||||
/// Files that never open: the viewer flashes "Too big." instead.
|
||||
public static let tooBigNames: Set<String> = ["composer.lock"]
|
||||
|
||||
private static let badges: [String: FileBadge] = [
|
||||
"php": FileBadge("php", .purple), "blade": FileBadge("php", .purple),
|
||||
"ts": FileBadge("ts", .purple), "tsx": FileBadge("tsx", .purple), "vue": FileBadge("vue", .purple),
|
||||
"js": FileBadge("js", .amber), "mjs": FileBadge("js", .amber), "cjs": FileBadge("js", .amber),
|
||||
"jsx": FileBadge("jsx", .amber), "json": FileBadge("json", .amber),
|
||||
"yml": FileBadge("yml", .amber), "yaml": FileBadge("yml", .amber),
|
||||
"css": FileBadge("css", .teal), "scss": FileBadge("scss", .teal), "pcss": FileBadge("css", .teal),
|
||||
"html": FileBadge("html", .teal), "sh": FileBadge("sh", .teal), "env": FileBadge("env", .teal),
|
||||
"py": FileBadge("py", .teal), "sql": FileBadge("sql", .teal),
|
||||
"md": FileBadge("md", .grey), "txt": FileBadge("txt", .grey),
|
||||
"lock": FileBadge("lock", .grey), "svg": FileBadge("svg", .grey),
|
||||
]
|
||||
|
||||
private static let nameBadges: [String: FileBadge] = [
|
||||
"composer.json": FileBadge("json", .purple),
|
||||
"package.json": FileBadge("json", .amber),
|
||||
".env": FileBadge("env", .teal),
|
||||
]
|
||||
|
||||
/// The badge for a path; unknown extensions get a grey chip with up to four letters, or "·".
|
||||
public static func badge(for path: String) -> FileBadge {
|
||||
if let named = nameBadges[PathUtils.basename(path)] { return named }
|
||||
let e = ext(path)
|
||||
return badges[e] ?? FileBadge(e.isEmpty ? "·" : String(e.prefix(4)), .grey)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user