Skip to content

Commit

Permalink
Add validation to parseVariables (substitute) (#1750)
Browse files Browse the repository at this point in the history
  • Loading branch information
int128 authored Dec 17, 2024
1 parent a6553fc commit 301a9d0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
16 changes: 10 additions & 6 deletions substitute/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,23 @@ import { promises as fs } from 'fs'
import * as core from '@actions/core'
import * as glob from '@actions/glob'

interface Inputs {
type Inputs = {
files: string
variables: Map<string, string>
}

export const parseVariables = (variables: string[]): Map<string, string> => {
const m = new Map<string, string>()
const map = new Map<string, string>()
for (const s of variables) {
const k = s.substring(0, s.indexOf('='))
const v = s.substring(s.indexOf('=') + 1)
m.set(k, v)
const equalIndex = s.indexOf('=')
if (equalIndex === -1) {
throw new Error(`variable must be in the form of key=value: ${s}`)
}
const k = s.substring(0, equalIndex)
const v = s.substring(equalIndex + 1)
map.set(k, v)
}
return m
return map
}

export const run = async (inputs: Inputs): Promise<void> => {
Expand Down
20 changes: 19 additions & 1 deletion substitute/tests/run.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as os from 'os'
import { promises as fs } from 'fs'
import * as path from 'path'
import { run } from '../src/run.js'
import { parseVariables, run } from '../src/run.js'

test('variables are replaced', async () => {
const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'substitute-action-'))
Expand All @@ -27,3 +27,21 @@ image: 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/example:latest
})

const readContent = async (f: string): Promise<string> => (await fs.readFile(f)).toString()

describe('parseVariables', () => {
it('parses variables', () => {
expect(parseVariables(['DOCKER_IMAGE=123', 'NAMESPACE=develop', 'VERSION='])).toStrictEqual(
new Map([
['DOCKER_IMAGE', '123'],
['NAMESPACE', 'develop'],
['VERSION', ''],
]),
)
})

it('throws an error if variable is not in the form of key=value', () => {
expect(() => parseVariables(['DOCKER_IMAGE=123', 'NAMESPACE'])).toThrow(
'variable must be in the form of key=value: NAMESPACE',
)
})
})

0 comments on commit 301a9d0

Please sign in to comment.