<commit_before>import { Command, getVersion, resolveBinary } from '@prisma/sdk'
import { getPlatform } from '@prisma/get-platform'
import fs from 'fs'
import path from 'path'
import { getBinaryName } from '@prisma/fetch-engine'
const packageJson = require('../package.json')
import Debug from 'debug'
const debug = Debug('version')

interface BinaryInfo {
  path: string
  version: string
  fromEnvVar?: string
}

/**
 * $ prisma version
 */
export class Version implements Command {
  static new(): Version {
    return new Version()
  }
  private constructor() {}
  async parse(argv: string[]) {
    const platform = await getPlatform()
    debug({ __dirname })

    const introspectionEngine = await this.resolveEngine(
      'introspection-engine',
      'PRISMA_INTROSPECTION_ENGINE_BINARY',
      platform,
    )
    const migrationEngine = await this.resolveEngine('migration-engine', 'PRISMA_MIGRATION_ENGINE_BINARY', platform)
    const queryEngine = await this.resolveEngine('query-engine', 'PRISMA_QUERY_ENGINE_BINARY', platform)

    const rows = [
      [packageJson.name, packageJson.version],
      ['Current platform', platform],
      ['Query Engine', this.printBinaryInfo(queryEngine)],
      ['Migration Engine', this.printBinaryInfo(migrationEngine)],
      ['Introspection Engine', this.printBinaryInfo(introspectionEngine)],
    ]

    return this.printTable(rows)
  }
  private printBinaryInfo({ path, version, fromEnvVar }: BinaryInfo): string {
    const resolved = fromEnvVar ? `, resolved by ${fromEnvVar}` : ''
    return `${version} (at ${path}${resolved})`
  }
  private async resolveEngine(binaryName: string, envVar: string, platform: string): Promise<BinaryInfo> {
    const pathFromEnv = process.env[envVar]
    if (pathFromEnv && fs.existsSync(pathFromEnv!)) {
      const version = await getVersion(pathFromEnv)
      return { version, path: pathFromEnv!, fromEnvVar: envVar }
    }

    const binaryPath = await resolveBinary(binaryName as any)
    const version = await getVersion(binaryPath)
    return { path: binaryPath, version }
  }
  private printTable(rows: string[][]) {
    const maxPad = rows.reduce((acc, curr) => Math.max(acc, curr[0].length), 0)
    return rows.map(([left, right]) => `${left.padEnd(maxPad)} : ${right}`).join('\n')
  }
}

// @prisma/cli          : 2.0.0-alpha.473
// Current platform     : darwin
// Query Engine         : version (at /.../.../, resolved by PRISMA_QUERY_ENGINE_BINARY)
// Migration Engine     : version (at /.../.../)
// Introspection Engine : version (at /.../.../)<commit_msg>Add version --json. Closes #2071<commit_after>import { Command, getVersion, resolveBinary, arg } from '@prisma/sdk'
import { getPlatform } from '@prisma/get-platform'
import fs from 'fs'
import path from 'path'
import { getBinaryName } from '@prisma/fetch-engine'
const packageJson = require('../package.json')
import Debug from 'debug'
const debug = Debug('version')

interface BinaryInfo {
  path: string
  version: string
  fromEnvVar?: string
}

/**
 * $ prisma version
 */
export class Version implements Command {
  static new(): Version {
    return new Version()
  }
  private constructor() {}
  async parse(argv: string[]) {
    const args = arg(argv, {
      '--json': Boolean,
    })
    const platform = await getPlatform()
    debug({ __dirname })

    const introspectionEngine = await this.resolveEngine(
      'introspection-engine',
      'PRISMA_INTROSPECTION_ENGINE_BINARY',
      platform,
    )
    const migrationEngine = await this.resolveEngine('migration-engine', 'PRISMA_MIGRATION_ENGINE_BINARY', platform)
    const queryEngine = await this.resolveEngine('query-engine', 'PRISMA_QUERY_ENGINE_BINARY', platform)

    const rows = [
      [packageJson.name, packageJson.version],
      ['Current platform', platform],
      ['Query Engine', this.printBinaryInfo(queryEngine)],
      ['Migration Engine', this.printBinaryInfo(migrationEngine)],
      ['Introspection Engine', this.printBinaryInfo(introspectionEngine)],
    ]

    return this.printTable(rows, args['--json'])
  }
  private printBinaryInfo({ path, version, fromEnvVar }: BinaryInfo): string {
    const resolved = fromEnvVar ? `, resolved by ${fromEnvVar}` : ''
    return `${version} (at ${path}${resolved})`
  }
  private async resolveEngine(binaryName: string, envVar: string, platform: string): Promise<BinaryInfo> {
    const pathFromEnv = process.env[envVar]
    if (pathFromEnv && fs.existsSync(pathFromEnv!)) {
      const version = await getVersion(pathFromEnv)
      return { version, path: pathFromEnv!, fromEnvVar: envVar }
    }

    const binaryPath = await resolveBinary(binaryName as any)
    const version = await getVersion(binaryPath)
    return { path: binaryPath, version }
  }
  private printTable(rows: string[][], json: boolean = false) {
    if (json) {
      const result = rows.reduce((acc, [name, value]) => {
        acc[slugify(name)] = value
        return acc
      }, {})
      return JSON.stringify(result, null, 2)
    }
    const maxPad = rows.reduce((acc, curr) => Math.max(acc, curr[0].length), 0)
    return rows.map(([left, right]) => `${left.padEnd(maxPad)} : ${right}`).join('\n')
  }
}

function slugify(str: string): string {
  return str.toString().toLowerCase().replace(/\s+/g, '-')
}

// @prisma/cli          : 2.0.0-alpha.473
// Current platform     : darwin
// Query Engine         : version (at /.../.../, resolved by PRISMA_QUERY_ENGINE_BINARY)
// Migration Engine     : version (at /.../.../)
// Introspection Engine : version (at /.../.../)
{'fraction_non_alphanumeric': 0.1418784928790337, 'fraction_numerical': 0.0037858301784748512, 'mean_word_length': 3.6233333333333335, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6687743', 'n_tokens_mistral': 1695, 'n_tokens_neox': 1662, 'n_words': 419}