universo-platform-2d

Форк
0
170 строк · 4.2 Кб
1
import { execSync } from 'node:child_process';
2
import { join } from 'node:path';
3
import { fileURLToPath } from 'node:url';
4

5
import { Clipboard } from '@napi-rs/clipboard';
6
import {
7
  FetchOptions,
8
  ProxyOptions,
9
  RemoteCallbacks,
10
  Repository,
11
  Sort,
12
} from '@napi-rs/simple-git';
13
import chalk from 'chalk';
14
import { ProxyAgent, setGlobalDispatcher } from 'undici';
15

16
import corePackage from '../../packages/frontend/core/package.json' assert { type: 'json' };
17

18
const clipboard = new Clipboard();
19

20
const oldHash = corePackage.dependencies['@blocksuite/affine'].split('-').pop();
21

22
const info = await fetch('https://registry.npmjs.org/@blocksuite/affine').then(
23
  res => res.json()
24
);
25

26
const latestVersion = info['dist-tags'].latest;
27
const latestHash = latestVersion.split('-').pop();
28

29
if (oldHash === latestHash) {
30
  console.info(chalk.greenBright('Already updated'));
31
  process.exit(0);
32
}
33

34
if (process.env.http_proxy) {
35
  setGlobalDispatcher(new ProxyAgent(process.env.http_proxy));
36
}
37

38
console.info(`Upgrade blocksuite from ${oldHash} -> ${latestHash}`);
39

40
const blockSuiteDeps = execSync(`yarn info -A --name-only --json`, {
41
  encoding: 'utf8',
42
});
43

44
const blocksuiteDepsList = blockSuiteDeps
45
  .split('\n')
46
  .map(s => s.trim())
47
  .filter(Boolean)
48
  .map(s => s.substring(1, s.length - 1))
49
  .filter(
50
    s => s.startsWith('@blocksuite') && !s.startsWith('@blocksuite/icons')
51
  )
52
  .map(s => s.split('@npm').at(0));
53

54
for (const pkg of blocksuiteDepsList) {
55
  const command = `yarn up ${pkg}@${latestVersion}`;
56
  console.info(chalk.bgCyan(`Executing ${command}`));
57
  execSync(command, {
58
    stdio: 'inherit',
59
  });
60
}
61

62
console.info(`Upgrade complete`);
63

64
const repo = new Repository(
65
  join(fileURLToPath(import.meta.url), '..', '..', '..', '..', 'BlockSuite')
66
);
67

68
const remote = repo.remoteAnonymous(
69
  'https://github.com/toeverything/BlockSuite.git'
70
);
71

72
remote.fetch(
73
  ['master'],
74
  new FetchOptions().proxyOptions(new ProxyOptions().auto()).remoteCallback(
75
    new RemoteCallbacks().transferProgress(progress => {
76
      if (progress.totalDeltas && progress.totalObjects) {
77
        console.log(
78
          `${(
79
            (progress.receivedObjects / progress.totalObjects) * 50 +
80
            (progress.indexedDeltas / progress.totalDeltas) * 50
81
          ).toFixed(2)}%`
82
        );
83
      }
84
    })
85
  )
86
);
87

88
const latest = repo.findCommit(latestHash);
89

90
const commits = {
91
  Features: [],
92
  Bugfix: [],
93
  Refactor: [],
94
  Misc: [],
95
};
96

97
for (const oid of repo
98
  .revWalk()
99
  .push(latest.id())
100
  .setSorting(Sort.Time & Sort.Topological)) {
101
  if (oid.startsWith(oldHash)) {
102
    break;
103
  }
104
  const commit = repo.findCommit(oid);
105
  const summary = commit.summary();
106
  if (summary.startsWith('feat')) {
107
    commits.Features.push(commit);
108
  } else if (summary.startsWith('fix')) {
109
    commits.Bugfix.push(commit);
110
  } else if (summary.startsWith('refactor')) {
111
    commits.Refactor.push(commit);
112
  } else {
113
    commits.Misc.push(commit);
114
  }
115
}
116

117
clipboard.setText(await formatCommits(commits));
118

119
console.info(`Changelog copied to clipboard`);
120

121
async function formatCommits(commits) {
122
  return `## Features
123
${await Promise.all(commits.Features.map(format)).then(commits =>
124
  commits.join('\n')
125
)}
126

127
## Bugfix
128
${await Promise.all(commits.Bugfix.map(format)).then(commits =>
129
  commits.join('\n')
130
)}
131

132
## Refactor
133
${await Promise.all(commits.Refactor.map(format)).then(commits =>
134
  commits.join('\n')
135
)}
136

137
## Misc
138
${await Promise.all(commits.Misc.map(format)).then(commits =>
139
  commits.join('\n')
140
)}
141
`;
142
  /**
143
   * @param {import('./index').Commit} commit
144
   * @returns string
145
   */
146
  async function format(commit) {
147
    const summary = commit.summary();
148
    const match = summary.match(/\(#(\d+)\)/);
149
    if (match) {
150
      const [_, pull] = match;
151
      const pullInfo = await fetch(
152
        `https://api.github.com/repos/toeverything/BlockSuite/pulls/${pull}`,
153
        {
154
          headers: {
155
            Accept: 'application/vnd.github+json',
156
            Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
157
            'X-GitHub-Api-Version': '2022-11-28',
158
          },
159
        }
160
      )
161
        .then(res => res.json())
162
        .catch(() => ({ user: {} }));
163
      const {
164
        user: { login },
165
      } = pullInfo;
166
      return `- https://github.com/toeverything/BlockSuite/pull/${pull} @${login}`;
167
    }
168
    return `- ${summary}`;
169
  }
170
}
171

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.