Add exists command

This commit is contained in:
2026-10-07 17:41:45 -05:00
parent 976f833536
commit d1c2d4f4b8
3 changed files with 59 additions and 0 deletions

View File

@@ -446,6 +446,12 @@ Assuming the current subject is a valid single data document, convert it `from`
Supports: `php`|`json`
Example: `{"a": 1}` -> `convert json php` -> `['a' => 1]`
#### `exists <fs|var> <name>`
Checks whether the given file or variable exists.
Supports: `fs` for filesystem checks, `var` for variable names
Example: `$a = 1` -> `exists var a` -> `1`
Example: `exists fs fake-file.txt` -> `0`
#### User-specific setup files
The file `~/.str.rc` is automatically executed when `str` starts up.
You can use this to define a user-specific environment.

51
src/vm/commands/exists.ts Normal file
View File

@@ -0,0 +1,51 @@
import {Command, ParseContext, processPath, StrLVal, StrTerm, wrapInt} from "./command.js";
import {LexInput} from "../lexer.js";
import {ExecutionError, StrVM} from "../vm.js";
import {Awaitable} from "../../util/types.js";
import * as fs from 'node:fs';
import {log} from "../../log.js";
export type ExistsData = {
check: 'fs'|'var',
lexical: StrTerm,
}
export class Exists extends Command<ExistsData> {
async attemptParse(context: ParseContext): Promise<ExistsData> {
return {
check: context.popKeywordInSet(['fs', 'var']).value,
lexical: await context.popTerm(),
}
}
getDisplayName(): string {
return 'exists'
}
isParseCandidate(token: LexInput): boolean {
return this.isKeyword(token, 'exists')
}
execute(vm: StrVM, data: ExistsData): Awaitable<StrVM> {
const logger = log.getStreamLogger('cmd-exists')
return vm.replaceContextMatchingTerm(ctx => ({
override: async () => {
if ( data.check === 'fs' ) {
const path = processPath(ctx.resolveString(data.lexical))
logger.debug({ checkPath: path })
return wrapInt(fs.existsSync(path) ? 1 : 0)
} else if ( data.check === 'var' ) {
const lval: StrLVal = { term: 'variable', name: '$' + ctx.resolveString(data.lexical) }
const val = ctx.resolve(lval)
logger.debug({ checkVar: lval, val })
return wrapInt(val ? 1 : 0)
}
throw new ExecutionError(`Existence operator not implemented: ${data.check}`)
},
}))
}
}

View File

@@ -66,6 +66,7 @@ import {Times} from "./times.js";
import {Divide} from "./divide.js";
import {Abs} from "./abs.js";
import {Rand} from "./rand.js";
import {Exists} from "./exists.js";
export type Commands = Command<CommandData>[]
export const commands: Commands = [
@@ -83,6 +84,7 @@ export const commands: Commands = [
new Each,
new Edit,
new Enclose,
new Exists,
new Exit,
new Flatten,
new From,