@shopify/cli-kit 3.81.2 → 3.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -99,7 +99,11 @@ This flag is required in non-interactive terminal environments, such as a CI env
99
99
  if (!environmentsFileName)
100
100
  return originalResult;
101
101
  const environmentFileExists = await environmentFilePath(environmentsFileName, { from: flags.path });
102
- const environments = flags.environment ?? [];
102
+ // Handle both string and array cases for environment flag
103
+ let environments = [];
104
+ if (flags.environment) {
105
+ environments = Array.isArray(flags.environment) ? flags.environment : [flags.environment];
106
+ }
103
107
  const environmentSpecified = environments.length > 0;
104
108
  // Noop if no environment file exists and none was specified
105
109
  if (!environmentFileExists && !environmentSpecified)
@@ -123,7 +127,7 @@ This flag is required in non-interactive terminal environments, such as a CI env
123
127
  ...(isDefaultEnvironment ? ['--environment', 'default'] : []),
124
128
  ]);
125
129
  // Report successful application of the environment.
126
- reportEnvironmentApplication(noDefaultsResult.flags, result.flags, isDefaultEnvironment ? 'default' : flags.environment?.[0], environment);
130
+ reportEnvironmentApplication(noDefaultsResult.flags, result.flags, isDefaultEnvironment ? 'default' : environments[0], environment);
127
131
  return result;
128
132
  }
129
133
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../../src/public/node/base-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,YAAY,EAAE,2CAA2C,EAAC,MAAM,oBAAoB,CAAA;AAC5F,OAAO,EAAC,eAAe,EAAE,mBAAmB,EAAC,MAAM,mBAAmB,CAAA;AACtE,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAA;AAChD,OAAO,EAAC,iBAAiB,EAAC,MAAM,eAAe,CAAA;AAC/C,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,EAAC,UAAU,EAAE,aAAa,EAAC,MAAM,SAAS,CAAA;AACjD,OAAO,EAAC,aAAa,EAAE,YAAY,EAAE,WAAW,EA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Plugins} from './error-handler.js'\nimport {loadEnvironment, environmentFilePath} from './environments.js'\nimport {isDevelopment} from './context/local.js'\nimport {addPublicMetadata} from './metadata.js'\nimport {AbortError} from './error.js'\nimport {renderInfo, renderWarning} from './ui.js'\nimport {outputContent, outputResult, outputToken} from './output.js'\nimport {terminalSupportsPrompting} from './system.js'\nimport {hashString} from './crypto.js'\nimport {isTruthy} from './context/utilities.js'\nimport {showNotificationsIfNeeded} from './notifications-system.js'\nimport {setCurrentCommandId} from './global-context.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {underscore} from '../common/string.js'\nimport {Command, Errors} from '@oclif/core'\nimport {FlagOutput, Input, ParserOutput, FlagInput, ArgOutput} from '@oclif/core/lib/interfaces/parser.js'\n\ninterface EnvironmentFlags {\n environment?: string[]\n path?: string\n}\n\nabstract class BaseCommand extends Command {\n // eslint-disable-next-line @typescript-eslint/ban-types\n static baseFlags: FlagInput<{}> = {}\n\n // Replace markdown links to plain text like: \"link label\" (url)\n public static descriptionWithoutMarkdown(): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ((this as any).descriptionWithMarkdown ?? '').replace(/(\\[)(.*?)(])(\\()(.*?)(\\))/gm, '\"$2\" ($5)')\n }\n\n public static analyticsNameOverride(): string | undefined {\n return undefined\n }\n\n public static analyticsStopCommand(): string | undefined {\n return undefined\n }\n\n async catch(error: Error & {skipOclifErrorHandling: boolean}): Promise<void> {\n error.skipOclifErrorHandling = true\n await errorHandler(error, this.config)\n return Errors.handle(error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async init(): Promise<any> {\n this.exitWithTimestampWhenEnvVariablePresent()\n setCurrentCommandId(this.id ?? '')\n if (!isDevelopment()) {\n // This function runs just prior to `run`\n await registerCleanBugsnagErrorsFromWithinPlugins(this.config)\n }\n this.showNpmFlagWarning()\n await showNotificationsIfNeeded()\n return super.init()\n }\n\n // NPM creates an environment variable for every flag passed to a script.\n // This function checks for the presence of any of the available CLI flags\n // and warns the user to use the `--` separator.\n protected showNpmFlagWarning(): void {\n const commandVariables = this.constructor as unknown as {flags: JsonMap}\n const commandFlags = Object.keys(commandVariables.flags || {})\n const possibleNpmEnvVars = commandFlags.map((key) => `npm_config_${underscore(key).replace(/^no_/, '')}`)\n\n if (possibleNpmEnvVars.some((flag) => process.env[flag] !== undefined)) {\n renderWarning({\n body: [\n 'NPM scripts require an extra',\n {command: '--'},\n 'separator to pass the flags. Example:',\n {command: 'npm run dev -- --reset'},\n ],\n })\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n protected exitWithTimestampWhenEnvVariablePresent() {\n if (isTruthy(process.env.SHOPIFY_CLI_ENV_STARTUP_PERFORMANCE_RUN)) {\n outputResult(`\n SHOPIFY_CLI_TIMESTAMP_START\n { \"timestamp\": ${Date.now()} }\n SHOPIFY_CLI_TIMESTAMP_END\n `)\n process.exit(0)\n }\n }\n\n protected async parse<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs> & {argv: string[]}> {\n let result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, argv)\n result = await this.resultWithEnvironment<TFlags, TGlobalFlags, TArgs>(result, options, argv)\n await addFromParsedFlags(result.flags)\n return {...result, ...{argv: result.argv as string[]}}\n }\n\n protected environmentsFilename(): string | undefined {\n // To be re-implemented if needed\n return undefined\n }\n\n protected failMissingNonTTYFlags(flags: FlagOutput, requiredFlags: string[]): void {\n if (terminalSupportsPrompting()) return\n\n requiredFlags.forEach((name: string) => {\n if (!(name in flags)) {\n throw new AbortError(\n outputContent`Flag not specified:\n\n${outputToken.cyan(name)}\n\nThis flag is required in non-interactive terminal environments, such as a CI environment, or when piping input from another process.`,\n 'To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.',\n )\n }\n })\n }\n\n private async resultWithEnvironment<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n originalResult: ParserOutput<TFlags, TGlobalFlags, TArgs>,\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs>> {\n const flags = originalResult.flags as EnvironmentFlags\n const environmentsFileName = this.environmentsFilename()\n\n if (!environmentsFileName) return originalResult\n\n const environmentFileExists = await environmentFilePath(environmentsFileName, {from: flags.path})\n const environments = flags.environment ?? []\n const environmentSpecified = environments.length > 0\n\n // Noop if no environment file exists and none was specified\n if (!environmentFileExists && !environmentSpecified) return originalResult\n\n // Noop if multiple environments were specified (let commands handle this)\n if (environmentSpecified && environments.length > 1) return originalResult\n\n const {environment, isDefaultEnvironment} = await this.loadEnvironmentForCommand(\n flags.path,\n environmentsFileName,\n environments[0],\n )\n\n if (!environment) return originalResult\n\n // Parse using noDefaultsOptions to derive a list of flags specified as\n // command-line arguments.\n const noDefaultsResult = await super.parse<TFlags, TGlobalFlags, TArgs>(noDefaultsOptions(options), argv)\n\n // Add the environment's settings to argv and pass them to `super.parse`. This\n // invokes oclif's validation system without breaking the oclif black box.\n // Replace the original result with this one.\n const result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, [\n // Need to specify argv default because we're merging with argsFromEnvironment.\n ...(argv ?? this.argv),\n ...argsFromEnvironment<TFlags, TGlobalFlags, TArgs>(environment, options, noDefaultsResult),\n ...(isDefaultEnvironment ? ['--environment', 'default'] : []),\n ])\n\n // Report successful application of the environment.\n reportEnvironmentApplication<TFlags, TGlobalFlags, TArgs>(\n noDefaultsResult.flags,\n result.flags,\n isDefaultEnvironment ? 'default' : (flags.environment?.[0] as string),\n environment,\n )\n\n return result\n }\n\n /**\n * Tries to load an environment to forward to the command. If no environment\n * is specified it will try to load a default environment.\n */\n private async loadEnvironmentForCommand(\n path: string | undefined,\n environmentsFileName: string,\n specifiedEnvironment: string | undefined,\n ): Promise<{environment: JsonMap | undefined; isDefaultEnvironment: boolean}> {\n if (specifiedEnvironment) {\n const environment = await loadEnvironment(specifiedEnvironment, environmentsFileName, {from: path})\n return {environment, isDefaultEnvironment: false}\n }\n\n const environment = await loadEnvironment('default', environmentsFileName, {from: path, silent: true})\n return {environment, isDefaultEnvironment: true}\n }\n}\n\nexport async function addFromParsedFlags(flags: {path?: string; verbose?: boolean}): Promise<void> {\n await addPublicMetadata(() => ({\n cmd_all_verbose: flags.verbose,\n cmd_all_path_override: flags.path !== undefined,\n cmd_all_path_override_hash: flags.path === undefined ? undefined : hashString(flags.path),\n }))\n}\n\n/**\n * Any flag which is:\n *\n * 1. Present in the final set of flags\n * 2. Specified in the environment\n * 3. Not specified by the user as a command line argument\n *\n * should be reported.\n *\n * It doesn't matter if the environment flag's value was the same as the default; from\n * the user's perspective, they want to know their environment was applied.\n */\nfunction reportEnvironmentApplication<\n TFlags extends FlagOutput,\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n>(\n noDefaultsFlags: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n flagsWithEnvironments: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n environmentName: string,\n environment: JsonMap,\n): void {\n const changes: JsonMap = {}\n for (const [name, value] of Object.entries(flagsWithEnvironments)) {\n const userSpecifiedThisFlag = Object.prototype.hasOwnProperty.call(noDefaultsFlags, name)\n const environmentContainsFlag = Object.prototype.hasOwnProperty.call(environment, name)\n if (!userSpecifiedThisFlag && environmentContainsFlag) {\n const valueToReport = name === 'password' ? `********${value.substr(-4)}` : value\n changes[name] = valueToReport\n }\n }\n if (Object.keys(changes).length === 0) return\n\n const items = Object.entries(changes).map(([name, value]) => `${name}: ${value}`)\n renderInfo({\n headline: ['Using applicable flags from', {userInput: environmentName}, 'environment:'],\n body: [{list: {items}}],\n })\n}\n\n/**\n * Strips the defaults from configured flags. For example, if flags contains:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag',\n * default: false\n * })\n * ```\n *\n * it becomes:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag'\n * })\n * ```\n *\n * If we parse using this configuration, the only specified flags will be those\n * the user actually passed on the command line.\n */\nfunction noDefaultsOptions<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n): Input<TFlags, TGlobalFlags, TArgs> | undefined {\n if (!options?.flags) return options\n return {\n ...options,\n flags: Object.fromEntries(\n Object.entries(options.flags).map(([label, settings]) => {\n const copiedSettings = {...(settings as {default?: unknown})}\n delete copiedSettings.default\n return [label, copiedSettings]\n }),\n ) as FlagInput<TFlags>,\n }\n}\n\n/**\n * Converts the environment's settings to arguments as though passed on the command\n * line, skipping any arguments the user specified on the command line.\n */\nfunction argsFromEnvironment<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n environment: JsonMap,\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n noDefaultsResult: ParserOutput<TFlags, TArgs>,\n): string[] {\n const args: string[] = []\n for (const [label, value] of Object.entries(environment)) {\n const flagIsRelevantToCommand = options?.flags && Object.prototype.hasOwnProperty.call(options.flags, label)\n const userSpecifiedThisFlag =\n noDefaultsResult.flags && Object.prototype.hasOwnProperty.call(noDefaultsResult.flags, label)\n if (flagIsRelevantToCommand && !userSpecifiedThisFlag) {\n if (typeof value === 'boolean') {\n if (value) {\n args.push(`--${label}`)\n } else {\n throw new AbortError(\n outputContent`Environments can only specify true for boolean flags. Attempted to set ${outputToken.yellow(\n label,\n )} to false.`,\n )\n }\n } else if (Array.isArray(value)) {\n value.forEach((element) => args.push(`--${label}`, `${element}`))\n } else {\n args.push(`--${label}`, `${value}`)\n }\n }\n }\n return args\n}\n\nexport default BaseCommand\n"]}
1
+ {"version":3,"file":"base-command.js","sourceRoot":"","sources":["../../../src/public/node/base-command.ts"],"names":[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qBAAM,CAAC;oBACN,MAAM,IAAI,UAAU,CAClB,aAAa,CAAA,0EAA0E,WAAW,CAAC,MAAM,CACvG,KAAK,CACN,YAAY,CACd,CAAA;gBACH,CAAC;YACH,CAAC;iBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBAChC,KAAK,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAA;YACnE,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,EAAE,EAAE,GAAG,KAAK,EAAE,CAAC,CAAA;YACrC,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,eAAe,WAAW,CAAA","sourcesContent":["import {errorHandler, registerCleanBugsnagErrorsFromWithinPlugins} from './error-handler.js'\nimport {loadEnvironment, environmentFilePath} from './environments.js'\nimport {isDevelopment} from './context/local.js'\nimport {addPublicMetadata} from './metadata.js'\nimport {AbortError} from './error.js'\nimport {renderInfo, renderWarning} from './ui.js'\nimport {outputContent, outputResult, outputToken} from './output.js'\nimport {terminalSupportsPrompting} from './system.js'\nimport {hashString} from './crypto.js'\nimport {isTruthy} from './context/utilities.js'\nimport {showNotificationsIfNeeded} from './notifications-system.js'\nimport {setCurrentCommandId} from './global-context.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {underscore} from '../common/string.js'\nimport {Command, Errors} from '@oclif/core'\nimport {FlagOutput, Input, ParserOutput, FlagInput, ArgOutput} from '@oclif/core/lib/interfaces/parser.js'\n\ninterface EnvironmentFlags {\n environment?: string[]\n path?: string\n}\n\nabstract class BaseCommand extends Command {\n // eslint-disable-next-line @typescript-eslint/ban-types\n static baseFlags: FlagInput<{}> = {}\n\n // Replace markdown links to plain text like: \"link label\" (url)\n public static descriptionWithoutMarkdown(): string | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ((this as any).descriptionWithMarkdown ?? '').replace(/(\\[)(.*?)(])(\\()(.*?)(\\))/gm, '\"$2\" ($5)')\n }\n\n public static analyticsNameOverride(): string | undefined {\n return undefined\n }\n\n public static analyticsStopCommand(): string | undefined {\n return undefined\n }\n\n async catch(error: Error & {skipOclifErrorHandling: boolean}): Promise<void> {\n error.skipOclifErrorHandling = true\n await errorHandler(error, this.config)\n return Errors.handle(error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async init(): Promise<any> {\n this.exitWithTimestampWhenEnvVariablePresent()\n setCurrentCommandId(this.id ?? '')\n if (!isDevelopment()) {\n // This function runs just prior to `run`\n await registerCleanBugsnagErrorsFromWithinPlugins(this.config)\n }\n this.showNpmFlagWarning()\n await showNotificationsIfNeeded()\n return super.init()\n }\n\n // NPM creates an environment variable for every flag passed to a script.\n // This function checks for the presence of any of the available CLI flags\n // and warns the user to use the `--` separator.\n protected showNpmFlagWarning(): void {\n const commandVariables = this.constructor as unknown as {flags: JsonMap}\n const commandFlags = Object.keys(commandVariables.flags || {})\n const possibleNpmEnvVars = commandFlags.map((key) => `npm_config_${underscore(key).replace(/^no_/, '')}`)\n\n if (possibleNpmEnvVars.some((flag) => process.env[flag] !== undefined)) {\n renderWarning({\n body: [\n 'NPM scripts require an extra',\n {command: '--'},\n 'separator to pass the flags. Example:',\n {command: 'npm run dev -- --reset'},\n ],\n })\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n protected exitWithTimestampWhenEnvVariablePresent() {\n if (isTruthy(process.env.SHOPIFY_CLI_ENV_STARTUP_PERFORMANCE_RUN)) {\n outputResult(`\n SHOPIFY_CLI_TIMESTAMP_START\n { \"timestamp\": ${Date.now()} }\n SHOPIFY_CLI_TIMESTAMP_END\n `)\n process.exit(0)\n }\n }\n\n protected async parse<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs> & {argv: string[]}> {\n let result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, argv)\n result = await this.resultWithEnvironment<TFlags, TGlobalFlags, TArgs>(result, options, argv)\n await addFromParsedFlags(result.flags)\n return {...result, ...{argv: result.argv as string[]}}\n }\n\n protected environmentsFilename(): string | undefined {\n // To be re-implemented if needed\n return undefined\n }\n\n protected failMissingNonTTYFlags(flags: FlagOutput, requiredFlags: string[]): void {\n if (terminalSupportsPrompting()) return\n\n requiredFlags.forEach((name: string) => {\n if (!(name in flags)) {\n throw new AbortError(\n outputContent`Flag not specified:\n\n${outputToken.cyan(name)}\n\nThis flag is required in non-interactive terminal environments, such as a CI environment, or when piping input from another process.`,\n 'To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.',\n )\n }\n })\n }\n\n private async resultWithEnvironment<\n TFlags extends FlagOutput & {path?: string; verbose?: boolean},\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n >(\n originalResult: ParserOutput<TFlags, TGlobalFlags, TArgs>,\n options?: Input<TFlags, TGlobalFlags, TArgs>,\n argv?: string[],\n ): Promise<ParserOutput<TFlags, TGlobalFlags, TArgs>> {\n const flags = originalResult.flags as EnvironmentFlags\n const environmentsFileName = this.environmentsFilename()\n\n if (!environmentsFileName) return originalResult\n\n const environmentFileExists = await environmentFilePath(environmentsFileName, {from: flags.path})\n\n // Handle both string and array cases for environment flag\n let environments: string[] = []\n if (flags.environment) {\n environments = Array.isArray(flags.environment) ? flags.environment : [flags.environment]\n }\n\n const environmentSpecified = environments.length > 0\n\n // Noop if no environment file exists and none was specified\n if (!environmentFileExists && !environmentSpecified) return originalResult\n\n // Noop if multiple environments were specified (let commands handle this)\n if (environmentSpecified && environments.length > 1) return originalResult\n\n const {environment, isDefaultEnvironment} = await this.loadEnvironmentForCommand(\n flags.path,\n environmentsFileName,\n environments[0],\n )\n\n if (!environment) return originalResult\n\n // Parse using noDefaultsOptions to derive a list of flags specified as\n // command-line arguments.\n const noDefaultsResult = await super.parse<TFlags, TGlobalFlags, TArgs>(noDefaultsOptions(options), argv)\n\n // Add the environment's settings to argv and pass them to `super.parse`. This\n // invokes oclif's validation system without breaking the oclif black box.\n // Replace the original result with this one.\n const result = await super.parse<TFlags, TGlobalFlags, TArgs>(options, [\n // Need to specify argv default because we're merging with argsFromEnvironment.\n ...(argv ?? this.argv),\n ...argsFromEnvironment<TFlags, TGlobalFlags, TArgs>(environment, options, noDefaultsResult),\n ...(isDefaultEnvironment ? ['--environment', 'default'] : []),\n ])\n\n // Report successful application of the environment.\n reportEnvironmentApplication<TFlags, TGlobalFlags, TArgs>(\n noDefaultsResult.flags,\n result.flags,\n isDefaultEnvironment ? 'default' : (environments[0] as string),\n environment,\n )\n\n return result\n }\n\n /**\n * Tries to load an environment to forward to the command. If no environment\n * is specified it will try to load a default environment.\n */\n private async loadEnvironmentForCommand(\n path: string | undefined,\n environmentsFileName: string,\n specifiedEnvironment: string | undefined,\n ): Promise<{environment: JsonMap | undefined; isDefaultEnvironment: boolean}> {\n if (specifiedEnvironment) {\n const environment = await loadEnvironment(specifiedEnvironment, environmentsFileName, {from: path})\n return {environment, isDefaultEnvironment: false}\n }\n\n const environment = await loadEnvironment('default', environmentsFileName, {from: path, silent: true})\n return {environment, isDefaultEnvironment: true}\n }\n}\n\nexport async function addFromParsedFlags(flags: {path?: string; verbose?: boolean}): Promise<void> {\n await addPublicMetadata(() => ({\n cmd_all_verbose: flags.verbose,\n cmd_all_path_override: flags.path !== undefined,\n cmd_all_path_override_hash: flags.path === undefined ? undefined : hashString(flags.path),\n }))\n}\n\n/**\n * Any flag which is:\n *\n * 1. Present in the final set of flags\n * 2. Specified in the environment\n * 3. Not specified by the user as a command line argument\n *\n * should be reported.\n *\n * It doesn't matter if the environment flag's value was the same as the default; from\n * the user's perspective, they want to know their environment was applied.\n */\nfunction reportEnvironmentApplication<\n TFlags extends FlagOutput,\n TGlobalFlags extends FlagOutput,\n TArgs extends ArgOutput,\n>(\n noDefaultsFlags: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n flagsWithEnvironments: ParserOutput<TFlags, TGlobalFlags, TArgs>['flags'],\n environmentName: string,\n environment: JsonMap,\n): void {\n const changes: JsonMap = {}\n for (const [name, value] of Object.entries(flagsWithEnvironments)) {\n const userSpecifiedThisFlag = Object.prototype.hasOwnProperty.call(noDefaultsFlags, name)\n const environmentContainsFlag = Object.prototype.hasOwnProperty.call(environment, name)\n if (!userSpecifiedThisFlag && environmentContainsFlag) {\n const valueToReport = name === 'password' ? `********${value.substr(-4)}` : value\n changes[name] = valueToReport\n }\n }\n if (Object.keys(changes).length === 0) return\n\n const items = Object.entries(changes).map(([name, value]) => `${name}: ${value}`)\n renderInfo({\n headline: ['Using applicable flags from', {userInput: environmentName}, 'environment:'],\n body: [{list: {items}}],\n })\n}\n\n/**\n * Strips the defaults from configured flags. For example, if flags contains:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag',\n * default: false\n * })\n * ```\n *\n * it becomes:\n *\n * ```\n * someFlag: Flags.boolean({\n * description: 'some flag'\n * })\n * ```\n *\n * If we parse using this configuration, the only specified flags will be those\n * the user actually passed on the command line.\n */\nfunction noDefaultsOptions<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n): Input<TFlags, TGlobalFlags, TArgs> | undefined {\n if (!options?.flags) return options\n return {\n ...options,\n flags: Object.fromEntries(\n Object.entries(options.flags).map(([label, settings]) => {\n const copiedSettings = {...(settings as {default?: unknown})}\n delete copiedSettings.default\n return [label, copiedSettings]\n }),\n ) as FlagInput<TFlags>,\n }\n}\n\n/**\n * Converts the environment's settings to arguments as though passed on the command\n * line, skipping any arguments the user specified on the command line.\n */\nfunction argsFromEnvironment<TFlags extends FlagOutput, TGlobalFlags extends FlagOutput, TArgs extends ArgOutput>(\n environment: JsonMap,\n options: Input<TFlags, TGlobalFlags, TArgs> | undefined,\n noDefaultsResult: ParserOutput<TFlags, TArgs>,\n): string[] {\n const args: string[] = []\n for (const [label, value] of Object.entries(environment)) {\n const flagIsRelevantToCommand = options?.flags && Object.prototype.hasOwnProperty.call(options.flags, label)\n const userSpecifiedThisFlag =\n noDefaultsResult.flags && Object.prototype.hasOwnProperty.call(noDefaultsResult.flags, label)\n if (flagIsRelevantToCommand && !userSpecifiedThisFlag) {\n if (typeof value === 'boolean') {\n if (value) {\n args.push(`--${label}`)\n } else {\n throw new AbortError(\n outputContent`Environments can only specify true for boolean flags. Attempted to set ${outputToken.yellow(\n label,\n )} to false.`,\n )\n }\n } else if (Array.isArray(value)) {\n value.forEach((element) => args.push(`--${label}`, `${element}`))\n } else {\n args.push(`--${label}`, `${value}`)\n }\n }\n }\n return args\n}\n\nexport default BaseCommand\n"]}
@@ -137,3 +137,11 @@ export declare function isClean(directory?: string): Promise<boolean>;
137
137
  * @returns String with the latest tag or undefined if no tags are found.
138
138
  */
139
139
  export declare function getLatestTag(directory?: string): Promise<string | undefined>;
140
+ /**
141
+ * Remove a git remote from the given directory.
142
+ *
143
+ * @param directory - The directory where the git repository is located.
144
+ * @param remoteName - The name of the remote to remove (defaults to 'origin').
145
+ * @returns A promise that resolves when the remote is removed.
146
+ */
147
+ export declare function removeGitRemote(directory: string, remoteName?: string): Promise<void>;
@@ -289,4 +289,26 @@ export async function getLatestTag(directory) {
289
289
  const tags = await git({ baseDir: directory }).tags();
290
290
  return tags.latest;
291
291
  }
292
+ /**
293
+ * Remove a git remote from the given directory.
294
+ *
295
+ * @param directory - The directory where the git repository is located.
296
+ * @param remoteName - The name of the remote to remove (defaults to 'origin').
297
+ * @returns A promise that resolves when the remote is removed.
298
+ */
299
+ export async function removeGitRemote(directory, remoteName = 'origin') {
300
+ outputDebug(outputContent `Removing git remote ${remoteName} from ${outputToken.path(directory)}...`);
301
+ await ensureGitIsPresentOrAbort();
302
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
303
+ // @ts-ignore
304
+ const repo = git(directory);
305
+ // Check if remote exists first
306
+ const remotes = await repo.getRemotes();
307
+ const remoteExists = remotes.some((remote) => remote.name === remoteName);
308
+ if (!remoteExists) {
309
+ outputDebug(outputContent `Remote ${remoteName} does not exist, no action needed`);
310
+ return;
311
+ }
312
+ await repo.removeRemote(remoteName);
313
+ }
292
314
  //# sourceMappingURL=git.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"git.js","sourceRoot":"","sources":["../../../src/public/node/git.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,OAAO,EAAC,MAAM,EAAE,qBAAqB,EAAC,MAAM,oBAAoB,CAAA;AAChE,OAAO,EAAC,cAAc,EAAE,SAAS,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAC,MAAM,SAAS,CAAA;AAC9F,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,EAAC,GAAG,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,GAAoF,MAAM,YAAY,CAAA;AAC7G,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,SAAiB,EAAE,aAAa,GAAG,MAAM;IACrF,WAAW,CAAC,aAAa,CAAA,kCAAkC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IAC5F,MAAM,yBAAyB,EAAE,CAAA;IACjC,gHAAgH;IAChH,6DAA6D;IAC7D,aAAa;IACb,MAAM,IAAI,GAAG,GAAG,CAAC,SAAS,CAAC,CAAA;IAC3B,MAAM,IAAI,CAAC,IAAI,EAAE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AAO,CAAC,MAAM,GAAG,CAAC,EAAC,OAAO,EAAE,SAAS,EAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,EAAE,CAAA;AAC7D,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,SAAkB;IACnD,6DAA6D;IAC7D,aAAa;IACb,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,EAAC,OAAO,EAAE,SAAS,EAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IACnD,OAAO,IAAI,CAAC,MAAM,CAAA;AACpB,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-base-to-string */\nimport {hasGit, isTerminalInteractive} from './context/local.js'\nimport {appendFileSync, detectEOL, fileExistsSync, readFileSync, writeFileSync} from './fs.js'\nimport {AbortError} from './error.js'\nimport {cwd, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport git, {TaskOptions, SimpleGitProgressEvent, DefaultLogFields, ListLogLine, SimpleGit} from 'simple-git'\nimport ignore from 'ignore'\n\n/**\n * Initialize a git repository at the given directory.\n *\n * @param directory - The directory where the git repository will be initialized.\n * @param initialBranch - The name of the initial branch.\n */\nexport async function initializeGitRepository(directory: string, initialBranch = 'main'): Promise<void> {\n outputDebug(outputContent`Initializing git repository at ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n // We use init and checkout instead of `init --initial-branch` because the latter is only supported in git 2.28+\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const repo = git(directory)\n await repo.init()\n await repo.checkoutLocalBranch(initialBranch)\n}\n\n/**\n * Given a Git repository and a list of absolute paths to files contained\n * in the repository, it filters and returns the files that are ignored\n * by the .gitignore.\n *\n * @param directory - The absolute path to the directory containing the files.\n * @param files - The list of files to check against.\n * @returns Files ignored by the lockfile.\n */\nexport async function checkIfIgnoredInGitRepository(directory: string, files: string[]): Promise<string[]> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const repo = git(directory)\n const ignoredLockfile = await repo.checkIgnore(files)\n return ignoredLockfile\n}\n\nexport interface GitIgnoreTemplate {\n [section: string]: string[]\n}\n/**\n * Create a .gitignore file in the given directory.\n *\n * @param directory - The directory where the .gitignore file will be created.\n * @param template - The template to use to create the .gitignore file.\n */\nexport function createGitIgnore(directory: string, template: GitIgnoreTemplate): void {\n outputDebug(outputContent`Creating .gitignore at ${outputToken.path(directory)}...`)\n const filePath = `${directory}/.gitignore`\n\n let fileContent = ''\n for (const [section, lines] of Object.entries(template)) {\n fileContent += `# ${section}\\n`\n fileContent += `${lines.join('\\n')}\\n\\n`\n }\n\n appendFileSync(filePath, fileContent)\n}\n\n/**\n * Add an entry to an existing .gitignore file.\n *\n * If the .gitignore file doesn't exist, or if the entry is already present,\n * no changes will be made.\n *\n * @param root - The directory containing the .gitignore file.\n * @param entry - The entry to add to the .gitignore file.\n */\nexport function addToGitIgnore(root: string, entry: string): void {\n const gitIgnorePath = joinPath(root, '.gitignore')\n\n if (!fileExistsSync(gitIgnorePath)) {\n // When the .gitignore file does not exist, the CLI should not be opinionated about creating it\n return\n }\n\n const gitIgnoreContent = readFileSync(gitIgnorePath).toString()\n const eol = detectEOL(gitIgnoreContent)\n\n const lines = gitIgnoreContent.split(eol).map((line) => line.trim())\n const ignoreManager = ignore.default({allowRelativePaths: true}).add(lines)\n\n const isIgnoredEntry = ignoreManager.ignores(joinPath(entry))\n const isIgnoredEntryAsDir = ignoreManager.ignores(joinPath(entry, 'ignored.txt'))\n const isAlreadyIgnored = isIgnoredEntry || isIgnoredEntryAsDir\n if (isAlreadyIgnored) {\n // The file is already ignored by an existing pattern\n return\n }\n\n if (gitIgnoreContent.endsWith(eol)) {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${entry}${eol}`)\n } else {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${eol}${entry}${eol}`)\n }\n}\n\n/**\n * Options to use when cloning a git repository.\n *\n * @param repoUrl - The URL of the repository to clone.\n * @param destination - The directory where the repository will be cloned.\n * @param progressUpdater - A function that will be called with the progress of the clone.\n * @param shallow - Whether to clone the repository shallowly.\n * @param latestTag - Whether to clone the latest tag instead of the default branch.\n */\nexport interface GitCloneOptions {\n repoUrl: string\n destination: string\n progressUpdater?: (statusString: string) => void\n shallow?: boolean\n latestTag?: boolean\n}\n/**\n * Clone a git repository.\n *\n * @param cloneOptions - The options to use to clone the repository.\n * @returns A promise that resolves when the clone is complete.\n */\nexport async function downloadGitRepository(cloneOptions: GitCloneOptions): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n const {repoUrl, destination, progressUpdater, shallow, latestTag} = cloneOptions\n outputDebug(outputContent`Git-cloning repository ${repoUrl} into ${outputToken.path(destination)}...`)\n await ensureGitIsPresentOrAbort()\n const [repository, branch] = repoUrl.split('#')\n const options: TaskOptions = {'--recurse-submodules': null}\n\n if (branch && latestTag) {\n throw new AbortError(\"Error cloning the repository. Git can't clone the latest release with a 'branch'.\")\n }\n if (branch) {\n options['--branch'] = branch\n }\n\n if (shallow && latestTag) {\n throw new AbortError(\n \"Error cloning the repository. Git can't clone the latest release with the 'shallow' property.\",\n )\n }\n if (shallow) {\n options['--depth'] = 1\n }\n\n const progress = ({stage, progress, processed, total}: SimpleGitProgressEvent) => {\n const updateString = `${stage}, ${processed}/${total} objects (${progress}% complete)`\n if (progressUpdater) progressUpdater(updateString)\n }\n\n const simpleGitOptions = {\n progress,\n ...(!isTerminalInteractive() && {config: ['core.askpass=true']}),\n }\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n await git(simpleGitOptions).clone(repository!, destination, options)\n\n if (latestTag) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const localGitRepository = git(destination)\n const latestTag = await getLocalLatestTag(localGitRepository, repoUrl)\n await localGitRepository.checkout(latestTag)\n }\n } catch (err) {\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n throw abortError\n }\n throw err\n }\n })\n}\n\n/**\n * Get the most recent tag of a local git repository.\n *\n * @param repository - The local git repository.\n * @param repoUrl - The URL of the repository.\n * @returns The most recent tag of the repository.\n */\nasync function getLocalLatestTag(repository: SimpleGit, repoUrl: string): Promise<string> {\n const latest = (await repository.tags()).latest\n\n if (!latest) {\n throw new AbortError(`Couldn't obtain the most recent tag of the repository ${repoUrl}`)\n }\n\n return latest\n}\n\n/**\n * Get the latest commit of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The latest commit of the repository.\n */\nexport async function getLatestGitCommit(directory?: string): Promise<DefaultLogFields & ListLogLine> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const logs = await git({baseDir: directory}).log({\n maxCount: 1,\n })\n if (!logs.latest) {\n throw new AbortError(\n 'Must have at least one commit to run command',\n outputContent`Run ${outputToken.genericShellCommand(\n \"git commit -m 'Initial commit'\",\n )} to create your first commit.`,\n )\n }\n return logs.latest\n}\n\n/**\n * Add all files to the git index from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @returns A promise that resolves when the files are added to the index.\n */\nexport async function addAllToGitFromDirectory(directory?: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const simpleGit = git({baseDir: directory})\n await simpleGit.raw('add', '--all')\n}\n\nexport interface CreateGitCommitOptions {\n directory?: string\n author?: string\n}\n\n/**\n * Create a git commit.\n *\n * @param message - The message of the commit.\n * @param options - The options to use to create the commit.\n * @returns The hash of the created commit.\n */\nexport async function createGitCommit(message: string, options?: CreateGitCommitOptions): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const simpleGit = git({baseDir: options?.directory})\n\n const commitOptions = options?.author ? {'--author': options.author} : undefined\n const result = await simpleGit.commit(message, commitOptions)\n\n return result.commit\n}\n\n/**\n * Get the HEAD symbolic reference of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The HEAD symbolic reference of the repository.\n */\nexport async function getHeadSymbolicRef(directory?: string): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const ref = await git({baseDir: directory}).raw('symbolic-ref', '-q', 'HEAD')\n if (!ref) {\n throw new AbortError(\n \"Git HEAD can't be detached to run command\",\n outputContent`Run ${outputToken.genericShellCommand(\n 'git checkout [branchName]',\n )} to reattach HEAD or see git ${outputToken.link(\n 'documentation',\n 'https://git-scm.com/book/en/v2/Git-Internals-Git-References',\n )} for more details`,\n )\n }\n return ref.trim()\n}\n\n/**\n * If \"git\" is not present in the environment it throws\n * an abort error.\n */\nexport async function ensureGitIsPresentOrAbort(): Promise<void> {\n if (!(await hasGit())) {\n throw new AbortError(\n `Git is necessary in the environment to continue`,\n outputContent`Install ${outputToken.link(\n 'git',\n 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git',\n )}`,\n )\n }\n}\n\nexport class OutsideGitDirectoryError extends AbortError {}\n/**\n * If command run from outside a .git directory tree\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureInsideGitDirectory(directory?: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (!(await insideGitDirectory(directory))) {\n throw new OutsideGitDirectoryError(`${outputToken.path(directory || cwd())} is not a Git directory`)\n }\n}\n\n/**\n * Returns true if the given directory is inside a .git directory tree.\n *\n * @param directory - The directory to check.\n * @returns True if the directory is inside a .git directory tree.\n */\nexport async function insideGitDirectory(directory?: string): Promise<boolean> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return git({baseDir: directory}).checkIsRepo()\n}\n\nexport class GitDirectoryNotCleanError extends AbortError {}\n/**\n * If the .git directory tree is not clean (has uncommitted changes)\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureIsClean(directory?: string): Promise<void> {\n if (!(await isClean(directory))) {\n throw new GitDirectoryNotCleanError(`${outputToken.path(directory || cwd())} is not a clean Git directory`)\n }\n}\n\n/**\n * Returns true if the .git directory tree is clean (no uncommitted changes).\n *\n * @param directory - The directory to check.\n * @returns True is the .git directory is clean.\n */\nexport async function isClean(directory?: string): Promise<boolean> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return (await git({baseDir: directory}).status()).isClean()\n}\n\n/**\n * Returns the latest tag of a git repository.\n *\n * @param directory - The directory to check.\n * @returns String with the latest tag or undefined if no tags are found.\n */\nexport async function getLatestTag(directory?: string): Promise<string | undefined> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const tags = await git({baseDir: directory}).tags()\n return tags.latest\n}\n"]}
1
+ {"version":3,"file":"git.js","sourceRoot":"","sources":["../../../src/public/node/git.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,OAAO,EAAC,MAAM,EAAE,qBAAqB,EAAC,MAAM,oBAAoB,CAAA;AAChE,OAAO,EAAC,cAAc,EAAE,SAAS,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAC,MAAM,SAAS,CAAA;AAC9F,OAAO,EAAC,UAAU,EAAC,MAAM,YAAY,CAAA;AACrC,OAAO,EAAC,GAAG,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AACvC,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,GAAoF,MAAM,YAAY,CAAA;AAC7G,OAAO,MAAM,MAAM,QAAQ,CAAA;AAE3B;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,SAAiB,EAAE,aAAa,GAAG,MAAM;IACrF,WAAW,CAAC,aAAa,CAAA,kCAAkC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,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A;AACrC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-base-to-string */\nimport {hasGit, isTerminalInteractive} from './context/local.js'\nimport {appendFileSync, detectEOL, fileExistsSync, readFileSync, writeFileSync} from './fs.js'\nimport {AbortError} from './error.js'\nimport {cwd, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport git, {TaskOptions, SimpleGitProgressEvent, DefaultLogFields, ListLogLine, SimpleGit} from 'simple-git'\nimport ignore from 'ignore'\n\n/**\n * Initialize a git repository at the given directory.\n *\n * @param directory - The directory where the git repository will be initialized.\n * @param initialBranch - The name of the initial branch.\n */\nexport async function initializeGitRepository(directory: string, initialBranch = 'main'): Promise<void> {\n outputDebug(outputContent`Initializing git repository at ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n // We use init and checkout instead of `init --initial-branch` because the latter is only supported in git 2.28+\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const repo = git(directory)\n await repo.init()\n await repo.checkoutLocalBranch(initialBranch)\n}\n\n/**\n * Given a Git repository and a list of absolute paths to files contained\n * in the repository, it filters and returns the files that are ignored\n * by the .gitignore.\n *\n * @param directory - The absolute path to the directory containing the files.\n * @param files - The list of files to check against.\n * @returns Files ignored by the lockfile.\n */\nexport async function checkIfIgnoredInGitRepository(directory: string, files: string[]): Promise<string[]> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const repo = git(directory)\n const ignoredLockfile = await repo.checkIgnore(files)\n return ignoredLockfile\n}\n\nexport interface GitIgnoreTemplate {\n [section: string]: string[]\n}\n/**\n * Create a .gitignore file in the given directory.\n *\n * @param directory - The directory where the .gitignore file will be created.\n * @param template - The template to use to create the .gitignore file.\n */\nexport function createGitIgnore(directory: string, template: GitIgnoreTemplate): void {\n outputDebug(outputContent`Creating .gitignore at ${outputToken.path(directory)}...`)\n const filePath = `${directory}/.gitignore`\n\n let fileContent = ''\n for (const [section, lines] of Object.entries(template)) {\n fileContent += `# ${section}\\n`\n fileContent += `${lines.join('\\n')}\\n\\n`\n }\n\n appendFileSync(filePath, fileContent)\n}\n\n/**\n * Add an entry to an existing .gitignore file.\n *\n * If the .gitignore file doesn't exist, or if the entry is already present,\n * no changes will be made.\n *\n * @param root - The directory containing the .gitignore file.\n * @param entry - The entry to add to the .gitignore file.\n */\nexport function addToGitIgnore(root: string, entry: string): void {\n const gitIgnorePath = joinPath(root, '.gitignore')\n\n if (!fileExistsSync(gitIgnorePath)) {\n // When the .gitignore file does not exist, the CLI should not be opinionated about creating it\n return\n }\n\n const gitIgnoreContent = readFileSync(gitIgnorePath).toString()\n const eol = detectEOL(gitIgnoreContent)\n\n const lines = gitIgnoreContent.split(eol).map((line) => line.trim())\n const ignoreManager = ignore.default({allowRelativePaths: true}).add(lines)\n\n const isIgnoredEntry = ignoreManager.ignores(joinPath(entry))\n const isIgnoredEntryAsDir = ignoreManager.ignores(joinPath(entry, 'ignored.txt'))\n const isAlreadyIgnored = isIgnoredEntry || isIgnoredEntryAsDir\n if (isAlreadyIgnored) {\n // The file is already ignored by an existing pattern\n return\n }\n\n if (gitIgnoreContent.endsWith(eol)) {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${entry}${eol}`)\n } else {\n writeFileSync(gitIgnorePath, `${gitIgnoreContent}${eol}${entry}${eol}`)\n }\n}\n\n/**\n * Options to use when cloning a git repository.\n *\n * @param repoUrl - The URL of the repository to clone.\n * @param destination - The directory where the repository will be cloned.\n * @param progressUpdater - A function that will be called with the progress of the clone.\n * @param shallow - Whether to clone the repository shallowly.\n * @param latestTag - Whether to clone the latest tag instead of the default branch.\n */\nexport interface GitCloneOptions {\n repoUrl: string\n destination: string\n progressUpdater?: (statusString: string) => void\n shallow?: boolean\n latestTag?: boolean\n}\n/**\n * Clone a git repository.\n *\n * @param cloneOptions - The options to use to clone the repository.\n * @returns A promise that resolves when the clone is complete.\n */\nexport async function downloadGitRepository(cloneOptions: GitCloneOptions): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n const {repoUrl, destination, progressUpdater, shallow, latestTag} = cloneOptions\n outputDebug(outputContent`Git-cloning repository ${repoUrl} into ${outputToken.path(destination)}...`)\n await ensureGitIsPresentOrAbort()\n const [repository, branch] = repoUrl.split('#')\n const options: TaskOptions = {'--recurse-submodules': null}\n\n if (branch && latestTag) {\n throw new AbortError(\"Error cloning the repository. Git can't clone the latest release with a 'branch'.\")\n }\n if (branch) {\n options['--branch'] = branch\n }\n\n if (shallow && latestTag) {\n throw new AbortError(\n \"Error cloning the repository. Git can't clone the latest release with the 'shallow' property.\",\n )\n }\n if (shallow) {\n options['--depth'] = 1\n }\n\n const progress = ({stage, progress, processed, total}: SimpleGitProgressEvent) => {\n const updateString = `${stage}, ${processed}/${total} objects (${progress}% complete)`\n if (progressUpdater) progressUpdater(updateString)\n }\n\n const simpleGitOptions = {\n progress,\n ...(!isTerminalInteractive() && {config: ['core.askpass=true']}),\n }\n try {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n await git(simpleGitOptions).clone(repository!, destination, options)\n\n if (latestTag) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const localGitRepository = git(destination)\n const latestTag = await getLocalLatestTag(localGitRepository, repoUrl)\n await localGitRepository.checkout(latestTag)\n }\n } catch (err) {\n if (err instanceof Error) {\n const abortError = new AbortError(err.message)\n abortError.stack = err.stack\n throw abortError\n }\n throw err\n }\n })\n}\n\n/**\n * Get the most recent tag of a local git repository.\n *\n * @param repository - The local git repository.\n * @param repoUrl - The URL of the repository.\n * @returns The most recent tag of the repository.\n */\nasync function getLocalLatestTag(repository: SimpleGit, repoUrl: string): Promise<string> {\n const latest = (await repository.tags()).latest\n\n if (!latest) {\n throw new AbortError(`Couldn't obtain the most recent tag of the repository ${repoUrl}`)\n }\n\n return latest\n}\n\n/**\n * Get the latest commit of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The latest commit of the repository.\n */\nexport async function getLatestGitCommit(directory?: string): Promise<DefaultLogFields & ListLogLine> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const logs = await git({baseDir: directory}).log({\n maxCount: 1,\n })\n if (!logs.latest) {\n throw new AbortError(\n 'Must have at least one commit to run command',\n outputContent`Run ${outputToken.genericShellCommand(\n \"git commit -m 'Initial commit'\",\n )} to create your first commit.`,\n )\n }\n return logs.latest\n}\n\n/**\n * Add all files to the git index from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @returns A promise that resolves when the files are added to the index.\n */\nexport async function addAllToGitFromDirectory(directory?: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const simpleGit = git({baseDir: directory})\n await simpleGit.raw('add', '--all')\n}\n\nexport interface CreateGitCommitOptions {\n directory?: string\n author?: string\n}\n\n/**\n * Create a git commit.\n *\n * @param message - The message of the commit.\n * @param options - The options to use to create the commit.\n * @returns The hash of the created commit.\n */\nexport async function createGitCommit(message: string, options?: CreateGitCommitOptions): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const simpleGit = git({baseDir: options?.directory})\n\n const commitOptions = options?.author ? {'--author': options.author} : undefined\n const result = await simpleGit.commit(message, commitOptions)\n\n return result.commit\n}\n\n/**\n * Get the HEAD symbolic reference of a git repository.\n *\n * @param directory - The directory of the git repository.\n * @returns The HEAD symbolic reference of the repository.\n */\nexport async function getHeadSymbolicRef(directory?: string): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const ref = await git({baseDir: directory}).raw('symbolic-ref', '-q', 'HEAD')\n if (!ref) {\n throw new AbortError(\n \"Git HEAD can't be detached to run command\",\n outputContent`Run ${outputToken.genericShellCommand(\n 'git checkout [branchName]',\n )} to reattach HEAD or see git ${outputToken.link(\n 'documentation',\n 'https://git-scm.com/book/en/v2/Git-Internals-Git-References',\n )} for more details`,\n )\n }\n return ref.trim()\n}\n\n/**\n * If \"git\" is not present in the environment it throws\n * an abort error.\n */\nexport async function ensureGitIsPresentOrAbort(): Promise<void> {\n if (!(await hasGit())) {\n throw new AbortError(\n `Git is necessary in the environment to continue`,\n outputContent`Install ${outputToken.link(\n 'git',\n 'https://git-scm.com/book/en/v2/Getting-Started-Installing-Git',\n )}`,\n )\n }\n}\n\nexport class OutsideGitDirectoryError extends AbortError {}\n/**\n * If command run from outside a .git directory tree\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureInsideGitDirectory(directory?: string): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (!(await insideGitDirectory(directory))) {\n throw new OutsideGitDirectoryError(`${outputToken.path(directory || cwd())} is not a Git directory`)\n }\n}\n\n/**\n * Returns true if the given directory is inside a .git directory tree.\n *\n * @param directory - The directory to check.\n * @returns True if the directory is inside a .git directory tree.\n */\nexport async function insideGitDirectory(directory?: string): Promise<boolean> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return git({baseDir: directory}).checkIsRepo()\n}\n\nexport class GitDirectoryNotCleanError extends AbortError {}\n/**\n * If the .git directory tree is not clean (has uncommitted changes)\n * it throws an abort error.\n *\n * @param directory - The directory to check.\n */\nexport async function ensureIsClean(directory?: string): Promise<void> {\n if (!(await isClean(directory))) {\n throw new GitDirectoryNotCleanError(`${outputToken.path(directory || cwd())} is not a clean Git directory`)\n }\n}\n\n/**\n * Returns true if the .git directory tree is clean (no uncommitted changes).\n *\n * @param directory - The directory to check.\n * @returns True is the .git directory is clean.\n */\nexport async function isClean(directory?: string): Promise<boolean> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return (await git({baseDir: directory}).status()).isClean()\n}\n\n/**\n * Returns the latest tag of a git repository.\n *\n * @param directory - The directory to check.\n * @returns String with the latest tag or undefined if no tags are found.\n */\nexport async function getLatestTag(directory?: string): Promise<string | undefined> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const tags = await git({baseDir: directory}).tags()\n return tags.latest\n}\n\n/**\n * Remove a git remote from the given directory.\n *\n * @param directory - The directory where the git repository is located.\n * @param remoteName - The name of the remote to remove (defaults to 'origin').\n * @returns A promise that resolves when the remote is removed.\n */\nexport async function removeGitRemote(directory: string, remoteName = 'origin'): Promise<void> {\n outputDebug(outputContent`Removing git remote ${remoteName} from ${outputToken.path(directory)}...`)\n await ensureGitIsPresentOrAbort()\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const repo = git(directory)\n\n // Check if remote exists first\n const remotes = await repo.getRemotes()\n const remoteExists = remotes.some((remote: {name: string}) => remote.name === remoteName)\n\n if (!remoteExists) {\n outputDebug(outputContent`Remote ${remoteName} does not exist, no action needed`)\n return\n }\n\n await repo.removeRemote(remoteName)\n}\n"]}