Skip to content

Commit 2fb81db

Browse files
authored
Merge pull request #8 from contentstack/fix/issues
Fix branch handling, stack api key handling
2 parents 4985ff5 + 4722c33 commit 2fb81db

File tree

10 files changed

+104
-20
lines changed

10 files changed

+104
-20
lines changed

.env-example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ENVIRONMENT=NON_PROD

.talismanrc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
fileignoreconfig:
2-
- filename: package-lock.json
3-
checksum: 4e00357992422982d516ee3231f87a1f98f27c12788c63a6a089cafa059b6b9e
2+
- filename: .env-example
3+
checksum: 591f1e672d4df287107092b8fd37c27913e09225c6ced55293e1d459b1119d05
44
version: '1.0'

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@contentstack/cli-cm-export-query",
33
"description": "Contentstack CLI plugin to export content from stack",
4-
"version": "1.0.0-beta.1",
4+
"version": "1.0.0-beta.2",
55
"author": "Contentstack",
66
"bugs": "https://github.com/contentstack/cli/issues",
77
"dependencies": {

snyk_output.log

Whitespace-only changes.

src/commands/cm/stacks/export-query.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from '@contentstack/cli-utilities';
1010
import { QueryExporter } from '../../../core/query-executor';
1111
import { QueryExportConfig } from '../../../types';
12-
import { log, setupQueryExportConfig } from '../../../utils';
12+
import { log, setupQueryExportConfig, setupBranches } from '../../../utils';
1313

1414
export default class ExportQueryCommand extends Command {
1515
static description = 'Export content from a stack using query-based filtering';
@@ -63,8 +63,6 @@ export default class ExportQueryCommand extends Command {
6363
}),
6464
};
6565

66-
static aliases = ['cm:export-query'];
67-
6866
async run(): Promise<void> {
6967
try {
7068
const { flags } = await this.parse(ExportQueryCommand);
@@ -79,8 +77,20 @@ export default class ExportQueryCommand extends Command {
7977
}
8078

8179
this.exportDir = sanitizePath(exportQueryConfig.exportDir);
82-
// Initialize and run query export
80+
81+
// Initialize management API client
8382
const managementAPIClient: ContentstackClient = await managementSDKClient(exportQueryConfig);
83+
84+
// Setup and validate branch configuration
85+
const stackAPIClient = managementAPIClient.stack({
86+
api_key: exportQueryConfig.stackApiKey,
87+
management_token: exportQueryConfig.managementToken,
88+
});
89+
90+
// Setup branches (validate branch or set default to 'main')
91+
await setupBranches(exportQueryConfig, stackAPIClient);
92+
93+
// Initialize and run query export
8494
const queryExporter = new QueryExporter(managementAPIClient, exportQueryConfig);
8595
await queryExporter.execute();
8696

src/core/module-exporter.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ export class ModuleExporter {
2020
// Build command arguments
2121
const cmd = this.buildExportCommand(moduleName, options);
2222

23-
log(this.exportQueryConfig, `Running export command: ${cmd.join(' ')}`, 'debug');
24-
2523
// Configurable delay
2624
const delay = this.exportQueryConfig.exportDelayMs || 2000;
2725
await new Promise((resolve) => setTimeout(resolve, delay));

src/utils/branch-helper.ts

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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;

src/utils/config-handler.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,19 @@ export async function setupQueryExportConfig(flags: any): Promise<QueryExportCon
2727
// Handle authentication
2828
if (flags.alias) {
2929
const { token, apiKey } = configHandler.get(`tokens.${flags.alias}`) || {};
30-
config.managementToken = token;
31-
config.stackApiKey = apiKey;
32-
if (!config.managementToken) {
30+
exportQueryConfig.managementToken = token;
31+
exportQueryConfig.stackApiKey = apiKey;
32+
if (!exportQueryConfig.managementToken) {
3333
throw new Error(`No management token found on given alias ${flags.alias}`);
3434
}
3535
}
3636

37-
if (!config.managementToken) {
37+
if (!exportQueryConfig.managementToken) {
3838
if (!isAuthenticated()) {
3939
throw new Error('Please login or provide an alias for the management token');
4040
} else {
41-
config.stackApiKey = flags['stack-api-key'] || (await askAPIKey());
42-
if (typeof config.stackApiKey !== 'string') {
41+
exportQueryConfig.stackApiKey = flags['stack-api-key'] || (await askAPIKey());
42+
if (typeof exportQueryConfig.stackApiKey !== 'string') {
4343
throw new Error('Invalid API key received');
4444
}
4545
}

src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export * from './config-handler';
66
export * from './content-type-helper';
77
export * from './dependency-resolver';
88
export * from './referenced-asset-handler';
9+
export { setupBranches } from './branch-helper';

src/utils/referenced-asset-handler.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,21 @@ export class AssetReferenceHandler {
109109
}
110110
}
111111

112+
let assetUrlRegex = '';
113+
let assetUIDMatchIndex;
114+
if (process.env.ENVIRONMENT === 'NON_PROD') {
115+
assetUrlRegex = '(https://.*?/v3/assets/(.*?)/(.*?)/(.*?)/(.*?)(?="))';
116+
assetUIDMatchIndex = 3;
117+
} else {
118+
assetUrlRegex =
119+
'(https://(assets|(eu-|azure-na-|azure-eu-|gcp-na-|gcp-eu-)?images).contentstack.(io|com)/v3/assets/(.*?)/(.*?)/(.*?)/(.*?)(?="))';
120+
assetUIDMatchIndex = 6;
121+
}
122+
112123
// Pattern 2: Contentstack asset URLs
113-
const urlRegex = new RegExp(
114-
'(https://(assets|(eu-|azure-na-|azure-eu-|gcp-na-|gcp-eu-)?images).contentstack.(io|com)/v3/assets/(.*?)/(.*?)/(.*?)/(.*?)(?="))',
115-
'g',
116-
);
124+
const urlRegex = new RegExp(assetUrlRegex, 'g');
117125
while ((match = urlRegex.exec(content)) !== null) {
118-
const assetUID = match[6]; // The asset UID is in the 6th capture group
126+
const assetUID = match[assetUIDMatchIndex]; // The asset UID is in the 6th capture group
119127
if (assetUID) {
120128
assetUIDs.add(assetUID);
121129
}

0 commit comments

Comments
 (0)