๐Ÿ“ฆ toeverything / AFFiNE

๐Ÿ“„ index.js ยท 184 lines
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

import { Repository, Sort } from '@napi-rs/simple-git';
import { WebClient } from '@slack/web-api';
import {
  generateMarkdown,
  parseCommits,
  resolveAuthors,
  resolveConfig,
} from 'changelogithub';

import { render } from './markdown.js';

const {
  DEPLOYED_URL,
  NAMESPACE,
  CHANNEL_ID,
  SLACK_BOT_TOKEN,
  PREV_VERSION,
  DEPLOYMENT,
  FLAVOR,
  BLOCKSUITE_REPO_PATH,
} = process.env;

const slack = new WebClient(SLACK_BOT_TOKEN);
const rootDir = join(fileURLToPath(import.meta.url), '..', '..', '..');
const repo = new Repository(rootDir);

/**
 * @param {import('@napi-rs/simple-git').Repository} repo
 * @param {string} name
 */
function findTagByName(repo, name) {
  let tag = null;
  repo.tagForeach((id, tagName) => {
    if (`refs/tags/v${name}` === tagName.toString('utf-8')) {
      tag = repo.findCommit(id);
      return false;
    }
    return true;
  });
  return tag;
}

/**
 * @param {import('@napi-rs/simple-git').Repository} repo
 * @param {string} previousCommit
 * @param {string | undefined} currentCommit
 * @returns {Promise<string>}
 */
async function getChangeLog(repo, previousCommit, currentCommit) {
  const prevCommit =
    repo.findCommit(previousCommit) ?? findTagByName(repo, previousCommit);
  if (!prevCommit) {
    console.log(
      `Previous commit ${previousCommit} in ${repo.path()} not found`
    );
    return '';
  }
  /** @type {typeof import('changelogithub')['parseCommits'] extends (commit: infer C, ...args: any[]) => any ? C : any} */
  const commits = [];

  const revWalk = repo.revWalk();

  let headId = repo.head().target();

  if (currentCommit) {
    const commit =
      repo.findCommit(currentCommit) ?? findTagByName(repo, currentCommit);
    if (!commit) {
      console.log(
        `Current commit ${currentCommit} not found in ${repo.path()}`
      );
      return '';
    }
    headId = commit.id();
    revWalk.push(commit.id());
  } else {
    revWalk.pushHead();
  }

  for (const commitId of revWalk.setSorting(Sort.Time & Sort.Topological)) {
    const commit = repo.findCommit(commitId);
    commits.push({
      message: commit.message(),
      body: commit.body() ?? '',
      shortHash: commit.id().substring(0, 8),
      author: {
        name: commit.author().name(),
        email: commit.author().email(),
      },
    });
    if (commitId === prevCommit.id()) {
      break;
    }
  }

  const parseConfig = await resolveConfig({
    token: process.env.GITHUB_TOKEN,
  });

  parseConfig.from = prevCommit.id();
  parseConfig.to = headId;

  const parsedCommits = parseCommits(commits, parseConfig);
  await resolveAuthors(parsedCommits, parseConfig);
  return generateMarkdown(parsedCommits, parseConfig)
    .replaceAll('&nbsp;', ' ')
    .replaceAll('<samp>', '')
    .replaceAll('</samp>', '');
}

let blockSuiteChangelog = '';
const pkgJsonPath = 'packages/frontend/core/package.json';

const content = await readFile(join(rootDir, pkgJsonPath), 'utf8');
const { dependencies } = JSON.parse(content);
const blocksuiteVersion = dependencies['@blocksuite/affine'];

const prevCommit = repo.findCommit(PREV_VERSION);

if (!prevCommit) {
  console.info(
    `Can't find prev commit ${PREV_VERSION} on the git tree, skip the changelog generation`
  );
  process.exit(0);
}

const previousPkgJsonBlob = prevCommit
  .tree()
  .getPath(pkgJsonPath)
  .toObject(repo)
  .peelToBlob();
const previousPkgJson = JSON.parse(
  Buffer.from(previousPkgJsonBlob.content()).toString('utf8')
);
const previousBlocksuiteVersion =
  previousPkgJson.dependencies['@blocksuite/affine'];

if (blocksuiteVersion !== previousBlocksuiteVersion) {
  const blockSuiteRepo = new Repository(
    BLOCKSUITE_REPO_PATH ?? join(rootDir, '..', 'blocksuite')
  );
  console.log(
    `Blocksuite ${previousBlocksuiteVersion} -> ${blocksuiteVersion}`
  );
  blockSuiteChangelog = await getChangeLog(
    blockSuiteRepo,
    previousBlocksuiteVersion,
    blocksuiteVersion
  );
}

const messageHead =
  DEPLOYMENT === 'server'
    ? `# Server deployed in ${NAMESPACE}

- [${DEPLOYED_URL}](${DEPLOYED_URL})
`
    : `# AFFiNE Client ${FLAVOR} released`;

let changelogMessage = `${messageHead}

${await getChangeLog(repo, PREV_VERSION)}
`;

if (blockSuiteChangelog) {
  changelogMessage += `

# Blocksuite Changelog

${blockSuiteChangelog}`;
}

const { ok } = await slack.chat.postMessage({
  channel: CHANNEL_ID,
  text: `${DEPLOYMENT === 'server' ? 'Server' : 'Client'} deployed`,
  blocks: render(changelogMessage),
});

console.assert(ok, 'Failed to send a message to Slack');