Skip to content

[POSIX] Kill getenv and adopt Process.env #2052

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

Merged
merged 3 commits into from
Mar 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -251,14 +251,10 @@ let package = Package(
// package dependency like this but there is no other good way of expressing
// this right now.

#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import class Foundation.ProcessInfo

if getenv("SWIFTPM_BOOTSTRAP") == nil {
if getenv("SWIFTCI_USE_LOCAL_DEPS") == nil {
if ProcessInfo.processInfo.environment["SWIFTPM_BOOTSTRAP"] == nil {
if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [
.package(url: "https://github.com/apple/swift-llbuild.git", .branch("master")),
]
Expand All @@ -272,7 +268,7 @@ if getenv("SWIFTPM_BOOTSTRAP") == nil {
package.targets.first(where: { $0.name == "SPMLLBuild" })!.dependencies += ["llbuildSwift"]
}

if getenv("SWIFTPM_BUILD_PACKAGE_EDITOR") != nil {
if ProcessInfo.processInfo.environment["SWIFTPM_BUILD_PACKAGE_EDITOR"] != nil {
package.targets += [
.target(name: "SPMPackageEditor", dependencies: ["Workspace", "SwiftSyntax"]),
.target(name: "swiftpm-manifest-tool", dependencies: ["SPMPackageEditor"]),
Expand Down
3 changes: 1 addition & 2 deletions Sources/Basic/Process.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import class Foundation.ProcessInfo

import enum POSIX.SystemError
import func POSIX.getenv
import SPMLibc
import Dispatch

Expand Down Expand Up @@ -239,7 +238,7 @@ public final class Process: ObjectIdentifierProtocol {
}
// FIXME: This can be cached.
let envSearchPaths = getEnvSearchPaths(
pathString: getenv("PATH"),
pathString: Process.env["PATH"],
currentWorkingDirectory: localFileSystem.currentWorkingDirectory
)
// Lookup and cache the executable path.
Expand Down
3 changes: 1 addition & 2 deletions Sources/Basic/TemporaryFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
*/

import SPMLibc
import func POSIX.getenv
import class Foundation.FileHandle
import class Foundation.FileManager

Expand Down Expand Up @@ -56,7 +55,7 @@ public func determineTempDirectory(_ dir: AbsolutePath? = nil) throws -> Absolut
/// Returns temporary directory location by searching relevant env variables.
/// Evaluates once per execution.
private var cachedTempDirectory: AbsolutePath = {
return AbsolutePath(getenv("TMPDIR") ?? getenv("TEMP") ?? getenv("TMP") ?? "/tmp/")
return AbsolutePath(Process.env["TMPDIR"] ?? Process.env["TEMP"] ?? Process.env["TMP"] ?? "/tmp/")
}()

/// This class is basically a wrapper over posix's mkstemps() function to creates disposable files.
Expand Down
5 changes: 2 additions & 3 deletions Sources/Basic/TerminalController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
*/

import SPMLibc
import func POSIX.getenv

/// A class to have better control on tty output streams: standard output and standard error.
/// Allows operations like cursor movement and colored text output on tty.
Expand Down Expand Up @@ -95,7 +94,7 @@ public final class TerminalController {

/// Computes the terminal type of the stream.
public static func terminalType(_ stream: LocalFileOutputByteStream) -> TerminalType {
if POSIX.getenv("TERM") == "dumb" {
if Process.env["TERM"] == "dumb" {
return .dumb
}
let isTTY = isatty(fileno(stream.filePointer)) != 0
Expand All @@ -108,7 +107,7 @@ public final class TerminalController {
/// - Returns: Current width of terminal if it was determinable.
public static func terminalWidth() -> Int? {
// Try to get from environment.
if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) {
if let columns = Process.env["COLUMNS"], let width = Int(columns) {
return width
}

Expand Down
3 changes: 2 additions & 1 deletion Sources/Build/BuildDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,8 @@ extension SwiftCompilerMessage {
}

private func generateProgressText(prefix: String, file: String) -> String {
let relativePath = AbsolutePath(file).relative(to: AbsolutePath(getcwd()))
// FIXME: Eliminate cwd from here.
let relativePath = AbsolutePath(file).relative(to: localFileSystem.currentWorkingDirectory!)
return "\(prefix) \(relativePath)"
}
}
3 changes: 1 addition & 2 deletions Sources/Build/BuildPlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import SPMUtility
import PackageModel
import PackageGraph
import PackageLoading
import func POSIX.getenv

public struct BuildParameters {

Expand All @@ -37,7 +36,7 @@ public struct BuildParameters {
let base: AbsolutePath
// FIXME: We use this hack to let swiftpm's functional test use shared
// cache so it doesn't become painfully slow.
if getenv("IS_SWIFTPM_TEST") != nil {
if Process.env["IS_SWIFTPM_TEST"] != nil {
base = BuildParameters.swiftpmTestCache
} else {
base = buildPath
Expand Down
4 changes: 2 additions & 2 deletions Sources/Commands/SwiftTool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -825,8 +825,8 @@ private func findPackageRoot() -> AbsolutePath? {
/// Returns the build path from the environment, if present.
private func getEnvBuildPath(workingDir: AbsolutePath) -> AbsolutePath? {
// Don't rely on build path from env for SwiftPM's own tests.
guard POSIX.getenv("IS_SWIFTPM_TEST") == nil else { return nil }
guard let env = POSIX.getenv("SWIFTPM_BUILD_DIR") else { return nil }
guard Process.env["IS_SWIFTPM_TEST"] == nil else { return nil }
guard let env = Process.env["SWIFTPM_BUILD_DIR"] else { return nil }
return AbsolutePath(env, relativeTo: workingDir)
}

Expand Down
3 changes: 0 additions & 3 deletions Sources/POSIX/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ public enum SystemError: Swift.Error {
case unlink(Int32, String)
case unsetenv(Int32, String)
case waitpid(Int32)
case usleep(Int32)
}

import func SPMLibc.strerror_r
Expand Down Expand Up @@ -112,8 +111,6 @@ extension SystemError: CustomStringConvertible {
return "unsetenv error: \(strerror(errno)): \(key)"
case .waitpid(let errno):
return "waitpid error: \(strerror(errno))"
case .usleep(let errno):
return "usleep error: \(strerror(errno))"
}
}
}
19 changes: 0 additions & 19 deletions Sources/POSIX/chdir.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,7 @@ import var SPMLibc.errno
Causes the named directory to become the current working directory.
*/
public func chdir(_ path: String) throws {
if memo == nil {
let argv0 = try realpath(CommandLine.arguments.first!)
let cwd = try realpath(getcwd())
memo = (argv0: argv0, wd: cwd)
}

guard SPMLibc.chdir(path) == 0 else {
throw SystemError.chdir(errno, path)
}
}

private var memo: (argv0: String, wd: String)?

/**
The initial working directory before any calls to POSIX.chdir.
*/
public func getiwd() -> String {
return memo?.wd ?? getcwd()
}

public var argv0: String {
return memo?.argv0 ?? CommandLine.arguments.first!
}
1 change: 1 addition & 0 deletions Sources/POSIX/env.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import func SPMLibc.setenv
import func SPMLibc.unsetenv
import var SPMLibc.errno

@available(*, deprecated, message: "Use Foundation.ProcessInfo instead.")
public func getenv(_ key: String) -> String? {
let out = SPMLibc.getenv(key)
return out == nil ? nil : String(validatingUTF8: out!) //FIXME locale may not be UTF8
Expand Down
41 changes: 0 additions & 41 deletions Sources/POSIX/getcwd.swift

This file was deleted.

17 changes: 0 additions & 17 deletions Sources/POSIX/usleep.swift

This file was deleted.

3 changes: 1 addition & 2 deletions Sources/SPMUtility/PkgConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import Basic
import Foundation
import func POSIX.getenv

public enum PkgConfigError: Swift.Error, CustomStringConvertible {
case couldNotFindConfigFile
Expand Down Expand Up @@ -173,7 +172,7 @@ public struct PkgConfig {
}

private static var envSearchPaths: [AbsolutePath] {
if let configPath = POSIX.getenv("PKG_CONFIG_PATH") {
if let configPath = Process.env["PKG_CONFIG_PATH"] {
return configPath.split(separator: ":").map({ AbsolutePath(String($0)) })
}
return []
Expand Down
5 changes: 3 additions & 2 deletions Sources/TestSupport/misc.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import func XCTest.XCTFail
import class Foundation.NSDate
import class Foundation.Thread

import Basic
import PackageGraph
Expand Down Expand Up @@ -242,7 +243,7 @@ public func loadPackageGraph(
/// - throws: errors thrown in `body`, POSIX.SystemError.setenv and
/// POSIX.SystemError.unsetenv
public func withCustomEnv(_ env: [String: String], body: () throws -> Void) throws {
let state = Array(env.keys).map({ ($0, getenv($0)) })
let state = Array(env.keys).map({ ($0, Process.env[$0]) })
let restore = {
for (key, value) in state {
if let value = value {
Expand Down Expand Up @@ -270,7 +271,7 @@ public func waitForFile(_ path: AbsolutePath) -> Bool {
let endTime = NSDate().timeIntervalSince1970 + 2
while NSDate().timeIntervalSince1970 < endTime {
// Sleep for a bit so we don't burn a lot of CPU.
try? usleep(microSeconds: 10000)
Thread.sleep(forTimeInterval: 0.01)
if localFileSystem.exists(path) {
return true
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Workspace/Destination.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public struct Destination {
#if os(macOS)
// Get the SDK.
let sdkPath: AbsolutePath
if let value = lookupExecutablePath(filename: getenv("SDKROOT")) {
if let value = lookupExecutablePath(filename: Process.env["SDKROOT"]) {
sdkPath = value
} else {
// No value in env, so search for it.
Expand Down
6 changes: 3 additions & 3 deletions Sources/Workspace/UserToolchain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public final class UserToolchain: Toolchain {
}

private static func lookup(variable: String, searchPaths: [AbsolutePath]) -> AbsolutePath? {
return lookupExecutablePath(filename: getenv(variable), searchPaths: searchPaths)
return lookupExecutablePath(filename: Process.env[variable], searchPaths: searchPaths)
}

/// Environment to use when looking up tools.
Expand Down Expand Up @@ -198,7 +198,7 @@ public final class UserToolchain: Toolchain {

// Get the search paths from PATH.
let searchPaths = getEnvSearchPaths(
pathString: getenv("PATH"), currentWorkingDirectory: localFileSystem.currentWorkingDirectory)
pathString: Process.env["PATH"], currentWorkingDirectory: localFileSystem.currentWorkingDirectory)

self.envSearchPaths = searchPaths

Expand Down Expand Up @@ -236,7 +236,7 @@ public final class UserToolchain: Toolchain {
var pdLibDir = binDir.parentDirectory.appending(components: "lib", "swift", "pm")

// Look for an override in the env.
if let pdLibDirEnvStr = getenv("SWIFTPM_PD_LIBS") {
if let pdLibDirEnvStr = Process.env["SWIFTPM_PD_LIBS"] {
// We pick the first path which exists in a colon seperated list.
let paths = pdLibDirEnvStr.split(separator: ":").map(String.init)
for pathString in paths {
Expand Down
6 changes: 0 additions & 6 deletions Tests/BasicTests/PathShimTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,6 @@ class PathShimTests : XCTestCase {
// Check that there's no error if we try to create the directory again.
try! makeDirectories(dirPath)
}

func testCurrentWorkingDirectory() {
// Test against what POSIX returns, at least for now.
let cwd = localFileSystem.currentWorkingDirectory!
XCTAssertEqual(cwd, AbsolutePath(getcwd()))
}
}

class WalkTests : XCTestCase {
Expand Down
1 change: 0 additions & 1 deletion Tests/BasicTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,6 @@ extension PathShimTests {
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__PathShimTests = [
("testCurrentWorkingDirectory", testCurrentWorkingDirectory),
("testRescursiveDirectoryCreation", testRescursiveDirectoryCreation),
("testResolvingSymlinks", testResolvingSymlinks),
]
Expand Down
3 changes: 2 additions & 1 deletion Tests/CommandsTests/RunToolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ final class RunToolTests: XCTestCase {
func testFileDeprecation() throws {
fixture(name: "Miscellaneous/EchoExecutable") { path in
let filePath = AbsolutePath(path, "Sources/secho/main.swift").pathString
let cwd = localFileSystem.currentWorkingDirectory!
XCTAssertEqual(try execute([filePath, "1", "2"], packagePath: path), """
"\(getcwd())" "1" "2"
"\(cwd)" "1" "2"
warning: 'swift run file.swift' command to interpret swift files is deprecated; use 'swift file.swift' instead

""")
Expand Down
7 changes: 4 additions & 3 deletions Tests/FunctionalTests/MiscellaneousTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import PackageModel
import SPMUtility
import SPMLibc
import class Foundation.ProcessInfo
import class Foundation.Thread
import Workspace

typealias ProcessID = Basic.Process.ProcessID
Expand Down Expand Up @@ -125,7 +126,7 @@ class MiscellaneousTestCase: XCTestCase {

// we need to sleep at least one second otherwise
// llbuild does not realize the file has changed
sleep(1)
Thread.sleep(forTimeInterval: 1)

try localFileSystem.writeFileContents(prefix.appending(components: "Bar", "Bar.swift"), bytes: "public let bar = \"Goodbye\"\n")

Expand All @@ -150,7 +151,7 @@ class MiscellaneousTestCase: XCTestCase {

// we need to sleep at least one second otherwise
// llbuild does not realize the file has changed
sleep(1)
Thread.sleep(forTimeInterval: 1)

let path = try SwiftPMProduct.packagePath(for: "FisherYates", packageRoot: packageRoot)
try localFileSystem.chmod(.userWritable, path: path, options: [.recursive])
Expand All @@ -177,7 +178,7 @@ class MiscellaneousTestCase: XCTestCase {

// we need to sleep at least one second otherwise
// llbuild does not realize the file has changed
sleep(1)
Thread.sleep(forTimeInterval: 1)

let path = try SwiftPMProduct.packagePath(for: "dep1", packageRoot: packageRoot)
try localFileSystem.chmod(.userWritable, path: path, options: [.recursive])
Expand Down
Loading