1
0
mirror of https://github.com/nicoverbruggen/phpmon.git synced 2025-08-10 13:00:07 +02:00

🏗 Checked and fixed various Task { } blocks

This commit is contained in:
2022-10-06 23:29:13 +02:00
parent ed3622cc4e
commit 45a82b2c9e
17 changed files with 88 additions and 86 deletions

View File

@@ -139,7 +139,7 @@ class Actions {
*/ */
public static func fixMyValet(completed: @escaping () -> Void) { public static func fixMyValet(completed: @escaping () -> Void) {
InternalSwitcher().performSwitch(to: PhpEnv.brewPhpAlias, completion: { InternalSwitcher().performSwitch(to: PhpEnv.brewPhpAlias, completion: {
Task { // restart all services and fire callback upon completion Task { // Restart all services asynchronously and fire callback upon completion
await brew("services restart dnsmasq", sudo: true) await brew("services restart dnsmasq", sudo: true)
await brew("services restart php", sudo: true) await brew("services restart php", sudo: true)
await brew("services restart nginx", sudo: true) await brew("services restart nginx", sudo: true)

View File

@@ -62,7 +62,12 @@ public class Paths {
} }
public static var homePath: String { public static var homePath: String {
return NSHomeDirectory() // TODO: Depending on the filesystem abstraction, return the correct information
if Shell is SystemShell {
return NSHomeDirectory()
}
return "/Users/\(Paths.whoami)"
} }
public static var cellarPath: String { public static var cellarPath: String {

View File

@@ -71,7 +71,7 @@ class AddProxyVC: NSViewController, NSTextFieldDelegate {
App.shared.domainListWindowController?.contentVC.setUIBusy() App.shared.domainListWindowController?.contentVC.setUIBusy()
Task { Task { // Ensure we proxy the site asynchronously and reload UI on main thread again
await Shell.quiet("\(Paths.valet) proxy \(domain) \(proxyName)\(secure)") await Shell.quiet("\(Paths.valet) proxy \(domain) \(proxyName)\(secure)")
await Actions.restartNginx() await Actions.restartNginx()

View File

@@ -71,9 +71,7 @@ class AddSiteVC: NSViewController, NSTextFieldDelegate {
// Adding `valet links` is a workaround for Valet malforming the config.json file // Adding `valet links` is a workaround for Valet malforming the config.json file
// TODO: I will have to investigate and report this behaviour if possible // TODO: I will have to investigate and report this behaviour if possible
Task { Task { await Shell.quiet("cd '\(path)' && \(Paths.valet) link '\(name)' && valet links") }
await Shell.quiet("cd '\(path)' && \(Paths.valet) link '\(name)' && valet links")
}
dismissView(outcome: .OK) dismissView(outcome: .OK)

View File

@@ -137,7 +137,7 @@ class DomainListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource
- Parameter completion: Callback that is fired when the work is done. - Parameter completion: Callback that is fired when the work is done.
*/ */
internal func waitAndExecute(_ execute: @escaping () async -> Void, completion: @escaping () -> Void = {}) { internal func waitAndExecute(_ execute: @escaping () async -> Void, completion: @escaping () -> Void = {}) {
Task { Task { // Legacy `waitAndExecute` with UI
setUIBusy() setUIBusy()
await execute() await execute()

View File

@@ -51,9 +51,7 @@ class DomainListWindowController: PMWindowController, NSSearchFieldDelegate, NST
// MARK: - Reload functionality // MARK: - Reload functionality
@IBAction func pressedReload(_ sender: Any?) { @IBAction func pressedReload(_ sender: Any?) {
Task { Task { await contentVC.reloadDomains() }
await contentVC.reloadDomains()
}
} }
@IBAction func pressedAddLink(_ sender: Any?) { @IBAction func pressedAddLink(_ sender: Any?) {

View File

@@ -59,7 +59,6 @@ extension MainMenu {
} }
} }
@MainActor @objc func restartValetServices() { @MainActor @objc func restartValetServices() {
Task { // Restart services and show notification Task { // Restart services and show notification
await Actions.restartDnsMasq() await Actions.restartDnsMasq()
@@ -135,7 +134,7 @@ extension MainMenu {
} }
@objc func toggleExtension(sender: ExtensionMenuItem) { @objc func toggleExtension(sender: ExtensionMenuItem) {
Task { Task { // Toggle extension async
await sender.phpExtension?.toggle() await sender.phpExtension?.toggle()
if Preferences.isEnabled(.autoServiceRestartAfterExtensionToggle) { if Preferences.isEnabled(.autoServiceRestartAfterExtensionToggle) {
@@ -145,7 +144,7 @@ extension MainMenu {
} }
private func performRollback() { private func performRollback() {
Task { Task { // Rollback preset async
await PresetHelper.rollbackPreset?.apply() await PresetHelper.rollbackPreset?.apply()
PresetHelper.rollbackPreset = nil PresetHelper.rollbackPreset = nil
MainMenu.shared.rebuild() MainMenu.shared.rebuild()
@@ -172,7 +171,7 @@ extension MainMenu {
} }
@objc func togglePreset(sender: PresetMenuItem) { @objc func togglePreset(sender: PresetMenuItem) {
Task { Task { // Apply preset async
await sender.preset?.apply() await sender.preset?.apply()
} }
} }
@@ -193,7 +192,7 @@ extension MainMenu {
@objc func openPhpInfo() { @objc func openPhpInfo() {
asyncWithBusyUI { asyncWithBusyUI {
Task { Task { // Create temporary file and open the URL
let url = await Actions.createTempPhpInfoFile() let url = await Actions.createTempPhpInfoFile()
NSWorkspace.shared.open(url) NSWorkspace.shared.open(url)
} }
@@ -257,10 +256,8 @@ extension MainMenu {
/** /**
This async-friendly version of the switcher can be invoked elsewhere in the app: This async-friendly version of the switcher can be invoked elsewhere in the app:
``` ```
Task { await MainMenu.shared.switchToPhp("8.1")
await MainMenu.shared.switchToPhp("8.1") // thing to do after the switch
// thing to do after the switch
}
``` ```
Since this async function uses `withCheckedContinuation` Since this async function uses `withCheckedContinuation`
any code after will run only after the switcher is done. any code after will run only after the switcher is done.

View File

@@ -70,7 +70,7 @@ extension MainMenu {
App.shared.handlePhpConfigWatcher() App.shared.handlePhpConfigWatcher()
// Detect built-in and custom applications // Detect built-in and custom applications
detectApplications() await detectApplications()
// Load the rollback preset // Load the rollback preset
PresetHelper.loadRollbackPresetFromFile() PresetHelper.loadRollbackPresetFromFile()
@@ -135,7 +135,9 @@ extension MainMenu {
}) })
.show() .show()
Task { await startup() } Task { // An issue occurred, fire startup checks again after dismissal
await startup()
}
} }
} }
@@ -157,30 +159,28 @@ extension MainMenu {
/** /**
Detect which applications are installed that can be used to open a domain's source directory. Detect which applications are installed that can be used to open a domain's source directory.
*/ */
private func detectApplications() { private func detectApplications() async {
Task { Log.info("Detecting applications...")
Log.info("Detecting applications...")
App.shared.detectedApplications = await Application.detectPresetApplications() App.shared.detectedApplications = await Application.detectPresetApplications()
let customApps = Preferences.custom.scanApps?.map { appName in let customApps = Preferences.custom.scanApps?.map { appName in
return Application(appName, .user_supplied) return Application(appName, .user_supplied)
} ?? [] } ?? []
var detectedCustomApps: [Application] = [] var detectedCustomApps: [Application] = []
for app in customApps where await app.isInstalled() { for app in customApps where await app.isInstalled() {
detectedCustomApps.append(app) detectedCustomApps.append(app)
}
App.shared.detectedApplications
.append(contentsOf: detectedCustomApps)
let appNames = App.shared.detectedApplications.map { app in
return app.name
}
Log.info("Detected applications: \(appNames)")
} }
App.shared.detectedApplications
.append(contentsOf: detectedCustomApps)
let appNames = App.shared.detectedApplications.map { app in
return app.name
}
Log.info("Detected applications: \(appNames)")
} }
} }

View File

@@ -18,8 +18,7 @@ extension MainMenu {
// Mark as no longer busy // Mark as no longer busy
PhpEnv.shared.isBusy = false PhpEnv.shared.isBusy = false
// Reload the site list Task { // Things to do after reloading domain list data
Task {
await self.reloadDomainListData() await self.reloadDomainListData()
// Perform UI updates on main thread // Perform UI updates on main thread
@@ -55,7 +54,7 @@ extension MainMenu {
} }
@MainActor private func checkForPlatformIssues() { @MainActor private func checkForPlatformIssues() {
Task { Task { // Asynchronously check for platform issues
if await Valet.shared.hasPlatformIssues() { if await Valet.shared.hasPlatformIssues() {
Log.info("Composer platform issue(s) detected.") Log.info("Composer platform issue(s) detected.")
self.suggestFixMyComposer() self.suggestFixMyComposer()

View File

@@ -194,7 +194,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
func menuWillOpen(_ menu: NSMenu) { func menuWillOpen(_ menu: NSMenu) {
// Make sure the shortcut key does not trigger this when the menu is open // Make sure the shortcut key does not trigger this when the menu is open
App.shared.shortcutHotkey?.isPaused = true App.shared.shortcutHotkey?.isPaused = true
Task { Task { // Reload Homebrew services information asynchronously
await ServicesManager.loadHomebrewServices() await ServicesManager.loadHomebrewServices()
} }
} }

View File

@@ -32,7 +32,7 @@ class BetterAlert {
public func withPrimary( public func withPrimary(
text: String, text: String,
action: @escaping (BetterAlertVC) -> Void = { vc in action: @escaping (BetterAlertVC) -> Void = { vc in
vc.close(with: .alertFirstButtonReturn) DispatchQueue.main.async { vc.close(with: .alertFirstButtonReturn) }
} }
) -> Self { ) -> Self {
self.noticeVC.buttonPrimary.title = text self.noticeVC.buttonPrimary.title = text
@@ -43,7 +43,7 @@ class BetterAlert {
public func withSecondary( public func withSecondary(
text: String, text: String,
action: ((BetterAlertVC) -> Void)? = { vc in action: ((BetterAlertVC) -> Void)? = { vc in
vc.close(with: .alertSecondButtonReturn) DispatchQueue.main.async { vc.close(with: .alertSecondButtonReturn) }
} }
) -> Self { ) -> Self {
self.noticeVC.buttonSecondary.title = text self.noticeVC.buttonSecondary.title = text

View File

@@ -70,7 +70,7 @@ class BetterAlertVC: NSViewController {
} }
} }
public func close(with code: NSApplication.ModalResponse) { @MainActor public func close(with code: NSApplication.ModalResponse) {
self.view.window?.close() self.view.window?.close()
NSApplication.shared.stopModal(withCode: code) NSApplication.shared.stopModal(withCode: code)
} }

View File

@@ -19,7 +19,7 @@ extension ActivePhpInstallation {
This method actively presents a modal if said checks fails, so don't call this method too many times. This method actively presents a modal if said checks fails, so don't call this method too many times.
*/ */
public func notifyAboutBrokenPhpFpm() { public func notifyAboutBrokenPhpFpm() {
Task { Task { // Determine whether FPM status is configured correctly in the background
let fpmStatusConfiguredCorrectly = await self.checkPhpFpmStatus() let fpmStatusConfiguredCorrectly = await self.checkPhpFpmStatus()
if fpmStatusConfiguredCorrectly { if fpmStatusConfiguredCorrectly {

View File

@@ -28,9 +28,7 @@ class Preferences {
environmentVariables: [:] environmentVariables: [:]
) )
Task { Task { await loadCustomPreferences() }
await loadCustomPreferences()
}
} }
// MARK: - First Time Run // MARK: - First Time Run

View File

@@ -68,52 +68,52 @@ struct Preset: Codable, Equatable {
Applies a given preset. Applies a given preset.
*/ */
public func apply() async { public func apply() async {
Task { // Was this a rollback?
// Was this a rollback? let wasRollback = (self.name == "AutomaticRevertSnapshot")
let wasRollback = (self.name == "AutomaticRevertSnapshot")
// Save the preset that would revert this preset // Save the preset that would revert this preset
await self.persistRevert() await self.persistRevert()
// Apply the PHP version if is considered a valid version // Apply the PHP version if is considered a valid version
if self.version != nil { if self.version != nil {
if await !switchToPhpVersionIfValid() { if await !switchToPhpVersionIfValid() {
PresetHelper.rollbackPreset = nil PresetHelper.rollbackPreset = nil
await Actions.restartPhpFpm() await Actions.restartPhpFpm()
return return
}
} }
}
// Apply the configuration changes first // Apply the configuration changes first
for conf in configuration { for conf in configuration {
applyConfigurationValue(key: conf.key, value: conf.value ?? "") applyConfigurationValue(key: conf.key, value: conf.value ?? "")
}
// Apply the extension changes in-place afterward
for ext in extensions {
for foundExt in PhpEnv.phpInstall.extensions
where foundExt.name == ext.key && foundExt.enabled != ext.value {
Log.info("Toggling extension \(foundExt.name) in \(foundExt.file)")
await foundExt.toggle()
break
} }
}
// Apply the extension changes in-place afterward // Reload what rollback file exists
for ext in extensions { PresetHelper.loadRollbackPresetFromFile()
for foundExt in PhpEnv.phpInstall.extensions
where foundExt.name == ext.key && foundExt.enabled != ext.value {
Log.info("Toggling extension \(foundExt.name) in \(foundExt.file)")
await foundExt.toggle()
break
}
}
// Reload what rollback file exists // Restart PHP FPM process (also reloads menu, which will show the preset rollback)
PresetHelper.loadRollbackPresetFromFile() await Actions.restartPhpFpm()
// Restart PHP FPM process (also reloads menu, which will show the preset rollback)
await Actions.restartPhpFpm()
DispatchQueue.main.async {
// Show the correct notification // Show the correct notification
if wasRollback { if wasRollback {
await LocalNotification.send( LocalNotification.send(
title: "notification.preset_reverted_title".localized, title: "notification.preset_reverted_title".localized,
subtitle: "notification.preset_reverted_desc".localized, subtitle: "notification.preset_reverted_desc".localized,
preference: .notifyAboutPresets preference: .notifyAboutPresets
) )
} else { } else {
await LocalNotification.send( LocalNotification.send(
title: "notification.preset_applied_title".localized, title: "notification.preset_applied_title".localized,
subtitle: "notification.preset_applied_desc".localized(self.name), subtitle: "notification.preset_applied_desc".localized(self.name),
preference: .notifyAboutPresets preference: .notifyAboutPresets

View File

@@ -38,7 +38,7 @@ struct WarningListView: View {
HStack(alignment: .center, spacing: 15) { HStack(alignment: .center, spacing: 15) {
Button("warnings.refresh.button".localizedForSwiftUI) { Button("warnings.refresh.button".localizedForSwiftUI) {
Task { Task { // Reload warnings
await WarningManager.shared.checkEnvironment() await WarningManager.shared.checkEnvironment()
self.warnings = WarningManager.shared.warnings self.warnings = WarningManager.shared.warnings
} }

View File

@@ -45,8 +45,10 @@ class Testables {
: .fake(.binary) : .fake(.binary)
], ],
shellOutput: [ shellOutput: [
"sysctl -n sysctl.proc_translated"
: .instant("0"),
"id -un" "id -un"
: .instant("username"), : .instant("nicoverbruggen"),
"which node" "which node"
: .instant("/opt/homebrew/bin/node"), : .instant("/opt/homebrew/bin/node"),
"php -v" "php -v"
@@ -77,8 +79,12 @@ class Testables {
nicoverbruggen/cask nicoverbruggen/cask
shivammathur/php shivammathur/php
"""), """),
"chmod +x /Users/nicoverbruggen/.config/phpmon/bin/pm81"
: .instant(""),
"mkdir -p ~/.config/phpmon" "mkdir -p ~/.config/phpmon"
: .instant(""), : .instant(""),
"mkdir -p ~/.config/phpmon/bin"
: .instant(""),
"/opt/homebrew/bin/brew info php --json" "/opt/homebrew/bin/brew info php --json"
: .instant(ShellStrings.brewJson), : .instant(ShellStrings.brewJson),
"brew info shivammathur/php/php --json" "brew info shivammathur/php/php --json"
@@ -92,7 +98,8 @@ class Testables {
"/usr/bin/open -Ra \"Sublime Merge\"" "/usr/bin/open -Ra \"Sublime Merge\""
: .instant("Unable to find application named 'Sublime Merge'", .stdErr), : .instant("Unable to find application named 'Sublime Merge'", .stdErr),
"/usr/bin/open -Ra \"iTerm\"" "/usr/bin/open -Ra \"iTerm\""
: .instant("Unable to find application named 'iTerm'", .stdErr) : .instant("Unable to find application named 'iTerm'", .stdErr),
] ]
) )
} }