Shell.swift 2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17 18 19
#if os(Linux)
import Glibc
#else
import Darwin
#endif
20

21
import atfoundation
22 23 24 25 26 27 28 29
import atpkg

/**
 * The shell tool forks a new process with `/bin/sh -c`. Any arguments specified
 * within the task will also be sent across.
 * If the tool returns with an error code of non-zero, the tool will fail.
 */
final class Shell : Tool {
Drew's avatar
Drew committed
30
    func run(task: Task, toolchain: String) {
Drew's avatar
Drew committed
31
        setenv("ATBUILD_PLATFORM", "\(Platform.targetPlatform)", 1)
32
        setenv("ATBUILD_USER_PATH", userPath().description, 1)
33 34 35
        if let version = task.package.version {
            setenv("ATBUILD_PACKAGE_VERSION", version, 1)
        }
36
        guard var script = task["script"]?.string else { fatalError("Invalid 'script' argument to shell tool.") }
37
        script = evaluateSubstitutions(input: script, package: task.package)
38
        do {
39 40 41 42 43 44 45 46 47
            let oldPath = try FS.getWorkingDirectory()
            defer {
                do {
                    try FS.changeWorkingDirectory(path: oldPath)
                } catch {
                    print("Can not revert to previous working directory '\(oldPath)': \(error)")
                    exit(42)
                }
            }
48

49
            try FS.changeWorkingDirectory(path: task.importedPath)
50

51
            anarchySystem("/bin/sh -c \"\(script)\"")
52 53 54
        } catch {
            print("Can not change working directory to '\(task.importedPath)': \(error)")
            exit(42)
55 56 57
        }
    }
}