All files / src/class/repository npm-repository.ts

47.37% Statements 18/38
30% Branches 3/10
42.86% Functions 3/7
54.55% Lines 18/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 745x 5x 5x 5x 5x 5x 5x     5x               5x 5x       1x   1x 1x   1x 1x 1x       1x       1x                                                                        
import childProcess from 'child_process'
import { promisify } from 'util'
import fs from 'fs-extra'
import { join } from 'path'
import { Repository } from './repository'
import { logger } from '@/utils'
import { TEMPLATE_STORAGE } from '@/consts'
 
 
const genIndexFile = (name: string): string => `
const { join } = require('path')
const config = require('${name}')
config.path = join('./node_modules/${name}', config.path)
 
module.exports = config
`
 
const exec = promisify(childProcess.exec)
export class NpmRepository extends Repository {
  public scope: string | null
 
  constructor(name) {
    super()
 
    this.type = 'npm'
    this.name = name
 
    const matched = name.match(/@(.*)\//)
    Iif (matched) this.scope = matched[1]
    else this.scope = null
  }
 
  get record(): string {
    return `npm:${this.name}`
  }
 
  get storage(): string {
    return join(TEMPLATE_STORAGE, encodeURIComponent(this.name), this.version || 'noversion')
  }
 
  public async getVersions(): Promise<string[]> {
    if (this.versions) return this.versions
 
    const { stdout, stderr } = await exec(`npm view ${this.name} versions  --json`)
    if (stderr) console.error(stderr)
    return JSON.parse(stdout).reverse()
  }
 
  public async download(): Promise<void> {
    const { name, version, storage } = this
    if (!version) throw new Error('Please checkout version before install npm template')
 
    await fs.emptyDir(storage)
 
    logger.info(`install ${name} template from npm...`)
 
    await fs.writeJSON(join(storage, 'package.json'), {
      main: 'index.js',
      description: '',
      license: 'MIT',
    })
    await fs.writeFile(join(storage, 'index.js'), genIndexFile(name))
    await fs.writeFile(join(storage, '.npmrc'), 'package-lock=false')
 
    const command = `npm install ${name}@${version}`
    await exec(command, { cwd: storage })
  }
 
  public async existed(): Promise<boolean> {
    const out = await exec(`npm view ${this.name} --json`)
    return !out.stderr
  }
}