Skip to content

Commit

Permalink
Add a sync command
Browse files Browse the repository at this point in the history
  • Loading branch information
eaviles committed Oct 8, 2021
1 parent 8147b72 commit f18f4c2
Show file tree
Hide file tree
Showing 14 changed files with 272 additions and 21 deletions.
83 changes: 83 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][mozilla coc].

For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][faq]. Translations are available at [https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
[mozilla coc]: https://github.com/mozilla/diversity
[faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# core-commons

[![npm version](https://badge.fury.io/js/core-commons.svg)](http://badge.fury.io/js/core-commons) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md)

Lifion's development setup in one command for our public Node.js projects.

## License

[Apache-2.0](./LICENSE)
9 changes: 9 additions & 0 deletions docs/templates/README.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# core-commons

[![npm version](https://badge.fury.io/js/core-commons.svg)](http://badge.fury.io/js/core-commons) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md)

Lifion's development setup in one command for our public Node.js projects.

## License

[Apache-2.0](./LICENSE)
3 changes: 2 additions & 1 deletion lib/commands/build-docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module.exports = {
const output = await jsdocToMd.render(cfg);
await writeFile(readmePath, output, 'utf8');
await $`git add ./README.md`;
await $`npm run prettier`;
const cli = path.relative(process.cwd(), path.resolve(__dirname, '../../bin/cli.js'));
await $`${cli} prettier`;
}
};
3 changes: 3 additions & 0 deletions lib/commands/build-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ module.exports = {
$.verbose = false;
const cli = path.relative(process.cwd(), path.resolve(__dirname, '../../bin/cli.js'));
await $`${cli} clean-types`;
if (process.argv.slice(-1)[0] === command) {
process.argv.splice(2, 1);
}
process.argv.push('--emitDeclarationOnly');
require('typescript/bin/tsc');
}
Expand Down
3 changes: 3 additions & 0 deletions lib/commands/check-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ module.exports = {
command,
describe: 'Check the types with TypeScript.',
handler: async () => {
if (process.argv.slice(-1)[0] === command) {
process.argv.splice(2, 1);
}
process.argv.push('--noEmit');
require('typescript/bin/tsc');
}
Expand Down
5 changes: 2 additions & 3 deletions lib/commands/prepare.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ module.exports = {
describe: 'Run configuration and project preparation tasks',
handler: async () => {
$.verbose = false;
const sharedDir = [__dirname, '..', '..', 'shared'];
const excludesFile = pathFromCwd(...sharedDir, 'git-ignore.txt');
const excludesFile = pathFromCwd(__dirname, '../../shared/git-ignore.txt');
await $`git config core.excludesFile ${excludesFile}`;
const hooksPath = pathFromCwd(...sharedDir, 'git-hooks');
const hooksPath = pathFromCwd(__dirname, '../../shared/git-hooks');
await $`git config core.hooksPath ${hooksPath}`;
require('check-engines/bin/check-engines');
}
Expand Down
7 changes: 6 additions & 1 deletion lib/commands/prettier.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@

const path = require('path');

const command = path.parse(__filename).name;

module.exports = {
command: path.parse(__filename).name,
command,
describe: 'Format the codebase with Prettier.',
handler: async () => {
const exts = ['hbs', 'js', 'json', 'md', 'ts'];
if (process.argv.slice(-1)[0] === command) {
process.argv.splice(2, 1);
}
process.argv.push('--write', `**/*.{${exts.join(',')}}`, '.*rc', '!coverage/**/*');
require('prettier/bin-prettier');
}
Expand Down
105 changes: 105 additions & 0 deletions lib/commands/sync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
'use strict';

const path = require('path');
const { $ } = require('zx');

const { loadJsonFile, pathFromCwd, storeJsonFile } = require('../utils');
const { name } = require('../../package.json');

module.exports = {
command: path.parse(__filename).name,
describe: 'Synchronizes the current codebase with core-commons.',
handler: async () => {
const pkg = await loadJsonFile('./package.json');
const { name: targetName, devDependencies = {} } = pkg;
const devDeps = new Set(Object.keys(devDependencies));

// Uninstall unneeded development dependencies.
const toUninstall = [];
for (const devDep of [
'auto-changelog',
'check-engines',
'codecov',
'eslint',
'eslint-config-lifion',
'husky',
'jest',
'jsdoc-to-markdown',
'lint-staged',
'npm-watch',
'pinst',
'prettier'
]) {
if (!devDeps.has(devDep)) continue;
toUninstall.push(devDep);
Object.assign(devDependencies, { [devDep]: undefined });
}
if (toUninstall.length > 0) {
await $`npm un ${toUninstall.join(' ')}`;
}

// Remove husky's files, change the git configuration.
await $`rm -rf ./.husky ./.gitignore ./.npmignore`;
await $`npx commons prepare`;

// Remove auto-changelog's configuration, delete the template.
await $`rm -rf ./.auto-changelog ./templates/CHANGELOG.hbs`;

// Move the README template.
await $`mkdir -p ./docs/templates`;
await $`mv ./templates/README.hbs ./docs/templates/README.hbs || true`;
await $`rm -rf ./templates`;

// Setup ESLint so it uses the shared configuration.
await $`rm -f ./.eslintignore ./.lintstagedrc`;
const { overrides, rules } = await loadJsonFile('./.eslintrc');
const eslintConfigPath = pathFromCwd(__dirname, '../../shared/eslint.json');
const eslintConfig = {
extends: eslintConfigPath,
...(rules && { rules }),
...(overrides && { overrides })
};
await storeJsonFile('./.eslintrc', eslintConfig);

// Remove the Prettier files.
await $`rm -f ./.prettierrc ./.prettierignore`;
const prettierConfigPath = pathFromCwd(__dirname, '../../shared/prettier.json');
await storeJsonFile('./.prettierrc', prettierConfigPath);

// Remove the Jest files.
await $`rm -f ./.jest.json`;

// Setup TypeScript so it uses the shared configuration.
await $`rm -f ./jsconfig.json`;
const tsConfigPath = pathFromCwd(__dirname, '../../shared/tsconfig.json');
const exclude = ['**/*.test.js', '**/__mocks__', 'coverage', 'node_modules'];
const tsConfig = { extends: tsConfigPath };
Object.assign(tsConfig, { exclude });
await storeJsonFile('./tsconfig.json', tsConfig);

// Copy the license and code of conduct.
await $`cp ${path.resolve(__dirname, '../../CODE_OF_CONDUCT.md')} . || true`;
await $`cp ${path.resolve(__dirname, '../../LICENSE')} . || true`;

// Hook the scripts with commons.
const cmd = name === targetName ? './bin/cli.js' : 'commons';
pkg.scripts = {
'build-docs': cmd,
'build-types': cmd,
'check-types': cmd,
'clean-types': cmd,
eslint: cmd,
prepare: cmd,
prepublishOnly: 'npm run build-types && npm run prettier',
prettier: cmd,
test: cmd,
version: cmd
};

// Store the changes in the target package.json file.
await storeJsonFile('./package.json', pkg);

// Upgrade dependencies.
await $`npx lifion-verify-deps -u`;
}
};
3 changes: 2 additions & 1 deletion lib/commands/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ module.exports = {
}
},
rootDir: path.resolve(process.cwd(), 'lib'),
testEnvironment: 'node'
testEnvironment: 'node',
testMatch: ['**/*.test.js']
};
const cfg = merge(baseCfg, test);
process.argv.push('--config', JSON.stringify(cfg));
Expand Down
27 changes: 15 additions & 12 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
'use strict';

const path = require('path');
const prettier = require('prettier');
const { cosmiconfig } = require('cosmiconfig');
const { readFile, writeFile } = require('fs').promises;

const { name } = require('../package.json');

const PKG_FILE = 'package.json';

/**
* Loads the configuration for this tool from the target package.json file.
*
Expand All @@ -17,7 +16,7 @@ async function loadConfig() {
try {
/** @type {*} */
const { filepath } = await cosmiconfig(name, {
searchPlaces: [PKG_FILE]
searchPlaces: ['package.json']
}).search();
const pkg = JSON.parse(await readFile(filepath, 'utf8'));
return pkg[name] || {};
Expand All @@ -33,29 +32,33 @@ async function loadConfig() {
* @returns {string}
*/
function pathFromCwd(...args) {
return path.relative(process.cwd(), path.resolve(...args));
const result = path.relative(process.cwd(), path.resolve(...args));
return !result.startsWith('.') ? `./${result}` : result;
}

/**
* Loads the contents of the package.json file at the target folder.
*
* @param {string} file - The path of the file to load.
* @returns {Promise<*>}
*/
async function loadPackage() {
const filePath = path.resolve(process.cwd(), PKG_FILE);
async function loadJsonFile(file) {
const filePath = path.resolve(process.cwd(), file);
return JSON.parse(await readFile(filePath, 'utf8'));
}

/**
* Stores the given object as the package.json file at the target folder.
*
* @param {*} pkg - The contents to store.
* @param {string} file - The path to the file to write.
* @param {*} data - The contents to store.
* @returns {Promise<void>}
*/
async function storePackage(pkg) {
const filePath = path.resolve(process.cwd(), PKG_FILE);
const pkgStr = `${JSON.stringify(pkg, null, 2)}\n`;
return writeFile(filePath, pkgStr, 'utf8');
async function storeJsonFile(file, data) {
const filePath = path.resolve(process.cwd(), file);
const dataStr = JSON.stringify(data);
const fileData = prettier.format(dataStr, { filepath: file });
return writeFile(filePath, fileData, 'utf8');
}

module.exports = { loadConfig, loadPackage, pathFromCwd, storePackage };
module.exports = { loadConfig, loadJsonFile, pathFromCwd, storeJsonFile };
14 changes: 14 additions & 0 deletions lib/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const utils = require('./utils');

describe('lib/utils', () => {
test('the module exports the expected', () => {
expect(utils).toEqual({
loadConfig: expect.any(Function),
loadJsonFile: expect.any(Function),
pathFromCwd: expect.any(Function),
storeJsonFile: expect.any(Function)
});
});
});
Loading

0 comments on commit f18f4c2

Please sign in to comment.