2022-01-20 03:58:10 +08:00
|
|
|
import { join } from "path"
|
2022-08-26 18:09:19 +08:00
|
|
|
import { isSudo } from "admina"
|
2024-01-23 08:23:22 +08:00
|
|
|
import { homedir } from "os"
|
2022-01-20 03:58:10 +08:00
|
|
|
|
2024-01-23 08:23:22 +08:00
|
|
|
export function userHomeDir() {
|
|
|
|
if (isSudo() && typeof process.env.SUDO_USER === "string" && process.env.SUDO_USER !== "") {
|
2022-01-20 03:58:10 +08:00
|
|
|
// use the user profile even if root
|
2022-04-25 07:24:58 +08:00
|
|
|
if (process.platform === "darwin") {
|
2024-01-23 08:23:22 +08:00
|
|
|
return join("/Users/", process.env.SUDO_USER)
|
2022-04-25 07:24:58 +08:00
|
|
|
} else {
|
2024-01-23 08:23:22 +08:00
|
|
|
return join("/home/", process.env.SUDO_USER)
|
2022-04-25 07:24:58 +08:00
|
|
|
}
|
2022-01-20 03:58:10 +08:00
|
|
|
} 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
|
2022-01-20 03:58:10 +08:00
|
|
|
}
|
2024-01-23 08:23:22 +08:00
|
|
|
|
|
|
|
return path.replace(tildeRegex, maybeHomeDir)
|
2022-01-20 03:58:10 +08:00
|
|
|
}
|