command-update.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { execSync } from 'child_process'
  2. import { writeFileSync } from 'fs'
  3. import { basename } from 'node:path'
  4. import * as p from 'picocolors'
  5. import { changePackageVersion } from './change-package-version'
  6. import { getDepsCount } from './get-deps-count'
  7. import { getRecursiveFileList } from './get-recursive-file-list'
  8. export function commandUpdate(path: string = '.', packageNames: string[] = []) {
  9. const files = getRecursiveFileList(path).filter((file) => basename(file) === 'package.json')
  10. const depsCounter = getDepsCount(files)
  11. const pkgNames = Object.keys(depsCounter).sort()
  12. if (packageNames.length > 0) {
  13. console.log(`Updating ${packageNames.join(', ')} in ${files.length} files`)
  14. }
  15. let total = 0
  16. for (const pkgName of pkgNames.filter((pkgName) => packageNames.length === 0 || packageNames.includes(pkgName))) {
  17. // Get latest version from npm
  18. const npmVersion = execSync(`npm view ${pkgName} version`).toString().trim()
  19. let count = 0
  20. for (const file of files) {
  21. const [changed, content] = changePackageVersion(file, pkgName, `^${npmVersion}`)
  22. if (changed) {
  23. writeFileSync(file, JSON.stringify(content, null, 2) + '\n')
  24. count++
  25. }
  26. }
  27. total += count
  28. if (count === 0) {
  29. console.log(p.dim(`Package ${pkgName} is up to date ${npmVersion}`))
  30. continue
  31. }
  32. console.log(p.green(` -> Updated ${count} files with ${pkgName} ${npmVersion}`))
  33. }
  34. if (total === 0) {
  35. console.log(`No files updated`)
  36. } else {
  37. console.log(`Updated ${total} files`)
  38. }
  39. }