diff --git a/README.md b/README.md index 9b6a6b8..6c51464 100644 --- a/README.md +++ b/README.md @@ -88,3 +88,20 @@ Output in `some/path/stamp.json`: "date": "2020-09-04T19:53:03.790Z" } ``` +### readBuildstamp(path) +Safely parses and returns buildstamp by given path. Returns `undefined` on error. +```javascript +import { readBuildstamp } from 'buildstamp' + +const stamp = getBuildstamp('some/path') +/* +{ + git: { + commitId: 'fc6e78b11ef4c7db1c8b89fa6b0d9b3ad4ad481d', + repoName: 'qiwi/buildstamp.git' + }, + docker: { imageTag: 'foo', bar: 'bar' }, + date: '2020-08-27T20:47:41.958Z' +} +*/ +``` diff --git a/src/main/ts/getter.ts b/src/main/ts/getter.ts new file mode 100644 index 0000000..d2438c0 --- /dev/null +++ b/src/main/ts/getter.ts @@ -0,0 +1,11 @@ +import { readFileToString } from './utils' +import { TStamp } from './interfaces' + +export const readBuildstamp = (stampPath: string): TStamp | undefined => { + try { + return JSON.parse(readFileToString(stampPath)) + } catch (e) { + console.error('Buildstamp reading error:', e.message) + } + return undefined +} diff --git a/src/main/ts/index.ts b/src/main/ts/index.ts index f402e0c..0d82723 100644 --- a/src/main/ts/index.ts +++ b/src/main/ts/index.ts @@ -2,3 +2,4 @@ import { execute } from './executor' export * from './interfaces' export { execute } +export { readBuildstamp } from './getter' diff --git a/src/test/ts/getter.ts b/src/test/ts/getter.ts new file mode 100644 index 0000000..c3b100a --- /dev/null +++ b/src/test/ts/getter.ts @@ -0,0 +1,35 @@ +import { readBuildstamp, TStamp } from '../../main/ts' +import * as utils from '../../main/ts/utils' + +const stamp: TStamp = { + git: { + commitId: 'foo', + repoName: 'bar', + repoUrl: 'baz', + }, + date: 0, + docker: { + imageTag: 'bat', + }, +} + +describe('readBuildstamp', () => { + it('reads and parses file', () => { + jest.spyOn(utils, 'readFileToString') + .mockImplementation(() => JSON.stringify(stamp)) + expect(readBuildstamp('some/path')).toEqual(stamp) + }) + + it('logs an error', () => { + jest.spyOn(utils, 'readFileToString') + .mockImplementation(() => { + throw new Error('foo') + }) + const errorSpy = jest.spyOn(console, 'error') + .mockImplementation(() => { /* noop */ }) + expect(readBuildstamp('some/path')).toBeUndefined() + expect(errorSpy).toHaveBeenCalled() + }) + + afterAll(jest.resetAllMocks) +})