diff --git a/app/assets/javascripts/diffs/store/diff_file.js b/app/assets/javascripts/diffs/store/diff_file.js new file mode 100644 index 0000000000000000000000000000000000000000..ca34c9a8e7bffee400b743c06f5c97a3fb8308bf --- /dev/null +++ b/app/assets/javascripts/diffs/store/diff_file.js @@ -0,0 +1,38 @@ +// https://gitlab.com/gitlab-org/frontend/rfcs/-/issues/20 +/* eslint-disable import/prefer-default-export */ + +const SHA1_REGEX = /^[a-f0-9]{40}$/i; +// Testers are quick checks to see if we can focus on a single matcher right away, ordered by preference +const testers = [ + { + type: 'sha1', + test: id => SHA1_REGEX.test(id), + }, + { + type: 'any', + test: () => true, + }, +]; +// Matchers are all the ways we know how to identify a Diff File, with `any` as a fallback +const matchers = { + path: function matchesPath(file, path) { + return file.file_path === path; + }, + sha1: function matchesSha(file, sha1) { + return file.file_hash === sha1; + }, + any: function matchesAnyIdentifier(file, identifier) { + return matchers.sha1(file, identifier) || matchers.path(file, identifier); + }, +}; + +function getIdentifierFilter(identifier) { + const { type } = testers.find(definition => definition.test(identifier)); + const check = matchers[type]; + + return file => check(file, identifier); +} + +export function getByIdentifier({ identifier, diffFiles }) { + return diffFiles.find(getIdentifierFilter(identifier)); +} diff --git a/spec/frontend/diffs/store/diff_file_spec.js b/spec/frontend/diffs/store/diff_file_spec.js new file mode 100644 index 0000000000000000000000000000000000000000..4b2f0e6c33cc992e055b8798dee5eb00e2d08b36 --- /dev/null +++ b/spec/frontend/diffs/store/diff_file_spec.js @@ -0,0 +1,30 @@ +import { getByIdentifier } from '~/diffs/store/diff_file'; + +function freeze(thing) { + return Object.freeze(thing); +} + +describe('DiffFile utilities', () => { + describe('getByIdentifier', () => { + const SHA1 = '2c20f4f1829ab02411cf31891e09809acca759f2'; + const DIFF_FILES = freeze([ + freeze({ testId: 'alpha', file_hash: SHA1 }), + freeze({ testId: 'beta', file_hash: 'file_hash' }), + freeze({ testId: 'gamma', file_path: 'file_path' }), + ]); + + it.each` + identifier | findFile + ${'2c20f4f1829ab02411cf31891e09809acca759f2'} | ${'alpha'} + ${'file_hash'} | ${'beta'} + ${'file_path'} | ${'gamma'} + `( + 'finds the correct file when given the identifier $identifier', + ({ identifier, findFile }) => { + const file = getByIdentifier({ diffFiles: DIFF_FILES, identifier }); + + expect(file.testId).toEqual(findFile); + }, + ); + }); +});