transform-lock.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const fs = require('fs');
  2. const util = require('util');
  3. const readFile = util.promisify(fs.readFile);
  4. const writeFile = util.promisify(fs.writeFile);
  5. const base = {
  6. parse(url) {
  7. const parts = url.slice(this.prefix.length).split('/');
  8. let scope;
  9. if (parts[0].startsWith('@')) scope = parts.shift();
  10. const name = parts.shift();
  11. const suffix = parts.pop();
  12. return { scope, name, suffix };
  13. },
  14. build({ scope, name, suffix }) {
  15. return this.prefix + [scope, name, '-', suffix].filter(Boolean).join('/');
  16. },
  17. };
  18. const targets = {
  19. taobao: Object.assign({}, base, {
  20. prefix: 'http://registry.npm.taobao.org/',
  21. build({ scope, name, suffix }) {
  22. return this.prefix + [scope, name, 'download', scope, suffix].filter(Boolean).join('/');
  23. },
  24. }),
  25. yarn: Object.assign({}, base, {
  26. prefix: 'https://registry.yarnpkg.com/',
  27. }),
  28. npm: Object.assign({}, base, {
  29. prefix: 'http://registry.npmjs.org/',
  30. }),
  31. };
  32. function parseResolved(resolved) {
  33. let result;
  34. Object.entries(targets)
  35. .some(([key, value]) => {
  36. if (resolved.startsWith(value.prefix)) {
  37. result = value.parse(resolved);
  38. return true;
  39. }
  40. });
  41. if (!result) throw new Error(`Unknown resolved value: ${resolved}`);
  42. return result;
  43. }
  44. function getProcessor(targetName) {
  45. const target = targets[targetName];
  46. return line => {
  47. const matches = line.match(/(\s+resolved\s+)"(.*)"/);
  48. if (!matches) return line;
  49. const parsed = parseResolved(matches[2]);
  50. return `${matches[1]}"${target.build(parsed)}"`;
  51. };
  52. }
  53. async function transformLock(name) {
  54. const disallowChange = name.startsWith('=');
  55. const targetName = disallowChange ? name.slice(1) : name;
  56. const originalContent = await readFile('yarn.lock', 'utf8');
  57. const content = originalContent.split('\n')
  58. .map(getProcessor(targetName))
  59. .join('\n');
  60. if (originalContent !== content) {
  61. await writeFile('yarn.lock', content, 'utf8');
  62. console.error('yarn.lock is updated.');
  63. if (disallowChange) process.exit(2);
  64. }
  65. }
  66. transformLock(process.argv[2]);