-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathGitDiff.swift
More file actions
114 lines (91 loc) · 3.48 KB
/
GitDiff.swift
File metadata and controls
114 lines (91 loc) · 3.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import Foundation
import SystemUtils
public enum GitDiffGroup {
case index // Staged
case workingTree // Unstaged
}
public struct GitDiff {
public static func getDiff(of filePath: String, repositoryURL: URL, group: GitDiffGroup) async -> String {
var arguments = ["diff"]
if group == .index {
arguments.append("--cached")
}
arguments.append(contentsOf: ["--", filePath])
let result = try? SystemUtils.executeCommand(
inDirectory: repositoryURL.path,
path: GitPath,
arguments: arguments
)
return result ?? ""
}
public static func getDiffFiles(repositoryURL: URL, group: GitDiffGroup) async -> [GitChange] {
var arguments = ["diff", "--name-status", "-z", "--diff-filter=ADMR"]
if group == .index {
arguments.append("--cached")
}
let result = try? SystemUtils.executeCommand(
inDirectory: repositoryURL.path,
path: GitPath,
arguments: arguments
)
return result == nil
? []
: Self.parseDiff(repositoryURL: repositoryURL, raw: result!)
}
private static func parseDiff(repositoryURL: URL, raw: String) -> [GitChange] {
var index = 0
var result: [GitChange] = []
let segments = raw.trimmingCharacters(in: .whitespacesAndNewlines)
.split(separator: "\0")
.map(String.init)
.filter { !$0.isEmpty }
segmentsLoop: while index < segments.count - 1 {
let change = segments[index]
index += 1
let resourcePath = segments[index]
index += 1
if change.isEmpty || resourcePath.isEmpty {
break
}
let originalURL: URL
if resourcePath.hasPrefix("/") {
originalURL = URL(fileURLWithPath: resourcePath)
} else {
originalURL = repositoryURL.appendingPathComponent(resourcePath)
}
var url = originalURL
var status = GitFileStatus.untracked
// Copy or Rename status comes with a number (ex: 'R100').
// We don't need the number, we use only first character of the status.
switch change.first {
case "A":
status = .indexAdded
case "M":
status = .modified
case "D":
status = .deleted
// Rename contains two paths, the second one is what the file is renamed/copied to.
case "R":
if index >= segments.count {
break
}
let newPath = segments[index]
index += 1
if newPath.isEmpty {
break
}
status = .indexRenamed
if newPath.hasPrefix("/") {
url = URL(fileURLWithPath: newPath)
} else {
url = repositoryURL.appendingPathComponent(newPath)
}
default:
// Unknown status
break segmentsLoop
}
result.append(.init(url: url, originalURL: originalURL, status: status))
}
return result
}
}