Sources/OrgApp/DenoteNote.swift
112 lines · 6821 bytes
12 symbols in this file
1import Foundation
2import OrgCore
3
4/// A new Denote note, as `denote` makes it: `IDENTIFIER==signature--title__keywords.org` in
5/// `denote-directory` or a folder under it, starting with the Org front matter and then the
6/// template.
7public enum DenoteNote {
8 /// `denote-directories`: the folders of `denote-directory`, separated by `:`, else the
9 /// first sidebar folder.
10 public static func directories(roots: [String], defaults: UserDefaults = .standard) -> [String] {
11 let folders = paths(OrgPreferences.denoteDirectory(defaults), roots: roots)
12 return folders.isEmpty ? Array(roots.prefix(1)) : folders
13 }
14
15 /// The folder new notes go in: the first of `denote-directory`.
16 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
17 directories(roots: roots, defaults: defaults).first
18 }
19
20 /// `denote-silo-directories`, separated by `:`; by default `denote-directory`'s folders.
21 public static func silos(roots: [String], defaults: UserDefaults = .standard) -> [String] {
22 let silos = paths(OrgPreferences.denoteSiloDirectories(defaults), roots: roots)
23 return silos.isEmpty ? directories(roots: roots, defaults: defaults) : silos
24 }
25
26 static func paths(_ setting: String, roots: [String]) -> [String] {
27 setting.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
28 .map { OrgAttach.expand($0, in: roots.first ?? OrgPaths.home) }
29 }
30
31 /// A folder as the folder prompts show it, under `~` when it's in the home folder.
32 public static func abbreviated(_ path: String) -> String {
33 let home = OrgPaths.home
34 return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
35 }
36
37 /// The `subdirectory` prompt's choices and their folders: `.` and the folders under the
38 /// one root, relative to it, or with several roots, each root and its folders in full.
39 public static func folderChoices(_ roots: [String]) -> [(label: String, path: String)] {
40 if roots.count == 1, let root = roots.first {
41 return [(".", root)] + subdirectories(of: root).map { ($0, (root as NSString).appendingPathComponent($0)) }
42 }
43 return roots.flatMap { root in
44 [root] + subdirectories(of: root).map { (root as NSString).appendingPathComponent($0) }
45 }.map { (abbreviated($0), $0) }
46 }
47
48 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without
49 /// hidden ones.
50 public static func subdirectories(of root: String) -> [String] {
51 let url = URL(fileURLWithPath: root)
52 guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] }
53 var found: [String] = []
54 for case let item as URL in walk where (try? item.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
55 found.append(String(item.standardizedFileURL.path.dropFirst(url.standardizedFileURL.path.count + 1)))
56 }
57 return found.sorted()
58 }
59
60 /// The identifiers in the names of the files under `root`.
61 static func identifiers(under root: String) -> Set<String> {
62 guard let walk = FileManager.default.enumerator(atPath: root) else { return [] }
63 var found = Set<String>()
64 for case let path as String in walk { if let id = Denote.identifier(ofFile: path) { found.insert(id) } }
65 return found
66 }
67
68 /// `denote-generate-identifier-as-date`: `date`'s identifier, or the first second after it
69 /// no file under `roots` has.
70 public static func unusedIdentifier(_ date: Date, roots: [String]) -> String {
71 let used = roots.reduce(into: Set<String>()) { $0.formUnion(identifiers(under: $1)) }
72 var stamp = date
73 while used.contains(Denote.identifier(for: stamp)) { stamp += 1 }
74 return Denote.identifier(for: stamp)
75 }
76
77 /// `denote-rename-file` of the file at `path` with `text`: its new path and text, the
78 /// keywords sorted, the identifier kept (or for a file without one, its modification
79 /// time's, unused under `roots`), the front matter rewritten or, without one, added.
80 /// A nil `date` keeps the front matter's.
81 public static func renaming(
82 _ path: String, text: String, title: String, keywords: [String], signature: String, date: Date?, roots: [String]
83 ) -> (path: String, text: String) {
84 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
85 let modified = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? Date()
86 let identifier = name.identifier ?? front.identifier ?? unusedIdentifier(date ?? modified, roots: roots)
87 let keywords = Denote.keywords(keywords), signature = Denote.signature(signature)
88 let target = ((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(
89 Denote.fileName(identifier: identifier, signature: signature, title: title, keywords: keywords, extension: name.ext.isEmpty ? "org" : name.ext))
90 guard name.ext == "org" || name.ext.isEmpty else { return (target, text) }
91 return (target, Denote.rewritingFrontMatter(text, title: title, keywords: keywords, signature: signature, date: date, identifier: identifier, now: date ?? modified))
92 }
93
94 /// Makes the note's file in `folder`. Its identifier is `now`'s, or as
95 /// `denote-generate-identifier-as-date` does, the first second after it no file under
96 /// `roots` (by default `folder`) has; the front matter keeps `now`. Fails rather than
97 /// replace a file.
98 public static func create(
99 title: String, keywords: [String], in folder: String, roots: [String] = [], now: Date = Date(), signature: String = "", template: String = ""
100 ) throws -> (path: String, id: String) {
101 let id = unusedIdentifier(now, roots: roots.isEmpty ? [folder] : roots)
102 let keywords = Denote.keywords(keywords)
103 let signature = Denote.signature(signature)
104 let name = Denote.fileName(identifier: id, signature: signature, title: title, keywords: keywords)
105 let path = (folder as NSString).appendingPathComponent(name)
106 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
107 guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") }
108 let text = Denote.frontMatter(title: title, date: now, keywords: keywords, identifier: id, signature: signature) + template
109 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
110 return (path, id)
111 }
112}