Skip to content

Commit

Permalink
grep expression
Browse files Browse the repository at this point in the history
  • Loading branch information
kla committed Sep 22, 2024
1 parent e7ed2af commit e7cc21f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/staxfile/expressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default class Expressions {
if (name === 'user_id') return process.getuid().toString()
if (name === 'dasherize') return dasherize(args[0])
if (name === 'exists') return existsSync(args[0]).toString()
if (name === 'grep') return this.grep(args[0], args[1]).toString()

this.staxfile.warnings.add(`Invalid template expression: ${name}`)
}
Expand Down Expand Up @@ -72,4 +73,10 @@ export default class Expressions {
'${{ stax.ssh_auth_sock }}:${{ stax.ssh_auth_sock }}' :
'${{ stax.host_services }}:/run/host-services'
}

private grep(filename: string, pattern: string): boolean {
const content = this.read(filename, '')
const regex = new RegExp(pattern)
return regex.test(content)
}
}
39 changes: 38 additions & 1 deletion tests/unit/staxfile/expressions.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach } from 'bun:test'
import { describe, it, expect, beforeEach, mock } from 'bun:test'
import Expressions from '~/staxfile/expressions'
import Staxfile from '~/staxfile'
import os from 'os'
Expand Down Expand Up @@ -75,4 +75,41 @@ describe('Expressions', () => {
console.log(staxfile.warnings)
expect(staxfile.warnings).toContain("Undefined reference to 'stax.undefined_key'")
})

describe('grep', () => {
let expressions
let mockStaxfile

beforeEach(() => {
mockStaxfile = {
warnings: { add: mock(() => {}) },
config: {
hasProperty: mock(() => true),
fetch: mock(() => 'mocked-value'),
},
location: {
readSync: mock(() => 'file content'),
},
}
expressions = new Expressions(mockStaxfile)
})

it('returns true when pattern is found in file', () => {
mockStaxfile.location.readSync.mockImplementation(() => 'Hello, world!')
const result = expressions.evaluate('grep', ['test.txt', 'world'])
expect(result).toBe('true')
})

it('returns false when pattern is not found in file', () => {
mockStaxfile.location.readSync.mockImplementation(() => 'Hello, world!')
const result = expressions.evaluate('grep', ['test.txt', 'foo'])
expect(result).toBe('false')
})

it('uses default value when file cannot be read', () => {
mockStaxfile.location.readSync.mockImplementation(() => { throw new Error('File not found') })
const result = expressions.evaluate('grep', ['nonexistent.txt', 'pattern'])
expect(result).toBe('false')
})
})
})

0 comments on commit e7cc21f

Please sign in to comment.