File size: 2,089 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
import fg from 'fast-glob';
import fs from 'fs-extra';
import path from 'path';
import cloneDeep from 'lodash/cloneDeep';
import isPlainObject from 'lodash/isPlainObject';

import rootPkg from '../package.json';

const examples = fg.sync(['examples/examples/**/package.json'], {
  cwd: process.cwd(),
  onlyFiles: true,
  ignore: ['**/node_modules/**', '.git'],
});

const _order = ['dependencies', 'devDependencies', 'peerDependencies'] as const;

function detectRootDepsVersion(pkgName: string) {
  const _pkg: any = rootPkg;

  for (let i = 0; i < _order.length; i++) {
    const depKey = _order[i];
    if (_pkg?.[depKey]?.[pkgName]) {
      return _pkg[depKey][pkgName];
    }
  }
}

function syncVersion(pkgJson = {}, deps: string[] = []) {
  const _pkgJson: any = cloneDeep(pkgJson);

  _order.forEach((key) => {
    const _processDeps = _pkgJson[key];

    if (isPlainObject(_processDeps)) {
      Object.keys(_processDeps).forEach((dep) => {
        if (deps.includes(dep)) {
          _processDeps[dep] = detectRootDepsVersion(dep) ?? _processDeps[dep];
        }
      });
    }
  });

  return _pkgJson;
}

function modifyPackageJson(pkgJson: any) {
  if (typeof pkgJson === 'object' && pkgJson !== null) {
    return {
      ...syncVersion(
        pkgJson,
        ['@ant-design/cssinjs'], // need to sync version
      ),
      private: true,
      author: 'antd GitHub CI',
    };
  }
}

function main() {
  for (let i = 0; i < examples.length; i++) {
    const example = examples[i];

    const pkgJson = fs.readJsonSync(example);
    const newPkgJson = modifyPackageJson(pkgJson) ?? pkgJson;

    // unique named package.json
    newPkgJson.name = path.basename(path.dirname(example));

    const rewritePath = process.env.CI ? example : `${example}.tmp`; // ignored

    fs.writeJsonSync(rewritePath, newPkgJson, { spaces: 2 });

    globalThis.console.log(`🔮 [prepare-examples] ${pkgJson.name} has been prepared.`);
  }
}

/**
 * 1. git clone --depth=1 git@github.com:ant-design/ant-design-examples.git examples
 * 2. npx tsx scripts/prepare-examples.ts
 */
main();