Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectCreationModels.swift

283 lines10.4 KB

1import Foundation
2​
3@MainActor
4protocol FeatureProjectCreationClient: AnyObject {
5 func addProject(environmentID: String, path: String) async throws
6 func browseProjectFolders(
7 environmentID: String,
8 partialPath: String
9 ) async throws -> FilesystemBrowseResult
10 func discoverProjectSources(environmentID: String) async throws -> SourceControlDiscoveryResult
11 func lookupProjectRepository(
12 environmentID: String,
13 provider: SourceControlProviderKind,
14 repository: String
15 ) async throws -> SourceControlRepositoryInfo
16 func cloneProjectRepository(
17 environmentID: String,
18 remoteURL: String,
19 destinationPath: String
20 ) async throws -> SourceControlCloneResult
22​
23enum ProjectRemoteSource: String, CaseIterable, Hashable, Identifiable {
24 case url
25 case github
26 case gitlab
27 case bitbucket
28 case azureDevOps = "azure-devops"
29​
30 var id: String { rawValue }
31​
32 var provider: SourceControlProviderKind? {
33 switch self {
34 case .url: nil
35 case .github: .github
36 case .gitlab: .gitlab
37 case .bitbucket: .bitbucket
38 case .azureDevOps: .azureDevOps
39 }
40 }
41​
42 var label: String {
43 switch self {
44 case .url: "Git URL"
45 case .github: "GitHub"
46 case .gitlab: "GitLab"
47 case .bitbucket: "Bitbucket"
48 case .azureDevOps: "Azure DevOps"
49 }
50 }
51​
52 var prompt: String {
53 switch self {
54 case .url: "https://github.com/org/repository.git"
55 case .github, .gitlab, .bitbucket: "owner/repository"
56 case .azureDevOps: "organization/project/repository"
57 }
58 }
60​
61struct ProjectRemoteSourceOption: Equatable, Identifiable {
62 let source: ProjectRemoteSource
63 let isReady: Bool
64 let detail: String?
65​
66 var id: String { source.id }
68​
69enum ProjectRemoteSourceOptions {
70 static func options(
71 discovery: SourceControlDiscoveryResult?
72 ) -> [ProjectRemoteSourceOption] {
73 let providerByKind = Dictionary(
74 uniqueKeysWithValues: (discovery?.sourceControlProviders ?? []).map {
75 ($0.kind.rawValue, $0)
76 }
77 )
78​
79 return ProjectRemoteSource.allCases.map { source in
80 guard let providerKind = source.provider else {
81 return ProjectRemoteSourceOption(source: source, isReady: true, detail: nil)
82 }
83 guard let provider = providerByKind[providerKind.rawValue] else {
84 return ProjectRemoteSourceOption(
85 source: source,
86 isReady: false,
87 detail: "Provider status unavailable"
88 )
89 }
90 guard provider.status == .available else {
91 return ProjectRemoteSourceOption(
92 source: source,
93 isReady: false,
94 detail: provider.detail ?? provider.installHint
95 )
96 }
97 guard provider.auth.status != .unauthenticated else {
98 return ProjectRemoteSourceOption(
99 source: source,
100 isReady: false,
101 detail: provider.auth.detail ?? "Authentication required"
102 )
103 }
104 let account = provider.auth.account.map { "Signed in as \($0)" }
105 return ProjectRemoteSourceOption(
106 source: source,
107 isReady: true,
108 detail: account ?? provider.version
109 )
110 }
111 }
113​
114enum ProjectCreationPath {
115 static func normalizedCloneURL(_ input: String) -> String {
116 let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
117 let pattern = #"^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]+(?:\.git)?$"#
118 guard trimmed.range(of: pattern, options: .regularExpression) != nil else {
119 return trimmed
120 }
121 let repository = trimmed.hasSuffix(".git") ? trimmed : "\(trimmed).git"
122 return "https://github.com/\(repository)"
123 }
124​
125 static func defaultCloneURL(for repository: SourceControlRepositoryInfo) -> String {
126 repository.provider == .github ? repository.url : repository.sshUrl
127 }
128​
129 static func validated(_ rawValue: String) -> Result<String, ProjectCreationValidationError> {
130 let path = rawValue.trimmingCharacters(in: .whitespacesAndNewlines)
131 guard !path.isEmpty else {
132 return .failure(.init(message: "Enter a project path."))
133 }
134 guard isAbsoluteOrHomeRelative(path) else {
135 return .failure(
136 .init(message: "Use an absolute path, or start with ~/.")
137 )
138 }
139 return .success(path)
140 }
141​
142 static func repositoryName(from value: String) -> String {
143 let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
144 guard !trimmed.isEmpty else { return "repository" }
145 let withoutQuery = trimmed.split(separator: "?", maxSplits: 1).first.map(String.init)
146 ?? trimmed
147 let withoutFragment = withoutQuery.split(separator: "#", maxSplits: 1).first.map(String.init)
148 ?? withoutQuery
149 let normalized = withoutFragment
150 .replacingOccurrences(of: "\\", with: "/")
151 .replacingOccurrences(of: ":", with: "/")
152 .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
153 let component = normalized.split(separator: "/").last.map(String.init) ?? "repository"
154 let withoutGit = component.lowercased().hasSuffix(".git")
155 ? String(component.dropLast(4))
156 : component
157 let sanitized = withoutGit.trimmingCharacters(in: .whitespacesAndNewlines)
158 return sanitized.isEmpty ? "repository" : sanitized
159 }
160​
161 static func appending(_ component: String, to basePath: String) -> String {
162 let base = basePath.trimmingCharacters(in: .whitespacesAndNewlines)
163 guard !base.isEmpty else { return component }
164 guard !component.isEmpty else { return base }
165 let separator = base.contains("\\") && !base.contains("/") ? "\\" : "/"
166 if base.hasSuffix("/") || base.hasSuffix("\\") {
167 return base + component
168 }
169 return base + separator + component
170 }
171​
172 /// `filesystem.browse` interprets a path without a trailing separator as
173 /// a prefix search. Directory navigation always sends an explicit folder.
174 static func directoryBrowsePath(_ value: String) -> String {
175 let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
176 guard !path.isEmpty,
177 !path.hasSuffix("/"),
178 !path.hasSuffix("\\") else {
179 return path
180 }
181 if isWindowsAbsolutePath(path) {
182 return path.replacingOccurrences(of: "/", with: "\\") + "\\"
183 }
184 return path + "/"
185 }
186​
187 static func parentBrowsePath(of value: String) -> String? {
188 let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
189 guard !path.isEmpty else { return nil }
190​
191 if isWindowsAbsolutePath(path) {
192 let normalized = path.replacingOccurrences(of: "/", with: "\\")
193 if normalized.hasPrefix("\\\\") {
194 let components = normalized.dropFirst(2).split(separator: "\\")
195 guard components.count > 2 else { return nil }
196 return "\\\\"
197 + components.dropLast().joined(separator: "\\")
198 + "\\"
199 }
200​
201 var trimmed = normalized
202 while trimmed.count > 3, trimmed.hasSuffix("\\") {
203 trimmed.removeLast()
204 }
205 guard trimmed.count > 3,
206 let separator = trimmed.lastIndex(of: "\\") else {
207 return nil
208 }
209 let parent = String(trimmed[...separator])
210 return parent.count == 3 ? parent : directoryBrowsePath(parent)
211 }
212​
213 var trimmed = path
214 while trimmed.count > 1, trimmed.hasSuffix("/") {
215 trimmed.removeLast()
216 }
217 guard trimmed != "/", trimmed != "~",
218 let separator = trimmed.lastIndex(of: "/") else {
219 return nil
220 }
221 let parent = String(trimmed[...separator])
222 guard parent != "~/" || trimmed != "~" else { return nil }
223 return directoryBrowsePath(parent)
224 }
225​
226 static func lastPathComponent(_ value: String) -> String {
227 let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
228 let normalized = isWindowsAbsolutePath(path)
229 ? path.replacingOccurrences(of: "\\", with: "/")
230 : path
231 return normalized
232 .split(separator: "/", omittingEmptySubsequences: true)
233 .last
234 .map(String.init) ?? path
235 }
236​
237 static func isCompatibleWithServerPath(_ value: String, serverPath: String) -> Bool {
238 let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
239 let reference = serverPath.trimmingCharacters(in: .whitespacesAndNewlines)
240 guard !path.hasPrefix("~"),
241 isAbsoluteOrHomeRelative(reference) else {
242 return true
243 }
244 return isWindowsAbsolutePath(path) == isWindowsAbsolutePath(reference)
245 }
246​
247 static func normalizedForComparison(_ value: String) -> String {
248 let path = value.trimmingCharacters(in: .whitespacesAndNewlines)
249 let isWindows = isWindowsAbsolutePath(path)
250 var normalized = isWindows
251 ? path.replacingOccurrences(of: "\\", with: "/")
252 : path
253 while normalized.count > 1, normalized.hasSuffix("/") {
254 normalized.removeLast()
255 }
256 return isWindows ? normalized.lowercased() : normalized
257 }
258​
259 private static func isAbsoluteOrHomeRelative(_ path: String) -> Bool {
260 if path == "~" || path.hasPrefix("~/") || path.hasPrefix("~\\") {
261 return true
262 }
263 if path.hasPrefix("/") || path.hasPrefix("\\\\") {
264 return true
265 }
266 return isWindowsAbsolutePath(path)
267 }
268​
269 private static func isWindowsAbsolutePath(_ path: String) -> Bool {
270 if path.hasPrefix("\\\\") || path.hasPrefix("//") { return true }
271 let scalars = Array(path.unicodeScalars.prefix(3))
272 return scalars.count == 3
273 && CharacterSet.letters.contains(scalars[0])
274 && scalars[1] == ":"
275 && (scalars[2] == "\\" || scalars[2] == "/")
276 }
278​
279struct ProjectCreationValidationError: LocalizedError, Equatable {
280 let message: String
281​
282 var errorDescription: String? { message }