Skip to content

Commit 0d44b09

Browse files
committed
chore: respond to comments
1 parent 3c5417e commit 0d44b09

File tree

6 files changed

+67
-43
lines changed

6 files changed

+67
-43
lines changed

packages/gapic-node-processing/src/combine-libraries.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ import {Dirent} from 'fs';
1717
const fs = require('fs/promises'); // For async file system operations
1818
const path = require('path');
1919

20+
export interface FilePaths {
21+
filePath: string
22+
}
23+
24+
export interface FilePathsAndContents {
25+
filePath: string,
26+
content: string
27+
}
2028
/**
2129
* Recursively removes a regex pattern from a specified property in an array of objects.
2230
*
@@ -63,7 +71,7 @@ export function removeRegexFromNestedProperty(
6371
* @returns A promise that resolves when all file contents have been read and added to the array.
6472
*/
6573
async function readFilesContent(
66-
filePaths: {filePath: string}[],
74+
filePaths: FilePaths[],
6775
): Promise<void> {
6876
const promises = filePaths.map(async item => {
6977
try {
@@ -128,7 +136,7 @@ export async function traverseDirectory(
128136
*/
129137
export async function generateFinalDirectoryPath(
130138
currentPath: string,
131-
): Promise<Array<{filePath: string; content: string}>> {
139+
): Promise<Array<FilePathsAndContents>> {
132140
// Get a full list of all the file paths in all the libraries
133141
let fullPaths: {filePath: string}[] = [];
134142
let fullPathsAndContents: {filePath: string; content: string}[] = [];
@@ -142,12 +150,12 @@ export async function generateFinalDirectoryPath(
142150
path.join(currentPath, directory),
143151
);
144152
fullPathsAndContents = fullPathsAndContents.concat(
145-
fullPaths as {filePath: string; content: string}[],
153+
fullPaths as FilePathsAndContents[],
146154
);
147155
}
148156

149157
// Now we need to clean out duplicates
150-
const uniquePaths = new Set();
158+
const uniquePaths = new Set<string>();
151159
const uniquefullPathAndContent = [];
152160

153161
for (const fullPathAndContent of fullPathsAndContents) {
@@ -174,8 +182,8 @@ export async function ensureDirectoryExists(filePath: string): Promise<void> {
174182
try {
175183
await fs.mkdir(dirPath, {recursive: true});
176184
} catch (error) {
185+
// EEXIST means it already exists, which is fine
177186
if ((error as any).code !== 'EEXIST') {
178-
// EEXIST means it already exists, which is fine
179187
console.error(`Error ensuring directory ${dirPath} exists:`, error);
180188
throw error;
181189
}

packages/gapic-node-processing/src/commands/generate-combined-library.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
import yargs = require('yargs');
1616
import {combineLibraries} from '../combine-libraries';
1717
import {generateIndexTs} from '../generate-index';
18+
1819
export interface CliArgs {
1920
'source-path': string;
2021
'default-version'?: string;
2122
'destination-path'?: string;
2223
'is-esm'?: boolean;
2324
}
25+
2426
/**
2527
* Command module for bootstrapping a library.
2628
*

packages/gapic-node-processing/src/commands/generate-readme.ts

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import yargs = require('yargs');
1616
import {initialGenerateReadMe, readAndWriteToReadme} from '../generate-readme';
1717

18-
export interface CliArgs {
18+
export interface CliArgsReadme {
1919
'source-path': string;
2020
'initial-generation'?: boolean;
2121
'destination-path'?: string;
@@ -29,7 +29,7 @@ export interface CliArgs {
2929
const DEFAULT_REPLACEMENT_STRING_SAMPLES = '[//]: # "samples"';
3030
const DEFAULT_REPLACEMENT_STRING_RELEASE_LEVEL = '[//]: # "releaseLevel"';
3131

32-
function validateCliArgs(argv: CliArgs) {
32+
function validateCliArgs(argv: CliArgsReadme) {
3333
if (
3434
!argv['initial-generation'] &&
3535
(!argv['string-to-replace'] || !argv['replacement-string'])
@@ -45,7 +45,7 @@ function validateCliArgs(argv: CliArgs) {
4545
}
4646
}
4747

48-
function getReplacementStringSamples(argv: CliArgs) {
48+
function getReplacementStringSamples(argv: CliArgsReadme) {
4949
const stringToReplaceForSampleTable = argv['replacement-string-samples'];
5050
if (argv['initial-generation'] && !stringToReplaceForSampleTable) {
5151
console.log(
@@ -57,7 +57,7 @@ function getReplacementStringSamples(argv: CliArgs) {
5757
return stringToReplaceForSampleTable;
5858
}
5959

60-
function getReplacementStringReleaseLevel(argv: CliArgs) {
60+
function getReplacementStringReleaseLevel(argv: CliArgsReadme) {
6161
const stringToReplaceForReleaseLevel =
6262
argv['replacement-string-release-level'];
6363
if (argv['initial-generation'] && !stringToReplaceForReleaseLevel) {
@@ -70,7 +70,7 @@ function getReplacementStringReleaseLevel(argv: CliArgs) {
7070
return stringToReplaceForReleaseLevel;
7171
}
7272

73-
function generateArgsForInitialReadme(argv: CliArgs, writeDestination: string) {
73+
function generateArgsForInitialReadme(argv: CliArgsReadme, writeDestination: string) {
7474
const stringToReplaceForSampleTable = getReplacementStringSamples(argv);
7575
const stringToReplaceForReleaseLevel = getReplacementStringReleaseLevel(argv);
7676
return {
@@ -87,7 +87,7 @@ function generateArgsForInitialReadme(argv: CliArgs, writeDestination: string) {
8787
*
8888
* This module defines a yargs command to generate a README.md
8989
*/
90-
export const generateReadme: yargs.CommandModule<{}, CliArgs> = {
90+
export const generateReadme: yargs.CommandModule<{}, CliArgsReadme> = {
9191
command: 'generate-readme',
9292
describe: 'Combines the versions for a given API into a single library',
9393
builder(yargs) {
@@ -131,15 +131,15 @@ export const generateReadme: yargs.CommandModule<{}, CliArgs> = {
131131
* Yargs command handler for generating a combined library.
132132
*
133133
* @param {CliArgs} argv - The command line arguments
134-
* @param {CliArgs} source-path: path in which a pre-combined library lives
135-
* @param {CliArgs} destination-path: path where to copy over the library
136-
* @param {CliArgs} initial-generation: path in which a pre-combined library lives; defaults to false
137-
* @param {CliArgs} release-level: what is the release level of the library (default is preview)
138-
* @param {CliArgs} string-to-replace: string to replace in the readme
139-
* @param {CliArgs} replacement-string-samples: string to replace with the string-to-replace for the samples table in the readme (only used with initial generation)
140-
* @param {CliArgs} replacement-string-release-level: string to replace with the string-to-replace for the releaseLevel in the readme (only used with initial generation)
134+
* source-path: path in which a pre-combined library lives
135+
* destination-path: path where to copy over the library
136+
* initial-generation: path in which a pre-combined library lives; defaults to false
137+
* release-level: what is the release level of the library (default is preview)
138+
* string-to-replace: string to replace in the readme
139+
* replacement-string-samples: string to replace with the string-to-replace for the samples table in the readme (only used with initial generation)
140+
* replacement-string-release-level: string to replace with the string-to-replace for the releaseLevel in the readme (only used with initial generation)
141141
*/
142-
async handler(argv: CliArgs) {
142+
async handler(argv: CliArgsReadme) {
143143
const destinationPath = argv['destination-path'] || argv['source-path'];
144144
validateCliArgs(argv);
145145
if (argv['initial-generation']) {

packages/gapic-node-processing/src/generate-index.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ const SRC_PATH = 'src';
2222
const INDEX_PATH = 'index.ts';
2323
const TEMPLATE_FILE_NAME = 'index.ts.njk';
2424

25+
export interface VersionsAndClients {
26+
version: string
27+
clients: string[]
28+
}
2529
export const POST_PROCESSING_TEMPLATES_PATH = path.resolve(
2630
__dirname,
2731
'../../templates/post-processing-templates',
@@ -80,7 +84,7 @@ export async function extractVersions(currentPath: string) {
8084
*/
8185
export async function extractClients(currentPath: string) {
8286
const directories = await extractVersions(currentPath);
83-
const clientsAndVersions: {version: string; clients: string[]}[] = [];
87+
const clientsAndVersions: VersionsAndClients[] = [];
8488
for (const directory of directories) {
8589
const indexFile = path.join(currentPath, SRC_PATH, directory, INDEX_PATH);
8690
if (await fs.stat(indexFile)) {
@@ -108,6 +112,7 @@ export async function extractClients(currentPath: string) {
108112
*
109113
* @param {string} currentLibrary - The path to the library's root directory.
110114
* @param {string} [defaultVersion] - An optional version string to explicitly set as the default.
115+
* @param {string} [isEsm] - An optional flag whether the library should be generated with ESM syntax
111116
*/
112117
export async function generateIndexTs(
113118
currentLibrary: string,
@@ -133,7 +138,7 @@ export async function generateIndexTs(
133138
);
134139

135140
// Render index.ts
136-
const variables = {versions, defaultClientAndVersions, isEsm: isEsm || false};
141+
const variables = {versions, defaultClientAndVersions, isEsm: isEsm ?? false};
137142

138143
// Create a new Nunjucks environment configured to load from the templateDirectory
139144
// This is necessary due to occurring in a Bazel environment or locally
@@ -151,6 +156,7 @@ export async function generateIndexTs(
151156
await fs.writeFile(outputPath, compiledTemplate);
152157
console.log(`Successfully wrote: ${outputPath}`);
153158
}
159+
154160
interface VersionSpec {
155161
version: string; // Stores the "best" version found so far
156162
major: number;
@@ -164,7 +170,7 @@ interface VersionSpec {
164170
// 3. Within same pre-release type, higher qualifier (e.g., beta2 > beta1)
165171
// 4. If everything else is equal, the current one is just as good
166172

167-
function isANewAHighestVersion(
173+
function isNewAHighestVersion(
168174
currentVersionSpec: VersionSpec,
169175
newVersionSpec: VersionSpec,
170176
): boolean {
@@ -238,7 +244,7 @@ export function getHighestVersionWithPrecedence(versions: string[]) {
238244
preReleaseQualifier: preReleaseQualifier,
239245
};
240246

241-
if (isANewAHighestVersion(currentVersionSpec, newVersionSpec)) {
247+
if (isNewAHighestVersion(currentVersionSpec, newVersionSpec)) {
242248
currentVersionSpec = newVersionSpec;
243249
}
244250
}

packages/gapic-node-processing/src/generate-readme.ts

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
import {ensureDirectoryExists, removeRegexFromNestedProperty, traverseDirectory} from './combine-libraries';
15+
import {ensureDirectoryExists, traverseDirectory, FilePaths} from './combine-libraries';
1616
import * as nj from 'nunjucks';
1717
import {POST_PROCESSING_TEMPLATES_PATH} from './generate-index';
18+
import { CliArgsReadme } from './commands/generate-readme';
1819

1920
const fs = require('fs/promises'); // For async file system operations
2021
const path = require('path');
@@ -31,6 +32,12 @@ export const RELEASE_LEVEL_PREVIEW = `This library is considered to be in **prev
3132
work-in-progress and under active development. Any release is subject to
3233
backwards-incompatible changes at any time.`;
3334

35+
interface SampleMetadata {
36+
filePath: string,
37+
content: string,
38+
title: string
39+
}
40+
3441
const DEFAULT_RELEASE_LEVEL = 'preview';
3542

3643
/**
@@ -41,33 +48,36 @@ const DEFAULT_RELEASE_LEVEL = 'preview';
4148
* the file path, content, and title for each sample.
4249
*
4350
* @param {string} currentLibrary - The path to the library's root directory.
44-
* @returns {Promise<{filePath: string; content: string; title: string}[]>} A promise that resolves to an array of sample metadata objects.
51+
* @returns {Promise<SampleMetadata[]>} A promise that resolves to an array of sample metadata objects.
4552
*/
4653
export async function getSamplesMetadata(
4754
currentLibrary: string,
48-
): Promise<{filePath: string; content: string; title: string}[]> {
49-
// Let's remove the main library from the samples paths
55+
): Promise<SampleMetadata[]> {
56+
// Let's separate out the absolute path so that we
57+
// can later remove it from the filePath (so that it
58+
// is relative to the working directory).
59+
// For example for CURRENT LIBRARY: google-cloud-node/packages/gapic-node-processing/test/fixtures/combined-library/google-cloud-speech
60+
// we would produce stringToRemove: /Users/sofialeon/gcp/google-cloud-node/packages/gapic-node-processing/test/fixtures/combined-library
61+
// which we then use to remove from the absolute filePath (so
62+
// /google-cloud-node/packages/gapic-node-processing/test/fixtures/combined-library/google-cloud-speech/samples/generated/v1/adaptation.create_custom_class.js
63+
// becomes just google-cloud-speech/samples/generated/v1/adaptation.create_custom_class.js (the relative path to the new directory)
5064
const stringToRemove = currentLibrary
5165
.split('/')
5266
.slice(0, currentLibrary.split('/').length - 1)
5367
.join('/');
54-
let samples = await traverseDirectory(
68+
69+
const samples = await traverseDirectory(
5570
path.join(currentLibrary, SAMPLES_PATH),
5671
[],
5772
);
58-
removeRegexFromNestedProperty(samples, 'filePath', stringToRemove)
5973
samples.map(sample => {
60-
// Here, the 'getSampleName' refers to the exported function
74+
sample.filePath = sample.filePath.replace(stringToRemove, '').replace('-nodejs', '');
6175
Object.assign(sample, {title: getSampleName(sample)});
6276
});
63-
// Remove 'nodejs' from the library title
64-
removeRegexFromNestedProperty(samples, 'filePath', '-nodejs')
65-
// Since we later assign the title property, it should exist
66-
return samples as unknown as {
67-
filePath: string;
68-
content: string;
69-
title: string;
70-
}[];
77+
console.log(samples)
78+
// Since we later assign the title property, we can coerce it into
79+
// this type
80+
return samples as unknown as SampleMetadata[];
7181
}
7282

7383
/**
@@ -77,7 +87,7 @@ export async function getSamplesMetadata(
7787
* stripping the file extension, API version, and replacing underscores with spaces.
7888
* If the path is not in the expected format, it logs an error and returns the original path.
7989
*
80-
* @param {{filePath: string; content: string}} sample - The sample object containing the file path.
90+
* @param {FilePaths} sample - The sample object containing the file path.
8191
* @returns {string} The formatted name of the sample.
8292
*/
8393
export function getSampleName(sample: {
@@ -103,16 +113,14 @@ export function getSampleName(sample: {
103113
return sampleName;
104114
}
105115

106-
// We have two readme generations because the initial generation step
107-
// will be a little different than what's available during post-processing
108116
/**
109117
* Generates the initial README file for a library by compiling templates and replacing placeholders.
110118
*
111119
* This function uses Nunjucks to render a sample table based on the found samples
112120
* and injects it along with the appropriate release level message into the README.md
113121
* template.
114122
*
115-
* @param {{currentLibrary: string; stringToReplaceForSampleTable: string; stringToReplaceForReleaseLevel: string; writeLibrary: string; releaseLevel?: string;}} args - An object containing the arguments for the function.
123+
* @param {CliArgsReadme} args - An object containing the arguments for the function.
116124
* @param {string} args.currentLibrary - The path to the library's root directory.
117125
* @param {string} args.stringToReplaceForSampleTable - The placeholder string to be replaced with the samples table.
118126
* @param {string} args.stringToReplaceForReleaseLevel - The placeholder string to be replaced with the release level message.

packages/gapic-node-processing/test/generate-readme.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ describe('generate readme.ts', () => {
6969
assert.ok(samples.map(x => x.title).includes('undelete recognizer'));
7070

7171
// Assert content exists
72-
assert.ok(samples.map(x => x.content));
72+
assert.ok(samples.map(x => x.content).length);
7373
});
7474

7575
it('should NOT throw if the sample name is not in the correct format; just return the name', async () => {

0 commit comments

Comments
 (0)