UNPKG

@cow-cli/package

Version:

@cow-cli package manager

112 lines (92 loc) 2.37 kB
import path from "path"; import { readFileSync } from "fs"; import { mkdirpSync } from "fs-extra"; import { pathExists } from "path-exists"; import { packageDirectory } from "pkg-dir"; import npminstall from "npminstall"; import npmInfo from "@cow-cli/npm-info"; const formatPath = (p) => { if (p && typeof p == "string") { const sep = path.sep; if (sep == "/") return p; return p.replace(/\\/g, "/"); } return p; }; class Package { constructor(options) { // this.target = options.target; this.store = options.store; this.name = options.name; this.version = options.version || "latest"; // npminstall 版本不用 缓存的最终目录也不同 this.npmCacheFilePathPrefix = this.name.replace("/", "+"); this.store && (this.prefixPath = path.resolve(this.store, ".store")); } get cacheFilePath() { return path.resolve( this.prefixPath, `${this.npmCacheFilePathPrefix}@${this.version}` ); } async prepare() { if (this.store && !pathExists(this.store)) { mkdirpSync(this.store); } if (this.version == "latest") { this.version = await npmInfo.latestVersion(this.name); } } async install() { await npminstall({ // 包 安装的目录 root: this.target, // 存储路径 storeDir: this.store, pkgs: [ { name: this.name, version: this.version, }, ], }); } async update() { await this.prepare(); const { hasNewVersion, newVersion } = await npmInfo.canUpgrade( this.version, this.name ); if (hasNewVersion) { // 查找最新版本 是否在本地有缓存 const folder = path.resolve( this.prefixPath, `${this.npmCacheFilePathPrefix}@${newVersion}` ); const isExists = await pathExists(folder); if (!isExists) { await npminstall({ root: this.target, storeDir: this.store, pkgs: [ { name: this.name, version: newVersion, }, ], }); } this.version = newVersion; } } async exists() { if (this.store) { await this.prepare(); return pathExists(this.cacheFilePath); } else { return pathExists(this.target); } } } export default Package;