-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTuistTool.swift
More file actions
executable file
·716 lines (619 loc) · 24.4 KB
/
Copy pathTuistTool.swift
File metadata and controls
executable file
·716 lines (619 loc) · 24.4 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//
// TuistTool.swift
// Picke
//
// Created by Wonji Suh on 9/7/26.
//
import Foundation
private enum Command: String {
case setup
case generate
case build
case install
case cache
case cacheSetup = "cache:setup"
case test
case format
case lint
case clean
case reset
case edit
case inspect
case inspectImports = "inspect-imports"
case inspectCoverage = "inspect-coverage"
case module
case moduleInit = "moduleinit"
case feature
case core
case service
case domain
case ui
case graph
case productionGraph = "graph:prod"
case help
}
@discardableResult
private func run(
_ executable: String,
arguments: [String],
environmentOverrides: [String: String] = [:]
) -> Int32 {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = [executable] + arguments
process.environment = ProcessInfo.processInfo.environment.merging(environmentOverrides) { _, new in new }
process.standardInput = FileHandle.standardInput
process.standardOutput = FileHandle.standardOutput
process.standardError = FileHandle.standardError
do {
try process.run()
process.waitUntilExit()
return process.terminationStatus
} catch {
FileHandle.standardError.write(Data("실행 실패: \(error)\n".utf8))
return 1
}
}
private func prompt(_ message: String) -> String {
print("\(message): ", terminator: "")
return readLine()?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
}
@discardableResult
private func runTuist(
arguments: [String],
environmentOverrides: [String: String] = [:]
) -> Int32 {
return run(
"mise",
arguments: ["exec", "--", "tuist"] + arguments,
environmentOverrides: environmentOverrides
)
}
private var didPrepareLocalTuistAccess = false
private var isLocalTuistAccessUnavailable = false
private var isCIEnvironment: Bool {
let environment = ProcessInfo.processInfo.environment
let ciValues = ["1", "true", "TRUE"]
return ciValues.contains(environment["CI"] ?? "")
|| ciValues.contains(environment["GITHUB_ACTIONS"] ?? "")
|| ciValues.contains(environment["BITRISE_IO"] ?? "")
|| ciValues.contains(environment["TUIST_CI"] ?? "")
}
private func usesBinaryCache(forwardedArguments: [String]) -> Bool {
return !forwardedArguments.contains("--no-binary-cache")
}
private func warnAndContinue(_ message: String) {
FileHandle.standardError.write(Data("⚠️ \(message)\n".utf8))
}
private func prepareLocalTuistAccess(allowFailure: Bool) -> Int32 {
guard !isCIEnvironment else {
print("CI 환경이라 Tuist Dashboard 인증과 프로젝트 확인을 건너뜁니다.")
return 0
}
guard !didPrepareLocalTuistAccess else { return 0 }
let whoamiStatus = runTuist(arguments: ["auth", "whoami"])
if whoamiStatus != 0 {
let loginStatus = runTuist(arguments: ["auth", "login"])
guard loginStatus == 0 else {
if allowFailure {
isLocalTuistAccessUnavailable = true
warnAndContinue("Tuist 인증에 실패했습니다. 바이너리 캐시 없이 계속 진행합니다.")
return 0
}
return loginStatus
}
}
let projectStatus = runTuist(arguments: ["project", "show"])
guard projectStatus == 0 else {
if allowFailure {
isLocalTuistAccessUnavailable = true
warnAndContinue("Tuist Dashboard 프로젝트 확인에 실패했습니다. 바이너리 캐시 없이 계속 진행합니다.")
return 0
}
return projectStatus
}
didPrepareLocalTuistAccess = true
isLocalTuistAccessUnavailable = false
return 0
}
private func prepareBinaryCacheIfNeeded(
forwardedArguments: [String],
allowFailure: Bool
) -> Int32 {
guard usesBinaryCache(forwardedArguments: forwardedArguments) else {
print("--no-binary-cache 옵션이 있어 Tuist Dashboard 인증과 캐시 준비를 건너뜁니다.")
return 0
}
return prepareLocalTuistAccess(allowFailure: allowFailure)
}
private func cacheWarmArguments(forwardedArguments: [String]) -> [String] {
if forwardedArguments.first == "print-hashes" {
return ["cache"] + forwardedArguments
}
var warmArguments = forwardedArguments
if warmArguments.first == "warm" {
warmArguments.removeFirst()
}
var arguments = ["cache", "warm"]
if !warmArguments.contains("--external-only"), !warmArguments.contains("--no-external-only") {
arguments.append("--external-only")
}
return arguments + warmArguments
}
private func installArguments(forwardedArguments: [String]) -> [String] {
return forwardedArguments.filter { argument in
argument != "--no-binary-cache" && argument != "--no-open"
}
}
private func filteredGenerateArguments(forwardedArguments: [String]) -> [String] {
return forwardedArguments.filter { argument in
argument == "--no-binary-cache" || argument == "--no-open"
}
}
private func generateArguments(forwardedArguments: [String]) -> [String] {
guard isLocalTuistAccessUnavailable, usesBinaryCache(forwardedArguments: forwardedArguments)
else {
return forwardedArguments
}
return forwardedArguments + ["--no-binary-cache"]
}
private func warmBinaryCache(forwardedArguments: [String] = []) -> Int32 {
guard !isCIEnvironment else {
print("CI 환경이라 Tuist 바이너리 캐시 준비를 건너뜁니다.")
return 0
}
guard usesBinaryCache(forwardedArguments: forwardedArguments) else {
print("--no-binary-cache 옵션이 있어 Tuist 바이너리 캐시 준비를 건너뜁니다.")
return 0
}
let authStatus = prepareLocalTuistAccess(allowFailure: false)
guard authStatus == 0 else { return authStatus }
return runTuist(
arguments: cacheWarmArguments(forwardedArguments: forwardedArguments),
environmentOverrides: ["TUIST_LOCAL_CACHE_ONLY": "true"]
)
}
private func installAndGenerate(forwardedArguments: [String] = []) -> Int32 {
let authStatus = prepareBinaryCacheIfNeeded(
forwardedArguments: forwardedArguments,
allowFailure: true
)
guard authStatus == 0 else { return authStatus }
let installStatus = runTuist(arguments: ["install"] + installArguments(forwardedArguments: forwardedArguments))
guard installStatus == 0 else { return installStatus }
let generateForwardedArguments = filteredGenerateArguments(forwardedArguments: forwardedArguments)
return runTuist(arguments: ["generate"] + generateArguments(forwardedArguments: generateForwardedArguments))
}
private enum StepResult {
case passed
case skipped(String)
case failed(Int32)
}
private func printSetupSummary(_ results: [(String, StepResult)]) {
print("")
print("📋 setup 결과")
for (name, result) in results {
switch result {
case .passed:
print(" ✅ \(name)")
case let .skipped(reason):
print(" ⚠️ \(name) — 건너뜀 (\(reason))")
case let .failed(status):
print(" ❌ \(name) — 실패 (exit \(status))")
}
}
}
private func resetProject() -> Int32 {
let fileManager = FileManager.default
let derivedDataURL = fileManager.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Developer/Xcode/DerivedData", isDirectory: true)
do {
let entries = try fileManager.contentsOfDirectory(
at: derivedDataURL,
includingPropertiesForKeys: nil
)
for entry in entries where entry.lastPathComponent.hasPrefix("Picke-") {
try fileManager.removeItem(at: entry)
print("DerivedData 삭제: \(entry.lastPathComponent)")
}
} catch CocoaError.fileReadNoSuchFile {
// DerivedData가 아직 없다면 정리할 것도 없으므로 다음 단계로 진행합니다.
} catch {
FileHandle.standardError.write(Data("DerivedData 정리 실패: \(error)\n".utf8))
return 1
}
let cleanStatus = runTuist(arguments: ["clean"])
guard cleanStatus == 0 else { return cleanStatus }
return installAndGenerate()
}
/// 레이어마다 scaffold 대상 디렉터리, 카탈로그 enum, 의존성 헬퍼, 엄브렐러가 다르다.
/// 이 대응표를 한곳에 두어야 모듈 추가가 손으로 세 파일을 고치는 일이 되지 않는다.
private enum ModuleLayer: String, CaseIterable {
case feature = "Feature"
case core = "Core"
case service = "Service"
case domain = "Domain"
case ui = "UI"
/// Modules.swift 안의 카탈로그 enum 이름.
var catalogEnumName: String {
switch self {
case .feature: return "FeatureModule"
case .core: return "CoreModule"
case .service: return "ServiceModule"
case .domain: return "DomainModule"
case .ui: return "UIModule"
}
}
/// `.feature(.splash)` 에서 `feature` 에 해당하는 TargetDependency 헬퍼 이름.
var dependencyHelperName: String {
switch self {
case .feature: return "feature"
case .core: return "core"
case .service: return "service"
case .domain: return "domain"
case .ui: return "ui"
}
}
/// 새 모듈을 자동으로 물릴 엄브렐러. UI 레이어는 엄브렐러가 없다.
var umbrellaManifestPath: String? {
switch self {
case .feature: return "Projects/Feature/FeatureAssembly/Project.swift"
case .core: return "Projects/Core/CoreAssembly/Project.swift"
case .service: return "Projects/Service/ServiceAssembly/Project.swift"
case .domain: return "Projects/Domain/DomainAssembly/Project.swift"
case .ui: return nil
}
}
/// 카탈로그 case 는 레이어 이름을 되풀이하지 않는다 — `AuthDomain` 은 `auth` 로 적힌다.
var redundantNameSuffix: String? {
switch self {
case .domain: return "Domain"
case .service: return "Service"
case .feature, .core, .ui: return nil
}
}
init?(argument: String) {
let normalized = argument.lowercased()
guard let matched = ModuleLayer.allCases.first(where: { $0.rawValue.lowercased() == normalized })
else {
return nil
}
self = matched
}
}
private let moduleCatalogPath =
"Plugins/DependencyPlugin/ProjectDescriptionHelpers/TargetDependency+Module/Modules.swift"
/// Module 템플릿이 author 를 required 로 받지만 파일 헤더는 저장소 전체가 같은 이름으로 통일돼 있다.
/// 명령 인자로 열어두면 헤더만 어긋나므로 고정값으로 넘긴다.
private let scaffoldAuthor = "Wonji Suh"
/// `PickeNetwork` → `network`, `AuthDomain` → `auth`, `Splash` → `splash`.
/// 카탈로그에는 `apiEndpoint = "APIEndpoint"` 처럼 두문자어라 규칙으로 못 맞추는 case 도 있어서
/// 어긋나는 이름은 `--case` 로 직접 지정한다.
private func defaultCaseName(for moduleName: String, layer: ModuleLayer) -> String {
var name = moduleName
if name.hasPrefix("Picke"), name.count > 5 {
name.removeFirst(5)
}
if let suffix = layer.redundantNameSuffix, name.hasSuffix(suffix), name.count > suffix.count {
name.removeLast(suffix.count)
}
guard let first = name.first else { return name }
return first.lowercased() + name.dropFirst()
}
/// 내부 모듈 그래프를 만든다.
///
/// 기본 그래프는 Tests·Testing·Interface 까지 포함해 각 모듈의 진입점을 함께 보여주되
/// Demo 앱은 제외한다. 배포 구조만 확인하는 `graph:prod`에서는 Tests까지 함께 제외한다.
/// Tuist에는 Demo 타깃만 제외하는 옵션이 없어 dot에서 Demo 노드와 간선을 걷어낸다.
private func renderGraph(
excludesDemo: Bool,
extraTuistArguments: [String],
forwardedArguments: [String]
) -> Int32 {
let fileManager = FileManager.default
let workDirectory = fileManager.temporaryDirectory
.appendingPathComponent("picke-graph-\(UUID().uuidString)")
do {
try fileManager.createDirectory(at: workDirectory, withIntermediateDirectories: true)
} catch {
FileHandle.standardError.write(Data("작업 디렉터리를 만들지 못했습니다: \(error)\n".utf8))
return 1
}
defer { try? fileManager.removeItem(at: workDirectory) }
let dotStatus = runTuist(arguments: [
"graph",
"--no-open",
"--skip-external-dependencies",
"--format", "dot",
"--output-path", workDirectory.path,
] + extraTuistArguments + forwardedArguments)
guard dotStatus == 0 else { return dotStatus }
let dotURL = workDirectory.appendingPathComponent("graph.dot")
guard let rawGraph = try? String(contentsOf: dotURL, encoding: .utf8) else {
FileHandle.standardError.write(Data("dot 파일을 읽지 못했습니다: \(dotURL.path)\n".utf8))
return 1
}
let graph: String = if excludesDemo {
// 노드 선언(`AuthDemo [..]`)과 엣지(`AuthDemo -> Auth`) 양쪽에서
// 이름이 Demo 로 끝나는 줄을 지운다. dot 출력은 식별자에 따옴표를 붙이지 않는다.
rawGraph
.split(separator: "\n", omittingEmptySubsequences: false)
.filter { line in
line.range(of: #"\b[A-Za-z0-9_]+Demo\b"#, options: .regularExpression) == nil
}
.joined(separator: "\n")
} else {
rawGraph
}
let renderedGraphURL = workDirectory.appendingPathComponent("rendered-graph.dot")
do {
try graph.write(to: renderedGraphURL, atomically: true, encoding: .utf8)
} catch {
FileHandle.standardError.write(Data("렌더링할 dot 을 쓰지 못했습니다: \(error)\n".utf8))
return 1
}
let renderStatus = run("dot", arguments: ["-Tpng", renderedGraphURL.path, "-o", "graph.png"])
guard renderStatus == 0 else {
FileHandle.standardError.write(Data("graphviz 렌더링에 실패했습니다. `brew install graphviz` 가 필요합니다.\n".utf8))
return renderStatus
}
let skipsTests = extraTuistArguments.contains("--skip-test-targets")
print(skipsTests
? "graph.png 를 만들었습니다 (Tests·Demo 제외)"
: "graph.png 를 만들었습니다 (Demo 제외, Tests·Testing·Interface 포함)")
return 0
}
/// `anchor` 가 들어간 첫 줄 바로 아래에 `line` 을 끼워 넣는다.
/// `guardText` 가 이미 파일에 있으면 재실행해도 중복으로 쌓이지 않는다.
@discardableResult
private func insertLine(
_ line: String,
afterLineContaining anchor: String,
skipIfContains guardText: String,
inFileAt path: String
) -> Bool {
guard let contents = try? String(contentsOfFile: path, encoding: .utf8) else {
FileHandle.standardError.write(Data("파일을 읽지 못했습니다: \(path)\n".utf8))
return false
}
if contents.contains(guardText) {
print("이미 등록되어 있어 건너뜁니다: \(guardText)")
return true
}
var lines = contents.components(separatedBy: "\n")
guard let anchorIndex = lines.firstIndex(where: { $0.contains(anchor) }) else {
FileHandle.standardError.write(Data("기준 위치를 찾지 못했습니다: \(anchor) (\(path))\n".utf8))
return false
}
lines.insert(line, at: lines.index(after: anchorIndex))
do {
try lines.joined(separator: "\n").write(toFile: path, atomically: true, encoding: .utf8)
} catch {
FileHandle.standardError.write(Data("파일을 쓰지 못했습니다: \(path) - \(error)\n".utf8))
return false
}
print("등록: \(line.trimmingCharacters(in: .whitespaces)) → \(path)")
return true
}
private func scaffoldModule(layer presetLayer: ModuleLayer?, arguments: [String]) -> Int32 {
var positional: [String] = []
var caseNameOverride: String?
var index = arguments.startIndex
while index < arguments.endIndex {
if arguments[index] == "--case", arguments.index(after: index) < arguments.endIndex {
caseNameOverride = arguments[arguments.index(after: index)]
index = arguments.index(index, offsetBy: 2)
} else {
positional.append(arguments[index])
index = arguments.index(after: index)
}
}
let layer: ModuleLayer
if let presetLayer {
layer = presetLayer
} else {
let rawLayer = positional.first ?? prompt("레이어를 입력하세요 (Feature/Core/Service/Domain/UI)")
guard let parsed = ModuleLayer(argument: rawLayer) else {
FileHandle.standardError.write(Data("알 수 없는 레이어: \(rawLayer)\n".utf8))
return 64
}
layer = parsed
positional = Array(positional.dropFirst())
}
let name = positional.first ?? prompt("\(layer.rawValue) 모듈 이름을 입력하세요")
guard !name.isEmpty else {
FileHandle.standardError.write(Data("모듈 이름이 필요합니다.\n".utf8))
return 64
}
let caseName = caseNameOverride ?? defaultCaseName(for: name, layer: layer)
let scaffoldStatus = runTuist(arguments: [
"scaffold", "Module",
"--layer", layer.rawValue,
"--name", name,
"--author", scaffoldAuthor,
])
guard scaffoldStatus == 0 else { return scaffoldStatus }
// 카탈로그에 case 가 있어야 `.feature(.x)` 같은 의존성 표기가 컴파일된다.
guard insertLine(
" case \(caseName) = \"\(name)\"",
afterLineContaining: "public enum \(layer.catalogEnumName): String, CaseIterable {",
skipIfContains: "= \"\(name)\"",
inFileAt: moduleCatalogPath
) else {
return 1
}
if let umbrellaManifestPath = layer.umbrellaManifestPath {
guard insertLine(
" .\(layer.dependencyHelperName)(.\(caseName)),",
afterLineContaining: "dependencies: [",
skipIfContains: ".\(layer.dependencyHelperName)(.\(caseName))",
inFileAt: umbrellaManifestPath
) else {
return 1
}
} else {
print("\(layer.rawValue) 레이어는 엄브렐러가 없어 의존성 등록을 건너뜁니다.")
}
return runTuist(arguments: ["generate"])
}
private func printHelp() {
print(
"""
🚀 Picke Tuist 도구
기본 명령어:
./make setup # mise 설치 + Dashboard 확인 + install + 외부 캐시 준비 + generate
./make generate # Demo 앱을 포함해 프로젝트 생성
./make build # 클린 + 의존성 설치 + 프로젝트 생성
./make install # 의존성 설치 + 프로젝트 생성
./make cache # 외부 바이너리 캐시 준비
./make cache:setup # 외부 바이너리 캐시 준비(cache 별칭)
./make test # 전체 테스트 실행
./make format # SwiftFormat 적용
./make lint # SwiftFormat 검사
./make clean # 프로젝트 정리
./make reset # 앱 DerivedData 정리 + clean + install + generate
./make edit # 매니페스트를 Xcode 로 열기
점검:
./make inspect # 프로젝트 구조 분석
./make inspect-imports # 암시적 의존성 검사
./make inspect-coverage # 코드 커버리지 분석
모듈 생성 (scaffold + 카탈로그 case + 엄브렐러 의존성 자동 등록):
./make feature <이름> [--case <케이스명>]
./make core <이름> [--case <케이스명>]
./make service <이름> [--case <케이스명>]
./make domain <이름> [--case <케이스명>]
./make ui <이름> [--case <케이스명>]
./make module <레이어> <이름> # 레이어를 인자로 받는 형태
./make moduleinit # module 명령의 호환 별칭
케이스명은 모듈명에서 Picke 접두와 레이어 접미를 떼고 첫 글자를 소문자로 바꿔 만든다
(PickeNetwork → network, AuthDomain → auth). 규칙과 다르면 --case 로 직접 지정한다.
의존성 그래프:
./make graph # 외부 패키지·Demo를 제외하고 Tests·Testing·Interface를 포함한 모듈 그래프 생성
./make graph:prod # 외부 패키지·Demo·테스트 타깃을 제외한 그래프 생성
"""
)
}
private func execute(_ command: Command, forwardedArguments: [String]) -> Int32 {
switch command {
case .setup:
var results: [(String, StepResult)] = []
let miseStatus = run("mise", arguments: ["install"])
results.append(("mise 도구 설치", miseStatus == 0 ? .passed : .failed(miseStatus)))
guard miseStatus == 0 else {
printSetupSummary(results)
return miseStatus
}
if usesBinaryCache(forwardedArguments: forwardedArguments), !isCIEnvironment {
let authStatus = prepareLocalTuistAccess(allowFailure: false)
results.append(("Tuist Dashboard 인증/프로젝트 확인", authStatus == 0 ? .passed : .failed(authStatus)))
guard authStatus == 0 else {
printSetupSummary(results)
return authStatus
}
} else {
let reason = isCIEnvironment ? "CI 환경" : "--no-binary-cache"
results.append(("Tuist Dashboard 인증/프로젝트 확인", .skipped(reason)))
}
let installStatus = runTuist(arguments: ["install"] + installArguments(forwardedArguments: forwardedArguments))
results.append(("의존성 설치", installStatus == 0 ? .passed : .failed(installStatus)))
guard installStatus == 0 else {
printSetupSummary(results)
return installStatus
}
if usesBinaryCache(forwardedArguments: forwardedArguments), !isCIEnvironment {
let cacheStatus = warmBinaryCache()
results.append(("외부 바이너리 캐시 준비", cacheStatus == 0 ? .passed : .failed(cacheStatus)))
guard cacheStatus == 0 else {
printSetupSummary(results)
return cacheStatus
}
} else {
let reason = isCIEnvironment ? "CI 환경" : "--no-binary-cache"
results.append(("외부 바이너리 캐시 준비", .skipped(reason)))
}
let generateForwardedArguments = filteredGenerateArguments(forwardedArguments: forwardedArguments)
let generateStatus = runTuist(
arguments: ["generate"] + generateArguments(forwardedArguments: generateForwardedArguments)
)
results.append(("프로젝트 생성", generateStatus == 0 ? .passed : .failed(generateStatus)))
printSetupSummary(results)
return generateStatus
case .generate:
let authStatus = prepareBinaryCacheIfNeeded(
forwardedArguments: forwardedArguments,
allowFailure: true
)
guard authStatus == 0 else { return authStatus }
return runTuist(arguments: ["generate"] + generateArguments(forwardedArguments: forwardedArguments))
case .build:
let cleanStatus = runTuist(arguments: ["clean"])
guard cleanStatus == 0 else { return cleanStatus }
return installAndGenerate(forwardedArguments: forwardedArguments)
case .install:
return installAndGenerate(forwardedArguments: forwardedArguments)
case .cache:
return warmBinaryCache(forwardedArguments: forwardedArguments)
case .cacheSetup:
return warmBinaryCache(forwardedArguments: forwardedArguments)
case .test:
let authStatus = prepareBinaryCacheIfNeeded(
forwardedArguments: forwardedArguments,
allowFailure: true
)
guard authStatus == 0 else { return authStatus }
return runTuist(arguments: ["test"] + generateArguments(forwardedArguments: forwardedArguments))
case .format:
return run("mise", arguments: ["exec", "--", "swiftformat", "."] + forwardedArguments)
case .lint:
return run("mise", arguments: ["exec", "--", "swiftformat", "--lint", "."] + forwardedArguments)
case .clean:
return runTuist(arguments: ["clean"] + forwardedArguments)
case .reset:
return resetProject()
case .edit:
return runTuist(arguments: ["edit"] + forwardedArguments)
case .inspect:
return runTuist(arguments: ["inspect"] + forwardedArguments)
case .inspectImports:
return runTuist(arguments: ["inspect", "implicit-imports"] + forwardedArguments)
case .inspectCoverage:
return runTuist(arguments: ["inspect", "code-coverage"] + forwardedArguments)
case .module, .moduleInit:
return scaffoldModule(layer: nil, arguments: forwardedArguments)
case .feature:
return scaffoldModule(layer: .feature, arguments: forwardedArguments)
case .core:
return scaffoldModule(layer: .core, arguments: forwardedArguments)
case .service:
return scaffoldModule(layer: .service, arguments: forwardedArguments)
case .domain:
return scaffoldModule(layer: .domain, arguments: forwardedArguments)
case .ui:
return scaffoldModule(layer: .ui, arguments: forwardedArguments)
case .graph:
return renderGraph(
excludesDemo: true,
extraTuistArguments: [],
forwardedArguments: forwardedArguments
)
case .productionGraph:
return renderGraph(
excludesDemo: true,
extraTuistArguments: ["--skip-test-targets"],
forwardedArguments: forwardedArguments
)
case .help:
printHelp()
return 0
}
}
let arguments = Array(CommandLine.arguments.dropFirst())
let rawCommand = arguments.first ?? Command.help.rawValue
let normalizedCommand = ["-h", "--help"].contains(rawCommand) ? Command.help.rawValue : rawCommand
let forwardedArguments = Array(arguments.dropFirst())
guard let command = Command(rawValue: normalizedCommand) else {
FileHandle.standardError.write(Data("알 수 없는 명령어: \(rawCommand)\n\n".utf8))
printHelp()
exit(64)
}
exit(execute(command, forwardedArguments: forwardedArguments))