-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharcdevtools-setup
More file actions
executable file
·1011 lines (825 loc) · 34.3 KB
/
Copy patharcdevtools-setup
File metadata and controls
executable file
·1011 lines (825 loc) · 34.3 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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env swift
//
// ARCDevTools Setup Script
// Version: 1.0.0
//
// Installs ARCDevTools configuration files, git hooks, and generates Makefile
// for ARC Labs Studio projects.
//
import Foundation
// MARK: - Constants
let version = "1.2.0"
// MARK: - Project Type Detection
enum ProjectType {
case swiftPackage
case iOSApp
var displayName: String {
switch self {
case .swiftPackage: return "Swift Package"
case .iOSApp: return "iOS App"
}
}
}
// MARK: - Command Line Arguments
struct Options {
var withWorkflows: Bool = false
var noWorkflows: Bool = false
var showHelp: Bool = false
var force: Bool = false
var isInteractive: Bool {
!withWorkflows && !noWorkflows
}
}
func parseArguments() -> Options {
var options = Options()
let args = CommandLine.arguments.dropFirst()
for arg in args {
switch arg {
case "--with-workflows":
options.withWorkflows = true
case "--no-workflows":
options.noWorkflows = true
case "--force", "-f":
options.force = true
case "--help", "-h":
options.showHelp = true
default:
break
}
}
return options
}
func printHelp() {
print("")
printInfo("🔧 ARCDevTools Setup v\(version)")
print("")
print("Usage: arcdevtools-setup [options]")
print("")
print("Options:")
print(" --with-workflows Install GitHub Actions workflows (non-interactive)")
print(" --no-workflows Skip GitHub Actions workflows (non-interactive)")
print(" --force, -f Overwrite project-owned configs (.swiftlint.yml, .swiftformat)")
print(" Studio-owned configs (.swiftlint.base.yml) always refresh.")
print(" --help, -h Show this help message")
print("")
print("Examples:")
print(" ./ARCDevTools/arcdevtools-setup # Interactive mode")
print(" ./ARCDevTools/arcdevtools-setup --with-workflows # CI mode with workflows")
print(" ./ARCDevTools/arcdevtools-setup --no-workflows # CI mode without workflows")
print(" ./ARCDevTools/arcdevtools-setup --force # Reset .swiftlint.yml + .swiftformat")
print("")
print("Config contract:")
print(" .swiftlint.base.yml — studio rules, refreshed every run (do not edit)")
print(" .swiftlint.yml — project-owned (paths + local tweaks), kept on re-run")
print(" .swiftformat — project-owned, kept on re-run")
print("")
}
// MARK: - ANSI Colors
enum Color {
static let red = "\u{001B}[0;31m"
static let green = "\u{001B}[0;32m"
static let yellow = "\u{001B}[1;33m"
static let blue = "\u{001B}[0;34m"
static let cyan = "\u{001B}[0;36m"
static let reset = "\u{001B}[0m"
}
// MARK: - Utility Functions
func print(_ message: String, color: String) {
print("\(color)\(message)\(Color.reset)")
}
func printInfo(_ message: String) {
print(message, color: Color.cyan)
}
func printSuccess(_ message: String) {
print("✓ \(message)", color: Color.green)
}
func printError(_ message: String) {
print("✗ \(message)", color: Color.red)
}
func printWarning(_ message: String) {
print("⚠ \(message)", color: Color.yellow)
}
// MARK: - Path Resolution
let fileManager = FileManager.default
let scriptURL = URL(fileURLWithPath: CommandLine.arguments[0])
let scriptDir = scriptURL.deletingLastPathComponent()
let projectRoot = URL(fileURLWithPath: fileManager.currentDirectoryPath)
// MARK: - Setup Functions
func printBanner() {
print("")
printInfo("🔧 ARCDevTools Setup v\(version)")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print("")
}
func detectProjectType() throws -> ProjectType {
printInfo("📂 Detecting project type...")
let hasPackageSwift = fileManager.fileExists(
atPath: projectRoot.appendingPathComponent("Package.swift").path
)
let contents = (try? fileManager.contentsOfDirectory(atPath: projectRoot.path)) ?? []
let hasXcodeProject = contents.contains { $0.hasSuffix(".xcodeproj") }
// Also check subdirectories for xcodeproj (common pattern: AppName/AppName.xcodeproj)
let hasNestedXcodeProject = contents.contains { item in
let itemPath = projectRoot.appendingPathComponent(item)
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir), isDir.boolValue else {
return false
}
let subContents = (try? fileManager.contentsOfDirectory(atPath: itemPath.path)) ?? []
return subContents.contains { $0.hasSuffix(".xcodeproj") }
}
let hasAnyXcodeProject = hasXcodeProject || hasNestedXcodeProject
guard hasPackageSwift || hasAnyXcodeProject else {
printError("No Package.swift or .xcodeproj detected")
printError("Run this script from your project root directory")
throw SetupError.invalidProjectRoot
}
// Swift Package takes priority (can have both Package.swift and xcodeproj)
if hasPackageSwift {
printSuccess("Swift Package detected")
return .swiftPackage
} else {
printSuccess("iOS App detected (Xcode project)")
return .iOSApp
}
}
func findXcodeProjectPath() -> String? {
// Check root directory
let contents = (try? fileManager.contentsOfDirectory(atPath: projectRoot.path)) ?? []
if let proj = contents.first(where: { $0.hasSuffix(".xcodeproj") }) {
return proj
}
// Check subdirectories
for item in contents {
let itemPath = projectRoot.appendingPathComponent(item)
var isDir: ObjCBool = false
guard fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir), isDir.boolValue else {
continue
}
let subContents = (try? fileManager.contentsOfDirectory(atPath: itemPath.path)) ?? []
if let proj = subContents.first(where: { $0.hasSuffix(".xcodeproj") }) {
return "\(item)/\(proj)"
}
}
return nil
}
func detectXcodeScheme() -> String? {
guard let projPath = findXcodeProjectPath() else { return nil }
let fullPath = projectRoot.appendingPathComponent(projPath).path
let task = Process()
let pipe = Pipe()
task.executableURL = URL(fileURLWithPath: "/usr/bin/xcodebuild")
task.arguments = ["-list", "-project", fullPath]
task.standardOutput = pipe
task.standardError = FileHandle.nullDevice
do {
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let output = String(data: data, encoding: .utf8) else { return nil }
// Parse schemes from xcodebuild output
let lines = output.components(separatedBy: "\n")
var inSchemes = false
for line in lines {
if line.contains("Schemes:") {
inSchemes = true
continue
}
if inSchemes {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty { break }
return trimmed // Return first scheme
}
}
} catch {
// Silently fail, will return nil
}
return nil
}
func setupSwiftVersion() throws {
print("")
printInfo("📋 Creating .swift-version...")
let swiftVersionDest = projectRoot.appendingPathComponent(".swift-version")
// Default to Swift 6.0
let swiftVersion = "6.0\n"
try swiftVersion.write(to: swiftVersionDest, atomically: true, encoding: .utf8)
printSuccess(" .swift-version (6.0)")
}
func setupConfigs(force: Bool) throws {
print("")
printInfo("📦 Copying configurations...")
// SwiftLint base — studio-owned, ALWAYS refreshed.
let swiftlintBaseSource = scriptDir.appendingPathComponent("configs/swiftlint.base.yml")
if fileManager.fileExists(atPath: swiftlintBaseSource.path) {
let dest = projectRoot.appendingPathComponent(".swiftlint.base.yml")
try? fileManager.removeItem(at: dest)
try fileManager.copyItem(at: swiftlintBaseSource, to: dest)
printSuccess(" .swiftlint.base.yml (refreshed — studio rules)")
} else {
printWarning(" configs/swiftlint.base.yml not found in ARCDevTools")
}
// SwiftLint project file — project-owned, skip-if-exists.
let swiftlintStarterSource = scriptDir.appendingPathComponent("configs/swiftlint.starter.yml")
if fileManager.fileExists(atPath: swiftlintStarterSource.path) {
let dest = projectRoot.appendingPathComponent(".swiftlint.yml")
if fileManager.fileExists(atPath: dest.path) && !force {
printInfo(" .swiftlint.yml exists — kept (re-run with --force to overwrite)")
} else {
try? fileManager.removeItem(at: dest)
try fileManager.copyItem(at: swiftlintStarterSource, to: dest)
printSuccess(" .swiftlint.yml (starter — adjust `included:` for your layout)")
}
} else {
printWarning(" configs/swiftlint.starter.yml not found in ARCDevTools")
}
// SwiftFormat — project-owned, skip-if-exists.
let swiftformatSource = scriptDir.appendingPathComponent("configs/swiftformat")
if fileManager.fileExists(atPath: swiftformatSource.path) {
let dest = projectRoot.appendingPathComponent(".swiftformat")
if fileManager.fileExists(atPath: dest.path) && !force {
printInfo(" .swiftformat exists — kept (re-run with --force to overwrite)")
} else {
try? fileManager.removeItem(at: dest)
try fileManager.copyItem(at: swiftformatSource, to: dest)
printSuccess(" .swiftformat")
}
} else {
printWarning(" swiftformat not found in ARCDevTools")
}
}
func setupGitHooks() throws {
print("")
printInfo("🪝 Installing git hooks...")
let gitDir = projectRoot.appendingPathComponent(".git")
guard fileManager.fileExists(atPath: gitDir.path) else {
printWarning(" .git not found (is this a git repository?)")
return
}
let gitHooksDir = projectRoot.appendingPathComponent(".git/hooks")
// Create hooks directory if it doesn't exist
if !fileManager.fileExists(atPath: gitHooksDir.path) {
try fileManager.createDirectory(at: gitHooksDir, withIntermediateDirectories: true)
printSuccess(" Created .git/hooks directory")
}
// Pre-commit hook
let preCommitSource = scriptDir.appendingPathComponent("hooks/pre-commit")
if fileManager.fileExists(atPath: preCommitSource.path) {
let preCommitDest = gitHooksDir.appendingPathComponent("pre-commit")
try? fileManager.removeItem(at: preCommitDest)
try fileManager.copyItem(at: preCommitSource, to: preCommitDest)
try makeExecutable(preCommitDest)
printSuccess(" pre-commit hook installed")
}
// Pre-push hook
let prePushSource = scriptDir.appendingPathComponent("hooks/pre-push")
if fileManager.fileExists(atPath: prePushSource.path) {
let prePushDest = gitHooksDir.appendingPathComponent("pre-push")
try? fileManager.removeItem(at: prePushDest)
try fileManager.copyItem(at: prePushSource, to: prePushDest)
try makeExecutable(prePushDest)
printSuccess(" pre-push hook installed")
}
// Configure git pull behavior (avoid unwanted merge commits)
let gitPullTask = Process()
gitPullTask.executableURL = URL(fileURLWithPath: "/usr/bin/git")
gitPullTask.arguments = ["config", "--local", "pull.rebase", "true"]
gitPullTask.currentDirectoryURL = projectRoot
gitPullTask.standardOutput = FileHandle.nullDevice
gitPullTask.standardError = FileHandle.nullDevice
try? gitPullTask.run()
gitPullTask.waitUntilExit()
printSuccess(" pull.rebase=true configured")
// Remove merge.ff=false if present (causes unwanted merge commits on pull)
let unsetFfTask = Process()
unsetFfTask.executableURL = URL(fileURLWithPath: "/usr/bin/git")
unsetFfTask.arguments = ["config", "--local", "--unset", "merge.ff"]
unsetFfTask.currentDirectoryURL = projectRoot
unsetFfTask.standardOutput = FileHandle.nullDevice
unsetFfTask.standardError = FileHandle.nullDevice
try? unsetFfTask.run()
unsetFfTask.waitUntilExit()
}
func makeExecutable(_ url: URL) throws {
let attributes = [FileAttributeKey.posixPermissions: 0o755]
try fileManager.setAttributes(attributes, ofItemAtPath: url.path)
}
func generateMakefile(for projectType: ProjectType) throws {
print("")
printInfo("📄 Generating Makefile...")
let makefileContent: String
switch projectType {
case .swiftPackage:
makefileContent = """
# ARCDevTools Makefile (Swift Package)
# Auto-generated - Do not edit manually
#
# build/test targets shell out to `swift` for CI and headless use.
# For interactive build, test, and diagnostics, prefer the Xcode MCP
# (see the `arc-mcp-xcode` skill) over running these targets by hand.
.PHONY: help lint format fix build test setup hooks clean
help:
\t@echo "ARCDevTools - Available commands:"
\t@echo " make lint - Run SwiftLint"
\t@echo " make format - Run SwiftFormat (dry-run)"
\t@echo " make fix - Apply SwiftFormat"
\t@echo " make build - Build the package"
\t@echo " make test - Run tests"
\t@echo " make setup - Re-install hooks and configs"
\t@echo " make hooks - Re-install git hooks only"
\t@echo " make clean - Clean build artifacts"
lint:
\t@if command -v swiftlint >/dev/null 2>&1; then \\
\t\tswiftlint lint --config .swiftlint.yml; \\
\telse \\
\t\techo "⚠️ SwiftLint not installed: brew install swiftlint"; \\
\tfi
format:
\t@if command -v swiftformat >/dev/null 2>&1; then \\
\t\tswiftformat --config .swiftformat --lint .; \\
\telse \\
\t\techo "⚠️ SwiftFormat not installed: brew install swiftformat"; \\
\tfi
fix:
\t@if command -v swiftformat >/dev/null 2>&1; then \\
\t\tswiftformat --config .swiftformat .; \\
\telse \\
\t\techo "⚠️ SwiftFormat not installed: brew install swiftformat"; \\
\tfi
build:
\t@swift build
test:
\t@swift test --parallel
setup:
\t@./ARCDevTools/arcdevtools-setup
hooks:
\t@./ARCDevTools/hooks/install-hooks.sh
clean:
\t@rm -rf .build DerivedData
\t@echo "✓ Build artifacts removed"
"""
case .iOSApp:
// Detect scheme for iOS apps
let scheme = detectXcodeScheme() ?? "$(SCHEME)"
let schemeNote = detectXcodeScheme() == nil
? "# NOTE: Set SCHEME variable or run: make build SCHEME=YourScheme\nSCHEME ?= \n"
: "SCHEME = \(scheme)\n"
makefileContent = """
# ARCDevTools Makefile (iOS App)
# Auto-generated - Do not edit manually
#
# build/test targets shell out to `xcodebuild` for CI and headless use.
# For interactive build, test, and diagnostics, prefer the Xcode MCP
# (see the `arc-mcp-xcode` skill) over running these targets by hand.
\(schemeNote)
DESTINATION ?= platform=iOS Simulator,name=iPhone 16,OS=latest
.PHONY: help lint format fix build test setup hooks clean
help:
\t@echo "ARCDevTools - Available commands:"
\t@echo " make lint - Run SwiftLint"
\t@echo " make format - Run SwiftFormat (dry-run)"
\t@echo " make fix - Apply SwiftFormat"
\t@echo " make build - Build the iOS app"
\t@echo " make test - Run tests on iOS Simulator"
\t@echo " make setup - Re-install hooks and configs"
\t@echo " make hooks - Re-install git hooks only"
\t@echo " make clean - Clean build artifacts"
lint:
\t@if command -v swiftlint >/dev/null 2>&1; then \\
\t\tswiftlint lint --config .swiftlint.yml; \\
\telse \\
\t\techo "⚠️ SwiftLint not installed: brew install swiftlint"; \\
\tfi
format:
\t@if command -v swiftformat >/dev/null 2>&1; then \\
\t\tswiftformat --config .swiftformat --lint .; \\
\telse \\
\t\techo "⚠️ SwiftFormat not installed: brew install swiftformat"; \\
\tfi
fix:
\t@if command -v swiftformat >/dev/null 2>&1; then \\
\t\tswiftformat --config .swiftformat .; \\
\telse \\
\t\techo "⚠️ SwiftFormat not installed: brew install swiftformat"; \\
\tfi
build:
\t@if [ -z "$(SCHEME)" ]; then \\
\t\techo "⚠️ SCHEME not set. Run: make build SCHEME=YourScheme"; \\
\t\texit 1; \\
\tfi
\t@xcodebuild build \\
\t\t-scheme "$(SCHEME)" \\
\t\t-destination "$(DESTINATION)" \\
\t\t-configuration Debug \\
\t\tCODE_SIGN_IDENTITY="" \\
\t\tCODE_SIGNING_REQUIRED=NO \\
\t\tCODE_SIGNING_ALLOWED=NO
test:
\t@if [ -z "$(SCHEME)" ]; then \\
\t\techo "⚠️ SCHEME not set. Run: make test SCHEME=YourScheme"; \\
\t\texit 1; \\
\tfi
\t@xcodebuild test \\
\t\t-scheme "$(SCHEME)" \\
\t\t-destination "$(DESTINATION)" \\
\t\t-configuration Debug \\
\t\tCODE_SIGN_IDENTITY="" \\
\t\tCODE_SIGNING_REQUIRED=NO \\
\t\tCODE_SIGNING_ALLOWED=NO
setup:
\t@./ARCDevTools/arcdevtools-setup
hooks:
\t@./ARCDevTools/hooks/install-hooks.sh
clean:
\t@rm -rf DerivedData
\t@xcodebuild clean -scheme "$(SCHEME)" 2>/dev/null || true
\t@echo "✓ Build artifacts removed"
"""
}
let makefileDest = projectRoot.appendingPathComponent("Makefile")
try makefileContent.write(to: makefileDest, atomically: true, encoding: .utf8)
printSuccess(" Makefile generated (\(projectType.displayName))")
}
func setupWorkflows(for projectType: ProjectType) throws {
print("")
printInfo("⚙️ Copying GitHub Actions workflows (\(projectType.displayName))...")
// Determine which workflow directory to use
let workflowsDirName: String
switch projectType {
case .swiftPackage:
workflowsDirName = "workflows-spm"
case .iOSApp:
workflowsDirName = "workflows-ios"
}
let workflowsSource = scriptDir.appendingPathComponent(workflowsDirName)
let sharedWorkflowsSource = scriptDir.appendingPathComponent("workflows-spm")
guard fileManager.fileExists(atPath: workflowsSource.path) else {
printWarning(" \(workflowsDirName)/ not found in ARCDevTools")
return
}
let githubWorkflowsDir = projectRoot.appendingPathComponent(".github/workflows")
try? fileManager.createDirectory(at: githubWorkflowsDir, withIntermediateDirectories: true)
// Workflows specific to project type (quality.yml, tests.yml)
let projectSpecificWorkflows = ["quality.yml", "tests.yml"]
// Copy project-specific workflows from the appropriate directory
let workflowFiles = try fileManager.contentsOfDirectory(atPath: workflowsSource.path)
for filename in workflowFiles where filename.hasSuffix(".yml") {
let sourceFile = workflowsSource.appendingPathComponent(filename)
let destFile = githubWorkflowsDir.appendingPathComponent(filename)
let originalContent = try String(contentsOf: sourceFile, encoding: .utf8)
let templateComment = """
# ARCDevTools Workflow Template (\(projectType.displayName))
# Source: https://github.com/arclabs-studio/ARCDevTools/\(workflowsDirName)/\(filename)
#
# This file was copied from ARCDevTools. You can customize it for your project.
# To update: re-run ./ARCDevTools/arcdevtools-setup or manually copy from ARCDevTools/\(workflowsDirName)/
"""
let newContent = templateComment + originalContent
try? fileManager.removeItem(at: destFile)
try newContent.write(to: destFile, atomically: true, encoding: .utf8)
printSuccess(" \(filename)")
}
// Copy shared workflows from workflows-spm/ directory (those not project-specific)
if fileManager.fileExists(atPath: sharedWorkflowsSource.path) {
let sharedFiles = try fileManager.contentsOfDirectory(atPath: sharedWorkflowsSource.path)
for filename in sharedFiles where filename.hasSuffix(".yml") && !projectSpecificWorkflows.contains(filename) {
let sourceFile = sharedWorkflowsSource.appendingPathComponent(filename)
let destFile = githubWorkflowsDir.appendingPathComponent(filename)
// Skip if already exists (don't overwrite project-specific)
if fileManager.fileExists(atPath: destFile.path) {
continue
}
let originalContent = try String(contentsOf: sourceFile, encoding: .utf8)
let templateComment = """
# ARCDevTools Workflow Template
# Source: https://github.com/arclabs-studio/ARCDevTools/workflows-spm/\(filename)
#
# This file was copied from ARCDevTools. You can customize it for your project.
# To update: re-run ./ARCDevTools/arcdevtools-setup or manually copy from ARCDevTools/workflows-spm/
"""
let newContent = templateComment + originalContent
try? fileManager.removeItem(at: destFile)
try newContent.write(to: destFile, atomically: true, encoding: .utf8)
printSuccess(" \(filename)")
}
}
// Copy templates
let templatesDir = scriptDir.appendingPathComponent("templates")
let githubDir = projectRoot.appendingPathComponent(".github")
if fileManager.fileExists(atPath: templatesDir.path) {
let templates = [
"PULL_REQUEST_TEMPLATE.md",
"markdown-link-check-config.json",
"release-drafter.yml"
]
for template in templates {
let source = templatesDir.appendingPathComponent(template)
let dest = githubDir.appendingPathComponent(template)
if fileManager.fileExists(atPath: source.path) {
try? fileManager.removeItem(at: dest)
try? fileManager.copyItem(at: source, to: dest)
}
}
}
}
func setupClaudeSkills() throws -> [String] {
print("")
printInfo("🤖 Installing Claude Code skills...")
let skillsDir = projectRoot.appendingPathComponent(".claude/skills")
// Create .claude/skills directory if it doesn't exist
try? fileManager.createDirectory(at: skillsDir, withIntermediateDirectories: true)
var installedSkills: [String] = []
var symlinkedSkills: [String] = []
// 1. Copy ARCDevTools-specific skills (like arc-package-validator)
let arcDevToolsSkillsSource = scriptDir.appendingPathComponent(".claude/skills")
if fileManager.fileExists(atPath: arcDevToolsSkillsSource.path) {
let skills = try fileManager.contentsOfDirectory(atPath: arcDevToolsSkillsSource.path)
for skillName in skills {
let sourceSkill = arcDevToolsSkillsSource.appendingPathComponent(skillName)
let destSkill = skillsDir.appendingPathComponent(skillName)
// Check if it's a directory (a skill)
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: sourceSkill.path, isDirectory: &isDirectory),
isDirectory.boolValue else {
continue
}
// Remove existing skill if present
try? fileManager.removeItem(at: destSkill)
// Copy skill directory recursively
try fileManager.copyItem(at: sourceSkill, to: destSkill)
// Make scripts executable
let scriptsDir = destSkill.appendingPathComponent("scripts")
if fileManager.fileExists(atPath: scriptsDir.path) {
let scripts = try? fileManager.contentsOfDirectory(atPath: scriptsDir.path)
for script in scripts ?? [] {
let scriptPath = scriptsDir.appendingPathComponent(script)
try? makeExecutable(scriptPath)
}
}
installedSkills.append(skillName)
printSuccess(" \(skillName) (copied)")
}
}
// 2. Create symlinks for ARCKnowledge skills
let arcKnowledgeSkillsSource = scriptDir.appendingPathComponent("ARCKnowledge/.claude/skills")
if fileManager.fileExists(atPath: arcKnowledgeSkillsSource.path) {
let skills = try fileManager.contentsOfDirectory(atPath: arcKnowledgeSkillsSource.path)
for skillName in skills {
let sourceSkill = arcKnowledgeSkillsSource.appendingPathComponent(skillName)
let destSkill = skillsDir.appendingPathComponent(skillName)
// Check if it's a directory (a skill)
var isDirectory: ObjCBool = false
guard fileManager.fileExists(atPath: sourceSkill.path, isDirectory: &isDirectory),
isDirectory.boolValue else {
continue
}
// Skip if already exists (don't overwrite ARCDevTools skills)
if fileManager.fileExists(atPath: destSkill.path) {
continue
}
// Calculate relative path for symlink
// From: .claude/skills/arc-workflow
// To: ARCDevTools/ARCKnowledge/.claude/skills/arc-workflow
let relativePath = calculateRelativePath(from: skillsDir, to: sourceSkill)
// Create symlink
try? fileManager.removeItem(at: destSkill)
try fileManager.createSymbolicLink(atPath: destSkill.path, withDestinationPath: relativePath)
installedSkills.append(skillName)
symlinkedSkills.append(skillName)
printSuccess(" \(skillName) (linked)")
}
}
// 3. Update .gitignore with symlinked skills
if !symlinkedSkills.isEmpty {
try updateGitignoreWithSkills(symlinkedSkills)
}
if installedSkills.isEmpty {
printWarning(" No skills found to install")
}
return installedSkills
}
func updateGitignoreWithSkills(_ skills: [String]) throws {
let gitignorePath = projectRoot.appendingPathComponent(".gitignore")
var gitignoreContent = ""
if fileManager.fileExists(atPath: gitignorePath.path) {
gitignoreContent = try String(contentsOf: gitignorePath, encoding: .utf8)
}
// Check if skills section already exists
let skillsHeader = "# ARCKnowledge skills (symlinks)"
if gitignoreContent.contains(skillsHeader) {
// Already configured, skip
return
}
// Build skills section
var skillsSection = "\n\n\(skillsHeader)\n"
for skill in skills.sorted() {
skillsSection += ".claude/skills/\(skill)\n"
}
// Append to .gitignore
gitignoreContent += skillsSection
try gitignoreContent.write(to: gitignorePath, atomically: true, encoding: .utf8)
printSuccess(" .gitignore updated with symlinked skills")
}
func calculateRelativePath(from source: URL, to target: URL) -> String {
// Get the ARCDevTools directory name relative to project root
let arcDevToolsName = scriptDir.lastPathComponent
// The relative path from .claude/skills/ to ARCDevTools/ARCKnowledge/.claude/skills/skillName
// is: ../../ARCDevTools/ARCKnowledge/.claude/skills/skillName
let skillName = target.lastPathComponent
return "../../\(arcDevToolsName)/ARCKnowledge/.claude/skills/\(skillName)"
}
func setupClaudeAgents() throws -> [String] {
print("")
printInfo("🤖 Installing Claude Code agents...")
let agentsDir = projectRoot.appendingPathComponent(".claude/agents")
try? fileManager.createDirectory(at: agentsDir, withIntermediateDirectories: true)
var installedAgents: [String] = []
var symlinkedAgents: [String] = []
let arcDevToolsName = scriptDir.lastPathComponent
let arcKnowledgeAgentsSource = scriptDir.appendingPathComponent("ARCKnowledge/.claude/agents")
guard fileManager.fileExists(atPath: arcKnowledgeAgentsSource.path) else {
printWarning(" ARCKnowledge/.claude/agents/ not found — skipping agents")
return []
}
let agentFiles = try fileManager.contentsOfDirectory(atPath: arcKnowledgeAgentsSource.path)
for filename in agentFiles where filename.hasSuffix(".md") && filename.hasPrefix("arc-") {
let destFile = agentsDir.appendingPathComponent(filename)
// Skip if already exists (project-local agent takes priority)
if fileManager.fileExists(atPath: destFile.path) {
printWarning(" \(filename) already exists — skipping")
continue
}
let relativePath = "../../\(arcDevToolsName)/ARCKnowledge/.claude/agents/\(filename)"
try? fileManager.removeItem(at: destFile)
try fileManager.createSymbolicLink(atPath: destFile.path, withDestinationPath: relativePath)
installedAgents.append(filename)
symlinkedAgents.append(filename)
printSuccess(" \(filename) (linked)")
}
if !symlinkedAgents.isEmpty {
try updateGitignoreWithAgents(symlinkedAgents)
}
if installedAgents.isEmpty {
printWarning(" No agents found to install")
}
return installedAgents
}
func updateGitignoreWithAgents(_ agents: [String]) throws {
let gitignorePath = projectRoot.appendingPathComponent(".gitignore")
var gitignoreContent = ""
if fileManager.fileExists(atPath: gitignorePath.path) {
gitignoreContent = try String(contentsOf: gitignorePath, encoding: .utf8)
}
let agentsHeader = "# ARCKnowledge agents (symlinks)"
if gitignoreContent.contains(agentsHeader) {
return
}
var agentsSection = "\n\n\(agentsHeader)\n"
for agent in agents.sorted() {
agentsSection += ".claude/agents/\(agent)\n"
}
gitignoreContent += agentsSection
try gitignoreContent.write(to: gitignorePath, atomically: true, encoding: .utf8)
printSuccess(" .gitignore updated with symlinked agents")
}
func askUserForWorkflows() -> Bool {
print("")
print("Do you want to copy GitHub Actions workflows? [y/N]: ", terminator: "")
guard let response = readLine()?.lowercased() else {
return false
}
return response == "y" || response == "yes"
}
func askUserForCIScripts() -> Bool {
print("")
print("Do you want to install Xcode Cloud ci_scripts/? [y/N]: ", terminator: "")
guard let response = readLine()?.lowercased() else {
return false
}
return response == "y" || response == "yes"
}
func setupCIScripts() throws {
print("")
printInfo("☁️ Installing Xcode Cloud ci_scripts/...")
let sourceDir = scriptDir.appendingPathComponent("templates/ci_scripts")
guard fileManager.fileExists(atPath: sourceDir.path) else {
printWarning(" templates/ci_scripts/ not found in ARCDevTools")
return
}
let destDir = projectRoot.appendingPathComponent("ci_scripts")
if !fileManager.fileExists(atPath: destDir.path) {
try fileManager.createDirectory(at: destDir, withIntermediateDirectories: true)
}
let scripts = try fileManager.contentsOfDirectory(atPath: sourceDir.path)
for filename in scripts where filename.hasSuffix(".sh") {
let sourceFile = sourceDir.appendingPathComponent(filename)
let destFile = destDir.appendingPathComponent(filename)
try? fileManager.removeItem(at: destFile)
try fileManager.copyItem(at: sourceFile, to: destFile)
try makeExecutable(destFile)
printSuccess(" ci_scripts/\(filename)")
}
print("")
print(" 💡 Commit ci_scripts/ to enable Xcode Cloud customization", color: Color.blue)
print(" 📖 See docs/xcode-cloud-setup.md for workflow configuration", color: Color.blue)
}
func printFinalSuccess(projectType: ProjectType, installedSkills: [String] = [], installedAgents: [String] = []) {
print("")
printSuccess("ARCDevTools v\(version) configured successfully")
print("")
print("📦 Project type: \(projectType.displayName)", color: Color.blue)
print("")
print("📋 Installed configurations:", color: Color.blue)
print(" • .swift-version (v\(version))")
print(" • .swiftlint.base.yml (v\(version)) — studio rules (refreshed every run)")
print(" • .swiftlint.yml (v\(version)) — project-owned (paths + local tweaks)")
print(" • .swiftformat (v\(version)) — project-owned")
print(" • Makefile (v\(version))")
print("")
if !installedSkills.isEmpty {
print("🤖 Claude Code skills installed:", color: Color.blue)
for skill in installedSkills {
print(" • \(skill)")
}
print("")
}
if !installedAgents.isEmpty {
print("🤖 Claude Code agents installed:", color: Color.blue)
for agent in installedAgents {
print(" • \(agent)")
}
print("")
}
print("📝 Next steps:", color: Color.blue)
print(" 1. Run: make lint")
print(" 2. Run: make format")
switch projectType {
case .swiftPackage:
print(" 3. Run: make build")
print(" 4. Run: make test")
case .iOSApp:
print(" 3. Run: make build SCHEME=YourScheme")
print(" 4. Run: make test SCHEME=YourScheme")
}
print(" 5. Make a commit to test pre-commit hook")
print("")
print("💡 See available commands: make help", color: Color.blue)
print("")
}
// MARK: - Error Handling
enum SetupError: Error {
case invalidProjectRoot
}
// MARK: - Main Execution
func main() {
let options = parseArguments()
if options.showHelp {
printHelp()
return
}
do {
printBanner()
let projectType = try detectProjectType()
try setupSwiftVersion()
try setupConfigs(force: options.force)
try setupGitHooks()
try generateMakefile(for: projectType)
// Handle workflows based on options
let shouldInstallWorkflows: Bool
if options.withWorkflows {
shouldInstallWorkflows = true
} else if options.noWorkflows {
shouldInstallWorkflows = false
} else {
// Interactive mode
shouldInstallWorkflows = askUserForWorkflows()
}
if shouldInstallWorkflows {
try setupWorkflows(for: projectType)
}
// Handle ci_scripts installation (iOS Apps only)
if projectType == .iOSApp {
let shouldInstallCIScripts: Bool
if options.withWorkflows {
shouldInstallCIScripts = true
} else if options.noWorkflows {
shouldInstallCIScripts = false
} else {
shouldInstallCIScripts = askUserForCIScripts()
}
if shouldInstallCIScripts {
try setupCIScripts()
}
}
// Install Claude Code skills
let installedSkills = try setupClaudeSkills()
// Install Claude Code agents
let installedAgents = try setupClaudeAgents()