Sources/OrgApp/TangleWriter.swift
85 lines · 3698 bytes
1import Foundation
2import OrgCore
3
4/// Writes what `Tangle.run` produced, as `org-babel-tangle` does: a file whose contents
5/// haven't changed is left alone, `:mkdirp` makes its folder, a read-only file is replaced,
6/// and the mode is set after writing. A mode that can't be set doesn't stop the others.
7public enum TangleWriter {
8 public struct Failure: Error, Equatable {
9 public let message: String
10 }
11
12 /// The paths written or already up to date, in order.
13 @discardableResult
14 public static func write(_ output: Tangle.Output, source: String) throws(Failure) -> [String] {
15 let manager = FileManager.default
16 var paths: [String] = []
17 var modeFailure: Failure?
18 for file in output.files {
19 let url = URL(fileURLWithPath: file.path)
20 let data = Data(file.contents.utf8)
21 if let existing = manager.contents(atPath: file.path), existing == data {
22 paths.append(file.path)
23 continue
24 }
25 if (file.path as NSString).standardizingPath == (source as NSString).standardizingPath {
26 throw Failure(message: "Not allowed to tangle into the same file as self")
27 }
28 let folder = url.deletingLastPathComponent()
29 if file.makeDirectories {
30 do {
31 try manager.createDirectory(at: folder, withIntermediateDirectories: true)
32 } catch {
33 throw Failure(message: "Can't make \(folder.path): \(error.localizedDescription)")
34 }
35 }
36 if manager.fileExists(atPath: file.path), !manager.isWritableFile(atPath: file.path) {
37 try? manager.removeItem(at: url)
38 }
39 do {
40 try data.write(to: url)
41 } catch {
42 throw Failure(message: "Can't write \(file.path): \(error.localizedDescription)")
43 }
44 if let mode = file.mode {
45 do {
46 try manager.setAttributes([.posixPermissions: mode], ofItemAtPath: file.path)
47 } catch {
48 modeFailure = modeFailure ?? Failure(message: "\(message(output, source: source)), but can't set the mode of \(file.path): \(error.localizedDescription)")
49 }
50 }
51 paths.append(file.path)
52 }
53 if let modeFailure { throw modeFailure }
54 return paths
55 }
56
57 /// `org-babel-tangle`'s message.
58 public static func message(_ output: Tangle.Output, source: String) -> String {
59 "Tangled \(output.blocks) code block\(output.blocks == 1 ? "" : "s") from \((source as NSString).lastPathComponent)"
60 }
61}
62
63extension DocumentSession {
64 /// The files `tangle` would write.
65 public func tangleFiles(_ scope: Tangle.Scope) -> [String] {
66 guard let path, let document, case .success(let output) = Tangle.run(text: document.text, path: path, scope: scope, tree: document.tree) else { return [] }
67 return output.files.map(\.path)
68 }
69
70 /// Tangles the open file: its text as it is now, written beside it.
71 public func tangle(_ scope: Tangle.Scope) -> String {
72 guard let path, let document else { return "No file is open" }
73 switch Tangle.run(text: document.text, path: path, scope: scope, tree: document.tree) {
74 case .failure(.message(let message)):
75 return message
76 case .success(let output):
77 do {
78 try TangleWriter.write(output, source: path)
79 return TangleWriter.message(output, source: path)
80 } catch {
81 return error.message
82 }
83 }
84 }
85}