Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XToolSupport / NewCommand.swift

NewCommand.swift181 lines · 5.6 KiBRaw
1import XUtils
2import XCLIUtils
3import ArgumentParser
4import Foundation
5import PackLib
6
7struct NewCommand: AsyncParsableCommand {
8 static let configuration = CommandConfiguration(
9 commandName: "new",
10 abstract: "Create a new xtool SwiftPM project"
11 )
12
13 @Argument var name: String?
14
15 @Flag(
16 help: ArgumentHelp(
17 "Skip setup steps. (default: false)",
18 discussion: """
19 By default, this command first invokes `xtool setup` to complete \
20 any missing setup steps, like authenticating and installing the SDK. Use \
21 this flag to always skip setup.
22 """
23 )
24 ) var skipSetup = false
25
26 // swiftlint:disable:next function_body_length
27 func run() async throws {
28 if !skipSetup {
29 // perform any remaining setup steps first
30 try await SetupOperation(quiet: true).run()
31 }
32
33 let name = try await Console.promptRequired("Package name: ", existing: self.name)
34
35 var allowedFirstCharacters: CharacterSet = ["_"]
36 allowedFirstCharacters.insert(charactersIn: "a"..."z")
37 allowedFirstCharacters.insert(charactersIn: "A"..."Z")
38
39 var allowedOtherCharacters = allowedFirstCharacters
40 allowedOtherCharacters.insert(charactersIn: "0"..."9")
41 allowedOtherCharacters.insert("-")
42
43 // promptRequired validates !isEmpty
44 let firstScalar = name.unicodeScalars.first!
45 guard allowedFirstCharacters.contains(firstScalar) else {
46 throw Console.Error("""
47 Package name '\(name)' is invalid. \
48 The package name must start with one of [a-z, A-Z, _]. Found '\(firstScalar)'.
49 """)
50 }
51
52 if let firstInvalid = name.rangeOfCharacter(from: allowedOtherCharacters.inverted) {
53 let invalidValue = name[firstInvalid]
54 throw Console.Error("""
55 Package name '\(name)' is invalid. \
56 The package name may only contain [a-z, A-Z, 0-9, _, -]. Found '\(invalidValue)'.
57 """)
58 }
59
60 let baseURL = URL(fileURLWithPath: name)
61
62 guard !baseURL.exists else {
63 throw Console.Error("Cannot create \(name): a file already exists at that path.")
64 }
65
66 d.out.print("Creating package: \(name)")
67
68 let moduleName = name.replacingOccurrences(of: "-", with: "_")
69
70 let files: [(String, String)] = [
71 (
72 "Package.swift",
73 """
74 // swift-tools-version: 6.0
75
76 import PackageDescription
77
78 let package = Package(
79 name: "\(name)",
80 platforms: [
81 .iOS(.v17),
82 .macOS(.v14),
83 ],
84 products: [
85 // An xtool project should contain exactly one library product,
86 // representing the main app.
87 .library(
88 name: "\(moduleName)",
89 targets: ["\(moduleName)"]
90 ),
91 ],
92 targets: [
93 .target(
94 name: "\(moduleName)"
95 ),
96 ]
97 )
98 """
99 ),
100
101 (
102 "xtool.yml",
103 """
104 version: 1
105 bundleID: com.example.\(name)
106 """
107 ),
108
109 (
110 ".gitignore",
111 """
112 .DS_Store
113 /.build
114 /Packages
115 xcuserdata/
116 DerivedData/
117 .swiftpm/configuration/registries.json
118 .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
119 .netrc
120
121 /xtool
122 """
123 ),
124
125 (
126 "Sources/\(moduleName)/\(moduleName)App.swift",
127 """
128 import SwiftUI
129
130 @main
131 struct \(moduleName)App: App {
132 var body: some Scene {
133 WindowGroup {
134 ContentView()
135 }
136 }
137 }
138 """
139 ),
140
141 (
142 "Sources/\(moduleName)/ContentView.swift",
143 """
144 import SwiftUI
145
146 struct ContentView: View {
147 var body: some View {
148 VStack {
149 Image(systemName: "globe")
150 .imageScale(.large)
151 .foregroundStyle(.tint)
152 Text("Hello, world!")
153 }
154 .padding()
155 }
156 }
157 """
158 ),
159 ]
160
161 for (path, contents) in files {
162 let url = baseURL.appendingPathComponent(path)
163 try? FileManager.default.createDirectory(
164 at: url.deletingLastPathComponent(),
165 withIntermediateDirectories: true
166 )
167 d.out.print("Creating \(path)")
168 try "\(contents)\n".write(to: url, atomically: true, encoding: .utf8)
169 }
170
171 await LSPConfig.tryEnsure(
172 using: .default,
173 quiet: true,
174 currentDirectory: baseURL,
175 )
176
177 d.out.print("\nFinished generating project \(name). Next steps:")
178 d.out.print("- Enter the directory with `cd \(name)`")
179 d.out.print("- Build and run with `xtool dev`")
180 }
181}