├── Package.swift ├── Package.resolved ├── LICENSE ├── .gitignore ├── README.md ├── CODE_OF_CONDUCT.md └── Sources └── Playground └── main.swift /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.1 2 | 3 | /** 4 | * Playground 5 | * Copyright (c) John Sundell 2017 6 | * Licensed under the MIT license. See LICENSE file. 7 | */ 8 | 9 | import PackageDescription 10 | 11 | let package = Package( 12 | name: "Playground", 13 | dependencies: [ 14 | .package(url: "https://github.com/JohnSundell/Files.git", from: "2.0.0"), 15 | .package(url: "https://github.com/JohnSundell/ShellOut.git", from: "2.0.0"), 16 | .package(url: "https://github.com/JohnSundell/Xgen.git", from: "2.0.0") 17 | ], 18 | targets: [ 19 | .target( 20 | name: "Playground", 21 | dependencies: ["Files", "ShellOut", "Xgen"] 22 | ) 23 | ] 24 | ) 25 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "Files", 6 | "repositoryURL": "https://github.com/JohnSundell/Files.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "a84615f4558151fab52ac38df697ce2442991f93", 10 | "version": "2.3.0" 11 | } 12 | }, 13 | { 14 | "package": "ShellOut", 15 | "repositoryURL": "https://github.com/JohnSundell/ShellOut.git", 16 | "state": { 17 | "branch": null, 18 | "revision": "4ebf25863deb9c3c02696704fc3d39736183f258", 19 | "version": "2.2.1" 20 | } 21 | }, 22 | { 23 | "package": "Xgen", 24 | "repositoryURL": "https://github.com/JohnSundell/Xgen.git", 25 | "state": { 26 | "branch": null, 27 | "revision": "444b9ad8f9c7720578fc46dbd09e0487eac7ddb5", 28 | "version": "2.2.0" 29 | } 30 | } 31 | ] 32 | }, 33 | "version": 1 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 John Sundell 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | *.ipa 28 | *.dSYM.zip 29 | *.dSYM 30 | 31 | ## Playgrounds 32 | timeline.xctimeline 33 | playground.xcworkspace 34 | 35 | # Swift Package Manager 36 | # 37 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 38 | # Packages/ 39 | # Package.pins 40 | .build/ 41 | .swiftpm 42 | 43 | # CocoaPods 44 | # 45 | # We recommend against adding the Pods directory to your .gitignore. However 46 | # you should judge for yourself, the pros and cons are mentioned at: 47 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 48 | # 49 | # Pods/ 50 | 51 | # Carthage 52 | # 53 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 54 | # Carthage/Checkouts 55 | 56 | Carthage/Build 57 | 58 | # fastlane 59 | # 60 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 61 | # screenshots whenever they are needed. 62 | # For more information about the recommended setup visit: 63 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 64 | 65 | fastlane/report.xml 66 | fastlane/Preview.html 67 | fastlane/screenshots 68 | fastlane/test_output 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Playground 2 | 3 | [![Swift 5.1](https://img.shields.io/badge/swift-5.1-orange.svg?style=flat)](#) 4 | [![SwiftPM](https://img.shields.io/badge/swiftpm-compatible-brightgreen.svg?style=flat)](https://github.com/apple/swift-package-manager) 5 | [![@johnsundell](https://img.shields.io/badge/contact-@johnsundell-blue.svg?style=flat)](https://twitter.com/johnsundell) 6 | 7 | Welcome to `playground`, a Swift script that enables you to super quickly generate Swift playgrounds from the command line - with or without dependencies - for any supported platform. 8 | 9 | It essentially provides a command line interface to [Xgen](https://github.com/johnsundell/xgen). 10 | 11 | **Features** 12 | 13 | - [X] Generate playgrounds in seconds. 14 | - [X] Automatically reuse any playground created today, for easy code note taking. 15 | - [X] Add dependencies to a playground with a simple command - no more fiddling with workspaces. 16 | - [X] Easily open a Gist or code from a GitHub URL in a playground. 17 | - [X] Supports iOS, macOS & tvOS. 18 | 19 | ## Usage 20 | 21 | **Simply run `playground` and a new playground will be created and opened** 22 | 23 | ``` 24 | $ playground 25 | ``` 26 | 27 | You can also supply various arguments to customize your playground: 28 | 29 | **Add a playground at a specific path** 30 | 31 | ``` 32 | $ playground -t ~/MyPlayground 33 | ``` 34 | 35 | **Add some dependencies to your playground** 36 | 37 | ``` 38 | $ playground -d ~/unbox/unbox.xcodeproj,~/files/files.xcodeproj 39 | ``` 40 | 41 | **Open the contents of a Gist, a GitHub URL or any other URL in a playground** 42 | 43 | ``` 44 | $ playground -u https://gist.github.com/JohnSundell/b7f901e8edb89d1396ede4d8db3e8c21 45 | ``` 46 | 47 | **Quickly get started with view code prototyping** 48 | 49 | ``` 50 | $ playground -v 51 | ``` 52 | 53 | **Specify what platform you want the playground to run on** 54 | 55 | ``` 56 | $ playground -p tvOS 57 | ``` 58 | 59 | *For all available options, run `$ playground -h`* 60 | 61 | ## Installation 62 | 63 | The easiest way to install `playground` is using the Swift Package Manager: 64 | 65 | ``` 66 | $ git clone https://github.com/JohnSundell/Playground.git 67 | $ cd Playground 68 | $ swift build -c release 69 | $ install .build/release/Playground /usr/local/bin/playground 70 | ``` 71 | 72 | ## Help, feedback or suggestions? 73 | 74 | - [Open a PR](https://github.com/JohnSundell/Playground/pull/new/master) if you want to make some change to `playground`. 75 | - Contact [@johnsundell on Twitter](https://twitter.com/johnsundell) for discussions, news & announcements about `playground` & other projects. 76 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Playground Code of Conduct 2 | 3 | Below is the Code of Conduct that all contributors and participants in the Playground community are expected to adhere to. 4 | It's adopted from the [Contributor Covenant Code of Conduct][homepage]. 5 | 6 | ## Our Pledge 7 | 8 | In the interest of fostering an open and welcoming environment, we as 9 | contributors and maintainers pledge to making participation in our project and 10 | our community a harassment-free experience for everyone, regardless of age, body 11 | size, disability, ethnicity, gender identity and expression, level of experience, 12 | nationality, personal appearance, race, religion, or sexual identity and 13 | orientation. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to creating a positive environment 18 | include: 19 | 20 | * Using welcoming and inclusive language 21 | * Being respectful of differing viewpoints and experiences 22 | * Gracefully accepting constructive criticism 23 | * Focusing on what is best for the community 24 | * Showing empathy towards other community members 25 | 26 | Examples of unacceptable behavior by participants include: 27 | 28 | * The use of sexualized language or imagery and unwelcome sexual attention or 29 | advances 30 | * Trolling, insulting/derogatory comments, and personal or political attacks 31 | * Public or private harassment 32 | * Publishing others' private information, such as a physical or electronic 33 | address, without explicit permission 34 | * Other conduct which could reasonably be considered inappropriate in a 35 | professional setting 36 | 37 | ## Our Responsibilities 38 | 39 | Project maintainers are responsible for clarifying the standards of acceptable 40 | behavior and are expected to take appropriate and fair corrective action in 41 | response to any instances of unacceptable behavior. 42 | 43 | Project maintainers have the right and responsibility to remove, edit, or 44 | reject comments, commits, code, wiki edits, issues, and other contributions 45 | that are not aligned to this Code of Conduct, or to ban temporarily or 46 | permanently any contributor for other behaviors that they deem inappropriate, 47 | threatening, offensive, or harmful. 48 | 49 | ## Scope 50 | 51 | This Code of Conduct applies both within project spaces and in public spaces 52 | when an individual is representing the project or its community. Examples of 53 | representing a project or community include using an official project e-mail 54 | address, posting via an official social media account, or acting as an appointed 55 | representative at an online or offline event. Representation of a project may be 56 | further defined and clarified by project maintainers. 57 | 58 | ## Enforcement 59 | 60 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 61 | reported by contacting the project leader at john@sundell.co. All 62 | complaints will be reviewed and investigated and will result in a response that 63 | is deemed necessary and appropriate to the circumstances. The project team is 64 | obligated to maintain confidentiality with regard to the reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 74 | available at [http://contributor-covenant.org/version/1/4][version] 75 | 76 | [homepage]: http://contributor-covenant.org 77 | [version]: http://contributor-covenant.org/version/1/4/ 78 | -------------------------------------------------------------------------------- /Sources/Playground/main.swift: -------------------------------------------------------------------------------- 1 | #!/usr/bin/swift 2 | 3 | import Foundation 4 | import Cocoa 5 | import Xgen 6 | import Files 7 | import ShellOut 8 | 9 | // MARK: - Extensions 10 | 11 | extension CommandLine { 12 | static var argumentsExcludingLaunchPath: [String] { 13 | var arguments = self.arguments 14 | arguments.removeFirst() 15 | return arguments 16 | } 17 | 18 | static func open(path: String) throws { 19 | print("🚀 Opening \(path)...") 20 | try shellOut(to: "open \(path)") 21 | } 22 | } 23 | 24 | extension Date { 25 | var today: String { 26 | let formatter = DateFormatter() 27 | formatter.dateStyle = .short 28 | let date = formatter.string(from: self) 29 | return date.replacingOccurrences(of: "/", with: "-") 30 | } 31 | } 32 | 33 | extension Playground { 34 | func apply(_ options: Options) throws { 35 | platform = options.platform 36 | autoRun = options.autoRun 37 | try options.code.map(add) 38 | } 39 | 40 | private func add(codeOption: Options.Code) throws { 41 | switch codeOption { 42 | case .view: 43 | addViewCode() 44 | case .fromClipboard: 45 | let pasteboard = NSPasteboard.general 46 | let copiedCode = pasteboard.string(forType: .string) ?? "" 47 | code = addFrameworkImportsIfNeeded(to: copiedCode) 48 | case .fromURL(let url): 49 | var loadedCode = try loadCode(from: url) 50 | 51 | if loadedCode.contains("import Cocoa") || loadedCode.contains("import AppKit") { 52 | platform = .macOS 53 | } else { 54 | loadedCode = addFrameworkImportsIfNeeded(to: loadedCode) 55 | } 56 | 57 | code = loadedCode 58 | case .custom(let customCode): 59 | code = customCode 60 | } 61 | } 62 | 63 | private func addViewCode() { 64 | let viewClass: String 65 | var viewCode: String 66 | 67 | switch platform { 68 | case .iOS, .tvOS: 69 | viewCode = "import UIKit" 70 | viewClass = "UIView" 71 | case .macOS: 72 | viewCode = "import Cocoa" 73 | viewClass = "NSView" 74 | } 75 | 76 | viewCode.append("\nimport PlaygroundSupport\n\n") 77 | viewCode.append("let viewFrame = CGRect(x: 0, y: 0, width: 500, height: 500)\n") 78 | viewCode.append("let view = \(viewClass)(frame: viewFrame)\n") 79 | 80 | switch platform { 81 | case .iOS, .tvOS: 82 | viewCode.append("view.backgroundColor = .white\n") 83 | case .macOS: 84 | viewCode.append("view.wantsLayer = true\n") 85 | viewCode.append("view.layer!.backgroundColor = NSColor.white.cgColor\n") 86 | } 87 | 88 | viewCode.append("PlaygroundPage.current.liveView = view\n") 89 | 90 | code = viewCode 91 | } 92 | 93 | private func loadCode(from url: URL) throws -> String { 94 | print("🌍 Downloading code from \(url)...") 95 | 96 | var url = url 97 | let urlString = url.absoluteString 98 | 99 | if urlString.contains("gist.github.com") { 100 | if !urlString.contains("/raw") { 101 | url = url.appendingPathComponent("raw") 102 | } 103 | } else if let gitHubRange = urlString.range(of: "github.com/") { 104 | let urlSuffix = urlString[gitHubRange.upperBound...] 105 | let rawURLSuffix = urlSuffix.replacingOccurrences(of: "/blob/", with: "/") 106 | url = URL(string: "https://raw.githubusercontent.com/" + rawURLSuffix)! 107 | } 108 | 109 | do { 110 | return try String(contentsOf: url, encoding: .utf8) 111 | } catch { 112 | throw PlaygroundError.codeDownloadFailed(error) 113 | } 114 | } 115 | 116 | private func addFrameworkImportsIfNeeded(to code: String) -> String { 117 | var frameworks = ["Foundation", "PlaygroundSupport"] 118 | 119 | switch platform { 120 | case .iOS, .tvOS: 121 | frameworks.append("UIKit") 122 | case .macOS: 123 | frameworks.append("Cocoa") 124 | } 125 | 126 | let imports: [String] = frameworks.compactMap { framework in 127 | guard !code.contains(framework) else { 128 | return nil 129 | } 130 | 131 | return "import \(framework)" 132 | } 133 | 134 | guard !imports.isEmpty else { 135 | return code 136 | } 137 | 138 | return imports.joined(separator: "\n") + "\n\n" + code 139 | } 140 | } 141 | 142 | // MARK: - Types 143 | 144 | enum PlaygroundError: Error { 145 | case invalidFlag(String) 146 | case missingValue(Flag) 147 | case invalidPlatform(String) 148 | case invalidDependency(String) 149 | case codeDownloadFailed(Error) 150 | } 151 | 152 | extension PlaygroundError: CustomStringConvertible { 153 | public var description: String { 154 | switch self { 155 | case .invalidFlag(let flag): 156 | return "Invalid flag '\(flag)'. Run 'playground -h' for available options." 157 | case .missingValue(let flag): 158 | return "Missing value for flag '\(flag.rawValue)'." 159 | case .invalidPlatform(let platform): 160 | return "Invalid platform '\(platform)'. Must be iOS, macOS or tvOS." 161 | case .invalidDependency(let dependency): 162 | return "Invalid dependency '\(dependency)'. Make sure that it's an Xcode project that exists." 163 | case .codeDownloadFailed(let error): 164 | return "Failed to download code from the given URL. Underlying error: \(error)." 165 | } 166 | } 167 | } 168 | 169 | enum Flag: String { 170 | case targetPath = "-t" 171 | case platform = "-p" 172 | case dependencies = "-d" 173 | case code = "-c" 174 | case url = "-u" 175 | case addViewCode = "-v" 176 | case forceOverwrite = "-f" 177 | case autoRun = "-a" 178 | case help = "-h" 179 | } 180 | 181 | struct Options { 182 | var targetPath: String 183 | var platform = Playground.Platform.iOS 184 | var dependencies = [Folder]() 185 | var code: Code? = nil 186 | var forceOverwrite = false 187 | var autoRun = false 188 | var displayHelp = false 189 | 190 | init(arguments: [String] = CommandLine.argumentsExcludingLaunchPath) throws { 191 | let defaultTargetPath = "~/Desktop/\(Date().today).playground" 192 | targetPath = defaultTargetPath 193 | 194 | var currentFlag: Flag? 195 | 196 | for argument in arguments { 197 | currentFlag = try parse(argument: argument, for: currentFlag) 198 | } 199 | 200 | if let danglingFlag = currentFlag { 201 | switch danglingFlag { 202 | case .targetPath, .platform, .dependencies, .url: 203 | throw PlaygroundError.missingValue(danglingFlag) 204 | case .forceOverwrite: 205 | forceOverwrite = true 206 | case .addViewCode: 207 | code = .view 208 | case .code: 209 | code = .fromClipboard 210 | case .autoRun: 211 | autoRun = true 212 | case .help: 213 | displayHelp = true 214 | } 215 | } 216 | 217 | if code != nil && (try? Folder(path: targetPath)) != nil { 218 | targetPath += "-\(UUID().uuidString)" 219 | } 220 | } 221 | 222 | private mutating func parse(argument: String, for currentFlag: Flag? = nil) throws -> Flag? { 223 | guard let flag = currentFlag else { 224 | guard let flag = Flag(rawValue: argument) else { 225 | throw PlaygroundError.invalidFlag(argument) 226 | } 227 | 228 | return flag 229 | } 230 | 231 | switch flag { 232 | case .targetPath: 233 | if let folder = try? Folder(path: argument) { 234 | targetPath = folder.path + Date().today 235 | } else { 236 | targetPath = argument 237 | } 238 | case .platform: 239 | guard let parsedPlatform = Playground.Platform(rawValue: argument.lowercased()) else { 240 | throw PlaygroundError.invalidPlatform(argument) 241 | } 242 | 243 | platform = parsedPlatform 244 | case .dependencies: 245 | let paths = argument.components(separatedBy: ",") 246 | dependencies = try paths.map { path in 247 | do { 248 | guard path.hasSuffix(".xcodeproj") else { 249 | throw PlaygroundError.invalidDependency(path) 250 | } 251 | 252 | return try Folder(path: path) 253 | } catch { 254 | throw PlaygroundError.invalidDependency(path) 255 | } 256 | } 257 | case .code: 258 | guard !argument.hasPrefix("-") else { 259 | code = .fromClipboard 260 | return try parse(argument: argument) 261 | } 262 | 263 | code = .custom(argument) 264 | case .url: 265 | code = URL(string: argument).map(Code.fromURL) 266 | case .addViewCode: 267 | code = .view 268 | return try parse(argument: argument) 269 | case .forceOverwrite: 270 | forceOverwrite = true 271 | return try parse(argument: argument) 272 | case .autoRun: 273 | autoRun = true 274 | return try parse(argument: argument) 275 | case .help: 276 | displayHelp = true 277 | return try parse(argument: argument) 278 | } 279 | 280 | return nil 281 | } 282 | } 283 | 284 | extension Options { 285 | enum Code { 286 | case view 287 | case fromClipboard 288 | case fromURL(URL) 289 | case custom(String) 290 | } 291 | } 292 | 293 | // MARK: - Functions 294 | 295 | func displayHelp() { 296 | print( 297 | """ 298 | Playground 299 | ---------- 300 | Easily create Swift playgrounds from the command line 301 | 302 | Options: 303 | 304 | 📁 -t Specify a target path where the playground should be created 305 | Default: ~/Desktop/ 306 | 📱 -p Select platform (iOS, macOS or tvOS) that the playground should run on 307 | Default: iOS 308 | 🏃‍♂️ -a Turn on auto run for the generated playground 309 | Default: False 310 | 📦 -d Specify any Xcode projects that you wish to add as dependencies 311 | Should be a comma-separated list of file paths 312 | 📄 -c Any code that you want the playground to contain 313 | Pass this flag without a value to use the contents of your clipboard 314 | Default: An empty playground that imports the system framework 315 | 🌍 -u Any URL to code that you want the playground to contain 316 | Gist & GitHub links are automatically handled 317 | 🌄 -v Fill the playground with the code required to prototype a view 318 | Default: Any code specified with -c or its default value 319 | 💪 -f Force overwrite any existing playground at the target path 320 | Default: Don't overwrite, and instead open any existing playground 321 | ℹ️ -h Display this information 322 | """ 323 | ) 324 | } 325 | 326 | // MARK: - Script 327 | 328 | do { 329 | let options = try Options() 330 | 331 | guard !options.displayHelp else { 332 | displayHelp() 333 | exit(0) 334 | } 335 | 336 | func openIfNeeded(path: String) throws { 337 | guard !options.forceOverwrite else { 338 | return 339 | } 340 | 341 | guard (try? Folder(path: path)) != nil else { 342 | return 343 | } 344 | 345 | try CommandLine.open(path: path) 346 | exit(0) 347 | } 348 | 349 | if !options.dependencies.isEmpty { 350 | let workspace = Workspace(path: options.targetPath) 351 | try openIfNeeded(path: workspace.path) 352 | 353 | let playground = workspace.addPlayground() 354 | try playground.apply(options) 355 | 356 | for dependency in options.dependencies { 357 | workspace.addProject(at: dependency.path) 358 | } 359 | 360 | try workspace.generate() 361 | 362 | print("✅ Generated Playground workspace at \(workspace.path)") 363 | try CommandLine.open(path: workspace.path) 364 | } else { 365 | let playground = Playground(path: options.targetPath) 366 | try openIfNeeded(path: playground.path) 367 | 368 | try playground.apply(options) 369 | try playground.generate() 370 | 371 | print("✅ Generated Playground at \(playground.path)") 372 | try CommandLine.open(path: playground.path) 373 | } 374 | } catch { 375 | print("💥 An error occured: \(error)") 376 | } 377 | --------------------------------------------------------------------------------