import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; import { rxTransformJsonFile } from '@ibm-wch-sdk/schematics-utils'; import { assertObject, isNil, isNotNil } from '@ibm-wch-sdk/utils'; import { of } from 'rxjs'; import { mapTo } from 'rxjs/operators'; import { updateField } from '../utilities/json'; import { DEP_TYPE, updateMinVersion } from '../utilities/package'; import { findSdkVersion } from '../utilities/wch'; import { BUILD_COMMAND, CLI_IMPORT, DEPLOY_COMMAND, SDK_IMPORT } from './constants'; import { Schema } from './schema'; export const PACKAGE_PATH = '/package.json'; export const NPM_RUN_ALL = 'npm-run-all'; export const NPM_RUN_ALL_VERSION = '4.1.3'; export const BUILD_PRODUCTION = 'build:production'; export const PACKAGE_PRODUCTION = 'package:production'; export const DEPLOY_PUSH = 'deploy:push'; export const DEPLOY = 'deploy'; const INSTALL_FROM_ZIP = 'install-layouts-from-zip'; function _isOsloBuild(aScripts: any): boolean { return isNotNil(aScripts[INSTALL_FROM_ZIP]) && isNotNil(aScripts[DEPLOY]); } function _isNormalBuild(aScripts: any): boolean { return ( isNotNil(aScripts[BUILD_PRODUCTION]) && isNotNil(aScripts[PACKAGE_PRODUCTION]) && isNotNil(aScripts[DEPLOY_PUSH]) && isNotNil(aScripts[DEPLOY]) ); } function _updatePackage(aPkg: any, aVersion: string, aOptions: Schema): any { // prepare the structures const deps = assertObject('dependencies', aPkg); const devDeps = assertObject('devDependencies', aPkg); const scripts = assertObject('scripts', aPkg); // add the import if (isNil(devDeps[CLI_IMPORT])) { devDeps[CLI_IMPORT] = aVersion; } // add the import if (isNil(deps[SDK_IMPORT])) { deps[SDK_IMPORT] = aVersion; } // check for the Oslo vs the normal build if (_isNormalBuild(scripts)) { // add the CI commands updateField( BUILD_COMMAND, () => 'npm-run-all build:production package:production', scripts ); updateField( DEPLOY_COMMAND, () => 'npm-run-all deploy:purge deploy:push', scripts ); // add the npm-run-all script updateMinVersion( NPM_RUN_ALL, NPM_RUN_ALL_VERSION, aPkg, DEP_TYPE.DEVELOPMENT ); } else if (_isOsloBuild(scripts)) { // add the CI commands updateField(BUILD_COMMAND, () => 'npm run build', scripts); updateField( DEPLOY_COMMAND, () => 'npm run deploy -- --url ${ibm_wch_sdk_cli_url} --user ${ibm_wch_sdk_cli_username} --password ${ibm_wch_sdk_cli_password}', scripts ); } else { // just update updateField( BUILD_COMMAND, () => 'TODO: Please add a CI build script.', scripts ); updateField( DEPLOY_COMMAND, () => 'TODO: Please add a CI deploy script.', scripts ); } return aPkg; } export function updatePackage(options: Schema): Rule { return (host: Tree, context: SchematicContext) => { // get versions const sdkVersion = findSdkVersion(host); return rxTransformJsonFile( PACKAGE_PATH, (aBuild: any) => of(_updatePackage(aBuild || {}, sdkVersion, options)), host ).pipe(mapTo(host)); }; }