-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Introduce the snippet
target type
#3694
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/* | ||
This source file is part of the Swift.org open source project | ||
|
||
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See http://swift.org/LICENSE.txt for license information | ||
See http://swift.org/CONTRIBUTORS.txt for Swift project authors | ||
*/ | ||
|
||
/// A terminal menu that takes up the whole terminal, accepting input and | ||
/// rendering in response. | ||
protocol Card { | ||
/// Render the contents to be printed to the terminal. | ||
func render() -> String | ||
|
||
/// Accept a line of input from the user's terminal and provide | ||
/// an optional ``CardEvent`` which can alter the card stack. | ||
func acceptLineInput<S: StringProtocol>(_ line: S) -> CardEvent? | ||
|
||
/// The input prompt to present to the user when accepting a line of input. | ||
var inputPrompt: String? { get } | ||
} | ||
|
||
extension Card { | ||
var defaultPrompt: String { | ||
return "Press enter to continue." | ||
} | ||
} | ||
|
||
extension Card { | ||
var inputPrompt: String? { | ||
return defaultPrompt | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/* | ||
This source file is part of the Swift.org open source project | ||
|
||
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See http://swift.org/LICENSE.txt for license information | ||
See http://swift.org/CONTRIBUTORS.txt for Swift project authors | ||
*/ | ||
|
||
/// An event that alters the card stack after some input from the user. | ||
enum CardEvent { | ||
/// Pop the top card from the stack, providing an optional error that | ||
/// may have occurred. | ||
case pop(Swift.Error? = nil) | ||
|
||
/// Push a new card onto the stack. | ||
case push(Card) | ||
|
||
/// Quit the program, providing an optional error that may have occurred. | ||
case quit(Swift.Error? = nil) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
/* | ||
This source file is part of the Swift.org open source project | ||
|
||
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See http://swift.org/LICENSE.txt for license information | ||
See http://swift.org/CONTRIBUTORS.txt for Swift project authors | ||
*/ | ||
|
||
import PackageModel | ||
import TSCBasic | ||
import PackageGraph | ||
|
||
fileprivate extension TerminalController { | ||
func clearScreen() { | ||
write("\u{001b}[2J") | ||
write("\u{001b}[H") | ||
flush() | ||
} | ||
} | ||
|
||
/// A stack of "cards" to display one at a time at the command line. | ||
struct CardStack { | ||
var terminal: TerminalController | ||
|
||
/// The representation of a stack of cards. | ||
var cards = [Card]() | ||
|
||
/// The tool used for eventually building and running a chosen snippet. | ||
var swiftTool: SwiftTool | ||
|
||
/// When true, the escape sequence for clearing the terminal should be | ||
/// printed first. | ||
private var needsToClearScreen = true | ||
|
||
init(package: ResolvedPackage, snippetGroups: [SnippetGroup], swiftTool: SwiftTool) { | ||
self.terminal = TerminalController(stream: stdoutStream)! | ||
self.cards = [TopCard(package: package, snippetGroups: snippetGroups, swiftTool: swiftTool)] | ||
self.swiftTool = swiftTool | ||
} | ||
|
||
mutating func push(_ card: Card) { | ||
cards.append(card) | ||
} | ||
|
||
mutating func pop() { | ||
cards.removeLast() | ||
} | ||
|
||
mutating func clear() { | ||
cards.removeAll() | ||
} | ||
|
||
func askForLineInput(prompt: String?) -> String? { | ||
if let prompt = prompt { | ||
print(brightBlack { prompt }.terminalString()) | ||
} | ||
terminal.write(">>> ", inColor: .green, bold: true) | ||
return readLine(strippingNewline: true) | ||
} | ||
|
||
mutating func run() { | ||
var inputFinished = false | ||
while !inputFinished { | ||
guard let top = cards.last else { | ||
break | ||
} | ||
|
||
if needsToClearScreen { | ||
terminal.clearScreen() | ||
needsToClearScreen = false | ||
} | ||
|
||
print(top.render()) | ||
|
||
// Assume input finished until proven otherwise, i.e. when readLine returns | ||
// `nil`. | ||
inputFinished = true | ||
|
||
askForLine: while let line = askForLineInput(prompt: top.inputPrompt) { | ||
inputFinished = false | ||
let trimmedLine = String(line.drop { $0.isWhitespace } | ||
.reversed() | ||
.drop { $0.isWhitespace } | ||
.reversed()) | ||
let response = top.acceptLineInput(trimmedLine) | ||
switch response { | ||
case .none: | ||
continue askForLine | ||
case .push(let card): | ||
push(card) | ||
needsToClearScreen = true | ||
break askForLine | ||
case let .pop(error): | ||
cards.removeLast() | ||
if let error = error { | ||
swiftTool.diagnostics.emit(error: error.localizedDescription) | ||
needsToClearScreen = false | ||
} else { | ||
needsToClearScreen = !cards.isEmpty | ||
} | ||
break askForLine | ||
case .quit: | ||
return | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
/* | ||
This source file is part of the Swift.org open source project | ||
|
||
Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors | ||
Licensed under Apache License v2.0 with Runtime Library Exception | ||
|
||
See http://swift.org/LICENSE.txt for license information | ||
See http://swift.org/CONTRIBUTORS.txt for Swift project authors | ||
*/ | ||
|
||
import PackageModel | ||
import TSCBasic | ||
|
||
/// A card displaying a ``Snippet`` at the terminal. | ||
struct SnippetCard: Card { | ||
enum Error: Swift.Error, CustomStringConvertible { | ||
case cantRunSnippet(reason: String) | ||
|
||
var description: String { | ||
switch self { | ||
case let .cantRunSnippet(reason): | ||
return "Can't run snippet: \(reason)" | ||
} | ||
} | ||
} | ||
/// The snippet to display in the terminal. | ||
var snippet: Snippet | ||
|
||
/// The snippet's index within its group. | ||
var number: Int | ||
|
||
/// The tool used for eventually building and running a chosen snippet. | ||
var swiftTool: SwiftTool | ||
|
||
func render() -> String { | ||
var rendered = colorized { | ||
brightYellow { | ||
"# " | ||
snippet.name | ||
} | ||
"\n\n" | ||
}.terminalString() | ||
|
||
if !snippet.explanation.isEmpty { | ||
rendered += brightBlack { | ||
snippet.explanation | ||
.split(separator: "\n", omittingEmptySubsequences: false) | ||
.map { "// " + $0 } | ||
.joined(separator: "\n") | ||
}.terminalString() | ||
|
||
rendered += "\n\n" | ||
} | ||
|
||
rendered += snippet.presentationCode | ||
|
||
return rendered | ||
} | ||
|
||
var inputPrompt: String? { | ||
return "\nRun this snippet? [R: run, or press Enter to return]" | ||
} | ||
|
||
func acceptLineInput<S>(_ line: S) -> CardEvent? where S : StringProtocol { | ||
let trimmed = line.drop { $0.isWhitespace }.prefix { !$0.isWhitespace }.lowercased() | ||
guard !trimmed.isEmpty else { | ||
return .pop() | ||
} | ||
|
||
switch trimmed { | ||
case "r", "run": | ||
do { | ||
try runExample() | ||
} catch { | ||
return .pop(SnippetCard.Error.cantRunSnippet(reason: error.localizedDescription)) | ||
} | ||
break | ||
case "c", "copy": | ||
print("Unimplemented") | ||
break | ||
default: | ||
break | ||
} | ||
|
||
return .pop() | ||
} | ||
|
||
func runExample() throws { | ||
print("Building '\(snippet.path)'\n") | ||
let buildSystem = try swiftTool.createBuildSystem(explicitProduct: snippet.name) | ||
try buildSystem.build(subset: .product(snippet.name)) | ||
let executablePath = try swiftTool.buildParameters().buildPath.appending(component: snippet.name) | ||
if let exampleTarget = try buildSystem.getPackageGraph().allTargets.first(where: { $0.name == snippet.name }) { | ||
try ProcessEnv.chdir(exampleTarget.sources.paths[0].parentDirectory) | ||
} | ||
try exec(path: executablePath.pathString, args: []) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if some of the UI for snippets should be in a distinct module from
Commands
. I could see that this would be something we may want to expose via libSwiftPM at some point.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was thinking the same thing actually. Before committing to that, what do you say we keep it here for now while we refine it some more? I think it will probably change a bit in the coming months.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, I think that's fine.