chalk#green TypeScript Examples

The following examples show how to use chalk#green. 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: reportPreviewer.ts    From cli with Apache License 2.0 6 votes vote down vote up
private getNoChangesReportHandler(): (
    this: SnapshotReporter
  ) => void | Promise<void> {
    return function (this: SnapshotReporter) {
      CliUx.ux.log(dedent`${green('No resources to change')}.

      The target organization already matches the configuration.`);
      return;
    };
  }
Example #2
Source File: log.ts    From yfm-transform with MIT License 6 votes vote down vote up
function createLogger(type: LogLevels) {
    const formatter: Record<string, (v: string) => string> = {
        [LogLevels.INFO]: (msg) => `${green('INFO')} ${msg}`,
        [LogLevels.WARN]: (msg) => `${yellow('WARN')} ${msg}`,
        [LogLevels.ERROR]: (msg) => `${red('ERR ')} ${msg}`,
    };

    return function log(msg: string) {
        const problem = formatter[type](msg);

        if (!problems[type].includes(problem)) {
            problems[type].push(problem);
        }
    };
}
Example #3
Source File: logger.ts    From yfm-docs with MIT License 6 votes vote down vote up
logger = {
    info: function (pathToFile: string, extraMessage?: string) {
        writeLog(`${grey('INFO')} ${extraMessage} ${pathToFile}`);
    },
    proc: function (pathToFile: string) {
        writeLog(`${blue('PROC')} Processing file ${pathToFile}`);
    },
    copy: function (pathToFile: string) {
        writeLog(`${green('COPY')} Copying file ${pathToFile}`);
    },
    upload: function (pathToFile: string) {
        writeLog(`${green('UPLOAD')} Uploading file ${pathToFile}`);
    },
}
Example #4
Source File: packet.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
async storeUnacknowledgedTicket(db: HoprDB) {
    if (this.ownKey == undefined) {
      throw Error(`Invalid state`)
    }

    const unacknowledged = new UnacknowledgedTicket(this.ticket, this.ownKey, this.previousHop)

    log(
      `Storing unacknowledged ticket. Expecting to receive a preImage for ${green(
        this.ackChallenge.toHex()
      )} from ${blue(pubKeyToPeerId(this.nextHop).toB58String())}`
    )

    await db.storePendingAcknowledgement(this.ackChallenge, false, unacknowledged)
  }
Example #5
Source File: vaultHandler.ts    From cli with Apache License 2.0 6 votes vote down vote up
private async doCreateVaultEntries(vaultEntryModels: VaultEntryModel[]) {
    const client = await this.client();
    if (vaultEntryModels.length > 0) {
      const entryPlurable: Plurable = ['entry', 'entries'];
      CliUx.ux.action.start(
        `Creating vault ${pluralizeIfNeeded(
          entryPlurable,
          vaultEntryModels.length
        )}`
      );
      await Promise.all(
        vaultEntryModels.map((entry) => client.vault.create(entry))
      );
      CliUx.ux.action.stop(green('✔'));
    }
  }
Example #6
Source File: snapshotFacade.ts    From cli with Apache License 2.0 6 votes vote down vote up
private async applySynchronizationPlan(plan: SynchronizationPlan) {
    CliUx.ux.action.start('Synchronizing resources');
    const reporter = await this.snapshot.applySynchronizationPlan(
      plan.model.id,
      this.waitUntilDone
    );
    const success = reporter.isSuccessReport();

    if (!success) {
      throw new SnapshotSynchronizationUnknownError(this.snapshot, this.cfg);
    }

    CliUx.ux.action.stop(green('✔'));
  }
Example #7
Source File: snapshotFacade.ts    From cli with Apache License 2.0 6 votes vote down vote up
private async createSynchronizationPlan() {
    CliUx.ux.action.start('Checking for automatic synchronization');
    const plan = await this.snapshot.createSynchronizationPlan();

    if (!plan.containsUnambiguousMatches()) {
      throw new SnapshotSynchronizationAmbiguousMatchesError(
        this.snapshot,
        this.cfg
      );
    }

    CliUx.ux.action.stop(green('✔'));
    return plan;
  }
Example #8
Source File: snapshotCommon.ts    From cli with Apache License 2.0 6 votes vote down vote up
async function internalDryRun(
  project: Project,
  snapshot: Snapshot,
  cfg: Configuration,
  options: DryRunOptions
) {
  let reporter = await snapshot.validate(
    options.deleteMissingResources,
    options.waitUntilDone
  );

  await reporter
    .setReportHandler(SnapshotReportStatus.SUCCESS, () => {
      CliUx.ux.action.stop(green('✔'));
    })
    .setReportHandler(SnapshotReportStatus.ERROR, async () => {
      if (!options.shouldAutoSync) {
        CliUx.ux.action.stop(red.bold('!'));
        return;
      }
      CliUx.ux.warn('Unsynchronized resource detected');
      await tryAutomaticSynchronization(snapshot, cfg, options);

      CliUx.ux.action.start('Validating synchronized snapshot');
      reporter = await internalDryRun(project, snapshot, cfg, {
        ...options,
        shouldAutoSync: false,
      });
    })
    .handleReport();
  return reporter;
}
Example #9
Source File: push.ts    From cli with Apache License 2.0 6 votes vote down vote up
private async applySnapshot(snapshot: Snapshot) {
    CliUx.ux.action.start('Applying snapshot');
    const cfg = this.configuration.get();
    const {flags} = await this.parse(Push);
    const {waitUntilDone} = await this.getOptions();
    const reporter = await snapshot.apply(
      flags.deleteMissingResources,
      waitUntilDone
    );
    await reporter
      .setReportHandler(SnapshotReportStatus.ERROR, async () => {
        await handleReportWithErrors(snapshot, cfg, this.projectPath);
        CliUx.ux.action.stop(red.bold('!'));
      })
      .setReportHandler(SnapshotReportStatus.SUCCESS, () => {
        CliUx.ux.action.stop(green('✔'));
      })
      .handleReport();
  }
Example #10
Source File: expandedPreviewer.ts    From cli with Apache License 2.0 6 votes vote down vote up
public async preview() {
    if (existsSync(ExpandedPreviewer.previewDirectory)) {
      this.deleteOldestPreviews();
    }
    const previewLocalSlug = `${this.orgId}-${Date.now()}`;
    const dirPath = join(ExpandedPreviewer.previewDirectory, previewLocalSlug);

    mkdirSync(dirPath, {
      recursive: true,
    });
    const project = new Project(resolve(dirPath));
    CliUx.ux.action.start('Generating preview details');
    await this.initPreviewDirectory(dirPath, project);
    await this.applySnapshotToPreview(dirPath);
    const commitHash = await this.getCommitHash(dirPath);

    CliUx.ux.info(dedent`

    A Git repository representing the modification has been created here:
    ${dirPath}

    with the associated commit hash: ${commitHash.stdout}
    `);
    CliUx.ux.action.stop(green('✔'));
  }
Example #11
Source File: userFeedback.ts    From cli with Apache License 2.0 6 votes vote down vote up
successMessage = (
  cmd: Command,
  tagLine: string,
  res?: AxiosResponse
) => {
  let message = dedent(`
      ${tagLine}
      `);
  if (res) {
    message += `Status code: ${green(res.status, res.statusText)}
    `;
  }
  cmd.log(message);
}
Example #12
Source File: new.ts    From cli with Apache License 2.0 6 votes vote down vote up
@Trackable()
  @Preconditions(
    IsAuthenticated(),
    HasNecessaryCoveoPrivileges(writeSourceContentPrivilege)
  )
  public async run() {
    const {flags, args} = await this.parse(SourcePushNew);
    const authenticatedClient = new AuthenticatedClient();
    const platformClient = await authenticatedClient.getClient();

    const res = await platformClient.source.create({
      sourceType: SourceType.PUSH,
      pushEnabled: true,
      name: args.name,
      sourceVisibility: flags.sourceVisibility,
    });

    this.log(
      green(
        dedent(
          `Source ${args.name} with visibility ${flags.sourceVisibility} has been successfully created.
        Id: ${res.id}`
        )
      )
    );
  }
Example #13
Source File: delete.ts    From cli with Apache License 2.0 6 votes vote down vote up
private successMessageOnDeletion(toDelete: string, res: AxiosResponse) {
    return successMessage(
      this,
      `The delete request for document: ${green(
        toDelete
      )} was accepted by the Push API.`,
      res
    );
  }
Example #14
Source File: add.ts    From cli with Apache License 2.0 6 votes vote down vote up
private successMessageOnAdd({batch, files, res}: UploadBatchCallbackData) {
    // Display the first 5 files (from the list of all files) being processed for end user feedback
    // Don't want to clutter the output too much if the list is very long.

    const numAdded = batch.length;
    let fileNames = files.slice(0, 5).join(', ');
    if (files.length > 5) {
      fileNames += ` and ${files.length - 5} more ...`;
    }

    return successMessage(
      this,
      `Success: ${green(numAdded)} document${
        numAdded > 1 ? 's' : ''
      } accepted by the Push API from ${green(fileNames)}.`,
      res
    );
  }
Example #15
Source File: add.ts    From cli with Apache License 2.0 6 votes vote down vote up
@Trackable()
  @Preconditions(
    IsAuthenticated(),
    HasNecessaryCoveoPrivileges(
      writeFieldsPrivilege,
      readOrganizationPrivilege,
      writeSourceContentPrivilege
    )
  )
  public async run() {
    await this.showDeprecatedFlagWarning();
    const {args, flags} = await this.parse(SourcePushAdd);
    const {accessToken, organization, environment, region} =
      await new AuthenticatedClient().cfg.get();
    const source = new PushSource(accessToken!, organization, {
      environment,
      region,
    });

    CliUx.ux.action.start('Processing files');

    const fileNames = await getFileNames(flags);
    const options = {
      maxConcurrent: flags.maxConcurrent,
      createFields: flags.createMissingFields,
    };
    await source.setSourceStatus(args.sourceId, 'REFRESH');

    await source
      .batchUpdateDocumentsFromFiles(args.sourceId, fileNames, options)
      .onBatchUpload((data) => this.successMessageOnAdd(data))
      .onBatchError((data) => this.errorMessageOnAdd(data))
      .batch();

    await source.setSourceStatus(args.sourceId, 'IDLE');

    CliUx.ux.action.stop(green('✔'));
  }
Example #16
Source File: new.ts    From cli with Apache License 2.0 6 votes vote down vote up
@Trackable()
  @Preconditions(
    IsAuthenticated(),
    HasNecessaryCoveoPrivileges(writeSourceContentPrivilege)
  )
  public async run() {
    const {flags, args} = await this.parse(SourceCataloghNew);
    const authenticatedClient = new AuthenticatedClient();
    const platformClient = await authenticatedClient.getClient();

    const res = await platformClient.source.create({
      sourceType: SourceType.CATALOG,
      pushEnabled: true,
      streamEnabled: true,
      name: args.name,
      sourceVisibility: flags.sourceVisibility,
    });

    this.log(
      green(
        dedent(
          `Source ${args.name} with visibility ${flags.sourceVisibility} has been successfully created.
        Id: ${res.id}`
        )
      )
    );
  }
Example #17
Source File: add.ts    From cli with Apache License 2.0 6 votes vote down vote up
private successMessageOnAdd({batch, files, res}: UploadBatchCallbackData) {
    // Display the first 5 files (from the list of all files) being processed for end user feedback.
    // Don't want to clutter the output too much if the list is very long.
    const numAdded = batch.length;
    let fileNames = files.slice(0, 5).join(', ');
    if (files.length > 5) {
      fileNames += ` and ${files.length - 5} more ...`;
    }

    return successMessage(
      this,
      `Success: ${green(numAdded)} document${
        numAdded > 1 ? 's' : ''
      } accepted by the API from ${green(fileNames)}.`,
      res
    );
  }
Example #18
Source File: transferFromOrganization.ts    From cli with Apache License 2.0 5 votes vote down vote up
export async function tryTransferFromOrganization({
  reporter,
  snapshot,
  projectPath,
}: VaultTransferFunctionsParam) {
  if (!projectPath) {
    return false;
  }

  const originOrgId = new Project(projectPath).getResourceManifest()?.orgId;
  if (!originOrgId) {
    return false;
  }

  const shouldTransfer = await CliUx.ux.confirm(
    `\nWould you like to try transfering the vault entries from ${bold.cyan(
      originOrgId
    )} to the destination organization ${bold.cyan(snapshot.targetId)}? (y/n)`
  );
  if (!shouldTransfer) {
    return false;
  }

  const authenticatedClient = new AuthenticatedClient();
  if (!(await authenticatedClient.getUserHasAccessToOrg(originOrgId))) {
    CliUx.ux.warn(dedent`
        We mapped this snapshot to ${bold.cyan(originOrgId)}.
        If you want to transfer the vault entries from ${bold.cyan(
          originOrgId
        )} to ${bold.cyan(snapshot.targetId)},
        authenticate with an account that has access to both organizations and then try again.
      `);
    return false;
  }

  const originOrgVaultEntries = await getAllVaultEntriesFrom(originOrgId);
  const missingEntriesFromOrigin = getEntriesMissingFromOrigin(
    originOrgVaultEntries,
    reporter.missingVaultEntries
  );

  if (missingEntriesFromOrigin.length > 0) {
    CliUx.ux.warn(
      new SnapshotMissingVaultEntriesFromOriginError(
        originOrgId,
        snapshot.targetId,
        missingEntriesFromOrigin
      )
    );
    return false;
  }

  const platformClient = await authenticatedClient.getClient({
    organization: snapshot.targetId,
  });

  try {
    CliUx.ux.action.start('Transfering vault entries');
    await platformClient.vault.import(
      snapshot.id,
      originOrgId,
      VaultFetchStrategy.onlyMissing
    );
    CliUx.ux.action.stop(green('✔'));
    return true;
  } catch (error) {
    CliUx.ux.action.stop(red.bold('!'));
    CliUx.ux.warn('Error encountered while transfering vault entries`');
    CliUx.ux.warn(typeof error === 'string' ? error : JSON.stringify(error));
    return false;
  }
}
Example #19
Source File: handshake.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Tries to establish a relayed connection to the given destination
   * @param relay relay to use
   * @param destination destination to connect to trough relay
   * @returns a relayed connection to `destination`
   */
  async initiate(relay: PeerId, destination: PeerId): Promise<Response> {
    this.shaker.write(destination.pubKey.marshal())

    let chunk: StreamType | undefined
    try {
      chunk = await this.shaker.read()
    } catch (err: any) {
      error(`Error while reading answer from ${green(relay.toB58String())}.`, err.message)
    }

    if (chunk == null || chunk.length == 0) {
      verbose(`Received empty message. Discarding`)
      this.shaker.rest()
      return {
        success: false,
        code: 'FAIL'
      }
    }

    const answer = chunk.slice(0, 1)[0]

    this.shaker.rest()

    // Anything can happen
    switch (answer as RelayHandshakeMessage) {
      case RelayHandshakeMessage.OK:
        log(
          `Successfully established outbound relayed connection with ${green(
            destination.toB58String()
          )} over relay ${green(relay.toB58String())}`
        )
        return {
          success: true,
          stream: this.shaker.stream
        }
      default:
        error(
          `Could not establish relayed connection to ${green(destination.toB58String())} over relay ${green(
            relay.toB58String()
          )}. Answer was: <${yellow(handshakeMessageToString(answer))}>`
        )

        return {
          success: false,
          code: 'FAIL'
        }
    }
  }
Example #20
Source File: handshake.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Handles an incoming request from a relay
   * @param source peerId of the relay
   * @returns a duplex stream with the initiator
   */
  async handle(source: PeerId): Promise<HandleResponse> {
    let chunk: StreamType | undefined
    try {
      chunk = await this.shaker.read()
    } catch (err) {
      error(err)
    }

    // Anything can happen
    if (chunk == null || chunk.length == 0) {
      error(`Received empty message. Ignoring request`)
      this.shaker.write(Uint8Array.of(RelayHandshakeMessage.FAIL))
      this.shaker.rest()

      return {
        success: false,
        code: 'FAIL'
      }
    }

    let initiator: PeerId | undefined

    try {
      initiator = pubKeyToPeerId(chunk.slice())
    } catch (err: any) {
      error(`Could not decode sender peerId.`, err.message)
    }

    if (initiator == null) {
      this.shaker.write(Uint8Array.of(RelayHandshakeMessage.FAIL))
      this.shaker.rest()

      return {
        success: false,
        code: 'FAIL'
      }
    }

    log(
      `Successfully established inbound relayed connection from initiator ${green(
        initiator.toB58String()
      )} over relay ${green(source.toB58String())}.`
    )

    this.shaker.write(Uint8Array.of(RelayHandshakeMessage.OK))
    this.shaker.rest()

    return {
      success: true,
      stream: this.shaker.stream,
      counterparty: initiator
    }
  }
Example #21
Source File: add.ts    From cli with Apache License 2.0 5 votes vote down vote up
@Trackable()
  @Preconditions(
    IsAuthenticated(),
    HasNecessaryCoveoPrivileges(
      writeFieldsPrivilege,
      readOrganizationPrivilege,
      writeSourceContentPrivilege
    )
  )
  public async run() {
    const {args, flags} = await this.parse(SourceCatalogAdd);

    if (
      !flags.fullUpload &&
      !flags.skipFullUploadCheck &&
      (await this.sourceIsEmpty(args.sourceId))
    ) {
      this.error(dedent`No items detected for this source at the moment.
        As a best practice, we recommend doing a full catalog upload by appending --fullUpload to your command.
        If you are still getting this message despite having already performed a full catalog upload, append --forceUpdate to your command to discard this message.
        `);
    }

    CliUx.ux.action.start('Processing files');

    const {accessToken, organization, environment, region} =
      await new AuthenticatedClient().cfg.get();
    const source = new CatalogSource(accessToken!, organization, {
      environment,
      region,
    });

    const fileNames = await getFileNames(flags);
    const options = {
      maxConcurrent: flags.maxConcurrent,
      createFields: flags.createMissingFields,
    };

    const batchOperation = flags.fullUpload
      ? source.batchStreamDocumentsFromFiles.bind(source)
      : source.batchUpdateDocumentsFromFiles.bind(source);

    await batchOperation(args.sourceId, fileNames, options)
      .onBatchUpload((data) => this.successMessageOnAdd(data))
      .onBatchError((data) => this.errorMessageOnAdd(data))
      .batch();

    CliUx.ux.action.stop(green('✔'));
  }