Skip to content

Commit

Permalink
feat(build): unify the windows and linux script (#1116)
Browse files Browse the repository at this point in the history
  • Loading branch information
alecarn authored Jan 23, 2024
1 parent 3f56d5b commit 4c9c8f7
Show file tree
Hide file tree
Showing 11 changed files with 822 additions and 40 deletions.
509 changes: 493 additions & 16 deletions package-lock.json

Large diffs are not rendered by default.

44 changes: 20 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,42 +14,34 @@
"ng": "ng",
"start": "ng serve",
"start-pwa": "ng build --configuration pwa --output-path ./dist/pwa && npm run serve.pwa",
"build": "ng build",
"build.prod": "ng build --configuration production",
"serve.prod": "http-server ./dist/igo2/ --port 4201 --no-browser",
"serve.pwa": "http-server ./dist/pwa/ --port 4201 --no-browser",
"serve.doc": "compodoc -s --port 4220",
"serve.coverage": "http-server ./coverage/ --port=4210 --no-browser",
"link.start": "ng serve --configuration developpement-link",
"link.build": "ng build --configuration production-link",
"build": "ng build",
"build.prod": "ng build --configuration production",
"build.github": "ng build --configuration=github --output-path ./dist/ghpages --base-href /igo2/",
"build.pwa": "ng build --configuration pwa --output-path ./dist/pwa",
"build.doc": "compodoc -p src/tsconfig.app.json",
"build.coverage": "ng test --code-coverage --watch=false",
"lint": "ng lint",
"lint.fix": "ng lint --fix",
"format": "prettier --write ./src/**/*.{ts,js,html,scss,css,json}",
"e2e": "ng run igo2:e2e:production",
"e2e.local": "ng run igo2:e2e:local",
"build.github": "ng build --configuration=github --output-path ./dist/ghpages --base-href /igo2/",
"build.pwa": "ng build --configuration pwa --output-path ./dist/pwa",
"serve.prod": "http-server ./dist/igo2/ --port 4201 --no-browser",
"serve.pwa": "http-server ./dist/pwa/ --port 4201 --no-browser",
"test": "ng test --watch=false --browsers=ChromeHeadless",
"test.watch": "ng test",
"doc": "compodoc -p src/tsconfig.app.json -s --port 4220",
"build.doc": "compodoc -p src/tsconfig.app.json",
"serve.doc": "compodoc -s --port 4220",
"coverage": "npm run build.coverage && npm run serve.coverage",
"build.coverage": "ng test --code-coverage --watch=false",
"serve.coverage": "http-server ./coverage/ --port=4210 --no-browser",
"i18n": "ng2-translate-extract --dir ./src --output ./src/assets/locale/ --format=json --clean",
"test": "ng test --watch=false --browsers=ChromeHeadless",
"test.watch": "ng test",
"test.all": "npm run test && npm run e2e",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"changelog-current": "conventional-changelog -p angular -r 2",
"preversion.linux": "npm run test.all",
"version.linux": "rimraf ./dist && npm run build.prod && npm run changelog && git add -A CHANGELOG.md",
"postversion.linux": "git push && git push --tags && npm run ghpages",
"preversion": "npm run test.all",
"version": "rimraf ./dist && npm run build.prod && npm run changelog && git add -A CHANGELOG.md",
"postversion": "git push && git push --tags && npm run ghpages.win",
"preghpages": "npm run build.github && echo \"include: ['_default.json', '_contexts.json', '_base.json']\" > dist/ghpages/_config.yml",
"ghpages": "VERSION=$(node -p -e \"require('./package.json').version\") && npx ngh --dir=dist/ghpages --no-silent=false --message=$VERSION",
"postghpages": "rimraf ./dist/ghpages",
"preghpages.win": "npm run build.github && echo include: ['_default.json', '_contexts.json', '_base.json'] > dist/ghpages/_config.yml",
"ghpages.win": "npx ngh --dir=dist/ghpages --no-silent=false --message=%npm_package_version%"
"preversion": "npm run test && npm run e2e",
"version": "npm run release",
"postversion": "npm run changelog && git add -u && git push && git push --tags",
"release": "ts-node scripts/src/release.ts"
},
"dependencies": {
"@angular/animations": "^17.0.7",
Expand Down Expand Up @@ -95,12 +87,15 @@
"@types/node": "^20.6.2",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"@swc/core": "1.3.100",
"@swc/wasm": "1.3.100",
"angular-cli-ghpages": "^1.0.3",
"conventional-changelog-cli": "^4.1.0",
"cypress": "^13.2.0",
"eslint": "^8.53.0",
"eslint-plugin-cypress": "^2.14.0",
"eslint-plugin-unused-imports": "^3.0.0",
"execa": "^8.0.1",
"http-server": "^14.1.0",
"jasmine-core": "~5.1.0",
"jasmine-spec-reporter": "~7.0.0",
Expand All @@ -110,6 +105,7 @@
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"prettier": "^3.0.3",
"ts-node": "^10.9.2",
"typescript": "~5.2.2"
}
}
27 changes: 27 additions & 0 deletions scripts/src/config/paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { resolve } from 'path';

type FolderCaterogy = 'dist' | 'root' | 'src' | 'nodeModules';

type IPaths = Record<FolderCaterogy, string> & { [index: string]: string };

const ROOT_LEVEL = '../../../';
const ROOT = resolve(__dirname, ROOT_LEVEL);

export const resolveRoot = (relativePath: string): string => {
return resolve(ROOT, relativePath);
};

export const PATHS: IPaths = {
dist: resolveRoot('dist'),
nodeModules: resolveRoot('node_modules'),
src: resolveRoot('src'),
root: ROOT
};

export const resolvePackage = (name: string, ...paths: string[]): string => {
return resolve(PATHS.packages, name, ...paths);
};

export const resolveDist = (name: string): string => {
return resolve(PATHS.dist, name);
};
19 changes: 19 additions & 0 deletions scripts/src/core/utils/version.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { readFileSync } from 'fs';
import { writeFile } from 'fs/promises';

import { resolveRoot } from '../../config/paths';
import * as log from '../../utils/log';

export async function setVersionFile(version: string) {
const filePath = resolveRoot('src/environments/version.ts');

let body = readFileSync(filePath, 'utf-8');
body = body.replace(/app: '[A-Za-z0-9\.\-]+'/g, `app: '${version}'`);
body = body.replace(
/releaseDateApp: [0-9]+/g,
`releaseDateApp: ${Date.now()}`
);

await writeFile(filePath, body, { flag: 'w' });
log.success('The version file has been written');
}
53 changes: 53 additions & 0 deletions scripts/src/release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { setVersionFile } from './core/utils/version.utils';
import { writeFile2 } from './utils/file-system.utils';
import * as log from './utils/log';
import { getDuration } from './utils/performance.utils';

const baseCmdName = 'Application release';

log.startMsg(baseCmdName);
(async () => {
const startTime = performance.now();
try {
const [_nodePath, _scriptPath, argVersion, type] = process.argv;
const version = argVersion ?? process.env.npm_new_version;

if (!version) {
throw new Error('No version detected');
}

log.info('Create the version.ts file');
await setVersionFile(version);

await deployGithubPage(version);

log.success(`Release version ${version}`);

const duration = getDuration(startTime);
log.info(`${baseCmdName} excuted in ${duration}.`);
} catch (err: any) {
log.error(`The release failed with: ${err?.message}`);
process.exit(1);
}
})();

async function deployGithubPage(version: string): Promise<void> {
const startTime = performance.now();
const { $ } = await import('execa');
const $$ = $({ stdio: 'inherit' });

log.info('Build the app for Github');
await $$`npm run build.github`;
await writeFile2(
'dist/ghpages/_config.yml',
"include: ['_default.json', '_contexts.json', '_base.json']",
false
);

await $$`npx ngh --dir=dist/ghpages --no-silent=false --message=${version}`;

const duration = getDuration(startTime);
log.success(
`Deploy the app v${version} on Github Page, excuted in ${duration}.`
);
}
43 changes: 43 additions & 0 deletions scripts/src/utils/color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Source: https://github.com/ng-packagr/ng-packagr/blob/ee4fd635a626e1ee2266b05cb572002bb09b4849/src/lib/utils/color.ts
*/
import * as ansiColors from 'ansi-colors';
import { WriteStream } from 'tty';

type AnsiColors = typeof ansiColors;

function supportColor(): boolean {
if (process.env.FORCE_COLOR !== undefined) {
// 2 colors: FORCE_COLOR = 0 (Disables colors), depth 1
// 16 colors: FORCE_COLOR = 1, depth 4
// 256 colors: FORCE_COLOR = 2, depth 8
// 16,777,216 colors: FORCE_COLOR = 3, depth 16
// See: https://nodejs.org/dist/latest-v12.x/docs/api/tty.html#tty_writestream_getcolordepth_env
// and https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/tty.js#L106;
switch (process.env.FORCE_COLOR) {
case '':
case 'true':
case '1':
case '2':
case '3':
return true;
default:
return false;
}
}

if (process.stdout instanceof WriteStream) {
return process.stdout.getColorDepth() > 1;
}

return false;
}

// Create a separate instance to prevent unintended global changes to the color configuration
// Create function is not defined in the typings. See: https://github.com/doowb/ansi-colors/pull/44
const colors = (
ansiColors as AnsiColors & { create: () => AnsiColors }
).create();
colors.enabled = supportColor();

export { colors };
81 changes: 81 additions & 0 deletions scripts/src/utils/file-system.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { existsSync, readFileSync } from 'fs';
import {
copyFile as fsCopyFile,
mkdir,
readFile,
writeFile
} from 'fs/promises';
import { normalize, sep } from 'path';

export const BUFFER_ENCODING: BufferEncoding = 'utf-8';

export async function readFileContent<T>(path: string): Promise<T> {
const body = await readFile(path, BUFFER_ENCODING);
return JSON.parse(body) as T;
}

export function readFileContentSync<T>(path: string): T {
const body = readFileSync(path, BUFFER_ENCODING);
return JSON.parse(body) as T;
}

export async function createFile(
fileName: string,
dest: string,
body: string
): Promise<void> {
const path = `${dest}/${fileName}`;
try {
await writeFile(path, body, BUFFER_ENCODING);
} catch (err: any) {
if (err.code === 'ENOENT') {
await createFolderRecursively(dest);
await writeFile(path, body, BUFFER_ENCODING);
}
}
}

export async function copyFile(src: string, dest: string): Promise<void> {
try {
await fsCopyFile(src, dest);
} catch (err: any) {
if (err.code === 'ENOENT') {
await createPreviousFolder(dest);
await fsCopyFile(src, dest);
}
}
}

export async function createFolderRecursively(dest: string): Promise<void> {
try {
await mkdir(dest);
} catch (err: any) {
if (err.code === 'ENOENT') {
await createPreviousFolder(dest);
await createFolderRecursively(dest);
}
}
}

async function createPreviousFolder(dest: string): Promise<void> {
const folders = normalize(dest).split(sep);
folders.pop();
await createFolderRecursively(folders.join(sep));
}

export function pathExist(path: string): boolean {
return existsSync(path);
}

export function writeFile2(
path: string,
body: object | string,
endLineBreak = true
): Promise<void> {
let formattedBody =
typeof body === 'string' ? body : JSON.stringify(body, null, 2);
if (endLineBreak) {
formattedBody = formattedBody.concat('\n');
}
return writeFile(path, formattedBody, BUFFER_ENCODING);
}
49 changes: 49 additions & 0 deletions scripts/src/utils/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Source: https://github.com/ng-packagr/ng-packagr/blob/ee4fd635a626e1ee2266b05cb572002bb09b4849/src/lib/utils/log.ts
*/
/* eslint-disable no-console */
import { colors } from './color';

export const error = (err: string | Error) => {
if (err instanceof Error) {
console.error(colors.red('ERROR: ' + err.message));

if (process.env.DEBUG) {
console.error(colors.red(err.stack ?? '') + '\n');
}
} else {
console.error(colors.red(err));
}
};

export const warn = (msg: string) => {
console.warn(colors.yellow('WARNING: ' + msg));
};

export const success = (msg: string) => {
console.log(colors.green(msg));
};

export const info = (msg: string) => {
console.log(colors.blue(msg));
};

export const msg = (msg: string) => {
console.log(colors.white(msg));
};

export const debug = (msg: string) => {
if (process.env.DEBUG) {
console.log(colors.inverse.cyan(`[debug] ${msg}`));
}
};

export const startMsg = (message: string) => {
msg(
'\n------------------------------------------------------------------------------'
);
msg(message);
msg(
'------------------------------------------------------------------------------'
);
};
5 changes: 5 additions & 0 deletions scripts/src/utils/performance.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** Duration in ms */
export function getDuration(startTime: number): string {
const duration = Math.round(performance.now() - startTime);
return `${duration}ms`;
}
20 changes: 20 additions & 0 deletions scripts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"lib": ["es2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "es2022",
"rootDir": "./",
"isolatedModules": true,
"noImplicitAny": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"exclude": ["node_modules"],
"ts-node": {
"swc": true
}
}
Loading

0 comments on commit 4c9c8f7

Please sign in to comment.