mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-08 09:11:26 +00:00
refactor: dedupe PATH prepend helpers
This commit is contained in:
58
src/infra/path-prepend.ts
Normal file
58
src/infra/path-prepend.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import path from "node:path";
|
||||
|
||||
export function normalizePathPrepend(entries?: string[]) {
|
||||
if (!Array.isArray(entries)) {
|
||||
return [];
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
const normalized: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (typeof entry !== "string") {
|
||||
continue;
|
||||
}
|
||||
const trimmed = entry.trim();
|
||||
if (!trimmed || seen.has(trimmed)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(trimmed);
|
||||
normalized.push(trimmed);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function mergePathPrepend(existing: string | undefined, prepend: string[]) {
|
||||
if (prepend.length === 0) {
|
||||
return existing;
|
||||
}
|
||||
const partsExisting = (existing ?? "")
|
||||
.split(path.delimiter)
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
const merged: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const part of [...prepend, ...partsExisting]) {
|
||||
if (seen.has(part)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(part);
|
||||
merged.push(part);
|
||||
}
|
||||
return merged.join(path.delimiter);
|
||||
}
|
||||
|
||||
export function applyPathPrepend(
|
||||
env: Record<string, string>,
|
||||
prepend: string[] | undefined,
|
||||
options?: { requireExisting?: boolean },
|
||||
) {
|
||||
if (!Array.isArray(prepend) || prepend.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (options?.requireExisting && !env.PATH) {
|
||||
return;
|
||||
}
|
||||
const merged = mergePathPrepend(env.PATH, prepend);
|
||||
if (merged) {
|
||||
env.PATH = merged;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user