Skip to content

Commit

Permalink
Sync Update - d8d1058 [feat: ts template]
Browse files Browse the repository at this point in the history
Co-Authored-By: 寻 <[email protected]>
  • Loading branch information
Lakr233 and Innei committed Aug 23, 2022
1 parent 43941de commit b57d001
Show file tree
Hide file tree
Showing 17 changed files with 353 additions and 40 deletions.
8 changes: 6 additions & 2 deletions App/Action/Action.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

/* Begin PBXBuildFile section */
13C6C62128AF1BF0008ADA60 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 13C6C62328AF1BF0008ADA60 /* Localizable.strings */; };
1F6BCF0628B219B400C2B417 /* Template+Node.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F6BCF0528B219B400C2B417 /* Template+Node.swift */; };
5001740128AA557100FF9B99 /* UserDefault.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5001740028AA557100FF9B99 /* UserDefault.swift */; };
5001740528AA818500FF9B99 /* DiagnosticLogView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5001740428AA818500FF9B99 /* DiagnosticLogView.swift */; };
5006F55E28A9663100C8ADBE /* Notification.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5006F55D28A9663100C8ADBE /* Notification.swift */; };
Expand Down Expand Up @@ -61,6 +62,7 @@
/* Begin PBXFileReference section */
13C6C62228AF1BF0008ADA60 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = "<group>"; };
13C6C62428AF1DEB008ADA60 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/Localizable.strings"; sourceTree = "<group>"; };
1F6BCF0528B219B400C2B417 /* Template+Node.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Template+Node.swift"; sourceTree = "<group>"; };
5001740028AA557100FF9B99 /* UserDefault.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserDefault.swift; sourceTree = "<group>"; };
5001740428AA818500FF9B99 /* DiagnosticLogView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticLogView.swift; sourceTree = "<group>"; };
5006F55D28A9663100C8ADBE /* Notification.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notification.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -204,6 +206,7 @@
505A10A728A95EC200D46DB3 /* ActionManager+Template.swift */,
50A7D80228ACD14B004F0B34 /* Template+Executable.swift */,
5067392528AB786A003A6A9C /* Template+Swift.swift */,
1F6BCF0528B219B400C2B417 /* Template+Node.swift */,
);
path = ActionModuleTemplates;
sourceTree = "<group>";
Expand Down Expand Up @@ -504,6 +507,7 @@
502E87A528AA95BF00CAB5E1 /* ModuleElementView.swift in Sources */,
5053CF9A288F9A5E00A92822 /* ModuleCreateView.swift in Sources */,
505A10A828A95EC200D46DB3 /* ActionManager+Template.swift in Sources */,
1F6BCF0628B219B400C2B417 /* Template+Node.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -664,7 +668,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 12.0;
MARKETING_VERSION = 1.1;
MARKETING_VERSION = 1.4;
PRODUCT_BUNDLE_IDENTIFIER = wiki.qaq.Action;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
Expand Down Expand Up @@ -697,7 +701,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 12.0;
MARKETING_VERSION = 1.1;
MARKETING_VERSION = 1.4;
PRODUCT_BUNDLE_IDENTIFIER = wiki.qaq.Action;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
Expand Down
2 changes: 1 addition & 1 deletion App/Action/Action/Application/License.txt
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,4 @@ SOFTWARE.

==========

Updated: 2022-08-19
Updated: 2022-08-23
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"Edit Action" = "编辑自动化模块";
"Save" = "保存";
"Compiling Source" = "正在编译模块...";
"Compile Finished" = "编译完成";
"Broken Module" = "损坏的模块";
"Delete" = "删除";
"Close" = "关闭";
Expand Down
4 changes: 2 additions & 2 deletions App/Action/Action/Backend/Action/ActionManager+Module.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ extension ActionManager {
invalidateBinaryCache(forAction: id)
}

func issueCompile(forAction actionId: Action.ID) -> Result<Void, GenericActionError> {
func issueCompile(forAction actionId: Action.ID, output: @escaping (String) -> Void) -> Result<Void, GenericActionError> {
assert(!Thread.isMainThread)
guard let action = self[actionId] else {
return .failure(.brokenResources)
}
let result = action.template
.obtainTemplateDetails()
.compileModule(id: actionId) { print($0) }
.compileModule(id: actionId, output: output)
return result
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,14 @@ extension ActionManager {
case executableSwift

case swift
case node

func obtainTemplateDetails() -> ModuleTemplate {
switch self {
case .executable: return ModuleTemplateExecutable()
case .executableSwift: return ModuleTemplateExecutableSwift()
case .swift: return ModuleTemplateSwift()
case .node: return ModuleTemplateExecutableNode()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//
// Template+Node.swift
// Action
//
// Created by Innei on 2022/8/21.
//

import AuxiliaryExecute
import Foundation

extension ActionManager {
class ModuleTemplateExecutableNode: ModuleTemplateExecutable {
override func getLanguage() -> String { "Source - Node" }
override func getTemplateBundleName() -> String { "SourceNode" }
override func getBuildHint() -> String { "To build Node Module, node and it's tool is required. Install them yourself." }

override func openDesignatedEditor(id: ActionManager.Action.ID) -> Result<Void, ActionManager.GenericActionError> {
let url = ActionManager.shared
.actionModuleBaseUrl
.appendingPathComponent(id.uuidString)

let recipe = AuxiliaryExecute.spawn(
command: "/bin/zsh",
args: ["-c", "code \(url.path)"]
)

guard recipe.exitCode == 0 else {
return .failure(.designatedEditorMissing)
}

return .success
}

override func compileModule(id: ActionManager.Action.ID, output: @escaping (String) -> Void) -> Result<Void, ActionManager.GenericActionError> {
guard let action = ActionManager.shared[id] else {
return .failure(.brokenResources)
}

let temporaryDir = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(UUID().uuidString)
try? FileManager.default.removeItem(at: temporaryDir)
defer {
try? FileManager.default.removeItem(at: temporaryDir)
}

do {
output("[*] starting compiler at \(temporaryDir.path)\n")
try FileManager.default.createDirectory(at: temporaryDir, withIntermediateDirectories: true)
try Executor.shared.unarchiveTar(at: getTemplateBundleURL(), toDest: temporaryDir)
let validatedSourcePathComponents = "src"
let userSrc = ActionManager.shared
.actionModuleBaseUrl
.appendingPathComponent(action.id.uuidString)
.appendingPathComponent(validatedSourcePathComponents)
let targetSrc = temporaryDir
.appendingPathComponent(validatedSourcePathComponents)
output("[*] copying user source from \(userSrc.path) to \(targetSrc.path)\n")
try FileManager.default.removeItem(at: targetSrc)
try FileManager.default.copyItem(at: userSrc, to: targetSrc)
FileManager.default.createFile(
atPath: temporaryDir.appendingPathComponent(".action").path,
contents: nil
)
} catch {
output("[E] \(error.localizedDescription)")
return .failure(.permissionDenied)
}

output("[*] calling compiler script\n")
let compileScript = temporaryDir
.appendingPathComponent(".supplement")
.appendingPathComponent("compile.sh")
let recipe = executeZshScript(atLocation: compileScript, output: output)
guard recipe.exitCode == 0 else {
return .failure(.compilerError)
}

let binaryLocation = temporaryDir
.appendingPathComponent("dist")
.appendingPathComponent("index.js")
guard FileManager.default.fileExists(atPath: binaryLocation.path) else {
return .failure(.permissionDenied)
}

output("[*] compiled binary at \(binaryLocation.path)\n")
ActionManager.shared.registerBianry(forAction: action.id, binary: binaryLocation)
return .success
}

override func executeModule(id: ActionManager.Action.ID, withPasteboardEvent event: PasteboardManager.PEvent, output: @escaping (String) -> Void) -> Result<ActionManager.ActionRecipeData, ActionManager.GenericActionError> {
assert(!Thread.isMainThread)

guard let action = ActionManager.shared[id] else {
return .failure(.brokenResources)
}

let script = ActionManager.shared
.actionBinaryBaseUrl
.appendingPathComponent(action.id.uuidString)

guard let argument = ArgumentData(
focusAppID: event.app?.bundleIdentifier,
focusAppName: event.app?.name,
pasteboardContent: event.content
)
.compileBase64()
else {
return .failure(.brokenResources)
}

print("[*] executing action \(id.uuidString)")

var resultData: ActionRecipeData?

let recipe = AuxiliaryExecute.spawn(
command: "/bin/zsh",
args: ["-c", "node \(script.path)"],
environment: ["Communicator_Message": argument],
timeout: Double(action.timeout),
output: output
)

var lastLine = recipe.stderr
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.last?
.trimmingCharacters(in: .whitespaces)
?? ""
let prefix = "ActionBee-Result-Recipe://"
if lastLine.hasPrefix(prefix) {
lastLine.removeFirst(prefix.count)
}
if let base64 = Data(base64Encoded: lastLine) {
resultData = ActionRecipeData.retrieve(withData: base64)
}

guard let result = resultData else {
return .failure(.invalidResponse)
}

return .success(result)
}

func executeZshScript(atLocation: URL, output: @escaping (String) -> Void = { _ in }) -> AuxiliaryExecute.ExecuteRecipe {
AuxiliaryExecute.spawn(
command: "/bin/zsh",
args: ["-c", atLocation.path],
output: output
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ extension ActionManager {
}

do {
output("[*] starting compiler at \(temporaryDir.path)")
output("[*] starting compiler at \(temporaryDir.path)\n")
try FileManager.default.createDirectory(at: temporaryDir, withIntermediateDirectories: true)
try Executor.shared.unarchiveTar(at: getTemplateBundleURL(), toDest: temporaryDir)
let validatedSourcePathComponents = "Source"
Expand All @@ -55,29 +55,23 @@ extension ActionManager {
.appendingPathComponent(validatedSourcePathComponents)
let targetSrc = temporaryDir
.appendingPathComponent(validatedSourcePathComponents)
output(
"""
[*] copying user source
from \(userSrc.path)
to \(targetSrc.path)
"""
)
output("[*] copying user source from \(userSrc.path) to \(targetSrc.path)\n")
try FileManager.default.removeItem(at: targetSrc)
try FileManager.default.copyItem(at: userSrc, to: targetSrc)
FileManager.default.createFile(
atPath: temporaryDir.appendingPathComponent(".action").path,
contents: nil
)
} catch {
print("[E] \(error.localizedDescription)")
output("[E] \(error.localizedDescription)")
return .failure(.permissionDenied)
}

output("[*] calling compiler script")
output("[*] calling compiler script\n")
let compileScript = temporaryDir
.appendingPathComponent(".supplement")
.appendingPathComponent("compile.sh")
let recipe = executeBashScript(atLocation: compileScript, output: output)
let recipe = executeZshScript(atLocation: compileScript, output: output)
guard recipe.exitCode == 0 else {
return .failure(.compilerError)
}
Expand All @@ -89,14 +83,14 @@ extension ActionManager {
return .failure(.permissionDenied)
}

output("[*] compiled binary at \(binaryLocation.path)")
output("[*] compiled binary at \(binaryLocation.path)\n")
ActionManager.shared.registerBianry(forAction: action.id, binary: binaryLocation)
return .success
}

func executeBashScript(atLocation: URL, output: @escaping (String) -> Void = { _ in }) -> AuxiliaryExecute.ExecuteRecipe {
func executeZshScript(atLocation: URL, output: @escaping (String) -> Void = { _ in }) -> AuxiliaryExecute.ExecuteRecipe {
AuxiliaryExecute.spawn(
command: "/bin/bash",
command: "/bin/zsh",
args: ["-c", atLocation.path],
output: output
)
Expand Down
22 changes: 22 additions & 0 deletions App/Action/Action/Backend/Executor/Executor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,28 @@ final class Executor {
}
print("[*] whoami \(username)")

do {
let findEnv = AuxiliaryExecute.spawn(
command: "/bin/zsh",
args: ["-c", "source ~/.zshrc 1>/dev/null 2>/dev/null && echo $PATH"]
)
let env = findEnv.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
print("[*] setting up env PATH value \(findEnv.stdout)")
let envPathBuilder = env.components(separatedBy: ":")
.filter { FileManager.default.fileExists(atPath: $0) }
let origPathBuilder = (
ProcessInfo
.processInfo
.environment["PATH"] ?? ""
)
.components(separatedBy: ":")
.filter { FileManager.default.fileExists(atPath: $0) }
let newPath = Array(Set(envPathBuilder + origPathBuilder))
.joined(separator: ":")

setenv("PATH", newPath, 1)
}

try? FileManager.default.createDirectory(at: executorDir, withIntermediateDirectories: true)
}

Expand Down
Loading

0 comments on commit b57d001

Please sign in to comment.