|
| 1 | +import * as path from 'path'; |
| 2 | +import { sanitizePath } from '@contentstack/cli-utilities'; |
| 3 | +import { QueryExportConfig } from '../types'; |
| 4 | +import { fsUtil } from './file-helper'; |
| 5 | +import { log } from './logger'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Validates and sets up branch configuration for the stack |
| 9 | + * |
| 10 | + * @param config The export configuration |
| 11 | + * @param stackAPIClient The stack API client |
| 12 | + * @returns Promise that resolves when branch setup is complete |
| 13 | + */ |
| 14 | +export const setupBranches = async (config: QueryExportConfig, stackAPIClient: any): Promise<void> => { |
| 15 | + if (typeof config !== 'object') { |
| 16 | + throw new Error('Invalid config to setup the branch'); |
| 17 | + } |
| 18 | + |
| 19 | + try { |
| 20 | + if (config.branchName) { |
| 21 | + // Check if the specified branch exists |
| 22 | + log(config, `Validating branch: ${config.branchName}`, 'info'); |
| 23 | + |
| 24 | + const result = await stackAPIClient |
| 25 | + .branch(config.branchName) |
| 26 | + .fetch() |
| 27 | + .catch((err: Error): any => { |
| 28 | + log(config, `Error fetching branch: ${err.message}`, 'error'); |
| 29 | + return null; |
| 30 | + }); |
| 31 | + |
| 32 | + if (result && typeof result === 'object') { |
| 33 | + log(config, `Branch '${config.branchName}' found`, 'success'); |
| 34 | + } else { |
| 35 | + throw new Error(`No branch found with the name '${config.branchName}'`); |
| 36 | + } |
| 37 | + } else { |
| 38 | + // If no branch name provided, check if the stack has branches |
| 39 | + log(config, 'No branch specified, checking if stack has branches', 'info'); |
| 40 | + |
| 41 | + const result = await stackAPIClient |
| 42 | + .branch() |
| 43 | + .query() |
| 44 | + .find() |
| 45 | + .catch((): any => { |
| 46 | + log(config, 'Stack does not have branches', 'info'); |
| 47 | + return null; |
| 48 | + }); |
| 49 | + |
| 50 | + if (result && result.items && Array.isArray(result.items) && result.items.length > 0) { |
| 51 | + // Set default branch to 'main' if it exists |
| 52 | + config.branchName = 'main'; |
| 53 | + } else { |
| 54 | + // Stack doesn't have branches |
| 55 | + log(config, 'Stack does not have branches', 'info'); |
| 56 | + return; |
| 57 | + } |
| 58 | + } |
| 59 | + config.branchEnabled = true; |
| 60 | + } catch (error) { |
| 61 | + log(config, `Error setting up branches: ${error.message}`, 'error'); |
| 62 | + throw error; |
| 63 | + } |
| 64 | +}; |
| 65 | + |
| 66 | +export default setupBranches; |
0 commit comments