Sources/OrgApp/AgendaFiles.swift
43 lines · 2337 bytes
1import Foundation
2
3/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its
4/// `.org` files not starting with a dot, in name order, not below it), an `.org` file, or a
5/// file listing more entries one per line, as the variable's string form names one.
6/// Relative paths count from `base`, standing in for `org-directory`. Missing files are left out.
7public enum AgendaFiles {
8 public static func resolve(_ entries: [String], base: String?, fileManager: FileManager = .default) -> [String] {
9 var out: [String] = []
10 var seen: Set<String> = []
11 func expand(_ entry: String, from base: String?) -> String {
12 let path = (entry as NSString).expandingTildeInPath
13 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath }
14 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath
15 }
16 func add(_ path: String) {
17 if seen.insert(path).inserted { out.append(path) }
18 }
19 func visit(_ entry: String, listed: Bool) {
20 let path = expand(entry, from: base)
21 var isDirectory: ObjCBool = false
22 guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) else { return }
23 if isDirectory.boolValue {
24 let names = (try? fileManager.contentsOfDirectory(atPath: path)) ?? []
25 for name in names.sorted() where !name.hasPrefix(".") && name.hasSuffix(".org") {
26 let file = (path as NSString).appendingPathComponent(name)
27 var dir: ObjCBool = false
28 if fileManager.fileExists(atPath: file, isDirectory: &dir), !dir.boolValue { add(file) }
29 }
30 } else if path.hasSuffix(".org") || listed {
31 add(path)
32 } else if let text = try? String(contentsOfFile: path, encoding: .utf8) {
33 // `org-read-agenda-file-list`.
34 for line in text.components(separatedBy: .newlines) {
35 let trimmed = line.trimmingCharacters(in: .whitespaces)
36 if !trimmed.isEmpty { visit(trimmed, listed: true) }
37 }
38 }
39 }
40 for entry in entries { visit(entry, listed: false) }
41 return out
42 }
43}