This commit is contained in:
Reinier Criel 2026-04-13 11:01:45 -07:00
parent 1cf8fd1241
commit d064d46668
32 changed files with 429 additions and 400 deletions

View file

@ -16,6 +16,7 @@ import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import { knownAikidoTools } from "../src/shell-integration/helpers.js";
import { getInstalledSafeChainDir } from "../src/installLocation.js";
/** @type {string} */
// This checks the current file's dirname in a way that's compatible with:
@ -67,6 +68,17 @@ if (tool) {
teardownDirectories();
} else if (command === "setup-ci") {
setupCi();
} else if (command === "get-install-dir") {
const installDir = getInstalledSafeChainDir();
if (!installDir) {
ui.writeError(
"Install directory is only available for packaged safe-chain binaries.",
);
process.exit(1);
}
ui.writeInformation(installDir);
process.exit(0);
} else if (command === "--version" || command === "-v" || command === "-v") {
(async () => {
ui.writeInformation(`Current safe-chain version: ${await getVersion()}`);
@ -88,7 +100,7 @@ function writeHelp() {
ui.writeInformation(
`Available commands: ${chalk.cyan("setup")}, ${chalk.cyan(
"teardown",
)}, ${chalk.cyan("setup-ci")}, ${chalk.cyan("help")}, ${chalk.cyan(
)}, ${chalk.cyan("setup-ci")}, ${chalk.cyan("get-install-dir")}, ${chalk.cyan("help")}, ${chalk.cyan(
"--version",
)}`,
);
@ -108,6 +120,11 @@ function writeHelp() {
"safe-chain setup-ci",
)}: This will setup safe-chain for CI environments by creating shims and modifying the PATH.`,
);
ui.writeInformation(
`- ${chalk.cyan(
"safe-chain get-install-dir",
)}: Print the install directory for packaged safe-chain binaries.`,
);
ui.writeInformation(
`- ${chalk.cyan("safe-chain --version")} (or ${chalk.cyan(
"-v",

View file

@ -3,7 +3,7 @@ import path from "path";
import os from "os";
import { ui } from "../environment/userInteraction.js";
import { getEcoSystem } from "./settings.js";
import { getSafeChainDir } from "./environmentVariables.js";
import { getSafeChainBaseDir } from "./safeChainDir.js";
/**
* @typedef {Object} SafeChainConfig
@ -305,7 +305,7 @@ function getConfigFilePath() {
* @returns {string}
*/
export function getSafeChainDirectory() {
const safeChainDir = getSafeChainDir() ?? path.join(os.homedir(), ".safe-chain");
const safeChainDir = getSafeChainBaseDir();
if (!fs.existsSync(safeChainDir)) {
fs.mkdirSync(safeChainDir, { recursive: true });

View file

@ -55,14 +55,3 @@ export function getMinimumPackageAgeExclusions() {
export function getMalwareListBaseUrl() {
return process.env.SAFE_CHAIN_MALWARE_LIST_BASE_URL;
}
/**
* Gets the safe-chain base directory from environment variable.
* When set, all safe-chain data (bin, shims, scripts) will be placed under this directory
* instead of the default ~/.safe-chain, enabling system-wide installations.
* Example: "/usr/local/.safe-chain"
* @returns {string | undefined}
*/
export function getSafeChainDir() {
return process.env.SAFE_CHAIN_DIR;
}

View file

@ -1,30 +0,0 @@
import { describe, it, beforeEach, afterEach } from "node:test";
import assert from "node:assert";
const { getSafeChainDir } = await import("./environmentVariables.js");
describe("getSafeChainDir", () => {
let original;
beforeEach(() => {
original = process.env.SAFE_CHAIN_DIR;
});
afterEach(() => {
if (original !== undefined) {
process.env.SAFE_CHAIN_DIR = original;
} else {
delete process.env.SAFE_CHAIN_DIR;
}
});
it("returns undefined when SAFE_CHAIN_DIR is not set", () => {
delete process.env.SAFE_CHAIN_DIR;
assert.strictEqual(getSafeChainDir(), undefined);
});
it("returns the value of SAFE_CHAIN_DIR when set", () => {
process.env.SAFE_CHAIN_DIR = "/usr/local/.safe-chain";
assert.strictEqual(getSafeChainDir(), "/usr/local/.safe-chain");
});
});

View file

@ -0,0 +1,10 @@
import os from "os";
import path from "path";
import { getInstalledSafeChainDir } from "../installLocation.js";
/**
* @returns {string}
*/
export function getSafeChainBaseDir() {
return getInstalledSafeChainDir() ?? path.join(os.homedir(), ".safe-chain");
}

View file

@ -0,0 +1,39 @@
import path from "path";
/**
* @param {string} executablePath
* @returns {string | undefined}
*/
export function deriveInstallDirFromExecutablePath(executablePath) {
if (!executablePath) {
return undefined;
}
const pathLibrary = executablePath.includes("\\") ? path.win32 : path.posix;
const executableDir = pathLibrary.dirname(executablePath);
if (pathLibrary.basename(executableDir) !== "bin") {
return undefined;
}
return pathLibrary.dirname(executableDir);
}
/**
* Returns the install directory for a packaged safe-chain binary.
* Custom installation directories only apply to packaged binary installs.
* For npm/global/dev-script executions this intentionally returns undefined,
* which causes callers to fall back to the default ~/.safe-chain layout.
*
* @param {{ isPackaged?: boolean, executablePath?: string }} [options]
* @returns {string | undefined}
*/
export function getInstalledSafeChainDir(options = {}) {
const isPackaged = options.isPackaged ?? Boolean(process.pkg);
if (!isPackaged) {
return undefined;
}
return deriveInstallDirFromExecutablePath(
options.executablePath ?? process.execPath,
);
}

View file

@ -0,0 +1,51 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import {
deriveInstallDirFromExecutablePath,
getInstalledSafeChainDir,
} from "./installLocation.js";
describe("deriveInstallDirFromExecutablePath", () => {
it("derives the install dir from a Unix binary path", () => {
assert.strictEqual(
deriveInstallDirFromExecutablePath("/usr/local/.safe-chain/bin/safe-chain"),
"/usr/local/.safe-chain",
);
});
it("derives the install dir from a Windows binary path", () => {
assert.strictEqual(
deriveInstallDirFromExecutablePath("C:\\ProgramData\\safe-chain\\bin\\safe-chain.exe"),
"C:\\ProgramData\\safe-chain",
);
});
it("returns undefined when the executable is not inside a bin directory", () => {
assert.strictEqual(
deriveInstallDirFromExecutablePath("/usr/local/.safe-chain/safe-chain"),
undefined,
);
});
});
describe("getInstalledSafeChainDir", () => {
it("returns undefined for non-packaged executions", () => {
assert.strictEqual(
getInstalledSafeChainDir({
isPackaged: false,
executablePath: "/usr/local/.safe-chain/bin/safe-chain",
}),
undefined,
);
});
it("returns the install dir for packaged executions", () => {
assert.strictEqual(
getInstalledSafeChainDir({
isPackaged: true,
executablePath: "/usr/local/.safe-chain/bin/safe-chain",
}),
"/usr/local/.safe-chain",
);
});
});

View file

@ -1,16 +1,14 @@
import forge from "node-forge";
import path from "path";
import fs from "fs";
import os from "os";
import { getSafeChainDir } from "../config/environmentVariables.js";
import { getSafeChainBaseDir } from "../config/safeChainDir.js";
const ca = loadCa();
const certCache = new Map();
function getCertFolder() {
const safeChainDir = getSafeChainDir() ?? path.join(os.homedir(), ".safe-chain");
return path.join(safeChainDir, "certs");
return path.join(getSafeChainBaseDir(), "certs");
}
/**

View file

@ -2,24 +2,23 @@ import { describe, it, beforeEach, afterEach, mock } from "node:test";
import assert from "node:assert";
describe("certUtils", () => {
let originalSafeChainDir;
let installedSafeChainDir;
beforeEach(() => {
originalSafeChainDir = process.env.SAFE_CHAIN_DIR;
installedSafeChainDir = undefined;
mock.module("../config/safeChainDir.js", {
namedExports: {
getSafeChainBaseDir: () => installedSafeChainDir ?? "/home/test/.safe-chain",
},
});
});
afterEach(() => {
if (originalSafeChainDir === undefined) {
delete process.env.SAFE_CHAIN_DIR;
} else {
process.env.SAFE_CHAIN_DIR = originalSafeChainDir;
}
mock.reset();
});
it("stores CA certificates in SAFE_CHAIN_DIR when configured", async () => {
process.env.SAFE_CHAIN_DIR = "/custom/safe-chain";
it("stores CA certificates in the packaged install dir when available", async () => {
installedSafeChainDir = "/custom/safe-chain";
mock.module("fs", {
defaultExport: {

View file

@ -3,8 +3,7 @@ import * as os from "os";
import fs from "fs";
import path from "path";
import { ECOSYSTEM_JS, ECOSYSTEM_PY } from "../config/settings.js";
import { getSafeChainDir } from "../config/environmentVariables.js";
export { getSafeChainDir };
import { getSafeChainBaseDir } from "../config/safeChainDir.js";
import { safeSpawn } from "../utils/safeSpawn.js";
import { ui } from "../environment/userInteraction.js";
@ -125,12 +124,10 @@ export function getPackageManagerList() {
/**
* Returns the safe-chain base directory.
* Uses SAFE_CHAIN_DIR environment variable when set, otherwise defaults to ~/.safe-chain.
* Uses the packaged binary location when available, otherwise defaults to ~/.safe-chain.
* @returns {string}
*/
export function getSafeChainBaseDir() {
return getSafeChainDir() ?? path.join(os.homedir(), ".safe-chain");
}
export { getSafeChainBaseDir };
/**
* @returns {string}

View file

@ -185,64 +185,23 @@ describe("removeLinesMatchingPatternTests", () => {
});
describe("getSafeChainBaseDir / getBinDir / getShimsDir / getScriptsDir", () => {
const customDir = "/usr/local/.safe-chain";
let originalSafeChainDir;
beforeEach(() => {
originalSafeChainDir = process.env.SAFE_CHAIN_DIR;
delete process.env.SAFE_CHAIN_DIR;
});
afterEach(() => {
if (originalSafeChainDir !== undefined) {
process.env.SAFE_CHAIN_DIR = originalSafeChainDir;
} else {
delete process.env.SAFE_CHAIN_DIR;
}
});
it("defaults base dir to ~/.safe-chain when SAFE_CHAIN_DIR is not set", async () => {
it("defaults base dir to ~/.safe-chain when no packaged install dir is available", async () => {
const { getSafeChainBaseDir } = await import("./helpers.js");
assert.strictEqual(getSafeChainBaseDir(), path.join(homedir(), ".safe-chain"));
});
it("uses SAFE_CHAIN_DIR as base dir when set", async () => {
process.env.SAFE_CHAIN_DIR = customDir;
const { getSafeChainBaseDir } = await import("./helpers.js");
assert.strictEqual(getSafeChainBaseDir(), customDir);
});
it("getBinDir returns ~/.safe-chain/bin by default", async () => {
const { getBinDir } = await import("./helpers.js");
assert.strictEqual(getBinDir(), path.join(homedir(), ".safe-chain", "bin"));
});
it("getBinDir returns custom dir + /bin when SAFE_CHAIN_DIR is set", async () => {
process.env.SAFE_CHAIN_DIR = customDir;
const { getBinDir } = await import("./helpers.js");
assert.strictEqual(getBinDir(), `${customDir}/bin`);
});
it("getShimsDir returns ~/.safe-chain/shims by default", async () => {
const { getShimsDir } = await import("./helpers.js");
assert.strictEqual(getShimsDir(), path.join(homedir(), ".safe-chain", "shims"));
});
it("getShimsDir returns custom dir + /shims when SAFE_CHAIN_DIR is set", async () => {
process.env.SAFE_CHAIN_DIR = customDir;
const { getShimsDir } = await import("./helpers.js");
assert.strictEqual(getShimsDir(), `${customDir}/shims`);
});
it("getScriptsDir returns ~/.safe-chain/scripts by default", async () => {
const { getScriptsDir } = await import("./helpers.js");
assert.strictEqual(getScriptsDir(), path.join(homedir(), ".safe-chain", "scripts"));
});
it("getScriptsDir returns custom dir + /scripts when SAFE_CHAIN_DIR is set", async () => {
process.env.SAFE_CHAIN_DIR = customDir;
const { getScriptsDir } = await import("./helpers.js");
assert.strictEqual(getScriptsDir(), `${customDir}/scripts`);
});
});

View file

@ -4,7 +4,7 @@
# Function to remove shim from PATH (POSIX-compliant)
remove_shim_from_path() {
_safe_chain_shims="{{SHIMS_DIR}}"
_safe_chain_shims=$(CDPATH= cd -- "$(dirname -- "$0")" 2>/dev/null && pwd -P)
echo "$PATH" | sed "s|${_safe_chain_shims}:||g"
}
@ -13,11 +13,7 @@ if command -v safe-chain >/dev/null 2>&1; then
PATH=$(remove_shim_from_path) exec safe-chain {{PACKAGE_MANAGER}} "$@"
else
# safe-chain is not reachable — warn the user so they know protection is inactive
if [ -n "$SAFE_CHAIN_DIR" ]; then
printf "\033[43;30mWarning:\033[0m safe-chain is not accessible. Check that '%s/bin' is readable and executable by the current user.\n" "$SAFE_CHAIN_DIR" >&2
else
printf "\033[43;30mWarning:\033[0m safe-chain is not available to protect you from installing malware. {{PACKAGE_MANAGER}} will run without it.\n" >&2
fi
printf "\033[43;30mWarning:\033[0m safe-chain is not available to protect you from installing malware. {{PACKAGE_MANAGER}} will run without it.\n" >&2
# Dynamically find original {{PACKAGE_MANAGER}} (excluding this shim directory)
original_cmd=$(PATH=$(remove_shim_from_path) command -v {{PACKAGE_MANAGER}})

View file

@ -3,7 +3,8 @@ REM Generated wrapper for {{PACKAGE_MANAGER}} by safe-chain
REM This wrapper intercepts {{PACKAGE_MANAGER}} calls for non-interactive environments
REM Remove shim directory from PATH to prevent infinite loops
set "SHIM_DIR={{SHIMS_DIR}}"
set "SHIM_DIR=%~dp0"
if "%SHIM_DIR:~-1%"=="\" set "SHIM_DIR=%SHIM_DIR:~0,-1%"
call set "CLEAN_PATH=%%PATH:%SHIM_DIR%;=%%"
REM Check if aikido command is available with clean PATH

View file

@ -69,8 +69,7 @@ function createUnixShims(shimsDir) {
for (const toolInfo of getToolsToSetup()) {
const shimContent = template
.replaceAll("{{PACKAGE_MANAGER}}", toolInfo.tool)
.replaceAll("{{AIKIDO_COMMAND}}", toolInfo.aikidoCommand)
.replaceAll("{{SHIMS_DIR}}", shimsDir);
.replaceAll("{{AIKIDO_COMMAND}}", toolInfo.aikidoCommand);
const shimPath = path.join(shimsDir, toolInfo.tool);
fs.writeFileSync(shimPath, shimContent, "utf-8");
@ -109,8 +108,7 @@ function createWindowsShims(shimsDir) {
for (const toolInfo of getToolsToSetup()) {
const shimContent = template
.replaceAll("{{PACKAGE_MANAGER}}", toolInfo.tool)
.replaceAll("{{AIKIDO_COMMAND}}", toolInfo.aikidoCommand)
.replaceAll("{{SHIMS_DIR}}", shimsDir);
.replaceAll("{{AIKIDO_COMMAND}}", toolInfo.aikidoCommand);
const shimPath = `${shimsDir}/${toolInfo.tool}.cmd`;
fs.writeFileSync(shimPath, shimContent, "utf-8");

View file

@ -1,8 +1,5 @@
# Guard against PATH separator injection: reject SAFE_CHAIN_DIR values containing ':'
set -l safe_chain_base $HOME/.safe-chain
if set -q SAFE_CHAIN_DIR; and not string match -q '*:*' -- $SAFE_CHAIN_DIR
set safe_chain_base $SAFE_CHAIN_DIR
end
set -l safe_chain_script (status filename)
set -l safe_chain_base (path dirname (path dirname $safe_chain_script))
set -gx PATH $PATH $safe_chain_base/bin
function npx

View file

@ -1,10 +1,22 @@
# Guard against PATH separator injection: reject SAFE_CHAIN_DIR values containing ':'
case "${SAFE_CHAIN_DIR}" in
*:*) _sc_base="${HOME}/.safe-chain" ;;
*) _sc_base="${SAFE_CHAIN_DIR:-${HOME}/.safe-chain}" ;;
esac
_get_safe_chain_script_path() {
if [ -n "${BASH_SOURCE[0]:-}" ]; then
printf '%s\n' "${BASH_SOURCE[0]}"
return
fi
if [ -n "${ZSH_VERSION:-}" ]; then
eval 'printf "%s\n" "${(%):-%N}"'
return
fi
printf '%s\n' "$0"
}
_sc_script_path="$(_get_safe_chain_script_path)"
_sc_scripts_dir=$(CDPATH= cd -- "$(dirname -- "$_sc_script_path")" 2>/dev/null && pwd -P)
_sc_base=$(dirname -- "$_sc_scripts_dir")
export PATH="$PATH:${_sc_base}/bin"
unset _sc_base
unset _sc_base _sc_script_path _sc_scripts_dir
function npx() {
wrapSafeChainCommand "npx" "$@"

View file

@ -2,8 +2,7 @@
# $IsWindows is only available in PowerShell Core 6.0+. If it doesn't exist, assume Windows PowerShell
$isWindowsPlatform = if (Test-Path variable:IsWindows) { $IsWindows } else { $true }
$pathSeparator = if ($isWindowsPlatform) { ';' } else { ':' }
# Guard against PATH separator injection: reject SAFE_CHAIN_DIR values containing the path separator
$safeChainBase = if ($env:SAFE_CHAIN_DIR -and -not $env:SAFE_CHAIN_DIR.Contains($pathSeparator)) { $env:SAFE_CHAIN_DIR } else { Join-Path $HOME '.safe-chain' }
$safeChainBase = Split-Path -Parent $PSScriptRoot
$safeChainBin = Join-Path $safeChainBase 'bin'
$env:PATH = "$env:PATH$pathSeparator$safeChainBin"

View file

@ -3,7 +3,6 @@ import {
doesExecutableExistOnSystem,
removeLinesMatchingPattern,
getScriptsDir,
getSafeChainDir,
} from "../helpers.js";
import { execSync, spawnSync } from "child_process";
import * as os from "os";
@ -54,15 +53,6 @@ function teardown(tools) {
function setup() {
const startupFile = getStartupFile();
const customDir = getSafeChainDir();
if (customDir) {
addLineToFile(
startupFile,
`export SAFE_CHAIN_DIR="${customDir}" # Safe-chain installation directory`,
eol
);
}
addLineToFile(
startupFile,
`source ${path.join(getScriptsDir(), "init-posix.sh")} # Safe-chain bash initialization script`,
@ -143,18 +133,7 @@ function cygpathw(path) {
/** @param {string} preamble */
function buildManualInstructions(preamble) {
const customDir = getSafeChainDir();
const instructions = [preamble];
if (customDir) {
instructions.push(
` export SAFE_CHAIN_DIR="${customDir}"`,
` source ${path.join(getScriptsDir(), "init-posix.sh")}`,
);
} else {
instructions.push(` source ~/.safe-chain/scripts/init-posix.sh`);
}
const instructions = [preamble, ` source ${path.join(getScriptsDir(), "init-posix.sh")}`];
instructions.push(`Then restart your terminal or run: source ~/.bashrc`);
return instructions;
}

View file

@ -10,7 +10,6 @@ describe("Bash shell integration", () => {
let bash;
let windowsCygwinPath = "";
let platform = "linux";
let getSafeChainDirResult = undefined;
beforeEach(async () => {
// Create temporary startup file for testing
@ -21,7 +20,6 @@ describe("Bash shell integration", () => {
namedExports: {
doesExecutableExistOnSystem: () => true,
getScriptsDir: () => "/test-home/.safe-chain/scripts",
getSafeChainDir: () => getSafeChainDirResult,
addLineToFile: (filePath, line) => {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
@ -91,7 +89,6 @@ describe("Bash shell integration", () => {
// Reset mocks
mock.reset();
platform = "linux";
getSafeChainDirResult = undefined;
});
describe("isInstalled", () => {
@ -203,26 +200,18 @@ describe("Bash shell integration", () => {
});
});
describe("SAFE_CHAIN_DIR", () => {
it("should write export line to rc file when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
describe("custom install dir", () => {
it("writes only the source line to the rc file", () => {
bash.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(
content.includes('export SAFE_CHAIN_DIR="/custom/safe-chain" # Safe-chain installation directory')
content.includes("source /test-home/.safe-chain/scripts/init-posix.sh")
);
});
it("should not write export line when no custom dir is set", () => {
getSafeChainDirResult = undefined;
bash.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should remove export line on teardown", () => {
it("removes legacy export lines on teardown", () => {
const initialContent = [
'#!/bin/bash',
'export SAFE_CHAIN_DIR="/custom/safe-chain" # Safe-chain installation directory',
@ -236,12 +225,9 @@ describe("Bash shell integration", () => {
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should show custom manual setup instructions when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
it("shows source-only manual setup instructions", () => {
assert.deepStrictEqual(bash.getManualSetupInstructions(), [
"Add the following line to your ~/.bashrc file:",
' export SAFE_CHAIN_DIR="/custom/safe-chain"',
" source /test-home/.safe-chain/scripts/init-posix.sh",
"Then restart your terminal or run: source ~/.bashrc",
]);

View file

@ -3,7 +3,6 @@ import {
doesExecutableExistOnSystem,
removeLinesMatchingPattern,
getScriptsDir,
getSafeChainDir,
} from "../helpers.js";
import { execSync } from "child_process";
import path from "path";
@ -53,15 +52,6 @@ function teardown(tools) {
function setup() {
const startupFile = getStartupFile();
const customDir = getSafeChainDir();
if (customDir) {
addLineToFile(
startupFile,
`set -gx SAFE_CHAIN_DIR "${customDir}" # Safe-chain installation directory`,
eol
);
}
addLineToFile(
startupFile,
`source ${path.join(getScriptsDir(), "init-fish.fish")} # Safe-chain Fish initialization script`,
@ -86,18 +76,7 @@ function getStartupFile() {
/** @param {string} preamble */
function buildManualInstructions(preamble) {
const customDir = getSafeChainDir();
const instructions = [preamble];
if (customDir) {
instructions.push(
` set -gx SAFE_CHAIN_DIR "${customDir}"`,
` source ${path.join(getScriptsDir(), "init-fish.fish")}`,
);
} else {
instructions.push(` source ~/.safe-chain/scripts/init-fish.fish`);
}
const instructions = [preamble, ` source ${path.join(getScriptsDir(), "init-fish.fish")}`];
instructions.push(
`Then restart your terminal or run: source ~/.config/fish/config.fish`,
);

View file

@ -8,7 +8,6 @@ import { knownAikidoTools } from "../helpers.js";
describe("Fish shell integration", () => {
let mockStartupFile;
let fish;
let getSafeChainDirResult = undefined;
beforeEach(async () => {
// Create temporary startup file for testing
@ -19,7 +18,6 @@ describe("Fish shell integration", () => {
namedExports: {
doesExecutableExistOnSystem: () => true,
getScriptsDir: () => "/test-home/.safe-chain/scripts",
getSafeChainDir: () => getSafeChainDirResult,
addLineToFile: (filePath, line) => {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
@ -55,7 +53,6 @@ describe("Fish shell integration", () => {
// Reset mocks
mock.reset();
getSafeChainDirResult = undefined;
});
describe("isInstalled", () => {
@ -156,26 +153,18 @@ describe("Fish shell integration", () => {
});
});
describe("SAFE_CHAIN_DIR", () => {
it("should write set line to config file when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
describe("custom install dir", () => {
it("writes only the source line to the config file", () => {
fish.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(
content.includes('set -gx SAFE_CHAIN_DIR "/custom/safe-chain" # Safe-chain installation directory')
content.includes("source /test-home/.safe-chain/scripts/init-fish.fish")
);
});
it("should not write set line when no custom dir is set", () => {
getSafeChainDirResult = undefined;
fish.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should remove set line on teardown", () => {
it("removes legacy set lines on teardown", () => {
const initialContent = [
'set -gx SAFE_CHAIN_DIR "/custom/safe-chain" # Safe-chain installation directory',
"source /test-home/.safe-chain/scripts/init-fish.fish # Safe-chain Fish initialization script",
@ -188,12 +177,9 @@ describe("Fish shell integration", () => {
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should show custom manual setup instructions when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
it("shows source-only manual setup instructions", () => {
assert.deepStrictEqual(fish.getManualSetupInstructions(), [
"Add the following line to your ~/.config/fish/config.fish file:",
' set -gx SAFE_CHAIN_DIR "/custom/safe-chain"',
" source /test-home/.safe-chain/scripts/init-fish.fish",
"Then restart your terminal or run: source ~/.config/fish/config.fish",
]);

View file

@ -4,7 +4,6 @@ import {
removeLinesMatchingPattern,
validatePowerShellExecutionPolicy,
getScriptsDir,
getSafeChainDir,
} from "../helpers.js";
import { execSync } from "child_process";
import path from "path";
@ -58,14 +57,6 @@ async function setup() {
const startupFile = getStartupFile();
const customDir = getSafeChainDir();
if (customDir) {
addLineToFile(
startupFile,
`$env:SAFE_CHAIN_DIR = '${customDir}' # Safe-chain installation directory`,
);
}
addLineToFile(
startupFile,
`. "${path.join(getScriptsDir(), "init-pwsh.ps1")}" # Safe-chain PowerShell initialization script`,
@ -89,18 +80,7 @@ function getStartupFile() {
/** @param {string} preamble */
function buildManualInstructions(preamble) {
const customDir = getSafeChainDir();
const instructions = [preamble];
if (customDir) {
instructions.push(
` $env:SAFE_CHAIN_DIR = '${customDir}'`,
` . "${path.join(getScriptsDir(), "init-pwsh.ps1")}"`,
);
} else {
instructions.push(` . "$HOME\\.safe-chain\\scripts\\init-pwsh.ps1"`);
}
const instructions = [preamble, ` . "${path.join(getScriptsDir(), "init-pwsh.ps1")}"`];
instructions.push(`Then restart your terminal or run: . $PROFILE`);
return instructions;
}

View file

@ -9,7 +9,6 @@ describe("PowerShell Core shell integration", () => {
let mockStartupFile;
let powershell;
let executionPolicyResult;
let getSafeChainDirResult = undefined;
beforeEach(async () => {
// Create temporary startup file for testing
@ -27,7 +26,6 @@ describe("PowerShell Core shell integration", () => {
mock.module("../helpers.js", {
namedExports: {
doesExecutableExistOnSystem: () => true,
getSafeChainDir: () => getSafeChainDirResult,
addLineToFile: (filePath, line) => {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
@ -65,7 +63,6 @@ describe("PowerShell Core shell integration", () => {
// Reset mocks
mock.reset();
getSafeChainDirResult = undefined;
});
describe("isInstalled", () => {
@ -209,26 +206,18 @@ describe("PowerShell Core shell integration", () => {
});
});
describe("SAFE_CHAIN_DIR", () => {
it("should write $env:SAFE_CHAIN_DIR line to profile when custom dir is set", async () => {
getSafeChainDirResult = "C:\\custom\\safe-chain";
describe("custom install dir", () => {
it("writes only the source line to the profile", async () => {
await powershell.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(
content.includes("$env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain' # Safe-chain installation directory")
content.includes('. "/test-home/.safe-chain/scripts/init-pwsh.ps1"')
);
});
it("should not write $env:SAFE_CHAIN_DIR line when no custom dir is set", async () => {
getSafeChainDirResult = undefined;
await powershell.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should remove $env:SAFE_CHAIN_DIR line on teardown", () => {
it("removes legacy env lines on teardown", () => {
const initialContent = [
"# PowerShell profile",
"$env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain' # Safe-chain installation directory",
@ -242,12 +231,9 @@ describe("PowerShell Core shell integration", () => {
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should show custom manual setup instructions when custom dir is set", () => {
getSafeChainDirResult = "C:\\custom\\safe-chain";
it("shows source-only manual setup instructions", () => {
assert.deepStrictEqual(powershell.getManualSetupInstructions(), [
'Add the following line to your PowerShell profile (run "echo $PROFILE" to find its location):',
" $env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain'",
' . "/test-home/.safe-chain/scripts/init-pwsh.ps1"',
"Then restart your terminal or run: . $PROFILE",
]);

View file

@ -4,7 +4,6 @@ import {
removeLinesMatchingPattern,
validatePowerShellExecutionPolicy,
getScriptsDir,
getSafeChainDir,
} from "../helpers.js";
import { execSync } from "child_process";
import path from "path";
@ -58,14 +57,6 @@ async function setup() {
const startupFile = getStartupFile();
const customDir = getSafeChainDir();
if (customDir) {
addLineToFile(
startupFile,
`$env:SAFE_CHAIN_DIR = '${customDir}' # Safe-chain installation directory`,
);
}
addLineToFile(
startupFile,
`. "${path.join(getScriptsDir(), "init-pwsh.ps1")}" # Safe-chain PowerShell initialization script`,
@ -89,18 +80,7 @@ function getStartupFile() {
/** @param {string} preamble */
function buildManualInstructions(preamble) {
const customDir = getSafeChainDir();
const instructions = [preamble];
if (customDir) {
instructions.push(
` $env:SAFE_CHAIN_DIR = '${customDir}'`,
` . "${path.join(getScriptsDir(), "init-pwsh.ps1")}"`,
);
} else {
instructions.push(` . "$HOME\\.safe-chain\\scripts\\init-pwsh.ps1"`);
}
const instructions = [preamble, ` . "${path.join(getScriptsDir(), "init-pwsh.ps1")}"`];
instructions.push(`Then restart your terminal or run: . $PROFILE`);
return instructions;
}

View file

@ -9,7 +9,6 @@ describe("Windows PowerShell shell integration", () => {
let mockStartupFile;
let windowsPowershell;
let executionPolicyResult;
let getSafeChainDirResult = undefined;
beforeEach(async () => {
// Create temporary startup file for testing
@ -27,7 +26,6 @@ describe("Windows PowerShell shell integration", () => {
mock.module("../helpers.js", {
namedExports: {
doesExecutableExistOnSystem: () => true,
getSafeChainDir: () => getSafeChainDirResult,
addLineToFile: (filePath, line) => {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
@ -65,7 +63,6 @@ describe("Windows PowerShell shell integration", () => {
// Reset mocks
mock.reset();
getSafeChainDirResult = undefined;
});
describe("isInstalled", () => {
@ -209,26 +206,18 @@ describe("Windows PowerShell shell integration", () => {
});
});
describe("SAFE_CHAIN_DIR", () => {
it("should write $env:SAFE_CHAIN_DIR line to profile when custom dir is set", async () => {
getSafeChainDirResult = "C:\\custom\\safe-chain";
describe("custom install dir", () => {
it("writes only the source line to the profile", async () => {
await windowsPowershell.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(
content.includes("$env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain' # Safe-chain installation directory")
content.includes('. "/test-home/.safe-chain/scripts/init-pwsh.ps1"')
);
});
it("should not write $env:SAFE_CHAIN_DIR line when no custom dir is set", async () => {
getSafeChainDirResult = undefined;
await windowsPowershell.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should remove $env:SAFE_CHAIN_DIR line on teardown", () => {
it("removes legacy env lines on teardown", () => {
const initialContent = [
"# Windows PowerShell profile",
"$env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain' # Safe-chain installation directory",
@ -242,12 +231,9 @@ describe("Windows PowerShell shell integration", () => {
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should show custom manual teardown instructions when custom dir is set", () => {
getSafeChainDirResult = "C:\\custom\\safe-chain";
it("shows source-only manual teardown instructions", () => {
assert.deepStrictEqual(windowsPowershell.getManualTeardownInstructions(), [
'Remove the following line from your PowerShell profile (run "echo $PROFILE" to find its location):',
" $env:SAFE_CHAIN_DIR = 'C:\\custom\\safe-chain'",
' . "/test-home/.safe-chain/scripts/init-pwsh.ps1"',
"Then restart your terminal or run: . $PROFILE",
]);

View file

@ -3,7 +3,6 @@ import {
doesExecutableExistOnSystem,
removeLinesMatchingPattern,
getScriptsDir,
getSafeChainDir,
} from "../helpers.js";
import { execSync } from "child_process";
import path from "path";
@ -53,15 +52,6 @@ function teardown(tools) {
function setup() {
const startupFile = getStartupFile();
const customDir = getSafeChainDir();
if (customDir) {
addLineToFile(
startupFile,
`export SAFE_CHAIN_DIR="${customDir}" # Safe-chain installation directory`,
eol
);
}
addLineToFile(
startupFile,
`source ${path.join(getScriptsDir(), "init-posix.sh")} # Safe-chain Zsh initialization script`,
@ -86,18 +76,7 @@ function getStartupFile() {
/** @param {string} preamble */
function buildManualInstructions(preamble) {
const customDir = getSafeChainDir();
const instructions = [preamble];
if (customDir) {
instructions.push(
` export SAFE_CHAIN_DIR="${customDir}"`,
` source ${path.join(getScriptsDir(), "init-posix.sh")}`,
);
} else {
instructions.push(` source ~/.safe-chain/scripts/init-posix.sh`);
}
const instructions = [preamble, ` source ${path.join(getScriptsDir(), "init-posix.sh")}`];
instructions.push(`Then restart your terminal or run: source ~/.zshrc`);
return instructions;
}

View file

@ -8,7 +8,6 @@ import { knownAikidoTools } from "../helpers.js";
describe("Zsh shell integration", () => {
let mockStartupFile;
let zsh;
let getSafeChainDirResult = undefined;
beforeEach(async () => {
// Create temporary startup file for testing
@ -19,7 +18,6 @@ describe("Zsh shell integration", () => {
namedExports: {
doesExecutableExistOnSystem: () => true,
getScriptsDir: () => "/test-home/.safe-chain/scripts",
getSafeChainDir: () => getSafeChainDirResult,
addLineToFile: (filePath, line) => {
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, "", "utf-8");
@ -55,7 +53,6 @@ describe("Zsh shell integration", () => {
// Reset mocks
mock.reset();
getSafeChainDirResult = undefined;
});
describe("isInstalled", () => {
@ -174,26 +171,18 @@ describe("Zsh shell integration", () => {
});
});
describe("SAFE_CHAIN_DIR", () => {
it("should write export line to rc file when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
describe("custom install dir", () => {
it("writes only the source line to the rc file", () => {
zsh.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(
content.includes('export SAFE_CHAIN_DIR="/custom/safe-chain" # Safe-chain installation directory')
content.includes("source /test-home/.safe-chain/scripts/init-posix.sh")
);
});
it("should not write export line when no custom dir is set", () => {
getSafeChainDirResult = undefined;
zsh.setup();
const content = fs.readFileSync(mockStartupFile, "utf-8");
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should remove export line on teardown", () => {
it("removes legacy export lines on teardown", () => {
const initialContent = [
"#!/bin/zsh",
'export SAFE_CHAIN_DIR="/custom/safe-chain" # Safe-chain installation directory',
@ -207,12 +196,9 @@ describe("Zsh shell integration", () => {
assert.ok(!content.includes("SAFE_CHAIN_DIR"));
});
it("should show custom manual teardown instructions when custom dir is set", () => {
getSafeChainDirResult = "/custom/safe-chain";
it("shows source-only manual teardown instructions", () => {
assert.deepStrictEqual(zsh.getManualTeardownInstructions(), [
"Remove the following line from your ~/.zshrc file:",
' export SAFE_CHAIN_DIR="/custom/safe-chain"',
" source /test-home/.safe-chain/scripts/init-posix.sh",
"Then restart your terminal or run: source ~/.zshrc",
]);