๐Ÿ“ฆ google-gemini / gemini-cli

๐Ÿ“„ generate-settings-doc.ts ยท 286 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { readFile, writeFile } from 'node:fs/promises';
import { generateSettingsSchema } from './generate-settings-schema.js';
import {
  escapeBackticks,
  formatDefaultValue,
  formatWithPrettier,
  injectBetweenMarkers,
  normalizeForCompare,
} from './utils/autogen.js';

import type {
  SettingDefinition,
  SettingsSchema,
  SettingsSchemaType,
} from '../packages/cli/src/config/settingsSchema.js';

const START_MARKER = '<!-- SETTINGS-AUTOGEN:START -->';
const END_MARKER = '<!-- SETTINGS-AUTOGEN:END -->';

const MANUAL_TOP_LEVEL = new Set(['mcpServers', 'telemetry', 'extensions']);

interface DocEntry {
  path: string;
  type: string;
  label: string;
  category: string;
  description: string;
  defaultValue: string;
  requiresRestart: boolean;
  enumValues?: string[];
}

export async function main(argv = process.argv.slice(2)) {
  const checkOnly = argv.includes('--check');

  await generateSettingsSchema({ checkOnly });

  const repoRoot = path.resolve(
    path.dirname(fileURLToPath(import.meta.url)),
    '..',
  );
  const docPath = path.join(repoRoot, 'docs/get-started/configuration.md');
  const cliSettingsDocPath = path.join(repoRoot, 'docs/cli/settings.md');

  const { getSettingsSchema } = await loadSettingsSchemaModule();
  const schema = getSettingsSchema();
  const allSettingsSections = collectEntries(schema, { includeAll: true });
  const filteredSettingsSections = collectEntries(schema, {
    includeAll: false,
  });

  const generatedBlock = renderSections(allSettingsSections);
  const generatedTableBlock = renderTableSections(filteredSettingsSections);

  await updateFile(docPath, generatedBlock, checkOnly);
  await updateFile(cliSettingsDocPath, generatedTableBlock, checkOnly);
}

async function updateFile(
  filePath: string,
  newContent: string,
  checkOnly: boolean,
) {
  const doc = await readFile(filePath, 'utf8');
  const injectedDoc = injectBetweenMarkers({
    document: doc,
    startMarker: START_MARKER,
    endMarker: END_MARKER,
    newContent: newContent,
    paddingBefore: '\n',
    paddingAfter: '\n',
  });
  const formattedDoc = await formatWithPrettier(injectedDoc, filePath);

  if (normalizeForCompare(doc) === normalizeForCompare(formattedDoc)) {
    if (!checkOnly) {
      console.log(
        `Settings documentation (${path.basename(filePath)}) already up to date.`,
      );
    }
    return;
  }

  if (checkOnly) {
    console.error(
      'Settings documentation (' +
        path.basename(filePath) +
        ') is out of date. Run `npm run docs:settings` to regenerate.',
    );
    process.exitCode = 1;
    return;
  }

  await writeFile(filePath, formattedDoc);
  console.log(
    `Settings documentation (${path.basename(filePath)}) regenerated.`,
  );
}

async function loadSettingsSchemaModule() {
  const modulePath = '../packages/cli/src/config/settingsSchema.ts';
  return import(modulePath);
}

function collectEntries(
  schema: SettingsSchemaType,
  options: { includeAll?: boolean } = {},
) {
  const sections = new Map<string, DocEntry[]>();

  const visit = (
    current: SettingsSchema,
    pathSegments: string[],
    topLevel?: string,
  ) => {
    for (const [key, definition] of Object.entries(current)) {
      if (pathSegments.length === 0 && MANUAL_TOP_LEVEL.has(key)) {
        continue;
      }

      const newPathSegments = [...pathSegments, key];
      const sectionKey = topLevel ?? key;
      const hasChildren =
        definition.type === 'object' &&
        definition.properties &&
        Object.keys(definition.properties).length > 0;

      if (definition.ignoreInDocs) {
        continue;
      }

      if (!hasChildren && (options.includeAll || definition.showInDialog)) {
        if (!sections.has(sectionKey)) {
          sections.set(sectionKey, []);
        }

        sections.get(sectionKey)!.push({
          path: newPathSegments.join('.'),
          type: formatType(definition),
          label: definition.label,
          category: definition.category,
          description: formatDescription(definition),
          defaultValue: formatDefaultValue(definition.default, {
            quoteStrings: true,
          }),
          requiresRestart: Boolean(definition.requiresRestart),
          enumValues: definition.options?.map((option) =>
            formatDefaultValue(option.value, { quoteStrings: true }),
          ),
        });
      }

      if (hasChildren && definition.properties) {
        visit(definition.properties, newPathSegments, sectionKey);
      }
    }
  };

  visit(schema, []);
  return sections;
}

function formatDescription(definition: SettingDefinition) {
  if (definition.description?.trim()) {
    return definition.description.trim();
  }
  return 'Description not provided.';
}

function formatType(definition: SettingDefinition): string {
  switch (definition.ref) {
    case 'StringOrStringArray':
      return 'string | string[]';
    case 'BooleanOrString':
      return 'boolean | string';
    default:
      return definition.type;
  }
}

function renderSections(sections: Map<string, DocEntry[]>) {
  const lines: string[] = [];

  for (const [section, entries] of sections) {
    if (entries.length === 0) {
      continue;
    }

    lines.push('#### `' + section + '`');
    lines.push('');

    for (const entry of entries) {
      lines.push('- **`' + entry.path + '`** (' + entry.type + '):');
      lines.push('  - **Description:** ' + entry.description);

      if (entry.defaultValue.includes('\n')) {
        lines.push('  - **Default:**');
        lines.push('');
        lines.push('    ```json');
        lines.push(
          entry.defaultValue
            .split('\n')
            .map((line) => '    ' + line)
            .join('\n'),
        );
        lines.push('    ```');
      } else {
        lines.push(
          '  - **Default:** `' + escapeBackticks(entry.defaultValue) + '`',
        );
      }

      if (entry.enumValues && entry.enumValues.length > 0) {
        const values = entry.enumValues
          .map((value) => '`' + escapeBackticks(value) + '`')
          .join(', ');
        lines.push('  - **Values:** ' + values);
      }

      if (entry.requiresRestart) {
        lines.push('  - **Requires restart:** Yes');
      }

      lines.push('');
    }
  }

  return lines.join('\n').trimEnd();
}

function renderTableSections(sections: Map<string, DocEntry[]>) {
  const lines: string[] = [];

  for (const [section, entries] of sections) {
    if (entries.length === 0) {
      continue;
    }

    let title = section.charAt(0).toUpperCase() + section.slice(1);
    if (title === 'Ui') {
      title = 'UI';
    } else if (title === 'Ide') {
      title = 'IDE';
    }
    lines.push(`### ${title}`);
    lines.push('');
    lines.push('| UI Label | Setting | Description | Default |');
    lines.push('| --- | --- | --- | --- |');

    for (const entry of entries) {
      const val = entry.defaultValue.replace(/\n/g, ' ');
      const defaultVal = '`' + escapeBackticks(val) + '`';
      lines.push(
        '| ' +
          entry.label +
          ' | `' +
          entry.path +
          '` | ' +
          entry.description +
          ' | ' +
          defaultVal +
          ' |',
      );
    }

    lines.push('');
  }

  return lines.join('\n').trimEnd();
}

if (process.argv[1]) {
  const entryUrl = pathToFileURL(path.resolve(process.argv[1])).href;
  if (entryUrl === import.meta.url) {
    await main();
  }
}