forked from giftbott/XcodeTemplateHelper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall_template.swift
More file actions
286 lines (235 loc) · 8.14 KB
/
install_template.swift
File metadata and controls
286 lines (235 loc) · 8.14 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
//
// install_template.swift
// Install Template
//
// Created by giftbott on 04/06/2017.
// Copyright © 2017 giftbott. All rights reserved.
//
import Foundation
// ==========================
// MARK: - Bash Shell Command
// ==========================
func bash(command: String, arguments: [String]) -> String {
let commandPath = shell(launchPath: "/bin/bash", arguments: ["-c", "which \(command)" ])
return shell(launchPath: commandPath, arguments: arguments)
}
func shell(launchPath: String, arguments: [String]) -> String {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)!
return output.trimmingCharacters(in: .newlines)
}
// ========================
// MARK: - Install template
// ========================
// UserName (currentUserName could be root)
let sessionUserName = bash(command: "who", arguments: ["am", "i"]).components(separatedBy: " ").first!
let currentUserName = bash(command: "whoami", arguments: [])
let fileManager = FileManager.default
/// Should select template only if more than one
func setup() {
let templateChecker = try? fileManager
.contentsOfDirectory(atPath: ".")
.filter { $0.hasSuffix(".xctemplate") }
guard let templates = templateChecker, !templates.isEmpty else {
printProcess("xctemplate does not exist")
return
}
guard templates.count > 1 else {
install(template: templates[0])
return
}
// Show xctemplates in current directory
print("Select Template")
print(String(repeating: "#", count:30))
print(templates.enumerated().map { String(describing: "\($0 + 1): \($1)") }.joined(separator: "\n"))
print(String(repeating: "#", count:30), terminator: "\n\n")
while true {
print("Select template number (q: quit) : ", terminator: "")
let input = readLine() ?? "1"
guard input.lowercased() != "q" else { exit(0) }
guard let num = Int(input), num >= 1, num <= templates.count else {
print("Wrong Value\n")
continue
}
let templateName = templates[num - 1]
printProcess("\(templateName) is selected\n")
install(template: templateName)
break
}
}
/// Copy template to selected target path
func install(template templateName: String) {
// Print Choiceable Target Directory Path
printPathOptions()
// Select Target Base Path
let userHomeDirectory = "/Users/".appending(sessionUserName)
let xcodeBasePath = bash(command: "xcode-select", arguments: ["--print-path"])
// Default Path (Custom File Template)
var basePath = userHomeDirectory
var pathEndPoint = PathEndPoint.customFileTemplate.rawValue
//
while true {
print("Input Target Number (q: quit) :", terminator: "")
let input = readLine() ?? "1"
guard input.lowercased() != "q" else { exit(0) }
guard let num = Int(input), num >= 1, num <= 4 else {
print("Wrong Value\n")
continue
}
switch num {
case 2:
pathEndPoint = PathEndPoint.customProjectTemplate.rawValue
case 3:
guard currentUserName == "root" else {
authorityAlert(needSudo: true)
return
}
basePath = xcodeBasePath
pathEndPoint = PathEndPoint.xcodeFileTemplate.rawValue
case 4:
guard currentUserName == "root" else {
authorityAlert(needSudo: true)
return
}
basePath = xcodeBasePath
pathEndPoint = PathEndPoint.xcodeProjectTemplate.rawValue
default:
break
}
break
}
let directoryPath = basePath.appending(pathEndPoint)
printProcess("Template will be installed at \(directoryPath)")
_ = bash(command: "mkdir", arguments: ["-p", directoryPath])
let fullPath = directoryPath.appending(templateName)
let isSuccess = copyTemplate(from: templateName, to: fullPath)
if isSuccess, basePath == userHomeDirectory, currentUserName == "root" {
changeOwner(of: fullPath)
let templateFiles = try? fileManager.contentsOfDirectory(atPath: fullPath)
guard let files = templateFiles else { return }
for file in files {
changeOwner(of: fullPath + "/\(file)")
}
}
}
/// Try copy
func copyTemplate(from: String, to: String) -> Bool {
do {
printProcess(".....")
defer { print() }
if !fileManager.fileExists(atPath: to) {
try fileManager.copyItem(atPath: from, toPath: to)
printProcess("Template installed successfully.")
} else {
try _ = fileManager.removeItem(atPath: to)
try fileManager.copyItem(atPath: from, toPath: to)
printProcess("Template has been replaced successfully.")
}
return true
} catch let error as NSError {
printProcess("Ooops! Something went wrong: \(error.localizedFailureReason!)")
return false
}
}
// MARK: - GetBaseTemplate
enum TemplateType {
case file
case project
}
/// Copy from Xcode Template (File: Swift, Project: Single View Application)
func getBaseTemplate(type: TemplateType) {
let (originPath, newPath) = configurePath(type)
guard copyTemplate(from: originPath, to: newPath) else { return }
// Change Owner of Directory
changeOwner(of: newPath)
// Change Owner of files
let templateFiles = try? fileManager.contentsOfDirectory(atPath: newPath)
guard let files = templateFiles else { return }
for file in files {
changeOwner(of: newPath + "/\(file)")
}
}
func configurePath(_ type: TemplateType) -> (String, String) {
let xcodeBasePath = bash(command: "xcode-select", arguments: ["--print-path"])
switch type {
case .file:
printProcess("Now Copy File Template")
let templatePath = xcodeBasePath + PathEndPoint.xcodeBaseFileTemplate.rawValue + "Swift File.xctemplate"
let copiedPath = "./BaseFileTemplate.xctemplate"
return (templatePath, copiedPath)
case .project:
printProcess("Now Copy Project Template")
let templatePath = xcodeBasePath + PathEndPoint.xcodeProjectTemplate.rawValue + "Single View Application.xctemplate"
let copiedPath = "./BaseProjectTemplate.xctemplate"
return (templatePath, copiedPath)
}
}
/// Need to change owner after using sudo command, root -> sessionUserName
func changeOwner(of path: String) {
_ = bash(command: "chown", arguments: [sessionUserName, path])
}
// MARK: - Helper
func printProcess(_ message: String) {
print(">>>>", message)
}
func printPathOptions() {
print("Select Path to Install Template")
print(String(repeating: "#", count:40))
print("1: Custom File Template")
print("2: Custom Project Template")
print("3: Xcode File Template (admin only)")
print("4: Xcode Project Template (admin only)")
print(String(repeating: "#", count:40), terminator: "\n\n")
}
func authorityAlert(needSudo: Bool) {
if needSudo {
print("It needs to be executed with sudo command\n")
} else {
print("CustomTemplate must be executed without sudo command\n")
}
}
func argumentsAlert() {
print("Illegal option.")
print("usage : swift install_template.swift [-g file / -g project]\n")
}
// MARK: Template Target Path
enum PathEndPoint: String {
case customFileTemplate = "/Library/Developer/Xcode/Templates/File Templates/Custom/"
case customProjectTemplate = "/Library/Developer/Xcode/Templates/Project Templates/Custom/"
//iOS Platform Path
case xcodeFileTemplate = "/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates/Source/"
case xcodeProjectTemplate = "/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/Project Templates/iOS/Application/"
//Xcode Base Template Path
case xcodeBaseFileTemplate = "/Library/Xcode/Templates/File Templates/Source/"
}
// ===============
// MARK: - Execute
// ===============
let arguments = CommandLine.arguments
switch CommandLine.argc {
case 1:
setup()
case 3:
let type = arguments[2]
guard arguments[1] == "-g", (type == "file" || type == "project") else {
argumentsAlert()
break
}
guard currentUserName == "root" else {
authorityAlert(needSudo: true)
break
}
if type == "file" {
getBaseTemplate(type: .file)
} else if type == "project" {
getBaseTemplate(type: .project)
}
default:
argumentsAlert()
}