Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 34 additions & 7 deletions .github/scripts/add-code-samples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,13 +310,32 @@ function mergeSamplesIntoSchema(
/**
* Write updated OpenAPI schemas back to files
*/
function writeOpenAPISchemas(schemas: Array<{ path: string; schema: any }>): void {
function writeOpenAPISchemas(schemas: Array<{ path: string; schema: any }>, outputPath?: string): void {
console.log(`💾 Writing ${schemas.length} updated schema(s)...`);

for (const schemaInfo of schemas) {
const content = JSON.stringify(schemaInfo.schema, null, 2);
fs.writeFileSync(schemaInfo.path, content, 'utf-8');
console.log(` ✓ Updated ${path.basename(schemaInfo.path)}`);

// Determine output file path
let outputFilePath: string;
if (outputPath) {
// If output path is provided, save files there
const fileName = path.basename(schemaInfo.path);

// Ensure output directory exists
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}

outputFilePath = path.join(outputPath, fileName);
console.log(` ✅ Writing ${fileName} to ${outputPath}`);
} else {
// Otherwise, save in place
outputFilePath = schemaInfo.path;
console.log(` ✅ Updated ${path.basename(schemaInfo.path)}`);
}

fs.writeFileSync(outputFilePath, content, 'utf-8');
}

console.log('✅ All schemas updated successfully');
Expand All @@ -341,35 +360,43 @@ function cleanup(dir: string): void {
/**
* Main execution function
*/
export async function main(directoryPath?: string, pattern?: string): Promise<number> {
export async function main(directoryPath?: string, pattern?: string, outputPath?: string): Promise<number> {
// Get command line arguments if not provided
let dir = directoryPath;
let pat = pattern;
let outPath = outputPath;

if (!dir || !pat) {
const args = process.argv.slice(2);

if (args.length < 2) {
console.error('❌ Error: Missing required arguments');
console.error('');
console.error('Usage: cd .github/scripts && npm run add-sdk-samples -- <directory> <pattern>');
console.error('Usage: cd .github/scripts && npm run add-sdk-samples -- <directory> <pattern> [output]');
console.error('');
console.error('Arguments:');
console.error(' <directory> - Path to directory containing OpenAPI JSON files');
console.error(' <pattern> - Regex pattern to match filenames');
console.error(' [output] - Optional output directory (if not provided, files are saved in place)');
console.error('');
console.error('Examples:');
console.error(' cd .github/scripts && npm run add-sdk-samples -- "../../openapi" "openapi.*\\.json"');
console.error(' cd .github/scripts && npm run add-sdk-samples -- "../../openapi" "openapi.*\\.json" "../../output"');
return 1;
}

dir = args[0];
pat = args[1];
outPath = args[2]; // Optional third argument
}

console.log('🚀 Starting multi-SDK sample extraction...\n');
console.log(`Searching in directory: ${dir}`);
console.log(`Pattern: ${pat}\n`);
console.log(`Pattern: ${pat}`);
if (outPath) {
console.log(`Output directory: ${outPath}`);
}
console.log();

// Find matching OpenAPI files
const openapiFiles = findMatchingFiles(dir, pat);
Expand Down Expand Up @@ -490,7 +517,7 @@ export async function main(directoryPath?: string, pattern?: string): Promise<nu
}

// Step 4: Write updated schemas
writeOpenAPISchemas(schemas);
writeOpenAPISchemas(schemas, outPath);
console.log();

// Summary
Expand Down
94 changes: 77 additions & 17 deletions .github/scripts/replace-links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,58 @@ import * as fs from 'fs';
import * as path from 'path';
import { findMatchingFiles } from './utils';

const replaceValuesForKey = (content: any, key: string, oldValue: string, newValue: string): { result: any, count: number } => {
if (typeof content !== 'object' || content === null) {
return { result: content, count: 0 }
}

if (Array.isArray(content)) {
const { result, count } = content.reduce((acc, item) => {
const { result: itemResult, count: itemCount } = replaceValuesForKey(item, key, oldValue, newValue)
return {
result: [...acc.result, itemResult],
count: acc.count + itemCount
}
}, { result: [] as any[], count: 0 })
return { result, count }
}

let regex = new RegExp(oldValue, 'g');
let totalCount = 0;

const result = Object.keys(content).reduce((acc, objKey) => {
const value = content[objKey]
if ((objKey === key) && typeof value === 'string') {
const matches = value.match(regex);
const count = matches ? matches.length : 0;
totalCount += count;
acc[objKey] = value.replace(regex, newValue)
} else if (typeof value === 'object' && value !== null) {
const { result: nestedResult, count } = replaceValuesForKey(value, key, oldValue, newValue)
totalCount += count;
acc[objKey] = nestedResult
} else {
acc[objKey] = value
}
return acc
}, {} as Record<string, any>)

return { result, count: totalCount }
}

/**
* Replace all occurrences of provided links with localised version in the given content
*/
function replaceLinks(content: string, oldUrl: string, newUrl: string): string {
return content.replace(new RegExp(oldUrl, 'g'), newUrl);
function replaceLinks(content: string, oldUrl: string, newUrl: string): { content: string, count: number } {
let parsed = JSON.parse(content);
let { result: updated, count } = replaceValuesForKey(parsed, 'description', oldUrl, newUrl)
return { content: JSON.stringify(updated, null, 2), count }
}

/**
* Process a single OpenAPI file
*/
function processFile(filePath: string, oldUrl: string, newUrl: string): void {
function processFile(filePath: string, oldUrl: string, newUrl: string, outputPath?: string): void {
try {
console.log(`Processing: ${filePath}`);

Expand All @@ -36,22 +77,35 @@ function processFile(filePath: string, oldUrl: string, newUrl: string): void {
process.exit(1);
}

// Count occurrences before replacement
const matches = content.match(new RegExp(oldUrl, 'g'));
const count = matches ? matches.length : 0;
// Replace links and get the actual count
const { content: updatedContent, count } = replaceLinks(content, oldUrl, newUrl);

if (count === 0) {
console.log(` ℹ️ No links to replace in ${filePath}`);
return;
}

// Replace links
const updatedContent = replaceLinks(content, oldUrl, newUrl);

// Write back to file
fs.writeFileSync(filePath, updatedContent, 'utf-8');
// Determine output file path
let outputFilePath: string;
if (outputPath) {
// If output path is provided, save files there
const fileName = path.basename(filePath);

// Ensure output directory exists
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}

outputFilePath = path.join(outputPath, fileName);
console.log(` ✅ Replaced ${count} occurrence(s), saved to ${outputFilePath}`);
} else {
// Otherwise, save in place
outputFilePath = filePath;
console.log(` ✅ Replaced ${count} occurrence(s) in ${filePath}`);
}

console.log(` ✅ Replaced ${count} occurrence(s) in ${filePath}`);
// Write to file
fs.writeFileSync(outputFilePath, updatedContent, 'utf-8');
} catch (e) {
console.error(` ❌ Error processing ${filePath}:`, (e as Error).message);
process.exit(1);
Expand All @@ -68,27 +122,34 @@ export function main(): number {
if (args.length < 4) {
console.error('❌ Error: Missing required arguments');
console.error('');
console.error('Usage: cd .github/scripts && npm run replace-links -- <directory> <pattern> <old_url> <new_url>');
console.error('Usage: cd .github/scripts && npm run replace-links -- <directory> <pattern> <old_url> <new_url> [output]');
console.error('');
console.error('Arguments:');
console.error(' <directory> - Path to directory containing JSON files');
console.error(' <pattern> - Regex pattern to match filenames');
console.error(' <old_url> - URL to replace');
console.error(' <new_url> - Replacement URL');
console.error(' [output] - Optional output directory (if not provided, files are saved in place)');
console.error('');
console.error('Examples:');
console.error(' cd .github/scripts && npm run replace-links -- "openapi" "openapi.*\\.json" "https://developer.box.com" "https://ja.developer.box.com"');
console.error(' cd .github/scripts && npm run replace-links -- "../../openapi" "openapi.*\\.json" "https://developer.box.com" "https://ja.developer.box.com"');
console.error(' cd .github/scripts && npm run replace-links -- "../../openapi" "openapi.*\\.json" "https://developer.box.com" "https://ja.developer.box.com" "output"');
return 1;
}

const directoryPath = args[0];
const pattern = args[1];
const oldUrl = args[2];
const newUrl = args[3];
const outputPath = args[4]; // Optional fifth argument

console.log(`Replacing "${oldUrl}" with "${newUrl}"`);
console.log(`Searching in directory: ${directoryPath}`);
console.log(`Pattern: ${pattern}\n`);
console.log(`Pattern: ${pattern}`);
if (outputPath) {
console.log(`Output directory: ${outputPath}`);
}
console.log();

// Find matching files
const filePaths = findMatchingFiles(directoryPath, pattern);
Expand All @@ -104,7 +165,7 @@ export function main(): number {

// Process each file
for (const filePath of filePaths) {
processFile(filePath, oldUrl, newUrl);
processFile(filePath, oldUrl, newUrl, outputPath);
}

console.log('\n✅ All files processed successfully!');
Expand All @@ -116,4 +177,3 @@ if (require.main === module) {
const exitCode = main();
process.exit(exitCode);
}

18 changes: 0 additions & 18 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,6 @@ jobs:
event-type: openapi-update
client-payload: "{}"

- name: "Trigger Netlify deployment"
uses: joelwmale/webhook-action@2.4.1
env:
WEBHOOK_URL: ${{ secrets.NETLIFY_BOXDEV_WEBHOOK }}
data: "{}"

- name: "Trigger Netlify deployment (Box.dev mirror)"
uses: joelwmale/webhook-action@2.4.1
env:
WEBHOOK_URL: ${{ secrets.NETLIFY_BOXDEV_MIRROR_WEBHOOK }}
data: "{}"

- name: Send Slack using Slack GHA notification
uses: slackapi/slack-github-action@v1.27.0
with:
Expand Down Expand Up @@ -113,12 +101,6 @@ jobs:
FOLDER: openapi
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

- name: "Trigger Netlify deployment"
uses: joelwmale/webhook-action@2.4.1
env:
WEBHOOK_URL: ${{ secrets.NETLIFY_BOXDEV_STAGING_WEBHOOK }}
data: "{}"

- name: Send Slack using Slack GHA notification
uses: slackapi/slack-github-action@v1.27.0
with:
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/en-api-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ jobs:

- name: Run add-code-samples script
working-directory: .github/scripts
run: npm run add-code-samples -- "../../openapi" "openapi.*\\.json"
run: npm run add-code-samples -- "../../openapi" "openapi.*\\.json" "../../output"

- name: Push openapi directory to en-api-docs branch
uses: s0/git-publish-subdir-action@v2.6.0
env:
REPO: self
BRANCH: refs/heads/en-api-docs
FOLDER: openapi
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: en-api-docs
FOLDER: output
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
8 changes: 4 additions & 4 deletions .github/workflows/jp-api-docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,16 @@ jobs:

- name: Run add-code-samples script
working-directory: .github/scripts
run: npm run add-code-samples -- "../../openapi" "openapi.*\\.json"
run: npm run add-code-samples -- "../../openapi" "openapi.*\\.json" "../../output"

- name: Run link replacement script
working-directory: .github/scripts
run: npm run replace-links -- "../../openapi" "openapi.*\\.json" "https://developer.box.com/" "https://developer.box.com/ja/"
run: npm run replace-links -- "../../output" "openapi.*\\.json" "https://developer.box.com" "https://developer.box.com/ja"

- name: Push openapi directory to jp-api-docs branch
uses: s0/git-publish-subdir-action@v2.6.0
env:
REPO: self
BRANCH: refs/heads/jp-api-docs
FOLDER: openapi
BRANCH: jp-api-docs
FOLDER: output
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
2 changes: 1 addition & 1 deletion .github/workflows/notify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ on:
- jp

jobs:
# A task that notifies Netlify of changes to the jp branch
# A task that notifies other repositories of changes to the jp branch
notify-from-jp:
# We run this on the latest ubuntu
runs-on: ubuntu-latest
Expand Down