Sources/OrgApp/DenoteNote.swift
118 lines · 7325 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` (or
5/// `.md`, `.txt` for those file types) in `denote-directory` or a folder under it, starting
6/// with the front matter and then the 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 in the file's type or, without
80 /// one, added; a Markdown file without front matter gets `preferred`'s when that is a
81 /// Markdown type. A nil `date` keeps the front matter's. The text of a file Denote has no
82 /// type for stays as it is.
83 public static func renaming(
84 _ path: String, text: String, title: String, keywords: [String], signature: String, date: Date?, roots: [String], preferred: Denote.FileType = .org
85 ) -> (path: String, text: String) {
86 let name = Denote.name(ofFile: path)
87 let type = name.ext.isEmpty ? .org : Denote.FileType(path: path, text: text, preferred: preferred)
88 let front = Denote.frontMatter(of: text, type: type ?? .org)
89 let modified = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? Date()
90 let identifier = name.identifier ?? front.identifier ?? unusedIdentifier(date ?? modified, roots: roots)
91 let keywords = Denote.keywords(keywords), signature = Denote.signature(signature)
92 let target = ((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(
93 Denote.fileName(identifier: identifier, signature: signature, title: title, keywords: keywords, extension: name.ext.isEmpty ? "org" : name.ext))
94 guard let type else { return (target, text) }
95 return (target, Denote.rewritingFrontMatter(text, title: title, keywords: keywords, signature: signature, date: date, identifier: identifier,
96 now: date ?? modified, type: type))
97 }
98
99 /// Makes the note's file of `type` in `folder`. Its identifier is `now`'s, or as
100 /// `denote-generate-identifier-as-date` does, the first second after it no file under
101 /// `roots` (by default `folder`) has; the front matter keeps `now`. Fails rather than
102 /// replace a file.
103 public static func create(
104 title: String, keywords: [String], in folder: String, roots: [String] = [], now: Date = Date(), signature: String = "", template: String = "",
105 type: Denote.FileType = .org
106 ) throws -> (path: String, id: String) {
107 let id = unusedIdentifier(now, roots: roots.isEmpty ? [folder] : roots)
108 let keywords = Denote.keywords(keywords)
109 let signature = Denote.signature(signature)
110 let name = Denote.fileName(identifier: id, signature: signature, title: title, keywords: keywords, extension: type.ext)
111 let path = (folder as NSString).appendingPathComponent(name)
112 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
113 guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") }
114 let text = Denote.frontMatter(title: title, date: now, keywords: keywords, identifier: id, signature: signature, type: type) + template
115 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
116 return (path, id)
117 }
118}