-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add proper tilda expansion (#92)
- Loading branch information
Showing
3 changed files
with
101 additions
and
61 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
export const ensureTrailingSlash = (str: string) => (str.endsWith("/") ? str : `${str}/`); | ||
|
||
const replaceTilde = (path: string, homeDir: string) => { | ||
if (path.startsWith("~") && (path.length === 1 || path.charAt(1) === "/")) { | ||
return path.replace("~", homeDir); | ||
} | ||
return path; | ||
}; | ||
|
||
const replaceVariables = (path: string, environmentVariables: Record<string, string>) => { | ||
// Replace simple $VAR variables | ||
const resolvedSimpleVariables = path.replace(/\$([A-Za-z0-9_]+)/g, (key) => { | ||
const envKey = key.slice(1); | ||
return environmentVariables[envKey] ?? key; | ||
}); | ||
|
||
// Replace complex ${VAR} variables | ||
const resolvedComplexVariables = resolvedSimpleVariables.replace( | ||
/\$\{([A-Za-z0-9_]+)(?::-([^}]+))?\}/g, | ||
(match, envKey, defaultValue) => environmentVariables[envKey] ?? defaultValue ?? match | ||
); | ||
|
||
return resolvedComplexVariables; | ||
}; | ||
|
||
export const shellExpand = (path: string, context: Fig.ShellContext): string => { | ||
const { environmentVariables } = context; | ||
return replaceVariables( | ||
replaceTilde(path, environmentVariables?.HOME ?? "~"), | ||
environmentVariables | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters