Sources/OrgApp/DenoteNote.swift
26 lines · 1529 bytes
1import Foundation
2import OrgCore
3
4/// A new Denote note, as `denote` makes it with the default `denote-prompts` (title and
5/// keywords): `IDENTIFIER--title__keywords.org` in `denote-directory`, starting with the
6/// Org front matter.
7public enum DenoteNote {
8 /// `denote-directory`: the setting, else the first folder.
9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10 let denote = OrgPreferences.denoteDirectory(defaults)
11 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory())
12 }
13
14 /// Makes the note's file in `folder`. Fails rather than replace a file that's there.
15 public static func create(title: String, keywords: [String], in folder: String, now: Date = Date()) throws -> (path: String, id: String) {
16 let id = Denote.identifier(for: now)
17 let keywords = Denote.keywords(keywords)
18 let name = Denote.fileName(identifier: id, title: title, keywords: keywords)
19 let path = (folder as NSString).appendingPathComponent(name)
20 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
21 guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") }
22 let text = Denote.frontMatter(title: title, date: now, keywords: keywords, identifier: id)
23 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
24 return (path, id)
25 }
26}