commander#OptionValues TypeScript Examples

The following examples show how to use commander#OptionValues. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PublisherConfig.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Retrieve valid GCS configuration based on the command.
   */
  private static getValidGoogleGcsConfig(
    opts: OptionValues,
  ): PublisherConfiguration {
    return {
      type: 'googleGcs',
      googleGcs: {
        bucketName: opts.storageName,
        ...(opts.gcsBucketRootPath && {
          bucketRootPath: opts.gcsBucketRootPath,
        }),
      },
    };
  }
Example #2
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('deposit')
	.argument('<amount>', 'The amount to deposit')
	.action(async (amount, options: OptionValues) => {
		await wrapActionInUserSubscribeUnsubscribe(
			options,
			async (user: ClearingHouseUser) => {
				log.info(`amount: ${amount}`);
				amount = new BN(amount);

				const associatedTokenPublicKey = await Token.getAssociatedTokenAddress(
					ASSOCIATED_TOKEN_PROGRAM_ID,
					TOKEN_PROGRAM_ID,
					user.clearingHouse.getStateAccount().collateralMint,
					user.authority
				);

				await user.clearingHouse.depositCollateral(
					amount,
					associatedTokenPublicKey
				);
			}
		);
	});
Example #3
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('reset-oracle-twap')
	.argument('<market>', 'The market to reset oracle twap for')
	.action(async (market, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`market: ${market}`);
				market = marketIndexFromSymbol(market);

				log.info(`Resetting amm oracle twap`);
				await admin.resetAmmOracleTwap(market);
				log.info(`Reset oracle twap`);
			}
		);
	});
Example #4
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('update-oracle-twap')
	.argument('<market>', 'The market to update oracle twap for')
	.action(async (market, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`market: ${market}`);
				market = marketIndexFromSymbol(market);

				log.info(`Updating amm oracle twap`);
				await admin.updateAmmOracleTwap(market);
				log.info(`Updated oracle twap`);
			}
		);
	});
Example #5
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('unpause-funding').action(
	async (options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				const answer = await promptly.prompt(
					`Are you sure you want to 'unpause' funding? y/n`
				);
				if (answer !== 'y') {
					log.info('Canceling');
					return;
				}
				await admin.updateFundingPaused(false);
				log.info(`Funding was unpaused`);
			}
		);
	}
);
Example #6
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('pause-funding').action(
	async (options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				const answer = await promptly.prompt(
					`Are you sure you want to 'pause' funding? y/n`
				);
				if (answer !== 'y') {
					log.info('Canceling');
					return;
				}
				await admin.updateFundingPaused(true);
				log.info(`Funding was paused`);
			}
		);
	}
);
Example #7
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('unpause-exchange').action(
	async (options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				const answer = await promptly.prompt(
					`Are you sure you want to 'unpause' the exchange? y/n`
				);
				if (answer !== 'y') {
					log.info('Canceling');
					return;
				}
				await admin.updateExchangePaused(false);
				log.info(`Exchange was unpaused`);
			}
		);
	}
);
Example #8
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('pause-exchange').action(
	async (options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				const answer = await promptly.prompt(
					`Are you sure you want to 'pause' the exchange? y/n`
				);
				if (answer !== 'y') {
					log.info('Canceling');
					return;
				}
				await admin.updateExchangePaused(true);
				log.info(`Exchange was paused`);
			}
		);
	}
);
Example #9
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('repeg')
	.argument('<market>', 'The market to adjust k for')
	.argument('<peg>', 'New Peg')
	.action(async (market, peg, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`market: ${market}`);
				log.info(`peg: ${peg}`);
				market = marketIndexFromSymbol(market);
				peg = new BN(peg);

				const amm = admin.getMarketsAccount().markets[market.toNumber()].amm;
				const oldPeg = amm.pegMultiplier;
				log.info(`Current peg: ${oldPeg.toString()}`);

				log.info(`Updating peg`);
				await admin.repegAmmCurve(peg, market);
				log.info(`Updated peg`);
			}
		);
	});
Example #10
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('update-discount-mint')
	.argument('<discount mint>', 'New discount mint')
	.action(async (discountMint, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`discountMint: ${discountMint}`);
				discountMint = new PublicKey(discountMint);
				await admin.updateDiscountMint(discountMint);
			}
		);
	});
Example #11
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('initialize')
	.argument('<collateral mint>', 'The collateral mint')
	.argument(
		'<admin controls prices>',
		'Whether the admin should control prices'
	)
	.action(
		async (collateralMint, adminControlsPrices, options: OptionValues) => {
			await wrapActionInAdminSubscribeUnsubscribe(
				options,
				async (admin: Admin) => {
					log.info(`collateralMint: ${collateralMint}`);
					log.info(`adminControlsPrices: ${adminControlsPrices}`);
					const collateralMintPublicKey = new PublicKey(collateralMint);
					log.info(`ClearingHouse initializing`);
					await admin.initialize(collateralMintPublicKey, adminControlsPrices);
				}
			);
		}
	);
Example #12
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
async function wrapActionInUserSubscribeUnsubscribe(
	options: OptionValues,
	action: (user: ClearingHouseUser) => Promise<void>
): Promise<void> {
	const admin = adminFromOptions(options);
	log.info(`ClearingHouse subscribing`);
	await admin.subscribe();
	log.info(`ClearingHouse subscribed`);
	const clearingHouseUser = ClearingHouseUser.from(
		admin,
		admin.wallet.publicKey
	);
	log.info(`User subscribing`);
	await clearingHouseUser.subscribe();
	log.info(`User subscribed`);

	try {
		await action(clearingHouseUser);
	} catch (e) {
		log.error(e);
	}

	log.info(`User unsubscribing`);
	await clearingHouseUser.unsubscribe();
	log.info(`User unsubscribed`);

	log.info(`ClearingHouse unsubscribing`);
	await admin.unsubscribe();
	log.info(`ClearingHouse unsubscribed`);
}
Example #13
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
async function wrapActionInAdminSubscribeUnsubscribe(
	options: OptionValues,
	action: (admin: Admin) => Promise<void>
): Promise<void> {
	const admin = adminFromOptions(options);
	log.info(`ClearingHouse subscribing`);
	await admin.subscribe();
	log.info(`ClearingHouse subscribed`);

	try {
		await action(admin);
	} catch (e) {
		log.error(e);
	}

	log.info(`ClearingHouse unsubscribing`);
	await admin.unsubscribe();
	log.info(`ClearingHouse unsubscribed`);
}
Example #14
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
function adminFromOptions(options: OptionValues): Admin {
	let { env, keypair, url } = options;
	const config = getConfig();
	if (!env) {
		env = config.env;
	}
	log.info(`env: ${env}`);
	const sdkConfig = initialize({ env: env });

	if (!url) {
		url = config.url;
	}
	log.info(`url: ${url}`);
	const connection = new Connection(url);

	if (!keypair) {
		keypair = config.keypair;
	}
	const wallet = new Wallet(loadKeypair(keypair));

	return Admin.from(
		connection,
		wallet,
		new PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID)
	);
}
Example #15
Source File: PublisherConfig.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Retrieves valid OpenStack Swift configuration based on the command.
   */
  private static getValidOpenStackSwiftConfig(
    opts: OptionValues,
  ): PublisherConfiguration {
    const missingParams = [
      'osCredentialId',
      'osSecret',
      'osAuthUrl',
      'osSwiftUrl',
    ].filter((param: string) => !opts[param]);

    if (missingParams.length) {
      throw new Error(
        `openStackSwift requires the following params to be specified: ${missingParams.join(
          ', ',
        )}`,
      );
    }

    return {
      type: 'openStackSwift',
      openStackSwift: {
        containerName: opts.storageName,
        credentials: {
          id: opts.osCredentialId,
          secret: opts.osSecret,
        },
        authUrl: opts.osAuthUrl,
        swiftUrl: opts.osSwiftUrl,
      },
    };
  }
Example #16
Source File: command.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export async function command(opts: OptionValues): Promise<void> {
  const role = await findRoleFromCommand(opts);

  if (role === 'frontend') {
    return buildFrontend({
      targetDir: paths.targetDir,
      configPaths: opts.config as string[],
      writeStats: Boolean(opts.stats),
    });
  }
  if (role === 'backend') {
    return buildBackend({
      targetDir: paths.targetDir,
      skipBuildDependencies: Boolean(opts.skipBuildDependencies),
    });
  }

  const roleInfo = getRoleInfo(role);

  const outputs = new Set<Output>();

  if (roleInfo.output.includes('cjs')) {
    outputs.add(Output.cjs);
  }
  if (roleInfo.output.includes('esm')) {
    outputs.add(Output.esm);
  }
  if (roleInfo.output.includes('types')) {
    outputs.add(Output.types);
  }

  return buildPackage({
    outputs,
    minify: Boolean(opts.minify),
    useApiExtractor: Boolean(opts.experimentalTypeBuild),
  });
}
Example #17
Source File: PublisherConfig.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Retrieve valid AWS S3 configuration based on the command.
   */
  private static getValidAwsS3Config(
    opts: OptionValues,
  ): PublisherConfiguration {
    return {
      type: 'awsS3',
      awsS3: {
        bucketName: opts.storageName,
        ...(opts.awsBucketRootPath && {
          bucketRootPath: opts.awsBucketRootPath,
        }),
        ...(opts.awsRoleArn && { credentials: { roleArn: opts.awsRoleArn } }),
        ...(opts.awsEndpoint && { endpoint: opts.awsEndpoint }),
        ...(opts.awsS3ForcePathStyle && { s3ForcePathStyle: true }),
        ...(opts.awsS3sse && { sse: opts.awsS3sse }),
      },
    };
  }
Example #18
Source File: print.ts    From backstage with Apache License 2.0 6 votes vote down vote up
function getVisibilityOption(opts: OptionValues): ConfigVisibility {
  if (opts.frontend && opts.withSecrets) {
    throw new Error('Not allowed to combine frontend and secret config');
  }
  if (opts.frontend) {
    return 'frontend';
  } else if (opts.withSecrets) {
    return 'secret';
  }
  return 'backend';
}
Example #19
Source File: command.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export async function command(opts: OptionValues): Promise<void> {
  const role = await findRoleFromCommand(opts);

  const options = {
    configPaths: opts.config as string[],
    checksEnabled: Boolean(opts.check),
    inspectEnabled: Boolean(opts.inspect),
    inspectBrkEnabled: Boolean(opts.inspectBrk),
  };

  switch (role) {
    case 'backend':
    case 'backend-plugin':
    case 'backend-plugin-module':
    case 'node-library':
      return startBackend(options);
    case 'frontend':
      return startFrontend({
        ...options,
        entry: 'src/index',
        verifyVersions: true,
      });
    case 'web-library':
    case 'frontend-plugin':
    case 'frontend-plugin-module':
      return startFrontend({ entry: 'dev/index', ...options });
    default:
      throw new Error(
        `Start command is not supported for package role '${role}'`,
      );
  }
}
Example #20
Source File: packageRoles.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export async function findRoleFromCommand(
  opts: OptionValues,
): Promise<PackageRole> {
  if (opts.role) {
    return getRoleInfo(opts.role)?.role;
  }

  const pkg = await fs.readJson(paths.resolveTarget('package.json'));
  const info = getRoleFromPackage(pkg);
  if (!info) {
    throw new Error(`Target package must have 'backstage.role' set`);
  }
  return info;
}
Example #21
Source File: migrate.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export default async function migrate(opts: OptionValues) {
  const logger = createLogger({ verbose: opts.verbose });

  const config = PublisherConfig.getValidConfig(opts);
  const discovery = SingleHostDiscovery.fromConfig(config);
  const publisher = await Publisher.fromConfig(config, { logger, discovery });

  if (!publisher.migrateDocsCase) {
    throw new Error(`Migration not implemented for ${opts.publisherType}`);
  }

  // Check that the publisher's underlying storage is ready and available.
  const { isAvailable } = await publisher.getReadiness();
  if (!isAvailable) {
    // Error messages printed in getReadiness() call. This ensures exit code 1.
    throw new Error('');
  }

  // Validate and parse migration arguments.
  const removeOriginal = opts.removeOriginal;
  const numericConcurrency = parseInt(opts.concurrency, 10);

  if (!Number.isInteger(numericConcurrency) || numericConcurrency <= 0) {
    throw new Error(
      `Concurrency must be a number greater than 1. ${opts.concurrency} provided.`,
    );
  }

  await publisher.migrateDocsCase({
    concurrency: numericConcurrency,
    removeOriginal,
  });
}
Example #22
Source File: publish.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export default async function publish(opts: OptionValues): Promise<any> {
  const logger = createLogger({ verbose: opts.verbose });

  const config = PublisherConfig.getValidConfig(opts);
  const discovery = SingleHostDiscovery.fromConfig(config);
  const publisher = await Publisher.fromConfig(config, { logger, discovery });

  // Check that the publisher's underlying storage is ready and available.
  const { isAvailable } = await publisher.getReadiness();
  if (!isAvailable) {
    // Error messages printed in getReadiness() call. This ensures exit code 1.
    return Promise.reject(new Error(''));
  }

  const [namespace, kind, name] = opts.entity.split('/');
  const entity = {
    kind,
    metadata: {
      namespace,
      name,
    },
  } as Entity;

  const directory = resolve(opts.directory);
  await publisher.publish({ entity, directory });

  return true;
}
Example #23
Source File: PublisherConfig.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Returns Backstage config suitable for use when instantiating a Publisher. If
   * there are any missing or invalid options provided, an error is thrown.
   *
   * Note: This assumes that proper credentials are set in Environment
   * variables for the respective GCS/AWS clients to work.
   */
  static getValidConfig(opts: OptionValues): ConfigReader {
    const publisherType = opts.publisherType;

    if (!PublisherConfig.isKnownPublisher(publisherType)) {
      throw new Error(`Unknown publisher type ${opts.publisherType}`);
    }

    return new ConfigReader({
      // This backend config is not used at all. Just something needed a create a mock discovery instance.
      backend: {
        baseUrl: 'http://localhost:7007',
        listen: {
          port: 7007,
        },
      },
      techdocs: {
        publisher: PublisherConfig.configFactories[publisherType](opts),
        legacyUseCaseSensitiveTripletPaths:
          opts.legacyUseCaseSensitiveTripletPaths,
      },
    });
  }
Example #24
Source File: PublisherConfig.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Retrieve valid Azure Blob Storage configuration based on the command.
   */
  private static getValidAzureConfig(
    opts: OptionValues,
  ): PublisherConfiguration {
    if (!opts.azureAccountName) {
      throw new Error(
        `azureBlobStorage requires --azureAccountName to be specified`,
      );
    }

    return {
      type: 'azureBlobStorage',
      azureBlobStorage: {
        containerName: opts.storageName,
        credentials: {
          accountName: opts.azureAccountName,
          accountKey: opts.azureAccountKey,
        },
      },
    };
  }
Example #25
Source File: mkdocs.ts    From backstage with Apache License 2.0 5 votes vote down vote up
export default async function serveMkdocs(opts: OptionValues) {
  const logger = createLogger({ verbose: opts.verbose });

  const dockerAddr = `http://0.0.0.0:${opts.port}`;
  const localAddr = `http://127.0.0.1:${opts.port}`;
  const expectedDevAddr = opts.docker ? dockerAddr : localAddr;
  // We want to open browser only once based on a log.
  let boolOpenBrowserTriggered = false;

  const logFunc: LogFunc = data => {
    // Sometimes the lines contain an unnecessary extra new line in between
    const logLines = data.toString().split('\n');
    const logPrefix = opts.docker ? '[docker/mkdocs]' : '[mkdocs]';
    logLines.forEach(line => {
      if (line === '') {
        return;
      }

      // Logs from container is verbose.
      logger.verbose(`${logPrefix} ${line}`);

      // When the server has started, open a new browser tab for the user.
      if (
        !boolOpenBrowserTriggered &&
        line.includes(`Serving on ${expectedDevAddr}`)
      ) {
        // Always open the local address, since 0.0.0.0 belongs to docker
        logger.info(`\nStarting mkdocs server on ${localAddr}\n`);
        openBrowser(localAddr);
        boolOpenBrowserTriggered = true;
      }
    });
  };
  // mkdocs writes all of its logs to stderr by default, and not stdout.
  // https://github.com/mkdocs/mkdocs/issues/879#issuecomment-203536006
  // Had me questioning this whole implementation for half an hour.

  // Commander stores --no-docker in cmd.docker variable
  const childProcess = await runMkdocsServer({
    port: opts.port,
    dockerImage: opts.dockerImage,
    dockerEntrypoint: opts.dockerEntrypoint,
    useDocker: opts.docker,
    stdoutLogFunc: logFunc,
    stderrLogFunc: logFunc,
  });

  // Keep waiting for user to cancel the process
  await waitForSignal([childProcess]);
}
Example #26
Source File: cli.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
commandWithDefaultOption('initialize-market')
	.argument(
		'<market index>',
		'Where the market will be initialized in the markets account'
	)
	.argument('<price oracle>', 'The public key for the oracle')
	.argument('<base asset reserve>', 'AMM base asset reserve')
	.argument('<quote asset reserve>', 'AMM quote asset reserve')
	.argument('<periodicity>', 'AMM quote asset reserve')
	.argument('<peg multiplier>', 'AMM peg multiplier')
	.action(
		async (
			marketIndex,
			priceOracle,
			baseAssetReserve,
			quoteAssetReserve,
			periodicity,
			pegMultiplier,
			options: OptionValues
		) => {
			await wrapActionInAdminSubscribeUnsubscribe(
				options,
				async (admin: Admin) => {
					log.info(`marketIndex: ${marketIndex}`);
					marketIndex = new BN(marketIndex);
					log.info(`priceOracle: ${priceOracle}`);
					priceOracle = new PublicKey(priceOracle);
					log.info(`baseAssetReserve: ${baseAssetReserve}`);
					baseAssetReserve = new BN(baseAssetReserve);
					log.info(`quoteAssetReserve: ${quoteAssetReserve}`);
					quoteAssetReserve = new BN(quoteAssetReserve);
					log.info(`periodicity: ${periodicity}`);
					periodicity = new BN(periodicity);
					log.info(`pegMultiplier: ${pegMultiplier}`);
					pegMultiplier = new BN(pegMultiplier);
					log.info(`Initializing market`);
					await admin.initializeMarket(
						marketIndex,
						priceOracle,
						baseAssetReserve,
						quoteAssetReserve,
						periodicity,
						pegMultiplier
					);
				}
			);
		}
	);
Example #27
Source File: cli.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
commandWithDefaultOption('increase-k')
	.argument('<market>', 'The market to adjust k for')
	.argument('<numerator>', 'Numerator to multiply k by')
	.argument('<denominator>', 'Denominator to divide k by')
	.option('--force', 'Skip percent change check')
	.action(async (market, numerator, denominator, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`market: ${market}`);
				log.info(`numerator: ${numerator}`);
				log.info(`denominator: ${denominator}`);
				market = marketIndexFromSymbol(market);
				numerator = new BN(numerator);
				denominator = new BN(denominator);

				if (numerator.lt(denominator)) {
					logError('To increase k, numerator must be larger than denominator');
					return;
				}

				const percentChange = Math.abs(
					(numerator.toNumber() / denominator.toNumber()) * 100 - 100
				);
				if (percentChange > 10 && options.force !== true) {
					logError(
						`Specified input would lead to ${percentChange.toFixed(2)}% change`
					);
					return;
				}

				const answer = await promptly.prompt(
					`You are increasing k by ${percentChange}%. Are you sure you want to do this? y/n`
				);
				if (answer !== 'y') {
					log.info('Canceling');
					return;
				}

				const amm = admin.getMarketsAccount().markets[market.toNumber()].amm;
				const oldSqrtK = amm.sqrtK;
				log.info(`Current sqrt k: ${oldSqrtK.toString()}`);

				const newSqrtK = oldSqrtK.mul(numerator).div(denominator);
				log.info(`New sqrt k: ${newSqrtK.toString()}`);

				log.info(`Updating K`);
				await admin.updateK(newSqrtK, market);
				log.info(`Updated K`);
			}
		);
	});
Example #28
Source File: cli.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
commandWithDefaultOption('decrease-k')
	.argument('<market>', 'The market to adjust k for')
	.argument('<numerator>', 'Numerator to multiply k by')
	.argument('<denominator>', 'Denominator to divide k by')
	.option('--force', 'Skip percent change check')
	.action(async (market, numerator, denominator, options: OptionValues) => {
		await wrapActionInAdminSubscribeUnsubscribe(
			options,
			async (admin: Admin) => {
				log.info(`market: ${market}`);
				log.info(`numerator: ${numerator}`);
				log.info(`denominator: ${denominator}`);
				market = marketIndexFromSymbol(market);
				numerator = new BN(numerator);
				denominator = new BN(denominator);

				if (numerator.gt(denominator)) {
					logError('To decrease k, numerator must be less than denominator');
					return;
				}

				const percentChange = Math.abs(
					(numerator.toNumber() / denominator.toNumber()) * 100 - 100
				);
				if (percentChange > 2) {
					logError(
						`Specified input would lead to ${percentChange.toFixed(2)}% change`
					);
					return;
				}

				const answer = await promptly.prompt(
					`You are decreasing k by ${percentChange}%. Are you sure you want to do this? y/n`
				);
				if (answer !== 'y' && options.force !== true) {
					log.info('Canceling');
					return;
				}

				const amm = admin.getMarketsAccount().markets[market.toNumber()].amm;
				const oldSqrtK = amm.sqrtK;
				log.info(`Current sqrt k: ${oldSqrtK.toString()}`);

				const newSqrtK = oldSqrtK.mul(numerator).div(denominator);
				log.info(`New sqrt k: ${newSqrtK.toString()}`);

				log.info(`Updating K`);
				await admin.updateK(newSqrtK, market);
				log.info(`Updated K`);
			}
		);
	});
Example #29
Source File: generate.ts    From backstage with Apache License 2.0 5 votes vote down vote up
export default async function generate(opts: OptionValues) {
  // Use techdocs-node package to generate docs. Keep consistency between Backstage and CI generating docs.
  // Docs can be prepared using actions/checkout or git clone, or similar paradigms on CI. The TechDocs CI workflow
  // will run on the CI pipeline containing the documentation files.

  const logger = createLogger({ verbose: opts.verbose });

  const sourceDir = resolve(opts.sourceDir);
  const outputDir = resolve(opts.outputDir);
  const omitTechdocsCorePlugin = opts.omitTechdocsCoreMkdocsPlugin;
  const dockerImage = opts.dockerImage;
  const pullImage = opts.pull;
  const legacyCopyReadmeMdToIndexMd = opts.legacyCopyReadmeMdToIndexMd;

  logger.info(`Using source dir ${sourceDir}`);
  logger.info(`Will output generated files in ${outputDir}`);

  logger.verbose('Creating output directory if it does not exist.');

  await fs.ensureDir(outputDir);

  const config = new ConfigReader({
    techdocs: {
      generator: {
        runIn: opts.docker ? 'docker' : 'local',
        dockerImage,
        pullImage,
        legacyCopyReadmeMdToIndexMd,
        mkdocs: {
          omitTechdocsCorePlugin,
        },
      },
    },
  });

  // Docker client (conditionally) used by the generators, based on techdocs.generators config.
  const dockerClient = new Docker();
  const containerRunner = new DockerContainerRunner({ dockerClient });

  let parsedLocationAnnotation = {} as ParsedLocationAnnotation;
  if (opts.techdocsRef) {
    try {
      parsedLocationAnnotation = convertTechDocsRefToLocationAnnotation(
        opts.techdocsRef,
      );
    } catch (err) {
      logger.error(err.message);
    }
  }

  // Generate docs using @backstage/plugin-techdocs-node
  const techdocsGenerator = await TechdocsGenerator.fromConfig(config, {
    logger,
    containerRunner,
  });

  logger.info('Generating documentation...');

  await techdocsGenerator.run({
    inputDir: sourceDir,
    outputDir,
    ...(opts.techdocsRef
      ? {
          parsedLocationAnnotation,
        }
      : {}),
    logger,
    etag: opts.etag,
    ...(process.env.LOG_LEVEL === 'debug' ? { logStream: stdout } : {}),
  });

  logger.info('Done!');
}