Skip to content

Commit 126c11b

Browse files
committed
feat(guides): push to repo
1 parent 77d4f78 commit 126c11b

File tree

7 files changed

+176
-131
lines changed

7 files changed

+176
-131
lines changed

.github/workflows/check.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ jobs:
275275

276276
- name: Generate code snippets
277277
run: yarn cli snippets javascript ${{ fromJSON(needs.setup.outputs.JAVASCRIPT_DATA).toRun }}
278-
278+
279279
- name: Build the snippets to check validity
280280
run: yarn cli build snippets javascript ${{ fromJSON(needs.setup.outputs.JAVASCRIPT_DATA).toRun }}
281281

@@ -693,6 +693,6 @@ jobs:
693693
GITHUB_TOKEN: ${{ secrets.ALGOLIA_BOT_TOKEN }}
694694

695695
- name: Push guides to algolia/AlgoliaWeb
696-
run: yarn workspace scripts pushToAlgoliaWeb
696+
run: yarn workspace scripts pushToRepo
697697
env:
698698
GITHUB_TOKEN: ${{ secrets.ALGOLIA_BOT_TOKEN }}

.github/workflows/push-to-algolia-web.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Push snippets to AlgoliaWeb
1+
name: Push snippets to Repos
22

33
on: workflow_dispatch
44

@@ -18,7 +18,7 @@ jobs:
1818
with:
1919
type: minimal
2020

21-
- run: yarn workspace scripts pushToAlgoliaWeb
21+
- run: yarn workspace scripts pushToRepo
2222
env:
2323
GITHUB_TOKEN: ${{ secrets.ALGOLIA_BOT_TOKEN }}
2424
FORCE: true

scripts/ci/codegen/pushConfigs.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
export interface PushConfig {
2+
destination: { repo: string; prBranch: string; baseBranch: string };
3+
commitMessage: string;
4+
guides: Array<string>;
5+
outputFilePath: string;
6+
}
7+
8+
export const pushConfigs: Array<PushConfig> = [
9+
{
10+
destination: {
11+
repo: 'AlgoliaWeb',
12+
prBranch: 'feat/automated-update-from-api-clients-automation-repository',
13+
baseBranch: 'develop',
14+
},
15+
commitMessage: 'feat: update generated guides',
16+
guides: ['saveObjectsMovies'],
17+
outputFilePath: '_client/src/routes/launchpad/onboarding-snippets.json',
18+
},
19+
];

scripts/ci/codegen/pushToAlgoliaWeb.ts

Lines changed: 0 additions & 126 deletions
This file was deleted.

scripts/ci/codegen/pushToRepo.ts

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import fsp from 'fs/promises';
2+
import { resolve } from 'path';
3+
4+
import { ensureGitHubToken, exists, LANGUAGES, OWNER, run, setVerbose, toAbsolutePath } from '../../common.js';
5+
import { pushConfigs, type PushConfig } from './pushConfigs.js';
6+
7+
import { getClientsConfigField } from '../../config.js';
8+
import { commitStartRelease } from './text.js';
9+
10+
async function generateJSON(outputFile: string, guideNames: PushConfig['guides']): Promise<void> {
11+
const guides = {};
12+
for (const language of LANGUAGES) {
13+
if (!(await exists(toAbsolutePath(`docs/guides/${language}`)))) {
14+
continue;
15+
}
16+
17+
const pathToGuides = toAbsolutePath(
18+
`docs/guides/${language}/${getClientsConfigField(language, ['snippets', 'outputFolder'])}`,
19+
);
20+
const files = await fsp.readdir(pathToGuides);
21+
22+
for (const file of files.filter((file) => guideNames.some((guideName) => guideName === file.split('.')[0]))) {
23+
const extension = getClientsConfigField(language, ['snippets', 'extension']);
24+
if (!file.endsWith(extension)) {
25+
continue;
26+
}
27+
28+
const guideName = file.replaceAll(extension, '');
29+
if (!guides[guideName]) {
30+
guides[guideName] = {};
31+
}
32+
33+
guides[guideName][language] = (await fsp.readFile(`${pathToGuides}/${file}`, 'utf-8'))
34+
.replace('ALGOLIA_APPLICATION_ID', 'YourApplicationID')
35+
.replace('ALGOLIA_API_KEY', 'YourWriteAPIKey')
36+
.replace('<YOUR_INDEX_NAME>', 'movies_index');
37+
}
38+
}
39+
40+
console.log(guides);
41+
await fsp.writeFile(outputFile, JSON.stringify(guides, null, 2));
42+
}
43+
44+
async function pushToRepo(config: PushConfig): Promise<void> {
45+
const githubToken = ensureGitHubToken();
46+
47+
const repository = config.destination.repo;
48+
const lastCommitMessage = await run('git log -1 --format="%s"');
49+
50+
if (!process.env.FORCE && !lastCommitMessage.startsWith(commitStartRelease)) {
51+
return;
52+
}
53+
54+
const githubURL = `https://${githubToken}:${githubToken}@github.com/${OWNER}/${repository}`;
55+
const tempGitDir = resolve(process.env.RUNNER_TEMP! || toAbsolutePath('foo/local/test'), repository);
56+
await fsp.rm(tempGitDir, { force: true, recursive: true });
57+
await run(`git clone --depth 1 ${githubURL} ${tempGitDir}`);
58+
59+
const outputFile = toAbsolutePath(`${tempGitDir}/${config.outputFilePath}`);
60+
61+
console.log(`Generating JSON output file from guides at path ${outputFile}`);
62+
63+
await generateJSON(toAbsolutePath(`${tempGitDir}/${config.outputFilePath}`), config.guides);
64+
65+
// console.log(`Pushing to ${OWNER}/${repository}`);
66+
// if (await gitBranchExists(targetBranch, tempGitDir)) {
67+
// await run(`git fetch origin ${targetBranch}`, { cwd: tempGitDir });
68+
// await run(`git push -d origin ${targetBranch}`, { cwd: tempGitDir });
69+
// }
70+
// await run(`git checkout -B ${targetBranch}`, { cwd: tempGitDir });
71+
72+
// if ((await getNbGitDiff({ head: null, cwd: tempGitDir })) === 0) {
73+
// console.log('❎ Skipping push to AlgoliaWeb because there is no change.');
74+
75+
// return;
76+
// }
77+
78+
// await configureGitHubAuthor(tempGitDir);
79+
80+
// await run('git add .', { cwd: tempGitDir });
81+
// await gitCommit({
82+
// message: config.commitMessage,
83+
// coAuthors: [author, ...coAuthors],
84+
// cwd: tempGitDir,
85+
// });
86+
// await run(`git push -f -u origin ${targetBranch}`, { cwd: tempGitDir });
87+
88+
// console.log(`Creating pull request on ${OWNER}/${repository}...`);
89+
// const octokit = getOctokit();
90+
// const { data } = await octokit.pulls.create({
91+
// owner: OWNER,
92+
// repo: repository,
93+
// title: config.commitMessage,
94+
// body: [
95+
// 'This PR is automatically created by https://github.com/algolia/api-clients-automation',
96+
// 'It contains the latest generated guides.',
97+
// ].join('\n\n'),
98+
// base: 'develop',
99+
// head: targetBranch,
100+
// });
101+
102+
// console.log(`Pull request created on ${OWNER}/${repository}`);
103+
// console.log(` > ${data.url}`);
104+
}
105+
106+
if (import.meta.url.endsWith(process.argv[1])) {
107+
setVerbose(false);
108+
const pushToRepos = pushConfigs.map((c) => pushToRepo(c));
109+
Promise.all(pushToRepos);
110+
}

scripts/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"pre-commit": "node ./ci/husky/pre-commit.mjs",
1414
"pushGeneratedCode": "yarn runScript dist/ci/codegen/pushGeneratedCode.js",
1515
"pushToAlgoliaDoc": "yarn runScript dist/ci/codegen/pushToAlgoliaDoc.js",
16-
"pushToAlgoliaWeb": "yarn runScript dist/ci/codegen/pushToAlgoliaWeb.js",
16+
"pushToRepo": "yarn runScript dist/ci/codegen/pushToRepo.js",
1717
"runScript": "NODE_NO_WARNINGS=1 node --enable-source-maps",
1818
"setRunVariables": "yarn runScript dist/ci/githubActions/setRunVariables.js",
1919
"spreadGeneration": "yarn runScript dist/ci/codegen/spreadGeneration.js",

website/docs/generating-guides.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
title: Generating Guides
3+
---
4+
5+
# Generating Guides
6+
7+
You can create guides which allow you to write arbitrary code in any language and let the CI test the code and push it to your repo automatically.
8+
9+
## Create guide templates
10+
11+
Go to `templates` and you will find folders for each language. Inside, you can add a `.mustache` file to each language's `/guides` folder. This `.mustache` file serves as the template for your guide, and allows you to compose guides that inject client code programmatically.
12+
13+
Whenever API client methods are updated, a PR will be automatically generated based on a `pushConfig` which describes the expected set of guides and destination repo details.
14+
15+
## Create a push config
16+
17+
Go to `scripts` > `ci` > `codegen` > `pushConfigs.ts` and add a new config to the `pushConfigs` array
18+
19+
### Push Config Properties
20+
21+
- `destination`: (`object`)
22+
- `repo`: (`string`) the name of the destination repository
23+
- `prBranch`: (`string`) the name of the branch referenced in the created pull request
24+
- `baseBranch`: (`string`) the branch in the destination repo that you want to merge the created PR into
25+
- `commitMessage`: (`string`) the PR commit message
26+
- `guides`: (`string[]`) an array containing the name of the generated guides to include in the output file
27+
- `outputFilePath`: (`string`) the path in the destination repo where the file will be written
28+
29+
### Example config
30+
31+
```js
32+
{
33+
destination: {
34+
repo: 'AlgoliaWeb',
35+
prBranch: 'feat/automated-update-from-api-clients-automation-repository',
36+
baseBranch: 'develop',
37+
},
38+
commitMessage: 'feat: update generated guides',
39+
guides: ['saveObjectsMovies'],
40+
outputFilePath: '_client/src/routes/launchpad/onboarding-snippets.json'
41+
}
42+
```

0 commit comments

Comments
 (0)