setup-cpp/packages/untildify-user/src/index.ts

40 lines
972 B
TypeScript
Raw Normal View History

2024-01-23 08:23:22 +08:00
import { homedir } from "os"
2024-04-03 15:15:43 +08:00
import { join } from "path"
2024-08-07 14:44:32 +08:00
import { isSudo } from "admina"
2024-01-23 08:23:22 +08:00
export function userHomeDir() {
if (isSudo() && typeof process.env.SUDO_USER === "string" && process.env.SUDO_USER !== "") {
// use the user profile even if root
if (process.platform === "darwin") {
2024-01-23 08:23:22 +08:00
return join("/Users/", process.env.SUDO_USER)
} else {
2024-01-23 08:23:22 +08:00
return join("/home/", process.env.SUDO_USER)
}
} else {
2024-01-23 08:23:22 +08:00
const maybeHomeDir = homedir()
if (maybeHomeDir === "") {
return undefined
}
return maybeHomeDir
}
}
const tildeRegex = /^~(?=$|\/|\\)/
/**
* Replaces a tilde with the user's home directory
*
* @example UntildifyUser("~/foo") // /home/user/foo
*
* @param path The path to untildify
* @returns The untildified path
*/
export function untildifyUser(path: string) {
const maybeHomeDir = userHomeDir()
if (maybeHomeDir === undefined) {
return path
}
2024-01-23 08:23:22 +08:00
return path.replace(tildeRegex, maybeHomeDir)
}