Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create test workflow with github actions #33

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
"plugins": ["import"],
"rules": {
"semi": [2, "always"],
"comma-dangle": ["error", "always-multiline"],
"import/newline-after-import": ["error", { "count": 2 }],
"no-multiple-empty-lines": "off"
"comma-dangle": ["error", "always-multiline"]
}
}
28 changes: 28 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
# Note: The package-lock must be present if
name: CI/CD

on:
push:
branches: [develop, master]
pull_request:
branches: [develop, master]

jobs:
test:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [10.x, 12.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: yarn install --ignore-engines
- run: yarn run --if-present build
- run: yarn test
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
*-lock.json
dist
.cache
/vendor
Expand Down Expand Up @@ -106,4 +105,4 @@ build/**/*
/client-secret.json
/lib
.tgz
/public/dist
/public/dist
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn pre-commit
8 changes: 8 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "http://json.schemastore.org/prettierrc",
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
11 changes: 11 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"typescript",
"typescriptreact"
]
}
22 changes: 14 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,22 @@
"description": "Library to internationalize literals",
"main": "index.js",
"scripts": {
"prepare": "husky install",
"test": "nyc --reporter=lcov --reporter=html --reporter=text ava --verbose",
"test:watch": "ava --watch",
"build": "babel src --out-dir=lib --ignore=**/*.spec.js",
"watch": "npm run build -- --watch",
"prepublishOnly": "npm run build && npm run lint && npm run test",
"format": "prettier --write src",
"lint": "eslint src examples",
"lint:fix": "eslint src examples --fix",
"example": "npm run build && babel-node examples/resolver.js",
"docs": "documentation build src/i18n.js -f md --shallow --markdown-toc=false --github",
"coverage": "codecov",
"release": "release-it -n"
"release": "release-it -n",
"pre-commit": "lint-staged"
},
"homepage": "https://github.com/k14v/i18njs#readme",
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm run lint && npm test"
}
},
"repository": {
"type": "git",
"url": "[email protected]:k14v/i18njs.git"
Expand Down Expand Up @@ -88,9 +85,18 @@
"documentation": "^12.1.4",
"eslint": "^6.8.0",
"eslint-plugin-import": "^2.20.2",
"husky": "^4.2.3",
"husky": "^8.0.3",
"lint-staged": "^13.2.2",
"nyc": "^15.0.1",
"prettier": "^2.8.8",
"release-it": "^13.5.1",
"sinon": "^9.0.1"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"yarn format",
"yarn lint:fix",
"yarn test"
]
}
}
12 changes: 5 additions & 7 deletions src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { assert, createSubscriber } from './utils';
// Constants
import { ERR_MSGS, STORE_EVENTS } from './constants';


export const defaultResolver = (locale, cache) => {
assert(cache[locale], `No locale implemented for: ${locale}`);
return Promise.resolve(cache[locale]);
Expand All @@ -22,11 +21,10 @@ const createStore = ({ cache = {}, resolver = defaultResolver, ...restOptions }
: store.removeListener(eventName, listener),
resolve: (locale) => {
store.emit(STORE_EVENTS.RESOLVING, { locale, cache });
return (!locale
? Promise
.reject(new Error(ERR_MSGS.LOCALE_UNDEFINED))
: Promise
.resolve(memoResolver(locale, cache, restOptions))
return (
!locale
? Promise.reject(new Error(ERR_MSGS.LOCALE_UNDEFINED))
: Promise.resolve(memoResolver(locale, cache, restOptions))
)
.then((catalog) => {
if (catalog) {
Expand All @@ -37,7 +35,7 @@ const createStore = ({ cache = {}, resolver = defaultResolver, ...restOptions }
return Promise.reject(new Error(ERR_MSGS.LOCALE_NOT_FOUND));
}
})
.catch(err => {
.catch((err) => {
store.emit(STORE_EVENTS.ERROR, err);
return Promise.reject(err);
});
Expand Down
25 changes: 12 additions & 13 deletions src/createStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { ERR_MSGS, STORE_EVENTS } from './constants';
// Test
import test from 'ava';


test('should return a store', (t) => {
const store = createStore();
t.truthy(store);
Expand All @@ -21,23 +20,23 @@ test('should return a instance with a resolve function', (t) => {
t.is(typeof store.resolve, 'function');
});

test('should raise reject when try resolve an undefined locale', async t => {
test('should raise reject when try resolve an undefined locale', async (t) => {
const store = createStore();
const error = await t.throwsAsync(store.resolve());
t.is(error.message, ERR_MSGS.LOCALE_UNDEFINED);
});

test('should raise reject when try resolve a locale that doesn\'t exists', async t => {
test("should raise reject when try resolve a locale that doesn't exists", async (t) => {
const store = createStore();
const error = await t.throwsAsync(store.resolve('de'));
t.is(error.message, ERR_MSGS.LOCALE_NOT_FOUND);
});

test('should return a catalog using locales map', async t => {
test('should return a catalog using locales map', async (t) => {
const localeEN = {};
const store = createStore({
cache: {
'en': localeEN,
en: localeEN,
},
});

Expand All @@ -46,7 +45,7 @@ test('should return a catalog using locales map', async t => {
t.true(localeEN === catalog);
});

test('should call the resolver with the options passed by arguments', async t => {
test('should call the resolver with the options passed by arguments', async (t) => {
t.plan(2);
const localeES = 'es';
const testArg = 'foo';
Expand All @@ -62,19 +61,19 @@ test('should call the resolver with the options passed by arguments', async t =>
await store.resolve(localeES);
});

test('should return a catalog using resolver async', async t => {
test('should return a catalog using resolver async', async (t) => {
const localeEN = {};
const store = createStore({
resolver: () => new Promise(resolve => setTimeout(() => resolve(localeEN), 600)),
resolver: () => new Promise((resolve) => setTimeout(() => resolve(localeEN), 600)),
});

const catalog = await store.resolve('en');

t.true(localeEN === catalog);
});

Object.values(STORE_EVENTS).map(eventName => {
test(`should subscribe to ${eventName} event`, async t => {
Object.values(STORE_EVENTS).map((eventName) => {
test(`should subscribe to ${eventName} event`, async (t) => {
const store = createStore({
cache: { en: {} },
});
Expand Down Expand Up @@ -103,7 +102,7 @@ Object.values(STORE_EVENTS).map(eventName => {
}
});

test(`should unsubscribe of event ${eventName}`, async t => {
test(`should unsubscribe of event ${eventName}`, async (t) => {
const store = createStore({
cache: { en: {} },
});
Expand All @@ -122,7 +121,7 @@ Object.values(STORE_EVENTS).map(eventName => {
});
});

test('should subscribe all events', async t => {
test('should subscribe all events', async (t) => {
const store = createStore({
cache: { en: {} },
});
Expand All @@ -145,7 +144,7 @@ test('should subscribe all events', async t => {
await t.throwsAsync(store.resolve('es'));
});

test('should unsubscribe of any events', async t => {
test('should unsubscribe of any events', async (t) => {
const store = createStore({
cache: { en: {} },
});
Expand Down
57 changes: 32 additions & 25 deletions src/createTranslator.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,49 @@ import rexpmat from '@k14v/rexpmat';
import printf from 'printf';
import { warn, assert } from './utils';


const parseLiteralScheme = (scheme, opts) => ({
const parseLiteralScheme = (scheme, opts) => ({
indexPlural: 0,
...(typeof scheme === 'string' ? {
one: scheme,
other: scheme,
} : scheme),
...(typeof scheme === 'string'
? {
one: scheme,
other: scheme,
}
: scheme),
...opts,
});

const getParsedValues = (tokens) => tokens.map(({parsedValue}) => parsedValue);
const getParsedValues = (tokens) => tokens.map(({ parsedValue }) => parsedValue);

const createCatalogChecker = (catalog) => fn => (...args) => {
assert(catalog !== null, `Catalog not loaded yet when calling translator with arguments: ${args}`);
const createCatalogChecker =
(catalog) =>
(fn) =>
(...args) => {
assert(
catalog !== null,
`Catalog not loaded yet when calling translator with arguments: ${args}`
);

assert(catalog !== undefined, `Not catalog defined when calling translator with arguments: ${args}`);
assert(
catalog !== undefined,
`Not catalog defined when calling translator with arguments: ${args}`
);

return fn(...args);
};
return fn(...args);
};

const createTranslator = (catalog) => {
// Reset warning store to show assertion messages of this catalog
warn.clear();
const memoTokenize = mem(tokenize);
const catalogChecker = createCatalogChecker(catalog);

const regexpMap = Object
.entries(catalog || {})
.filter(literal => /%./.test(literal[0]))
const regexpMap = Object.entries(catalog || {})
.filter((literal) => /%./.test(literal[0]))
.map((literal) => [rexpmat(literal[0]), literal[0]]);

const matchPattern = (str) => {
for (let pattern of regexpMap) {
if (new RegExp(pattern[0]).test(str)){
if (new RegExp(pattern[0]).test(str)) {
return pattern;
}
}
Expand Down Expand Up @@ -83,25 +92,23 @@ const createTranslator = (catalog) => {
parsedValue = processLiteral(parsedValue);
break;
}
paramTokens[pidx++] = ({
paramTokens[pidx++] = {
...tokens[idx],
parsedValue,
});
};
}
}

const { indexPlural, one, other } = literalScheme;

if (params.length) {
const paramTokenPlural = paramTokens
.filter(token => token.kind === 'Number')[(
// Sum length to indexPlural to handle negative values
paramTokensDigitLength + indexPlural
) % paramTokensDigitLength];
const paramTokenPlural = paramTokens.filter((token) => token.kind === 'Number')[
// Sum length to indexPlural to handle negative values
(paramTokensDigitLength + indexPlural) % paramTokensDigitLength
];
if (paramTokenPlural) {
return printf(
paramTokenPlural.parsedValue === 1
? one : other,
paramTokenPlural.parsedValue === 1 ? one : other,
...getParsedValues(paramTokens)
);
}
Expand Down
Loading