diff --git a/packages/sfp-cli/messages/build.json b/packages/sfp-cli/messages/build.json index fddd4ee44..91471c932 100644 --- a/packages/sfp-cli/messages/build.json +++ b/packages/sfp-cli/messages/build.json @@ -1,5 +1,5 @@ { - "commandDescription": "Build all packages (unlocked/source/data) in a repo in parallel, respecting the dependency of each packages and generate artifacts to a provided directory", + "commandDescription": "Build artifacts of your packages in the current project", "devhubAliasFlagDescription": "Provide the alias of the devhub previously authenticated, default value is HubOrg if using the Authenticate Devhub task", "diffCheckFlagDescription": "Only build the packages which have changed by analyzing previous tags", "gitTagFlagDescription": "Tag the current commit ID with an annotated tag containing the package name and version - does not push tag", diff --git a/packages/sfp-cli/messages/deploy.json b/packages/sfp-cli/messages/deploy.json index 12e357891..f7522fe41 100644 --- a/packages/sfp-cli/messages/deploy.json +++ b/packages/sfp-cli/messages/deploy.json @@ -1,5 +1,5 @@ { - "commandDescription": "Deploy packages from the provided aritfact directory, to a given org, using the order and configurable flags provided in sfdx-project.json", + "commandDescription": "Deploy artifacts from a given directory to a target org", "targetOrgFlagDescription": "Alias/User Name of the target environment", "artifactDirectoryFlagDescription": "The directory containing artifacts to be deployed", "waitTimeFlagDescription": "Wait time for command to finish in minutes", diff --git a/packages/sfp-cli/messages/fetch.json b/packages/sfp-cli/messages/fetch.json index c86cb016b..602914aeb 100644 --- a/packages/sfp-cli/messages/fetch.json +++ b/packages/sfp-cli/messages/fetch.json @@ -1,5 +1,5 @@ { - "commandDescription": "Fetch artifacts from an artifact registry that is either NPM compatible or supports universal artifacts", + "commandDescription": "Fetch sfp artifacts from a NPM compatible registry using a release definition file", "releaseDefinitionFlagDescription": "Path to YAML file containing map of packages and package versions to download", "artifactDirectoryFlagDescription": "Directory to save downloaded artifacts", "scriptPathFlagDescription": "(Optional: no-NPM) Path to script that authenticates and downloads artifacts from the registry", diff --git a/packages/sfp-cli/messages/patch.json b/packages/sfp-cli/messages/patch.json index ff60ea2e1..9cdf10c21 100644 --- a/packages/sfp-cli/messages/patch.json +++ b/packages/sfp-cli/messages/patch.json @@ -1,5 +1,5 @@ { - "commandDescription": "[Alpha] Patch a branch in the repository as per the release definition and create a new branch", + "commandDescription": "Generate a dynamic branch with the packages patched to the contents as mentioned in the release config file", "releaseDefinitionFlagDescription": "Path to release definiton yaml", "sourcebranchNameFlagDescription": "Name of the source branch to be used on which the alignment need to be applied", "targetbranchNameFlagDescription": "Name of the target branch to be created after the alignment", diff --git a/packages/sfp-cli/messages/profile_merge.json b/packages/sfp-cli/messages/profile_merge.json index f477a2467..613c2bb80 100644 --- a/packages/sfp-cli/messages/profile_merge.json +++ b/packages/sfp-cli/messages/profile_merge.json @@ -1,5 +1,5 @@ { - "commandDescription": "This command is used in the lower environments such as ScratchOrgs , Development / System Testing Sandboxes, inorder to apply the changes made in the environment to retrieved profile, so that it can be deployed to the higher environments", + "commandDescription": "Merge changes made in the profile directly in the org to the profile files in the local project", "folderFlagDescription": "comma separated list of folders to scan for profiles. If ommited, the folders in the packageDirectories configuration will be used.", "profileListFlagDescription": "comma separated list of profiles. If ommited, all the profiles found in the folder(s) will be merged", "metadataFlagDescription": "comma separated list of metadata for which the permissions will be retrieved.", diff --git a/packages/sfp-cli/messages/profile_reconcile.json b/packages/sfp-cli/messages/profile_reconcile.json index 8248bc9d6..928e03ad2 100644 --- a/packages/sfp-cli/messages/profile_reconcile.json +++ b/packages/sfp-cli/messages/profile_reconcile.json @@ -1,5 +1,5 @@ { - "commandDescription": "This command is used in the lower environments such as ScratchOrgs , Development / System Testing Sandboxes, where a retrieved profile from production has to be cleaned up only for the metadata that is contained in the environment or base it only as per the metadata that is contained in the packaging directory.", + "commandDescription": "Reconcile profiles in the local directory only with the attributes that are available in the target org", "folderFlagDescription": "path to the folder which contains the profiles to be reconciled,if project contain multiple package directories, please provide a comma seperated list, if omitted, all the package directories will be checked for profiles", "nameFlagDescription": "list of profiles to be reconciled. If ommited, all the profiles components will be reconciled.", "destFolderFlagDescription": " the destination folder for reconciled profiles, if omitted existing profiles will be reconciled and will be rewritten in the current location", diff --git a/packages/sfp-cli/messages/publish.json b/packages/sfp-cli/messages/publish.json index 3ef3c9acc..07e411faa 100644 --- a/packages/sfp-cli/messages/publish.json +++ b/packages/sfp-cli/messages/publish.json @@ -1,5 +1,5 @@ { - "commandDescription": "Publish packages to an artifact registry, using a user-provided script that is responsible for authenticating & uploading to the registry.", + "commandDescription": "Publish packages to a NPM Compatible artifact registry", "artifactDirectoryFlagDescription": "The directory containing artifacts to be published", "publishPromotedOnlyFlagDescription": "Only publish unlocked packages that have been promoted", "devhubAliasFlagDescription": "Provide the alias of the devhub previously authenticated", diff --git a/packages/sfp-cli/messages/quickbuild.json b/packages/sfp-cli/messages/quickbuild.json index 700b8dcbc..15326a638 100644 --- a/packages/sfp-cli/messages/quickbuild.json +++ b/packages/sfp-cli/messages/quickbuild.json @@ -1,5 +1,5 @@ { - "commandDescription": "Build packages (unlocked/source/data) in a repo in parallel, without validating depenencies or coverage in the case of unlocked packages", + "commandDescription": "Build artifacts of your packages in the current project without dependency validation for unlocked packages", "devhubAliasFlagDescription": "Provide the alias of the devhub previously authenticated, default value is HubOrg if using the Authenticate Devhub task", "diffCheckFlagDescription": "Only build the packages which have changed by analyzing previous tags", "gitTagFlagDescription": "Tag the current commit ID with an annotated tag containing the package name and version - does not push tag", diff --git a/packages/sfp-cli/messages/release.json b/packages/sfp-cli/messages/release.json index 890fd0a22..ab9c2e852 100644 --- a/packages/sfp-cli/messages/release.json +++ b/packages/sfp-cli/messages/release.json @@ -1,5 +1,5 @@ { - "commandDescription": "Release a collection of artifacts as defined in the release definition file", + "commandDescription": "Deploy a release definition to a target org", "releaseDefinitionFlagDescription": "Path to release definiton yaml, Multiple paths can be seperated by commas", "targetOrgFlagDescription": "Alias/User Name of the target environment", "scriptPathFlagDescription": "(Optional: no-NPM) Path to script that authenticates and downloads artifacts from the registry", diff --git a/packages/sfp-cli/messages/releasedefinition_generate.json b/packages/sfp-cli/messages/releasedefinition_generate.json index f3072d865..e00a840c4 100644 --- a/packages/sfp-cli/messages/releasedefinition_generate.json +++ b/packages/sfp-cli/messages/releasedefinition_generate.json @@ -1,5 +1,5 @@ { - "commandDescription": "Generates release definition based on the artifacts installed from a commit reference", + "commandDescription": "Generates release definition based on the artifacts at the specified head of source branch/commit ref", "configFileFlagDescription":"Path to the release config file which determines how the release definition should be generated", "releaseNameFlagDescription": "Set a release name on the release definition file created", "commitFlagDescription": "Utilize the tags on the source branch to generate release definiton", diff --git a/packages/sfp-cli/messages/validate.json b/packages/sfp-cli/messages/validate.json index d39050221..ffed11035 100644 --- a/packages/sfp-cli/messages/validate.json +++ b/packages/sfp-cli/messages/validate.json @@ -1,5 +1,5 @@ { - "commandDescription": "Validate the incoming change against an earlier prepared scratchorg", + "commandDescription": "Build and Validate a set of artifacts against an enviroments prepared by Prepare Command", "devhubUsernameFlagDescription": "Authentication username for Dev Hub", "poolsFlagDescription": "Fetch scratch-org validation environment from one of listed pools, sequentially", "configFileFlagDescription":"(Required if the release modes are ff-relese-config or thorough-release-config), Path to the config file which determines how the release defintion should be generated", diff --git a/packages/sfp-cli/messages/validateAgainstOrg.json b/packages/sfp-cli/messages/validateAgainstOrg.json index 395d98d4f..4a0846e36 100644 --- a/packages/sfp-cli/messages/validateAgainstOrg.json +++ b/packages/sfp-cli/messages/validateAgainstOrg.json @@ -1,5 +1,5 @@ { - "commandDescription": "Validate the incoming change against target org", + "commandDescription": "Build and Validate a set of artifacts against a provided org", "targetOrgFlagDescription": "Alias/User Name of the target environment", "coveragePercentFlagDescription": "Minimum required percentage coverage for validating code coverage of packages with Apex classes", "logsGroupSymbolFlagDescription": "Symbol used by CICD platform to group/collapse logs in the console. Provide an opening group, and an optional closing group symbol.", diff --git a/packages/sfp-cli/package.json b/packages/sfp-cli/package.json index 3309875a9..414e7e492 100644 --- a/packages/sfp-cli/package.json +++ b/packages/sfp-cli/package.json @@ -107,9 +107,6 @@ "releasedefinition": { "description": "Commands around release definition" }, - "orchestrator": { - "description": "[Deprecated] Orchestrate packages from a monorepo through its lifecycle, driven by descriptors in your sfdx-project.json" - }, "pool": { "description": "Manage the pooled orgs created by the sfp orchestrator in prepare stage" }, diff --git a/packages/sfp-cli/src/commands/orchestrator/build.ts b/packages/sfp-cli/src/commands/orchestrator/build.ts deleted file mode 100644 index 6cbcfb656..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/build.ts +++ /dev/null @@ -1,45 +0,0 @@ -import BuildImpl, { BuildProps } from '../../impl/parallelBuilder/BuildImpl'; -import { Stage } from '../../impl/Stage'; -import BuildBase from '../../BuildBase'; -import { Messages } from '@salesforce/core'; - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'build'); - -export default class Build extends BuildBase { - public static description = messages.getMessage('commandDescription'); - - getStage() { - return Stage.BUILD; - } - - getBuildProps(): BuildProps { - let buildProps: BuildProps = { - configFilePath: this.flags.configfilepath, - devhubAlias: this.flags.devhubalias, - repourl: this.flags.repourl, - waitTime: this.flags.waittime, - isQuickBuild: false, - isDiffCheckEnabled: this.flags.diffcheck, - buildNumber: this.flags.buildnumber, - executorcount: this.flags.executorcount, - branch: this.flags.branch, - currentStage: Stage.BUILD, - isBuildAllAsSourcePackages: false, - diffOptions: { - useLatestGitTags: true, - skipPackageDescriptorChange: false, - }, - }; - return buildProps; - } - - getBuildImplementer(buildProps: BuildProps): BuildImpl { - let buildImpl = new BuildImpl(buildProps); - return buildImpl; - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/deploy.ts b/packages/sfp-cli/src/commands/orchestrator/deploy.ts deleted file mode 100644 index a9d8c9ce9..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/deploy.ts +++ /dev/null @@ -1,168 +0,0 @@ -import SfpCommand from '../../SfpCommand'; -import { Messages } from '@salesforce/core'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import DeployImpl, { DeploymentMode, DeployProps, DeploymentResult } from '../../impl/deploy/DeployImpl'; -import { Stage } from '../../impl/Stage'; -import SFPLogger, { - COLOR_ERROR, - COLOR_HEADER, - COLOR_KEY_MESSAGE, - COLOR_SUCCESS, -} from '@flxblio/sfp-logger'; -import { COLOR_TIME } from '@flxblio/sfp-logger'; -import getFormattedTime from '../../core/utils/GetFormattedTime'; -import { Flags } from '@oclif/core'; -import { arrayFlagSfdxStyle, loglevel, logsgroupsymbol, requiredUserNameFlag } from '../../flags/sfdxflags'; -import { LoggerLevel } from '@flxblio/sfp-logger'; - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'deploy'); - -export default class Deploy extends SfpCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp orchestrator:deploy -u `]; - - protected static requiresUsername = false; - protected static requiresDevhubUsername = false; - protected static requiresProject = false; - - public static flags = { - targetorg: requiredUserNameFlag, - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - waittime: Flags.integer({ - description: messages.getMessage('waitTimeFlagDescription'), - default: 120, - }), - tag: Flags.string({ - char: 't', - description: messages.getMessage('tagFlagDescription'), - }), - skipifalreadyinstalled: Flags.boolean({ - required: false, - default: false, - description: messages.getMessage('skipIfAlreadyInstalled'), - }), - baselineorg: Flags.string({ - char: 'b', - description: messages.getMessage('baselineorgFlagDescription'), - required: false, - dependsOn: ['skipifalreadyinstalled'], - }), - allowunpromotedpackages: Flags.boolean({ - description: messages.getMessage('allowUnpromotedPackagesFlagDescription'), - deprecated: { - message: '--allowunpromotedpackages is deprecated, All packages are allowed' - }, - hidden: true, - }), - retryonfailure: Flags.boolean({ - description: messages.getMessage('retryOnFailureFlagDescription'), - hidden: true, - }), - releaseconfig: Flags.string({ - description: messages.getMessage('configFileFlagDescription'), - }), - enablesourcetracking: Flags.boolean({ - description: messages.getMessage('enableSourceTrackingFlagDescription'), - }), - logsgroupsymbol, - loglevel - }; - - public async execute() { - let executionStartTime = Date.now(); - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`deploy`)}`)); - SFPLogger.log(COLOR_HEADER(`Skip Packages If Already Installed: ${this.flags.skipifalreadyinstalled}`)); - SFPLogger.log(COLOR_HEADER(`Artifact Directory: ${this.flags.artifactdir}`)); - SFPLogger.log(COLOR_HEADER(`Target Environment: ${this.flags.targetorg}`)); - if(this.flags.releaseconfig) SFPLogger.log(COLOR_HEADER(`Filter according to: ${this.flags.releaseconfig}`)); - if (this.flags.baselineorg) SFPLogger.log(COLOR_HEADER(`Baselined Against Org: ${this.flags.baselineorg}`)); - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - let deploymentResult: DeploymentResult; - - let tags = { - targetOrg: this.flags.targetorg, - }; - - if (this.flags.tag != null) { - tags['tag'] = this.flags.tag; - } - - let deployProps: DeployProps = { - targetUsername: this.flags.targetorg, - artifactDir: this.flags.artifactdir, - waitTime: this.flags.waittime, - tags: tags, - isTestsToBeTriggered: false, - deploymentMode: this.flags.enablesourcetracking? DeploymentMode.SOURCEPACKAGES_PUSH: DeploymentMode.NORMAL, - skipIfPackageInstalled: this.flags.skipifalreadyinstalled, - logsGroupSymbol: this.flags.logsgroupsymbol, - currentStage: Stage.DEPLOY, - baselineOrg: this.flags.baselineorg, - isRetryOnFailure: this.flags.retryonfailure, - releaseConfigPath: this.flags.releaseconfig, - }; - - try { - let deployImpl: DeployImpl = new DeployImpl(deployProps); - - deploymentResult = await deployImpl.exec(); - - if (deploymentResult.failed.length > 0 || deploymentResult.error) { - process.exitCode = 1; - } - } catch (error) { - SFPLogger.log(COLOR_ERROR(error)); - process.exitCode = 1; - } finally { - let totalElapsedTime: number = Date.now() - executionStartTime; - - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - SFPLogger.log( - COLOR_SUCCESS( - `${deploymentResult.deployed.length} packages deployed in ${COLOR_TIME( - getFormattedTime(totalElapsedTime) - )} with {${deploymentResult.failed.length}} errors` - ) - ); - - if (deploymentResult.failed.length > 0) { - SFPLogger.log( - COLOR_ERROR( - `\nPackages Failed to Deploy`, - deploymentResult.failed.map((packageInfo) => packageInfo.sfpPackage.packageName) - ) - ); - } - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - - SFPStatsSender.logCount('deploy.scheduled', tags); - - SFPStatsSender.logGauge('deploy.packages.scheduled', deploymentResult.scheduled, tags); - - SFPStatsSender.logGauge('deploy.duration', totalElapsedTime, tags); - - SFPStatsSender.logGauge('deploy.succeeded.packages', deploymentResult.deployed.length, tags); - - SFPStatsSender.logGauge('deploy.failed.packages', deploymentResult.failed.length, tags); - - if (deploymentResult.failed.length > 0) { - SFPStatsSender.logCount('deploy.failed', tags); - } else { - SFPStatsSender.logCount('deploy.succeeded', tags); - } - } - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/prepare.ts b/packages/sfp-cli/src/commands/orchestrator/prepare.ts deleted file mode 100644 index 0e6c3a024..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/prepare.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { Messages } from '@salesforce/core'; -import SfpCommand from '../../SfpCommand'; -import PrepareImpl from '../../impl/prepare/PrepareImpl'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import { Stage } from '../../impl/Stage'; -import * as fs from 'fs-extra'; -import ScratchOrgInfoFetcher from '../../core/scratchorg/pool/services/fetchers/ScratchOrgInfoFetcher'; -import Ajv from 'ajv'; -import path = require('path'); -import { PoolErrorCodes } from '../../core/scratchorg/pool/PoolError'; -import SFPLogger, { - LoggerLevel, - COLOR_ERROR, - COLOR_HEADER, - COLOR_SUCCESS, - COLOR_TIME, - COLOR_KEY_MESSAGE, -} from '@flxblio/sfp-logger'; -import getFormattedTime from '../../core/utils/GetFormattedTime'; -import { PoolConfig } from '../../core/scratchorg/pool/PoolConfig'; -import { COLOR_WARNING } from '@flxblio/sfp-logger'; -import SFPOrg from '../../core/org/SFPOrg'; -import { Flags } from '@oclif/core'; -import { loglevel, logsgroupsymbol, targetdevhubusername } from '../../flags/sfdxflags'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'prepare'); - -export default class Prepare extends SfpCommand { - protected static requiresDevhubUsername = true; - protected static requiresProject = true; - - public static flags = { - targetdevhubusername, - poolconfig: Flags.file({ - required: false, - default: 'config/poolconfig.json', - char: 'f', - description: messages.getMessage('poolConfigFlagDescription'), - }), - npmrcpath: Flags.file({ - description: messages.getMessage('npmrcPathFlagDescription'), - required: false, - }), - keys: Flags.string({ - required: false, - description: messages.getMessage('keysDescription'), - }), - logsgroupsymbol, - loglevel - }; - - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp orchestrator:prepare -f config/mypoolconfig.json -v `]; - - public async execute(): Promise { - let executionStartTime = Date.now(); - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`prepare`)}`)); - - //Read pool config - try { - let poolConfig: PoolConfig = fs.readJSONSync(this.flags.poolconfig); - this.validatePoolConfig(poolConfig); - //Assign Keys to the config - if (this.flags.keys) poolConfig.keys = this.flags.keys; - - this.displayHeader(poolConfig); - - //Assign npmrcPath to the config - if (this.flags.npmrcpath) { - if (poolConfig.fetchArtifacts?.npm) poolConfig.fetchArtifacts.npm.npmrcPath = this.flags.npmrcpath; - else - SFPLogger.log( - COLOR_WARNING( - 'npmrcPath found in flag, however the configuration doesnt seem to use npm, Are you sure your schema is good?' - ) - ); - } - - let tags = { - stage: Stage.PREPARE, - poolName: poolConfig.tag, - }; - - await this.hubOrg.refreshAuth(); - const hubConn = this.hubOrg.getConnection(); - - this.flags.apiversion = this.flags.apiversion || (await hubConn.retrieveMaxApiVersion()); - - let hubOrgAsSfPOrg = await SFPOrg.create({ connection: this.hubOrg.getConnection() }); - let prepareImpl = new PrepareImpl(hubOrgAsSfPOrg, poolConfig, this.flags.loglevel); - - let results = await prepareImpl.exec(); - if (results.isOk()) { - let totalElapsedTime = Date.now() - executionStartTime; - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - SFPLogger.log( - COLOR_SUCCESS( - `Provisioned {${results.value.scratchOrgs.length}} scratchorgs out of ${ - results.value.to_allocate - } requested with ${COLOR_ERROR(results.value.failedToCreate)} failed in ${COLOR_TIME( - getFormattedTime(totalElapsedTime) - )} ` - ) - ); - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - await this.getCurrentRemainingNumberOfOrgsInPoolAndReport(poolConfig); - - SFPStatsSender.logGauge('prepare.succeededorgs', results.value.scratchOrgs.length, tags); - if (results.value.scratchOrgs.length > 0) - SFPStatsSender.logGauge('prepare.duration', Date.now() - executionStartTime, tags); - } else if (results.isErr()) { - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - SFPLogger.log(COLOR_ERROR(results.error.message), LoggerLevel.ERROR); - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - switch (results.error.errorCode) { - case PoolErrorCodes.Max_Capacity: - process.exitCode = 0; - break; - case PoolErrorCodes.No_Capacity: - process.exitCode = 0; - break; - case PoolErrorCodes.PrerequisiteMissing: - process.exitCode = 1; - break; - case PoolErrorCodes.UnableToProvisionAny: - SFPStatsSender.logGauge('prepare.failedorgs', results.error.failed, tags); - process.exitCode = 1; - break; - } - } - } catch (err) { - throw new Error('Unable to execute command .. ' + err); - } - } - - private displayHeader(poolConfig: PoolConfig) { - SFPLogger.log(COLOR_HEADER(`Pool Name: ${poolConfig.tag}`)); - SFPLogger.log(COLOR_HEADER(`Requested Count of Orgs: ${poolConfig.maxAllocation}`)); - SFPLogger.log( - COLOR_HEADER( - `Scratch Orgs to be submitted to pool in case of failures: ${ - poolConfig.succeedOnDeploymentErrors ? 'true' : 'false' - }` - ) - ); - - SFPLogger.log( - COLOR_HEADER(`All packages in the repo to be installed: ${poolConfig.installAll ? 'true' : 'false'}`) - ); - - SFPLogger.log( - COLOR_HEADER( - `Enable Source Tracking: ${ - poolConfig.enableSourceTracking || poolConfig.enableSourceTracking === undefined ? 'true' : 'false' - }` - ) - ); - - if (poolConfig.enableVlocity) SFPLogger.log(COLOR_HEADER(`Enable Vlocity Config: true`)); - - if (poolConfig.fetchArtifacts) { - if (poolConfig.fetchArtifacts.artifactFetchScript) - SFPLogger.log( - COLOR_HEADER(`Script provided to fetch artifacts: ${poolConfig.fetchArtifacts.artifactFetchScript}`) - ); - if (poolConfig.fetchArtifacts.npm) { - SFPLogger.log(COLOR_HEADER(`Fetch artifacts from pre-authenticated NPM registry: true`)); - } - } - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - } - - private async getCurrentRemainingNumberOfOrgsInPoolAndReport(poolConfig: PoolConfig) { - try { - const results = await new ScratchOrgInfoFetcher(this.hubOrg).getScratchOrgsByTag( - this.flags.tag, - false, - true - ); - - let tags = { - stage: Stage.PREPARE, - poolName: poolConfig.tag, - }; - - let availableSo = results.records.filter((soInfo) => soInfo.Allocation_status__c === 'Available'); - - SFPStatsSender.logGauge('pool.available', availableSo.length, tags); - } catch (error) { - //do nothing, we are not reporting anything if anything goes wrong here - } - } - - public validatePoolConfig(poolConfig: any) { - let ajv = new Ajv({ allErrors: true }); - let schema = fs.readJSONSync( - path.join(__dirname, '..', '..', '..', 'resources', 'schemas', 'pooldefinition.schema.json'), - { encoding: 'UTF-8' } - ); - let validator = ajv.compile(schema); - let isSchemaValid = validator(poolConfig); - if (!isSchemaValid) { - let errorMsg: string = `The pool configuration is invalid, Please fix the following errors\n`; - - validator.errors.forEach((error, errorNum) => { - errorMsg += `\n${errorNum + 1}: ${error.instancePath}: ${error.message} ${JSON.stringify( - error.params, - null, - 4 - )}`; - }); - - throw new Error(errorMsg); - } - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/promote.ts b/packages/sfp-cli/src/commands/orchestrator/promote.ts deleted file mode 100644 index fb067b87e..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/promote.ts +++ /dev/null @@ -1,115 +0,0 @@ -import SfpCommand from '../../SfpCommand'; -import { Messages } from '@salesforce/core'; -import PromoteUnlockedPackageImpl from '../../core/package/promote/PromoteUnlockedPackageImpl' -import ArtifactFetcher from '../../core/artifacts/ArtifactFetcher'; -import { ConsoleLogger } from '@flxblio/sfp-logger'; -import SfpPackageBuilder from '../../core/package/SfpPackageBuilder'; -import { PackageType } from '../../core/package/SfpPackage'; -import { Flags, ux } from '@oclif/core'; -import { loglevel, targetdevhubusername } from '../../flags/sfdxflags'; -import { LoggerLevel } from '@flxblio/sfp-logger'; -import { COLOR_HEADER } from '@flxblio/sfp-logger'; -import SFPLogger from '@flxblio/sfp-logger'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'promote'); - -export default class Promote extends SfpCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp orchestrator:promote -d path/to/artifacts -v `]; - - protected static requiresDevhubUsername = true; - - public static flags = { - targetdevhubusername, - artifactdir: Flags.directory({ - required: true, - char: 'd', - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - outputdir: Flags.directory({ - required: false, - char: 'o', - description: messages.getMessage('outputDirectoryFlagDescription'), - hidden: true, - deprecated: { - message: '--outputdir is deprecated, Artifacts are no longer modified after promote', - }, - }), - loglevel - }; - - public async execute() { - SFPLogger.log(COLOR_HEADER('command: promote')); - SFPLogger.log(COLOR_HEADER(`Artifact Directory: ${this.flags.artifactdir}`)); - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - //Refresh HubOrg Authentication - await this.hubOrg.refreshAuth(); - - let unpromotedPackages: { name: string; error: string }[] = []; - try { - let artifacts = ArtifactFetcher.fetchArtifacts(this.flags.artifactdir); - - if (artifacts.length === 0) { - throw new Error(`No artifacts found at ${this.flags.artifactdir}`); - } - - let result: boolean = true; - let promotedPackages: string[] = []; - for (let artifact of artifacts) { - let sfpPackage = await SfpPackageBuilder.buildPackageFromArtifact(artifact, new ConsoleLogger()); - try { - if (sfpPackage.package_type === PackageType.Unlocked) { - let promoteUnlockedPackageImpl = new PromoteUnlockedPackageImpl( - artifact.sourceDirectoryPath, - sfpPackage.package_version_id, - this.hubOrg.getUsername() - ); - await promoteUnlockedPackageImpl.promote(); - } - - promotedPackages.push(sfpPackage.packageName); - } catch (err) { - result = false; - - unpromotedPackages.push({ - name: sfpPackage.packageName, - error: err.message, - }); - } - } - console.log(`Promoted packages:`, promotedPackages); - - // Overall exit status is 1 if a package failed to promote - if (!result) { - throw new Error(); - } - } catch (err) { - console.log(err.message); - - // Print unpromoted packages with reason for failure - if (unpromotedPackages.length > 0) { - ux.table(unpromotedPackages, { name: {}, error: {} }); - } - - // Fail the task when an error occurs - process.exitCode = 1; - } - } - - private substituteBuildNumberWithPreRelease(packageVersionNumber: string) { - let segments = packageVersionNumber.split('.'); - - if (segments.length === 4) { - packageVersionNumber = segments.reduce((version, segment, segmentsIdx) => { - if (segmentsIdx === 3) return version + '-' + segment; - else return version + '.' + segment; - }); - } - - return packageVersionNumber; - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/publish.ts b/packages/sfp-cli/src/commands/orchestrator/publish.ts deleted file mode 100644 index 2209abba3..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/publish.ts +++ /dev/null @@ -1,460 +0,0 @@ -import SfpCommand from '../../SfpCommand'; -import { Messages } from '@salesforce/core'; -import * as fs from 'fs-extra'; -import path = require('path'); -import ArtifactFetcher, { Artifact } from '../../core/artifacts/ArtifactFetcher'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import SFPLogger, { - COLOR_ERROR, - COLOR_HEADER, - COLOR_KEY_MESSAGE, - COLOR_SUCCESS, - COLOR_TIME, -} from '@flxblio/sfp-logger'; -import getFormattedTime from '../../core/utils/GetFormattedTime'; -import defaultShell from '../../core/utils/DefaultShell'; -import SfpPackage, { PackageType } from '../../core/package/SfpPackage'; -import { ConsoleLogger } from '@flxblio/sfp-logger'; -import SfpPackageBuilder from '../../core/package/SfpPackageBuilder'; -import Git from '../../core/git/Git'; -import GroupConsoleLogs from '../../ui/GroupConsoleLogs'; -import PackageVersionLister from '../../core/package/version/PackageVersionLister'; -import SFPOrg from '../../core/org/SFPOrg'; -import ExecuteCommand from '@flxblio/sfdx-process-wrapper/lib/commandExecutor/ExecuteCommand'; -import { LoggerLevel } from '@flxblio/sfp-logger'; -import GitTags from '../../core/git/GitTags'; -import { arrayFlagSfdxStyle, loglevel, logsgroupsymbol, optionalDevHubFlag } from '../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'publish'); - -export default class Promote extends SfpCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [ - `$ sfp orchestrator:publish -f path/to/script`, - `$ sfp orchestrator:publish --npm`, - `$ sfp orchestrator:publish -f path/to/script -p -v HubOrg`, - `$ sfp orchestrator:publish -f path/to/script --gittag --pushgittag`, - ]; - - protected static requiresUsername = false; - protected static requiresDevhubUsername = false; - - public static flags = { - artifactdir: Flags.directory({ - required: true, - char: 'd', - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - publishpromotedonly: Flags.boolean({ - char: 'p', - description: messages.getMessage('publishPromotedOnlyFlagDescription'), - dependsOn: ['devhubalias'], - }), - 'devhubalias':optionalDevHubFlag, - scriptpath: Flags.file({ - char: 'f', - description: messages.getMessage('scriptPathFlagDescription'), - }), - tag: Flags.string({ - char: 't', - description: messages.getMessage('tagFlagDescription'), - }), - gittag: Flags.boolean({ - description: messages.getMessage('gitTagFlagDescription'), - default: false, - }), - gittaglimit: Flags.integer({ - description: messages.getMessage('gitTagLimitFlagDescription'), - }), - gittagage: Flags.integer({ - description: messages.getMessage('gitTagAgeFlagDescription'), - }), - pushgittag: Flags.boolean({ - description: messages.getMessage('gitPushTagFlagDescription'), - default: false, - }), - npm: Flags.boolean({ - description: messages.getMessage('npmFlagDescription'), - exclusive: ['scriptpath'], - }), - scope: Flags.string({ - description: messages.getMessage('scopeFlagDescription'), - dependsOn: ['npm'], - parse: async (scope) => scope.replace(/@/g, '').toLowerCase(), - }), - npmtag: Flags.string({ - description: messages.getMessage('npmTagFlagDescription'), - dependsOn: ['npm'], - required: false, - deprecated: { - message: - '--npmtag is deprecated, sfp will automatically tag the artifact with the branch name', - }, - }), - npmrcpath: Flags.file({ - description: messages.getMessage('npmrcPathFlagDescription'), - dependsOn: ['npm'], - required: false, - }), - logsgroupsymbol, - loglevel - }; - private git: Git; - - public async execute() { - let nPublishedArtifacts: number = 0; - let failedArtifacts: string[] = []; - - let executionStartTime = Date.now(); - - let succesfullyPublishedPackageNamesForTagging: { - name: string; - version: string; - type: string; - tag: string; - commitId: string; - }[] = []; - - let npmrcFilesToCleanup: string[] = []; - this.git = await Git.initiateRepo(new ConsoleLogger()); - - try { - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`publish`)}`)); - SFPLogger.log(COLOR_HEADER(`target: ${this.flags.scriptpath ? this.flags.scriptpath : 'NPM'}`)); - SFPLogger.log( - COLOR_HEADER(`Publish promoted artifacts only: ${this.flags.publishpromotedonly ? true : false}`) - ); - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - let packageVersionList: any; - if (this.flags.publishpromotedonly) { - let hubOrg = await SFPOrg.create({ aliasOrUsername: this.flags.devhubalias }); - let packageVersionLister: PackageVersionLister = new PackageVersionLister(hubOrg); - packageVersionList = await packageVersionLister.listAllReleasedVersions(process.cwd()); - } - - let artifacts = ArtifactFetcher.findArtifacts(this.flags.artifactdir); - let artifactFilePaths = ArtifactFetcher.fetchArtifacts(this.flags.artifactdir); - - // Pattern captures two named groups, the "package" name and "version" number - let pattern = new RegExp('(?^.*)(?:_sfpowerscripts_artifact_)(?.*)(?:\\.zip)'); - for (let artifact of artifacts) { - let packageName: string; - let packageVersionNumber: string; - - let match: RegExpMatchArray = path.basename(artifact).match(pattern); - - if (match !== null) { - packageName = match.groups.package; - packageVersionNumber = match.groups.version; - } else { - // artifact filename doesn't match pattern - continue; - } - - let sfpPackage = await this.getPackageInfo(artifactFilePaths, packageName, packageVersionNumber); - - let packageType = sfpPackage.package_type; - let packageVersionId = sfpPackage.package_version_id; - - if (this.flags.publishpromotedonly && packageType === PackageType.Unlocked) { - let isReleased = this.isPackageVersionIdReleased(packageVersionList, packageVersionId); - - if (!isReleased) { - failedArtifacts.push(`${packageName} v${packageVersionNumber}`); - SFPLogger.log( - `Skipping ${packageName} Version ${packageVersionNumber}. Package Version Id ${packageVersionId} has not been promoted.` - ); - process.exitCode = 1; - continue; - } - } - - try { - if (this.flags.npm) { - await this.publishUsingNpm(sfpPackage, packageVersionNumber, npmrcFilesToCleanup); - } else { - await this.publishUsingScript(packageName, packageVersionNumber, artifact); - } - - succesfullyPublishedPackageNamesForTagging.push({ - name: packageName, - version: packageVersionNumber.replace('-', '.'), - type: packageType, - tag: `${packageName}_v${packageVersionNumber.replace('-', '.')}`, - commitId: sfpPackage.sourceVersion - }); - - nPublishedArtifacts++; - } catch (err) { - failedArtifacts.push(`${packageName} v${packageVersionNumber}`); - SFPLogger.log(err.message); - process.exitCode = 1; - } - } - - if (this.flags.gittag) { - await this.createGitTags(succesfullyPublishedPackageNamesForTagging); - await this.pushGitTags(succesfullyPublishedPackageNamesForTagging); - } - - - if (this.flags.gittagage && this.flags.gittaglimit) { - await this.deleteGitTagsOlderThan(succesfullyPublishedPackageNamesForTagging, this.flags.gittagage, this.flags.gittaglimit); - } else if (this.flags.gittagage) { - await this.deleteGitTagsOlderThan(succesfullyPublishedPackageNamesForTagging, this.flags.gittagage); - } else if (this.flags.gittaglimit) { - await this.deleteExcessGitTags(succesfullyPublishedPackageNamesForTagging, this.flags.gittaglimit); - } - - - } catch (err) { - SFPLogger.log(err.message); - - // Fail the task when an error occurs - process.exitCode = 1; - } finally { - if (npmrcFilesToCleanup.length > 0) { - npmrcFilesToCleanup.forEach((npmrcFile) => { - fs.unlinkSync(npmrcFile); - }); - } - - let totalElapsedTime: number = Date.now() - executionStartTime; - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - SFPLogger.log( - COLOR_SUCCESS( - `${nPublishedArtifacts} artifacts published in ${COLOR_TIME( - getFormattedTime(totalElapsedTime) - )} with {${COLOR_ERROR(failedArtifacts.length)}} errors` - ) - ); - - if (failedArtifacts.length > 0) { - SFPLogger.log(COLOR_ERROR(`Packages Failed to Publish`, failedArtifacts)); - } - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - let tags = { - publish_promoted_only: this.flags.publishpromotedonly ? 'true' : 'false', - }; - - if (this.flags.tag != null) { - tags['tag'] = this.flags.tag; - } - - SFPStatsSender.logGauge('publish.duration', totalElapsedTime, tags); - - SFPStatsSender.logGauge('publish.succeeded', nPublishedArtifacts, tags); - - if (failedArtifacts.length > 0) { - SFPStatsSender.logGauge('publish.failed', failedArtifacts.length, tags); - } - } - } - - private async publishUsingNpm(sfpPackage: SfpPackage, packageVersionNumber: string, npmrcFilesToCleanup: string[]) { - let publishGroupSection = new GroupConsoleLogs(`Publishing ${sfpPackage.packageName}`).begin(); - let artifactRootDirectory = path.dirname(sfpPackage.sourceDir); - - // NPM does not accept packages with uppercase characters - let name: string = sfpPackage.packageName.toLowerCase() + '_sfpowerscripts_artifact'; - - //Check whether the user has already passed in @ - - if (this.flags.scope) { - let scope: string = this.flags.scope.replace(/@/g, '').toLowerCase(); - name = `@${scope}/` + name; - } - - let packageJson = { - name: name, - version: packageVersionNumber, - repository: sfpPackage.repository_url, - }; - - fs.writeFileSync(path.join(artifactRootDirectory, 'package.json'), JSON.stringify(packageJson, null, 4)); - - if (this.flags.npmrcpath) { - fs.copyFileSync(this.flags.npmrcpath, path.join(artifactRootDirectory, '.npmrc')); - - npmrcFilesToCleanup.push(path.join(artifactRootDirectory, '.npmrc')); - } - - let cmd = `npm publish`; - - //Do a tag based on the branch - if (sfpPackage.branch) { - cmd += ` --tag ${sfpPackage.branch}`; - SFPLogger.log( - COLOR_KEY_MESSAGE( - `Publishing ${sfpPackage.packageName} Version ${packageVersionNumber} with tag ${sfpPackage.branch}...` - ) - ); - } - - let npmPublishExecutor: ExecuteCommand = new ExecuteCommand(new ConsoleLogger(), LoggerLevel.INFO, true); - await npmPublishExecutor.execCommand(cmd, artifactRootDirectory); - - publishGroupSection.end(); - } - - private async publishUsingScript(packageName: string, packageVersionNumber: string, artifact: string) { - let publishGroupSection = new GroupConsoleLogs(`Publishing ${packageName}`).begin(); - let cmd: string; - if (process.platform !== 'win32') { - cmd = `${defaultShell()} -e ${this.flags.scriptpath} ${packageName} ${packageVersionNumber} ${artifact} ${ - this.flags.publishpromotedonly ? true : false - }`; - } else { - cmd = `cmd.exe /c ${this.flags.scriptpath} ${packageName} ${packageVersionNumber} ${artifact} ${ - this.flags.publishpromotedonly ? true : false - }`; - } - - SFPLogger.log(COLOR_KEY_MESSAGE(`Publishing ${packageName} Version ${packageVersionNumber}...`)); - - let scriptExecutor: ExecuteCommand = new ExecuteCommand(new ConsoleLogger(), LoggerLevel.INFO, true); - await scriptExecutor.execCommand(cmd, process.cwd()); - publishGroupSection.end(); - } - - protected validateFlags() { - if (this.flags.scriptpath === undefined && this.flags.npm === undefined) - throw new Error('Either --scriptpath or --npm flag must be provided'); - - if (this.flags.scriptpath && !fs.existsSync(this.flags.scriptpath)) - throw new Error(`Script path ${this.flags.scriptpath} does not exist`); - - if (this.flags.npm && !this.flags.scope) throw new Error('--scope parameter is required for NPM'); - } - - private async pushGitTags( - sucessfullyPublishedPackages: { - name: string; - version: string; - type: string; - tag: string; - commitId: string; - }[] - ) { - - if (this.flags.pushgittag) { - let tagsForPushing:string[]=[]; - for (let succesfullyPublishedPackage of sucessfullyPublishedPackages) { - SFPLogger.log(COLOR_KEY_MESSAGE(`Pushing Git Tags to Repo ${succesfullyPublishedPackage.tag}`)); - tagsForPushing.push(succesfullyPublishedPackage.tag); - } - await this.git.pushTags(tagsForPushing) - } - } - - private async createGitTags( - sucessfullyPublishedPackages: { - name: string; - version: string; - type: string; - tag: string; - commitId: string; - }[] - ) { - - for (let sucessFullyPublishedPackage of sucessfullyPublishedPackages) { - SFPLogger.log(COLOR_KEY_MESSAGE(`Creating Git Tags in Repo ${sucessFullyPublishedPackage.tag}`)); - await this.git.addAnnotatedTag( - sucessFullyPublishedPackage.tag, - `${sucessFullyPublishedPackage.name} ${sucessFullyPublishedPackage.type} Package ${sucessFullyPublishedPackage.version}`, - sucessFullyPublishedPackage.commitId - ); - } - } - - //Exclude the latest git tag up to a specified number of tags, and then deletes the excess tags that exceed that limit. - private async deleteExcessGitTags( tags: { - name: string; - version: string; - type: string; - tag: string; - commitId: string; - }[], limit: number) { - //const pkgs = ProjectConfig.getAllPackages(this.git.getRepositoryPath()); - const tagsToDelete: string[] = []; - - await Promise.all(tags.map(async (tag) => { - const gitTags = new GitTags(this.git, tag.name); - const tags = await gitTags.limitTags(limit); - tagsToDelete.push(...tags); - })); - - if (tagsToDelete.length > 0) { - SFPLogger.log(COLOR_KEY_MESSAGE('Removing the following Git tag(s):')); - for (let tag of tagsToDelete) { - SFPLogger.log(COLOR_KEY_MESSAGE(tag)); - } - await this.git.deleteTags(tagsToDelete); - } - } - - //Deletes Git tags that are older than a specified number of days. - private async deleteGitTagsOlderThan( tags: { - name: string; - version: string; - type: string; - tag: string; - commitId: string; - }[], daysToKeep: number - , limit?: number) { - - const tagsToDelete: string[] = []; - - await Promise.all(tags.map(async (tag) => { - const gitTags = new GitTags(this.git, tag.name); - const tags = await gitTags.filteredOldTags(daysToKeep, limit); - tagsToDelete.push(...tags); - })); - - if (tagsToDelete.length > 0) { - SFPLogger.log(COLOR_KEY_MESSAGE('Removing the following Git tag(s):')); - for (let tag of tagsToDelete) { - SFPLogger.log(COLOR_KEY_MESSAGE(tag)); - } - await this.git.deleteTags(tagsToDelete); - } - - } - - - private isPackageVersionIdReleased(packageVersionList: any, packageVersionId: string): boolean { - let packageVersion = packageVersionList.find((pkg) => { - return pkg.SubscriberPackageVersionId === packageVersionId; - }); - - if (packageVersion) return true; - else return false; - } - - /** - * Get sourceDirectory and packageMetadata of artifact with package name and version - * @param artifacts - * @param packageName - * @param packageVersionNumber - */ - private async getPackageInfo(artifacts: Artifact[], packageName, packageVersionNumber): Promise { - for (let artifact of artifacts) { - let sfpPackage = await SfpPackageBuilder.buildPackageFromArtifact(artifact, new ConsoleLogger()); - if ( - sfpPackage.packageName === packageName && - sfpPackage.versionNumber === packageVersionNumber.replace('-', '.') - ) { - return sfpPackage; - } - } - - throw new Error( - `Unable to find artifact metadata for ${packageName} Version ${packageVersionNumber.replace('-', '.')}` - ); - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/quickbuild.ts b/packages/sfp-cli/src/commands/orchestrator/quickbuild.ts deleted file mode 100644 index 0ff13dabb..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/quickbuild.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Messages } from '@salesforce/core'; -import BuildImpl, { BuildProps } from '../../impl/parallelBuilder/BuildImpl'; -import { Stage } from '../../impl/Stage'; -import BuildBase from '../../BuildBase'; - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'quickbuild'); - -export default class QuickBuild extends BuildBase { - public static description = messages.getMessage('commandDescription'); - - getStage() { - return Stage.QUICKBUILD; - } - - getBuildProps(): BuildProps { - let buildProps: BuildProps = { - configFilePath: this.flags.configfilepath, - devhubAlias: this.flags.devhubalias, - repourl: this.flags.repourl, - waitTime: this.flags.waittime, - isQuickBuild: true, - isDiffCheckEnabled: this.flags.diffcheck, - buildNumber: this.flags.buildnumber, - executorcount: this.flags.executorcount, - branch: this.flags.branch, - currentStage: Stage.QUICKBUILD, - isBuildAllAsSourcePackages: false, - diffOptions: { - useLatestGitTags: true, - skipPackageDescriptorChange: false, - }, - }; - return buildProps; - } - getBuildImplementer(buildProps: BuildProps): BuildImpl { - let buildImpl = new BuildImpl(buildProps); - return buildImpl; - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/release.ts b/packages/sfp-cli/src/commands/orchestrator/release.ts deleted file mode 100644 index 6a88f1933..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/release.ts +++ /dev/null @@ -1,273 +0,0 @@ -import SfpCommand from '../../SfpCommand'; -import { LoggerLevel, Messages } from '@salesforce/core'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import ReleaseImpl, { ReleaseProps, ReleaseResult } from '../../impl/release/ReleaseImpl'; -import ReleaseDefinitionLoader from '../../impl/release/ReleaseDefinitionLoader'; -import ReleaseError from '../../errors/ReleaseError'; -import path = require('path'); -import SFPLogger, { - COLOR_ERROR, - COLOR_HEADER, - COLOR_TIME, - COLOR_SUCCESS, - COLOR_WARNING, - COLOR_KEY_MESSAGE, - ConsoleLogger, -} from '@flxblio/sfp-logger'; -import ReleaseDefinition from '../../impl/release/ReleaseDefinition'; -import { - arrayFlagSfdxStyle, - loglevel, - logsgroupsymbol, - optionalDevHubFlag, - requiredUserNameFlag, -} from '../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'release'); - -export default class Release extends SfpCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [ - `sfp orchestrator:release -p path/to/releasedefinition.yml -u myorg --npm --scope myscope --generatechangelog`, - ]; - - protected static requiresUsername = false; - protected static requiresDevhubUsername = false; - protected static requiresProject = false; - - public static flags = { - releasedefinition: arrayFlagSfdxStyle({ - char: 'p', - description: messages.getMessage('releaseDefinitionFlagDescription'), - required: true, - }), - targetorg: requiredUserNameFlag, - scriptpath: Flags.file({ - char: 'f', - description: messages.getMessage('scriptPathFlagDescription'), - }), - npm: Flags.boolean({ - description: messages.getMessage('npmFlagDescription'), - exclusive: ['scriptpath'], - }), - scope: Flags.string({ - description: messages.getMessage('scopeFlagDescription'), - dependsOn: ['npm'], - parse: async (scope) => scope.replace(/@/g, '').toLowerCase(), - }), - npmrcpath: Flags.file({ - description: messages.getMessage('npmrcPathFlagDescription'), - dependsOn: ['npm'], - required: false, - }), - logsgroupsymbol, - tag: Flags.string({ - char: 't', - description: messages.getMessage('tagFlagDescription'), - }), - dryrun: Flags.boolean({ - description: messages.getMessage('dryRunFlagDescription'), - default: false, - hidden: true, - }), - waittime: Flags.integer({ - description: messages.getMessage('waitTimeFlagDescription'), - default: 120, - }), - keys: Flags.string({ - required: false, - description: messages.getMessage('keysFlagDescription'), - }), - generatechangelog: Flags.boolean({ - default: false, - description: messages.getMessage('generateChangelogFlagDescription'), - }), - directory: Flags.string({ - char: 'd', - description: messages.getMessage('directoryFlagDescription'), - }), - branchname: Flags.string({ - dependsOn: ['generatechangelog'], - char: 'b', - description: messages.getMessage('branchNameFlagDescription'), - }), - allowunpromotedpackages: Flags.boolean({ - description: messages.getMessage('allowUnpromotedPackagesFlagDescription'), - hidden: true, - deprecated: { - message: '--allowunpromotedpackages is deprecated, All packages are allowed', - }, - }), - changelogByDomains: Flags.boolean({ - description: messages.getMessage('changelogByDomainsFlagDescription'), - hidden: true, - }), - devhubalias: optionalDevHubFlag, - loglevel, - }; - - public async execute() { - this.validateFlags(); - - let tags = { - targetOrg: this.flags.targetorg, - }; - - if (this.flags.tag != null) { - tags['tag'] = this.flags.tag; - } - - let executionStartTime = Date.now(); - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`release`)}`)); - SFPLogger.log(COLOR_HEADER(`Target Org: ${this.flags.targetorg}`)); - SFPLogger.log(COLOR_HEADER(`Release Definitions: ${this.flags.releasedefinition}`)); - SFPLogger.log(COLOR_HEADER(`Artifact Directory: ${path.resolve('artifacts')}`)); - - SFPLogger.printHeaderLine('', COLOR_HEADER, LoggerLevel.INFO); - - let releaseDefinitions: ReleaseDefinition[] = []; - for (const pathToReleaseDefintion of this.flags.releasedefinition) { - let releaseDefinition = await ReleaseDefinitionLoader.loadReleaseDefinition(pathToReleaseDefintion); - - //Support Legacy by taking the existing single workItemFilter and pushing it to the new model - if (releaseDefinition.changelog?.workItemFilter) { - releaseDefinition.changelog.workItemFilters = new Array(); - releaseDefinition.changelog.workItemFilters.push(releaseDefinition.changelog?.workItemFilter); - } - - if (this.flags.isGenerateChangelog && !releaseDefinition.changelog) - throw new Error('changelog parameters must be specified in release definition to generate changelog'); - - if ( - releaseDefinition.promotePackagesBeforeDeploymentToOrg && - this.flags.targetorg == releaseDefinition.promotePackagesBeforeDeploymentToOrg && - !this.flags.devhubalias - ) - throw new Error('DevHub is mandatory when promote is used within release defintion'); - - releaseDefinitions.push(releaseDefinition); - } - - let releaseResult: ReleaseResult; - try { - let props: ReleaseProps = { - releaseDefinitions: releaseDefinitions, - targetOrg: this.flags.targetorg, - fetchArtifactScript: this.flags.scriptpath, - isNpm: this.flags.npm, - scope: this.flags.scope, - npmrcPath: this.flags.npmrcpath, - logsGroupSymbol: this.flags.logsgroupsymbol, - tags: tags, - isDryRun: this.flags.dryrun, - waitTime: this.flags.waittime, - keys: this.flags.keys, - isGenerateChangelog: this.flags.generatechangelog, - devhubUserName: this.flags.devhubalias, - branch: this.flags.branchname, - directory: this.flags.directory, - }; - - let releaseImpl: ReleaseImpl = new ReleaseImpl(props, new ConsoleLogger()); - - releaseResult = await releaseImpl.exec(); - if (!this.flags.dryrun) SFPStatsSender.logCount('release.succeeded', tags); - } catch (err) { - if (err instanceof ReleaseError) { - releaseResult = err.data; - } else SFPLogger.log(err.message); - - if (!this.flags.dryrun) SFPStatsSender.logCount('release.failed', tags); - - // Fail the task when an error occurs - process.exitCode = 1; - } finally { - let totalElapsedTime: number = Date.now() - executionStartTime; - - if (releaseResult) { - this.printReleaseSummary(releaseResult, totalElapsedTime); - this.sendMetrics(releaseResult, tags, totalElapsedTime); - } - } - } - - private sendMetrics(releaseResult: ReleaseResult, tags: any, totalElapsedTime: number) { - if (!this.flags.dryrun) { - SFPStatsSender.logCount('release.scheduled', tags); - - SFPStatsSender.logGauge('release.duration', totalElapsedTime, tags); - - let packagesScheduled = 0; - let packagesSucceeded = 0; - let packagesFailed = 0; - - for (const deploymentResults of releaseResult.succeededDeployments) { - packagesScheduled += deploymentResults.result.scheduled; - packagesSucceeded += deploymentResults.result.deployed.length; - } - - for (const deploymentResults of releaseResult.failedDeployments) { - packagesScheduled += deploymentResults.result.scheduled; - packagesSucceeded += deploymentResults.result.deployed.length; - packagesFailed += deploymentResults.result.failed.length; - } - - SFPStatsSender.logGauge('release.packages.scheduled', packagesScheduled, tags); - SFPStatsSender.logGauge('release.packages.succeeded', packagesSucceeded, tags); - SFPStatsSender.logGauge('release.packages.failed', packagesFailed, tags); - } - } - - private printReleaseSummary(releaseResult: ReleaseResult, totalElapsedTime: number): void { - if (this.flags.logsgroupsymbol?.[0]) - SFPLogger.log(COLOR_HEADER(this.flags.logsgroupsymbol[0], 'Release Summary')); - - SFPLogger.printHeaderLine('', COLOR_HEADER, LoggerLevel.INFO); - if (releaseResult.installDependenciesResult) { - SFPLogger.log(COLOR_HEADER(`\nPackage Dependencies`)); - SFPLogger.log(COLOR_SUCCESS(` ${releaseResult.installDependenciesResult.success.length} succeeded`)); - SFPLogger.log(COLOR_WARNING(` ${releaseResult.installDependenciesResult.skipped.length} skipped`)); - SFPLogger.log(COLOR_ERROR(` ${releaseResult.installDependenciesResult.failed.length} failed`)); - } - - for (const succeededDeployment of releaseResult.succeededDeployments) { - SFPLogger.log( - COLOR_HEADER( - `\n Release Defintion: ${succeededDeployment.releaseDefinition.release} for Release Config: ${ - succeededDeployment.releaseDefinition.releaseConfigName - ? succeededDeployment.releaseDefinition.releaseConfigName - : 'N/A' - }` - ) - ); - SFPLogger.log(COLOR_SUCCESS(` ${succeededDeployment.result.deployed.length} succeeded`)); - SFPLogger.log(COLOR_ERROR(` ${succeededDeployment.result.failed.length} failed`)); - } - - for (const failedDeployment of releaseResult.failedDeployments) { - SFPLogger.log(COLOR_HEADER(`\n Release Defintion: ${failedDeployment.releaseDefinition.release} for for Release Config: ${ - failedDeployment.releaseDefinition.releaseConfigName - ? failedDeployment.releaseDefinition.releaseConfigName - : 'N/A' - }`)); - SFPLogger.log(COLOR_SUCCESS(` ${failedDeployment.result.deployed.length} succeeded`)); - SFPLogger.log( - COLOR_ERROR( - `\nPackages Failed to Deploy`, - failedDeployment.result.failed.map((packageInfo) => packageInfo.sfpPackage.packageName) - ) - ); - } - - SFPLogger.log(COLOR_TIME(`\nElapsed Time: ${new Date(totalElapsedTime).toISOString().substring(11,19)}`)); - SFPLogger.printHeaderLine('', COLOR_HEADER, LoggerLevel.INFO); - } - - protected validateFlags() { - if (this.flags.npm && !this.flags.scope) throw new Error('--scope parameter is required for NPM'); - } -} diff --git a/packages/sfp-cli/src/commands/orchestrator/validate.ts b/packages/sfp-cli/src/commands/orchestrator/validate.ts deleted file mode 100644 index 272abc423..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/validate.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { Messages } from '@salesforce/core'; -import SfpCommand from '../../SfpCommand'; -import ValidateImpl, { ValidateAgainst, ValidateProps, ValidationMode } from '../../impl/validate/ValidateImpl'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import SFPLogger, { COLOR_HEADER, COLOR_KEY_MESSAGE } from '@flxblio/sfp-logger'; -import ValidateError from '../../errors/ValidateError'; -import ValidateResult from '../../impl/validate/ValidateResult'; -import * as fs from 'fs-extra'; -import { arrayFlagSfdxStyle, loglevel, logsgroupsymbol, targetdevhubusername } from '../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; -import { LoggerLevel } from '@flxblio/sfp-logger'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'validate'); - -export default class Validate extends SfpCommand { - protected static requiresProject = true; - - public static description = messages.getMessage('commandDescription'); - - protected static requiresDevhubUsername = true; - - public static examples = [ - `$ sfp orchestrator:validate -p "POOL_TAG_1,POOL_TAG_2" -v `, - ]; - - //Fix Typo - public static flags = { - pools: arrayFlagSfdxStyle({ - char: 'p', - description: messages.getMessage('poolsFlagDescription'), - required: true, - }), - targetdevhubusername, - mode: Flags.string({ - description: 'validation mode', - default: 'thorough', - required: true, - options: ['individual', 'fastfeedback', 'thorough', 'ff-release-config', 'thorough-release-config'], - }), - installdeps: Flags.boolean({ - description: messages.getMessage('installDepsFlagDescription'), - default: false, - }), - releaseconfig: Flags.string({ - description: messages.getMessage('configFileFlagDescription'), - }), - coveragepercent: Flags.integer({ - description: messages.getMessage('coveragePercentFlagDescription'), - default: 75, - }), - disablesourcepkgoverride: Flags.boolean({ - description: messages.getMessage('disableSourcePackageOverride'), - default: false, - }), - deletescratchorg: Flags.boolean({ - char: 'x', - description: messages.getMessage('deleteScratchOrgFlagDescription'), - default: false, - }), - orginfo: Flags.boolean({ - description: messages.getMessage('orgInfoFlagDescription'), - default: false, - }), - keys: Flags.string({ - required: false, - description: messages.getMessage('keysFlagDescription'), - }), - basebranch: Flags.string({ - description: messages.getMessage('baseBranchFlagDescription'), - }), - enableimpactanalysis: Flags.boolean({ - description: messages.getMessage('enableImpactAnalysisFlagDescription'), - dependsOn: ['basebranch'], - }), - enabledependencyvalidation: Flags.boolean({ - description: messages.getMessage('enableDependencyValidation'), - dependsOn: ['basebranch'], - }), - tag: Flags.string({ - description: messages.getMessage('tagFlagDescription'), - }), - disableparalleltesting: Flags.boolean({ - description: messages.getMessage('disableParallelTestingFlagDescription'), - default: false, - }), - disablediffcheck: Flags.boolean({ - description: messages.getMessage('disableDiffCheckFlagDescription'), - default: false, - }), - disableartifactupdate: Flags.boolean({ - description: messages.getMessage('disableArtifactUpdateFlagDescription'), - default: false, - }), - logsgroupsymbol, - loglevel - }; - - async execute(): Promise { - let executionStartTime = Date.now(); - - await this.hubOrg.refreshAuth(); - - let tags: { [p: string]: string }; - tags = { - tag: this.flags.tag != null ? this.flags.tag : undefined, - validation_mode: this.flags.mode, - releaseConfig: this.flags.releaseconfig, - }; - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`validate`)}`)); - SFPLogger.log(COLOR_HEADER(`Pools being used: ${this.flags.pools}`)); - SFPLogger.log( - COLOR_HEADER( - `Validation Mode: ${COLOR_KEY_MESSAGE( - `${ - ValidationMode[ - Object.keys(ValidationMode)[ - (Object.values(ValidationMode) as string[]).indexOf(this.flags.mode) - ] - ] - }` - )}` - ) - ); - if (this.flags.mode != ValidationMode.FAST_FEEDBACK) { - SFPLogger.log(COLOR_HEADER(`Coverage Percentage: ${this.flags.coveragepercent}`)); - } - SFPLogger.log( - COLOR_HEADER(`Dependency Validation: ${this.flags.enabledependencyvalidation ? 'true' : 'false'}`) - ); - - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - let validateResult: ValidateResult; - try { - let validateProps: ValidateProps = { - validateAgainst: ValidateAgainst.PRECREATED_POOL, - validationMode: - ValidationMode[ - Object.keys(ValidationMode)[ - (Object.values(ValidationMode) as string[]).indexOf(this.flags.mode) - ] - ], - coverageThreshold: this.flags.coveragepercent, - logsGroupSymbol: this.flags.logsgroupsymbol, - pools: this.flags.pools, - hubOrg: this.hubOrg, - shapeFile: this.flags.shapefile, - isDeleteScratchOrg: this.flags.deletescratchorg, - keys: this.flags.keys, - baseBranch: this.flags.basebranch, - diffcheck: !this.flags.disablediffcheck, - disableArtifactCommit: this.flags.disableartifactupdate, - orgInfo: this.flags.orginfo, - disableSourcePackageOverride : this.flags.disablesourcepkgoverride, - disableParallelTestExecution: this.flags.disableparalleltesting, - installExternalDependencies: this.flags.installdeps, - }; - - setReleaseConfigForReleaseBasedModes(this.flags.releaseconfig,validateProps); - - let validateImpl: ValidateImpl = new ValidateImpl(validateProps); - - validateResult = await validateImpl.exec(); - - SFPStatsSender.logCount('validate.succeeded', tags); - } catch (error) { - if (error instanceof ValidateError) { - validateResult = error.data; - } else SFPLogger.log(error.message); - - SFPStatsSender.logCount('validate.failed', tags); - - process.exitCode = 1; - } finally { - let totalElapsedTime: number = Date.now() - executionStartTime; - - SFPStatsSender.logGauge('validate.duration', totalElapsedTime, tags); - - SFPStatsSender.logCount('validate.scheduled', tags); - - if (validateResult) { - SFPStatsSender.logGauge( - 'validate.packages.scheduled', - validateResult.deploymentResult?.scheduled, - tags - ); - - SFPStatsSender.logGauge( - 'validate.packages.succeeded', - validateResult.deploymentResult?.deployed?.length, - tags - ); - - SFPStatsSender.logGauge( - 'validate.packages.failed', - validateResult.deploymentResult?.failed?.length, - tags - ); - } - } - - function setReleaseConfigForReleaseBasedModes(releaseconfigPath:string,validateProps: ValidateProps) { - if (validateProps.validationMode == ValidationMode.FASTFEEDBACK_LIMITED_BY_RELEASE_CONFIG || - validateProps.validationMode == ValidationMode.THOROUGH_LIMITED_BY_RELEASE_CONFIG) { - if (releaseconfigPath && fs.existsSync(releaseconfigPath)) { - validateProps.releaseConfigPath = releaseconfigPath; - } - - else { - if (!releaseconfigPath) - throw new Error(`Release config is required when using validation by release config`); - else if (!fs.existsSync(releaseconfigPath)) - throw new Error(`Release config at ${releaseconfigPath} doesnt exist, Please check the path`); - } - } - } - } -} \ No newline at end of file diff --git a/packages/sfp-cli/src/commands/orchestrator/validateAgainstOrg.ts b/packages/sfp-cli/src/commands/orchestrator/validateAgainstOrg.ts deleted file mode 100644 index 88201ef37..000000000 --- a/packages/sfp-cli/src/commands/orchestrator/validateAgainstOrg.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { LoggerLevel, Messages, Org } from '@salesforce/core'; -import SfpCommand from '../../SfpCommand'; -import ValidateImpl, { ValidateAgainst, ValidateProps, ValidationMode } from '../../impl/validate/ValidateImpl'; -import SFPStatsSender from '../../core/stats/SFPStatsSender'; -import SFPLogger, { COLOR_HEADER, COLOR_KEY_MESSAGE } from '@flxblio/sfp-logger'; -import * as fs from 'fs-extra'; -import ValidateError from '../../errors/ValidateError'; -import ValidateResult from '../../impl/validate/ValidateResult'; -import { loglevel, logsgroupsymbol, requiredUserNameFlag, targetdevhubusername } from '../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; - - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'validateAgainstOrg'); - -export default class ValidateAgainstOrg extends SfpCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp orchestrator:validateAgainstOrg -u `]; - - public static flags = { - targetorg: requiredUserNameFlag, - mode: Flags.string({ - description: 'validation mode', - default: 'thorough', - required: true, - options: ['individual', 'fastfeedback', 'thorough', 'ff-release-config', 'thorough-release-config'], - }), - releaseconfig: Flags.string({ - description: messages.getMessage('configFileFlagDescription'), - }), - coveragepercent: Flags.integer({ - description: messages.getMessage('coveragePercentFlagDescription'), - default: 75, - }), - diffcheck: Flags.boolean({ - description: messages.getMessage('diffCheckFlagDescription'), - default: false, - }), - disableartifactupdate: Flags.boolean({ - description: messages.getMessage('disableArtifactUpdateFlagDescription'), - default: false, - }), - logsgroupsymbol, - basebranch: Flags.string({ - description: messages.getMessage('baseBranchFlagDescription'), - }), - orginfo: Flags.boolean({ - description: messages.getMessage('orgInfoFlagDescription'), - default: false, - }), - installdeps: Flags.boolean({ - description: messages.getMessage('installDepsFlagDescription'), - default: false, - }), - devhubalias: targetdevhubusername, - disablesourcepkgoverride: Flags.boolean({ - description: messages.getMessage('disableSourcePackageOverride'), - dependsOn:['devhubalias'] - }), - disableparalleltesting: Flags.boolean({ - description: messages.getMessage('disableParallelTestingFlagDescription'), - default: false, - }), - loglevel - }; - - async execute(): Promise { - let executionStartTime = Date.now(); - - let tags: { [p: string]: string }; - tags = { - tag: this.flags.tag != null ? this.flags.tag : undefined, - validation_mode: this.flags.mode, - releaseConfig: this.flags.releaseconfig, - }; - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`validateAgainstOrg`)}`)); - SFPLogger.log(COLOR_HEADER(`Target Org: ${this.flags.targetorg}`)); - SFPLogger.log( - COLOR_HEADER( - `Validation Mode: ${COLOR_KEY_MESSAGE( - `${ - ValidationMode[ - Object.keys(ValidationMode)[ - (Object.values(ValidationMode) as string[]).indexOf(this.flags.mode) - ] - ] - }` - )}` - ) - ); - if (this.flags.mode != ValidationMode.FAST_FEEDBACK) { - SFPLogger.log(COLOR_HEADER(`Coverage Percentage: ${this.flags.coveragepercent}`)); - } - - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - - let validateResult: ValidateResult; - try { - let validateProps: ValidateProps = { - validateAgainst: ValidateAgainst.PROVIDED_ORG, - validationMode: ValidationMode[ - Object.keys(ValidationMode)[ - (Object.values(ValidationMode) as string[]).indexOf(this.flags.mode) - ] - ], - coverageThreshold: this.flags.coveragepercent, - logsGroupSymbol: this.flags.logsgroupsymbol, - targetOrg: this.flags.targetorg, - diffcheck: this.flags.diffcheck, - baseBranch: this.flags.basebranch, - disableArtifactCommit: this.flags.disableartifactupdate, - disableSourcePackageOverride: this.flags.disablesourcepkgoverride, - disableParallelTestExecution: this.flags.disableparalleltesting, - orgInfo: this.flags.orginfo, - installExternalDependencies: this.flags.installdeps, - }; - - - //Add check for devhub - if(this.flags.devhubalias) - { - validateProps.hubOrg = await Org.create({aliasOrUsername:this.flags.devhubalias}); - } - - setReleaseConfigForReleaseBasedModes(this.flags.releaseconfig,validateProps); - let validateImpl: ValidateImpl = new ValidateImpl(validateProps); - validateResult = await validateImpl.exec(); - } catch (error) { - if (error instanceof ValidateError) { - validateResult = error.data; - } - - SFPStatsSender.logCount('validate.failed', tags); - - process.exitCode = 1; - } finally { - let totalElapsedTime: number = Date.now() - executionStartTime; - - SFPStatsSender.logGauge('validate.duration', totalElapsedTime, tags); - - SFPStatsSender.logCount('validate.scheduled', tags); - - if (validateResult) { - SFPStatsSender.logGauge( - 'validate.packages.scheduled', - validateResult.deploymentResult?.scheduled, - tags - ); - - SFPStatsSender.logGauge( - 'validate.packages.succeeded', - validateResult.deploymentResult?.deployed?.length, - tags - ); - - SFPStatsSender.logGauge( - 'validate.packages.failed', - validateResult.deploymentResult?.failed?.length, - tags - ); - } - } - - function setReleaseConfigForReleaseBasedModes(releaseconfigPath:string,validateProps: ValidateProps) { - if (validateProps.validationMode == ValidationMode.FASTFEEDBACK_LIMITED_BY_RELEASE_CONFIG || - validateProps.validationMode == ValidationMode.THOROUGH_LIMITED_BY_RELEASE_CONFIG) { - if (releaseconfigPath && fs.existsSync(releaseconfigPath)) { - validateProps.releaseConfigPath = releaseconfigPath; - } - - else { - if (!releaseconfigPath) - throw new Error(`Release config is required when using validation by release config`); - else if (!fs.existsSync(releaseconfigPath)) - throw new Error(`Release config at ${releaseconfigPath} doesnt exist, Please check the path`); - } - } - } - } -} diff --git a/packages/sfp-cli/src/commands/package/data/create.ts b/packages/sfp-cli/src/commands/package/data/create.ts deleted file mode 100644 index 4631d2c51..000000000 --- a/packages/sfp-cli/src/commands/package/data/create.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { Messages } from '@salesforce/core'; -import ProjectConfig from '../../../core/project/ProjectConfig' -import { COLOR_SUCCESS, ConsoleLogger } from '@flxblio/sfp-logger'; -import PackageCreateCommand from '../../../PackageCreateCommand'; -import SfpPackage, { PackageType } from '../../../core/package/SfpPackage'; -import SfpPackageBuilder from '../../../core/package/SfpPackageBuilder'; -import { Flags } from '@oclif/core'; -import { loglevel } from '../../../flags/sfdxflags'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'create_data_package'); - -export default class CreateDataPackage extends PackageCreateCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [ - `$ sfp package:data:create -n mypackage -v `, - `$ sfp package:data:create -n -v --diffcheck --gittag`, - ]; - - public static flags = { - package: Flags.string({ - required: true, - char: 'n', - description: messages.getMessage('packageFlagDescription'), - }), - versionnumber: Flags.string({ - required: true, - char: 'v', - description: messages.getMessage('versionNumberFlagDescription'), - }), - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - diffcheck: Flags.boolean({ - description: messages.getMessage('diffCheckFlagDescription'), - }), - branch: Flags.string({ - description: messages.getMessage('branchFlagDescription'), - }), - gittag: Flags.boolean({ - description: messages.getMessage('gitTagFlagDescription'), - }), - repourl: Flags.string({ - char: 'r', - description: messages.getMessage('repoUrlFlagDescription'), - }), - refname: Flags.string({ - description: messages.getMessage('refNameFlagDescription'), - }), - loglevel - }; - - protected async create(): Promise { - let packageDescriptor = ProjectConfig.getSFDXPackageDescriptor(null, this.sfdxPackage); - if (packageDescriptor.type?.toLowerCase() !== PackageType.Data) { - throw new Error("Data packages must have 'type' property of PackageType.Data defined in sfdx-project.json"); - } - - let sfpPackage = await SfpPackageBuilder.buildPackageFromProjectDirectory( - new ConsoleLogger(), - null, - this.sfdxPackage, - { - packageVersionNumber: this.versionNumber, - sourceVersion: this.commitId, - repositoryUrl: this.repositoryURL, - branch: this.branch, - } - ); - - console.log(COLOR_SUCCESS(`Created data package ${sfpPackage.packageName}`)); - return sfpPackage; - } - - protected getConfigFilePath(): string { - return null; - } -} diff --git a/packages/sfp-cli/src/commands/package/data/install.ts b/packages/sfp-cli/src/commands/package/data/install.ts deleted file mode 100644 index 51827ebb6..000000000 --- a/packages/sfp-cli/src/commands/package/data/install.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Messages } from '@salesforce/core'; -import InstallPackageCommand from '../../../InstallPackageCommand'; -import { PackageInstallationStatus } from '../../../core/package/packageInstallers/PackageInstallationResult'; -import SFPLogger, { ConsoleLogger, LoggerLevel } from '@flxblio/sfp-logger'; -import SfpPackageInstaller from '../../../core/package/SfpPackageInstaller'; -import { SfpPackageInstallationOptions } from '../../../core/package/packageInstallers/InstallPackage'; -import { Flags } from '@oclif/core'; -import { loglevel, requiredUserNameFlag } from '../../../flags/sfdxflags'; - - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'install_data_package'); - -export default class InstallDataPackage extends InstallPackageCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp package:data:install -n mypackage -u `]; - - public static deprecated:boolean = true; - - public static flags = { - package: Flags.string({ - char: 'n', - description: messages.getMessage('packageFlagDescription'), - required: true, - }), - targetorg: requiredUserNameFlag, - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - skiponmissingartifact: Flags.boolean({ - char: 's', - description: messages.getMessage('skipOnMissingArtifactFlagDescription'), - }), - skipifalreadyinstalled: Flags.boolean({ description: messages.getMessage('skipIfAlreadyInstalled') }), - loglevel - }; - - protected static requiresUsername = false; - protected static requiresDevhubUsername = false; - - public async install() { - try { - - SFPLogger.log(`This command is now deprecated, please proceed to use sfp package:install instead`,LoggerLevel.WARN) - - - const skipIfAlreadyInstalled = this.flags.skipifalreadyinstalled; - let options: SfpPackageInstallationOptions = { - skipIfPackageInstalled: skipIfAlreadyInstalled - }; - - - let result = await SfpPackageInstaller.installPackage( - new ConsoleLogger(), - this.sfpPackage, - this.sfpOrg, - options - ); - - - - if (result.result === PackageInstallationStatus.Failed) { - throw new Error(result.message); - } - } catch (err) { - console.log(err); - process.exitCode = 1; - } - } -} diff --git a/packages/sfp-cli/src/commands/package/install.ts b/packages/sfp-cli/src/commands/package/install.ts deleted file mode 100644 index 7dd37751d..000000000 --- a/packages/sfp-cli/src/commands/package/install.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { Messages } from '@salesforce/core'; -import InstallPackageCommand from '../../InstallPackageCommand'; -import { PackageInstallationStatus } from '../../core/package/packageInstallers/PackageInstallationResult'; -import SFPLogger, { COLOR_HEADER, COLOR_KEY_MESSAGE, ConsoleLogger, LoggerLevel } from '@flxblio/sfp-logger'; -import { SfpPackageInstallationOptions } from '../../core/package/packageInstallers/InstallPackage'; -import SfpPackageInstaller from '../../core/package/SfpPackageInstaller'; -import { Flags } from '@oclif/core'; -import { loglevel, requiredUserNameFlag } from '../../flags/sfdxflags'; -import { PackageType } from '../../core/package/SfpPackage'; - - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'install_package'); - -export default class Install extends InstallPackageCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp package:install -n packagename -u sandboxalias -i`]; - - public static flags = { - package: Flags.string({ - char: 'n', - description: messages.getMessage('packageFlagDescription'), - }), - targetorg: requiredUserNameFlag, - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - securitytype: Flags.string({ - description: messages.getMessage('securityTypeFlagDescription'), - options: ['full', 'none'], - default: 'none', - }), - skipifalreadyinstalled: Flags.boolean({ - char: 'f', - description: messages.getMessage('skipIfAlreadyInstalled'), - }), - upgradetype: Flags.string({ - description: messages.getMessage('upgradeTypeFlagDescription'), - options: ['delete-only', 'deprecate-only', 'mixed-mode'], - default: 'mixed-mode', - }), - optimizedeployment: Flags.boolean({ - char: 'o', - description: messages.getMessage('optimizedeployment'), - default: false, - required: false, - }), - skiptesting: Flags.boolean({ - char: 't', - description: messages.getMessage('skiptesting'), - default: false, - required: false, - }), - waittime: Flags.string({ - description: messages.getMessage('waitTimeFlagDescription'), - default: '120', - }), - publishwaittime: Flags.string({ - description: messages.getMessage('publishWaitTimeFlagDescription'), - default: '10', - }), - loglevel - }; - - protected static requiresUsername = true; - protected static requiresDevhubUsername = false; - - public async install() { - try { - const installationkey = this.flags.installationkey; - const security_type = this.flags.securitytype; - const upgrade_type = this.flags.upgradetype; - const waitTime = this.flags.waittime; - const publishWaitTime = this.flags.publishwaittime; - const skipIfAlreadyInstalled = this.flags.skipifalreadyinstalled; - const optimizeDeployment: boolean = this.flags.optimizedeployment; - const skipTesting: boolean = this.flags.skiptesting; - - - SFPLogger.log(COLOR_HEADER(`command: ${COLOR_KEY_MESSAGE(`install`)}`)); - SFPLogger.log(COLOR_HEADER(`Package Name: ${this.sfpPackage.packageName}`)); - SFPLogger.log(COLOR_HEADER(`Package Type: ${this.sfpPackage.packageType}`)); - SFPLogger.log(COLOR_HEADER(`Skip Packages If Already Installed: ${this.flags.skipifalreadyinstalled?`true`:`false`}`)); - SFPLogger.log(COLOR_HEADER(`Artifact Directory: ${this.flags.artifactdir}`)); - SFPLogger.log(COLOR_HEADER(`Target Environment: ${this.flags.targetorg}`)); - - - if(this.sfpPackage.packageType == PackageType.Unlocked) - { - - SFPLogger.log(COLOR_HEADER(`Security Type: ${this.flags.securitytype}`)); - SFPLogger.log(COLOR_HEADER(`Upgrade Type: ${this.flags.upgradetype}`)); - SFPLogger.log(COLOR_HEADER(`Apex Compile Mode: package`)); - } - else if(this.sfpPackage.packageType == PackageType.Source) - { - SFPLogger.log(COLOR_HEADER(`Optimize Deployment: ${this.flags.optimizedeployment}`)); - SFPLogger.log(COLOR_HEADER(`Skip Testing: ${this.flags.skiptesting}`)); - } - - - SFPLogger.printHeaderLine('',COLOR_HEADER,LoggerLevel.INFO); - - - let options: SfpPackageInstallationOptions = { - installationkey: installationkey, - apexcompile: `package`, - securitytype: security_type, - optimizeDeployment: optimizeDeployment, - skipTesting: skipTesting, - upgradetype: upgrade_type, - waitTime: waitTime, - publishWaitTime: publishWaitTime, - disableArtifactCommit: false, - skipIfPackageInstalled: skipIfAlreadyInstalled, - apiVersion: this.sfpPackage.apiVersion - }; - - let result = await SfpPackageInstaller.installPackage( - new ConsoleLogger(), - this.sfpPackage, - this.sfpOrg, - options - ); - - if (result.result === PackageInstallationStatus.Failed) { - throw new Error(result.message); - } - } catch (err) { - console.log(err); - process.exitCode = 1; - } - } -} diff --git a/packages/sfp-cli/src/commands/package/source/create.ts b/packages/sfp-cli/src/commands/package/source/create.ts deleted file mode 100644 index 0c2817fd6..000000000 --- a/packages/sfp-cli/src/commands/package/source/create.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { Messages } from '@salesforce/core'; -import { COLOR_SUCCESS, ConsoleLogger } from '@flxblio/sfp-logger'; -import PackageCreateCommand from '../../../PackageCreateCommand'; -import SfpPackage, { PackageType } from '../../../core/package/SfpPackage'; -import SfpPackageBuilder from '../../../core/package/SfpPackageBuilder'; -import { Flags } from '@oclif/core'; -import { loglevel } from '../../../flags/sfdxflags'; - -Messages.importMessagesDirectory(__dirname); -const messages = Messages.loadMessages('@flxblio/sfp', 'create_source_package'); - -export default class CreateSourcePackage extends PackageCreateCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [ - `$ sfp package:source:create -n mypackage -v `, - `$ sfp package:source:create -n -v --diffcheck --gittag` - ]; - - protected static requiresUsername = false; - protected static requiresDevhubUsername = false; - protected static requiresProject = true; - - public static flags = { - package: Flags.string({ - required: true, - char: 'n', - description: messages.getMessage('packageFlagDescription'), - }), - versionnumber: Flags.string({ - required: true, - char: 'v', - description: messages.getMessage('versionNumberFlagDescription'), - }), - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - diffcheck: Flags.boolean({ description: messages.getMessage('diffCheckFlagDescription') }), - branch: Flags.string({ - description: messages.getMessage('branchFlagDescription'), - }), - gittag: Flags.boolean({ description: messages.getMessage('gitTagFlagDescription') }), - repourl: Flags.string({ char: 'r', description: messages.getMessage('repoUrlFlagDescription') }), - refname: Flags.string({ description: messages.getMessage('refNameFlagDescription') }), - loglevel - }; - - protected async create(): Promise { - let sfpPackage = await SfpPackageBuilder.buildPackageFromProjectDirectory( - new ConsoleLogger(), - null, - this.sfdxPackage, - { - overridePackageTypeWith: PackageType.Source, - packageVersionNumber: this.versionNumber, - sourceVersion: this.commitId, - repositoryUrl: this.repositoryURL, - branch: this.branch, - } - ); - - console.log(COLOR_SUCCESS(`Created source package ${sfpPackage.packageName}`)); - - return sfpPackage; - } - - protected getConfigFilePath(): string { - return null; - } -} diff --git a/packages/sfp-cli/src/commands/package/source/install.ts b/packages/sfp-cli/src/commands/package/source/install.ts deleted file mode 100644 index b8f4aeaa1..000000000 --- a/packages/sfp-cli/src/commands/package/source/install.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { Messages } from '@salesforce/core'; -import InstallPackageCommand from '../../../InstallPackageCommand'; -import * as fs from 'fs-extra'; -import { PackageInstallationStatus } from '../../../core/package/packageInstallers/PackageInstallationResult'; -import SFPLogger, { ConsoleLogger, LoggerLevel } from '@flxblio/sfp-logger'; -import { DeploymentType } from '../../../core/deployers/DeploymentExecutor'; -import { SfpPackageInstallationOptions } from '../../../core/package/packageInstallers/InstallPackage'; -import SfpPackageInstaller from '../../../core/package/SfpPackageInstaller'; -import { loglevel, requiredUserNameFlag } from '../../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'install_source_package'); - -export default class InstallSourcePackage extends InstallPackageCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp package:source:install -n mypackage -u `]; - - public static deprecated:boolean = true; - - public static flags = { - package: Flags.string({ - char: 'n', - description: messages.getMessage('packageFlagDescription'), - required: true, - }), - targetorg: requiredUserNameFlag, - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - skipifalreadyinstalled: Flags.boolean({ - description: messages.getMessage('skipIfAlreadyInstalled'), - }), - skiponmissingartifact: Flags.boolean({ - char: 's', - description: messages.getMessage('skipOnMissingArtifactFlagDescription'), - }), - optimizedeployment: Flags.boolean({ - char: 'o', - description: messages.getMessage('optimizedeployment'), - default: false, - required: false, - }), - skiptesting: Flags.boolean({ - char: 't', - description: messages.getMessage('skiptesting'), - default: false, - required: false, - }), - waittime: Flags.string({ - description: messages.getMessage('waitTimeFlagDescription'), - default: '120', - }), - refname: Flags.string({ - description: messages.getMessage('refNameFlagDescription'), - }), - loglevel - }; - - public async install(): Promise { - - SFPLogger.log(`This command is now deprecated, please proceed to use sfp package:install instead`,LoggerLevel.WARN) - - - const sfdx_package: string = this.flags.package; - const optimizeDeployment: boolean = this.flags.optimizedeployment; - const skipTesting: boolean = this.flags.skiptesting; - const wait_time: string = this.flags.waittime; - const skipIfAlreadyInstalled = this.flags.skipifalreadyinstalled; - - console.log('sfp.Install Source Package To Org'); - - try { - let options: SfpPackageInstallationOptions = { - optimizeDeployment: optimizeDeployment, - skipTesting: skipTesting, - waitTime: wait_time, - deploymentType: DeploymentType.MDAPI_DEPLOY, - apiVersion: this.sfpPackage.apiVersion || this.sfpPackage.payload.Package.version, // Use package.xml version for backwards compat with old artifacts - disableArtifactCommit: false, - skipIfPackageInstalled : skipIfAlreadyInstalled - }; - - - let result = await SfpPackageInstaller.installPackage( - new ConsoleLogger(), - this.sfpPackage, - this.sfpOrg, - options - ); - - - if (result.result == PackageInstallationStatus.Failed) { - throw new Error(result.message); - } else { - console.log(`Succesfully Installed source package ${sfdx_package}`); - - console.log('\n\nOutput variables:'); - if (result.deploy_id) { - if (this.flags.refname) { - fs.writeFileSync( - '.env', - `${this.flags.refname}_sfpowerscripts_installsourcepackage_deployment_id=${result.deploy_id}\n`, - { flag: 'a' } - ); - console.log( - `${this.flags.refname}_sfpowerscripts_installsourcepackage_deployment_id=${result.deploy_id}` - ); - } else { - fs.writeFileSync( - '.env', - `sfpowerscripts_installsourcepackage_deployment_id=${result.deploy_id}\n`, - { flag: 'a' } - ); - console.log(`sfpowerscripts_installsourcepackage_deployment_id=${result.deploy_id}`); - } - } - } - } catch (error) { - console.log(error.message); - process.exitCode = 1; - } - } -} diff --git a/packages/sfp-cli/src/commands/package/unlocked/create.ts b/packages/sfp-cli/src/commands/package/unlocked/create.ts deleted file mode 100644 index 81972d059..000000000 --- a/packages/sfp-cli/src/commands/package/unlocked/create.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { Messages } from '@salesforce/core'; -import PackageCreateCommand from '../../../PackageCreateCommand'; -import { COLOR_SUCCESS, ConsoleLogger } from '@flxblio/sfp-logger'; -import SfpPackage from '../../../core/package/SfpPackage'; -import SfpPackageBuilder from '../../../core/package/SfpPackageBuilder'; -import { loglevel, targetdevhubusername } from '../../../flags/sfdxflags'; -import { Flags } from '@oclif/core'; - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'create_unlocked_package'); - -export default class CreateUnlockedPackage extends PackageCreateCommand { - public static description = messages.getMessage('commandDescription'); - - protected static requiresUsername = false; - protected static requiresDevhubUsername = true; - protected static requiresProject = true; - - public static examples = [ - `$ sfp package:unlocked:create -n -b -x -v --refname `, - `$ sfp package:unlocked:create -n -b -x -v --diffcheck --gittag`, - ]; - - public static flags = { - package: Flags.string({ - required: true, - char: 'n', - description: messages.getMessage('packageFlagDescription'), - }), - installationkey: Flags.string({ - char: 'k', - description: messages.getMessage('installationKeyFlagDescription'), - exclusive: ['installationkeybypass'], - }), - installationkeybypass: Flags.boolean({ - char: 'x', - description: messages.getMessage('installationKeyBypassFlagDescription'), - exclusive: ['installationkey'], - }), - diffcheck: Flags.boolean({ - description: messages.getMessage('diffCheckFlagDescription'), - }), - gittag: Flags.boolean({ - description: messages.getMessage('gitTagFlagDescription'), - }), - targetdevhubusername, - repourl: Flags.string({ - char: 'r', - description: messages.getMessage('repoUrlFlagDescription'), - }), - versionnumber: Flags.string({ - description: messages.getMessage('versionNumberFlagDescription'), - }), - configfilepath: Flags.file({ - char: 'f', - description: messages.getMessage('configFilePathFlagDescription'), - default: 'config/project-scratch-def.json', - }), - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - enablecoverage: Flags.boolean({ - description: messages.getMessage('enableCoverageFlagDescription'), - }), - isvalidationtobeskipped: Flags.boolean({ - char: 's', - description: messages.getMessage('isValidationToBeSkippedFlagDescription'), - }), - branch: Flags.string({ - description: messages.getMessage('branchFlagDescription'), - }), - tag: Flags.string({ - description: messages.getMessage('tagFlagDescription'), - }), - waittime: Flags.string({ - description: messages.getMessage('waitTimeFlagDescription'), - default: '120', - }), - refname: Flags.string({ - description: messages.getMessage('refNameFlagDescription'), - }), - loglevel - }; - - public async create(): Promise { - //TODO: Use tag info - let tag: string = this.flags.tag; - let installationkeybypass = this.flags.installationkeybypass; - let isCoverageEnabled: boolean = this.flags.enablecoverage; - let isSkipValidation: boolean = this.flags.isvalidationtobeskipped; - let installationkey = this.flags.installationkey; - let waitTime = this.flags.waittime; - - //Handle Installation Keys - if (installationkey === null || installationkey === undefined) { - installationkeybypass = true; - } - - let sfpPackage = await SfpPackageBuilder.buildPackageFromProjectDirectory( - new ConsoleLogger(), - null, - this.sfdxPackage, - { - packageVersionNumber: this.versionNumber, - sourceVersion: this.commitId, - repositoryUrl: this.repositoryURL, - branch: this.branch, - configFilePath: this.flags.configfilepath, - }, - { - devHub: this.hubOrg.getUsername(), - installationkeybypass: installationkeybypass as boolean, - breakBuildIfEmpty: true, - waitTime: waitTime as string, - isCoverageEnabled: isCoverageEnabled as boolean, - isSkipValidation: isSkipValidation as boolean, - } - ); - - console.log(COLOR_SUCCESS(`Created unlocked package ${sfpPackage.packageName}`)); - return sfpPackage; - } - - protected getConfigFilePath(): string { - return this.flags.configfilepath; - } -} diff --git a/packages/sfp-cli/src/commands/package/unlocked/install.ts b/packages/sfp-cli/src/commands/package/unlocked/install.ts deleted file mode 100644 index 001e06743..000000000 --- a/packages/sfp-cli/src/commands/package/unlocked/install.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { Messages } from '@salesforce/core'; -import InstallPackageCommand from '../../../InstallPackageCommand'; -import { PackageInstallationStatus } from '../../../core/package/packageInstallers/PackageInstallationResult'; -import SFPLogger, { ConsoleLogger, LoggerLevel } from '@flxblio/sfp-logger'; -import { SfpPackageInstallationOptions } from '../../../core/package/packageInstallers/InstallPackage'; -import SfpPackageInstaller from '../../../core/package/SfpPackageInstaller'; -import { Flags } from '@oclif/core'; -import { loglevel, requiredUserNameFlag } from '../../../flags/sfdxflags'; - - -// Initialize Messages with the current plugin directory -Messages.importMessagesDirectory(__dirname); - -// Load the specific messages for this file. Messages from @salesforce/command, @salesforce/core, -// or any library that is using the messages framework can also be loaded this way. -const messages = Messages.loadMessages('@flxblio/sfp', 'install_unlocked_package'); - -export default class InstallUnlockedPackage extends InstallPackageCommand { - public static description = messages.getMessage('commandDescription'); - - public static examples = [`$ sfp package:unlocked:install -n packagename -u sandboxalias -i`]; - - public static deprecated:boolean = true; - - public static flags = { - package: Flags.string({ - char: 'n', - description: messages.getMessage('packageFlagDescription'), - }), - targetorg: requiredUserNameFlag, - installationkey: Flags.string({ - char: 'k', - description: messages.getMessage('installationKeyFlagDescription'), - }), - apexcompileonlypackage: Flags.boolean({ - char: 'a', - description: messages.getMessage('apexCompileOnlyPackageFlagDescription'), - }), - artifactdir: Flags.directory({ - description: messages.getMessage('artifactDirectoryFlagDescription'), - default: 'artifacts', - }), - securitytype: Flags.string({ - description: messages.getMessage('securityTypeFlagDescription'), - options: ['Custom', 'Full', 'None'], - default: 'Full', - }), - skipifalreadyinstalled: Flags.boolean({ - char: 'f', - description: messages.getMessage('skipIfAlreadyInstalled'), - }), - skiponmissingartifact: Flags.boolean({ - char: 's', - description: messages.getMessage('skipOnMissingArtifactFlagDescription'), - dependsOn: ['packageinstalledfrom'], - }), - upgradetype: Flags.string({ - description: messages.getMessage('upgradeTypeFlagDescription'), - options: ['delete-only', 'deprecate-only', 'mixed-mode'], - default: 'mixed-mode', - }), - waittime: Flags.string({ - description: messages.getMessage('waitTimeFlagDescription'), - default: '120', - }), - publishwaittime: Flags.string({ - description: messages.getMessage('publishWaitTimeFlagDescription'), - default: '10', - }), - loglevel - }; - - protected static requiresUsername = true; - protected static requiresDevhubUsername = false; - - public async install() { - - SFPLogger.log(`This command is now deprecated, please proceed to use sfp package:install instead`,LoggerLevel.WARN) - - try { - const installationkey = this.flags.installationkey; - const apexcompileonlypackage = this.flags.apexcompileonlypackage; - const security_type = this.flags.securitytype; - const upgrade_type = this.flags.upgradetype; - const waitTime = this.flags.waittime; - const publishWaitTime = this.flags.publishwaittime; - const skipIfAlreadyInstalled = this.flags.skipifalreadyinstalled; - - let options: SfpPackageInstallationOptions = { - installationkey: installationkey, - apexcompile: apexcompileonlypackage ? `package` : `all`, - securitytype: security_type, - upgradetype: upgrade_type, - waitTime: waitTime, - publishWaitTime: publishWaitTime, - disableArtifactCommit: false, - skipIfPackageInstalled: skipIfAlreadyInstalled, - apiVersion: this.sfpPackage.apiVersion || this.sfpPackage.payload.Package.version, // Use package.xml version for backwards compat with old artifacts - }; - - let result = await SfpPackageInstaller.installPackage( - new ConsoleLogger(), - this.sfpPackage, - this.sfpOrg, - options - ); - - if (result.result === PackageInstallationStatus.Failed) { - throw new Error(result.message); - } - } catch (err) { - console.log(err); - process.exitCode = 1; - } - } -}