Skip to content

Commit 49f23a3

Browse files
authored
Merge pull request #56 from sushobhit-lt/DOT-1554
fix validation errors and added logger
2 parents 33b97eb + 3ae16ea commit 49f23a3

File tree

9 files changed

+173
-76
lines changed

9 files changed

+173
-76
lines changed

commands/capture.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ const { fetchDOM, upload } = require('./utils/dom')
22
const { cleanup } = require('./utils/cleanup')
33

44

5-
async function capture(screenshots, options) {
6-
await fetchDOM(screenshots,options);
7-
await upload(screenshots, options);
8-
cleanup();
5+
async function capture(screenshots, options, logger) {
6+
await fetchDOM(screenshots,options, logger);
7+
await upload(screenshots, options, logger);
8+
cleanup(logger);
99
}
1010

1111

commands/config.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,50 @@ const fs = require('fs');
33
const { defaultSmartUIConfig, defaultScreenshotConfig } = require('./utils/config');
44
var { constants } = require('./utils/constants');
55

6-
function createConfig(filepath) {
6+
function createConfig(filepath, logger) {
77
// default filepath
88
filepath = filepath || '.smartui.json';
99
let filetype = path.extname(filepath);
1010
if (filetype != '.json') {
11-
console.log(`[smartui] Error: Config file must have .json extension`);
11+
logger.error(`[smartui] Error: Config file must have .json extension`);
1212
process.exitCode = constants.ERROR_CATCHALL;
1313
return
1414
}
1515

1616
// verify the file does not already exist
1717
if (fs.existsSync(filepath)) {
18-
console.log(`[smartui] Error: LambdaTest SmartUI config already exists: ${filepath}`);
18+
logger.error(`[smartui] Error: LambdaTest SmartUI config already exists: ${filepath}`);
1919
process.exitCode = constants.ERROR_CATCHALL;
2020
return
2121
}
2222

2323
// write stringified default config options to the filepath
2424
fs.mkdirSync(path.dirname(filepath), { recursive: true });
2525
fs.writeFileSync(filepath, JSON.stringify(defaultSmartUIConfig, null, 2) + '\n');
26-
console.log(`[smartui] Created LambdaTest SmartUI config: ${filepath}`);
26+
logger.info(`[smartui] Created LambdaTest SmartUI config: ${filepath}`);
2727
};
2828

29-
function createScreenshotConfig(filepath) {
29+
function createScreenshotConfig(filepath, logger) {
3030
// default filepath
3131
filepath = filepath || 'screenshot.json';
3232
let filetype = path.extname(filepath);
3333
if (filetype != '.json') {
34-
console.log(`[smartui] Error: Config file must have .json extension`);
34+
logger.error(`[smartui] Error: Config file must have .json extension`);
3535
process.exitCode = constants.ERROR_CATCHALL;
3636
return
3737
}
3838

3939
// verify the file does not already exist
4040
if (fs.existsSync(filepath)) {
41-
console.log(`[smartui] Error: Screenshot config already exists: ${filepath}`);
41+
logger.error(`[smartui] Error: Screenshot config already exists: ${filepath}`);
4242
process.exitCode = constants.ERROR_CATCHALL;
4343
return
4444
}
4545

4646
// write stringified default config options to the filepath
4747
fs.mkdirSync(path.dirname(filepath), { recursive: true });
4848
fs.writeFileSync(filepath, JSON.stringify(defaultScreenshotConfig, null, 2) + '\n');
49-
console.log(`[smartui] Created Screenshot config: ${filepath}`);
49+
logger.info(`[smartui] Created Screenshot config: ${filepath}`);
5050
};
5151

5252
module.exports = { createConfig, createScreenshotConfig };

commands/utils/cleanup.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
const fs = require('fs');
22

3-
function cleanup(){
3+
function cleanup(logger){
44
fs.rm('doms', { recursive: true }, (err) => {
55
if (err) {
6-
return console.error(err);
6+
return logger.error(err);
77
}
88
});
99
return true

commands/utils/dom.js

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -98,25 +98,25 @@ async function sendDoM(storybookUrl, stories, storybookConfig, options) {
9898
});
9999
};
100100

101-
async function fetchDOM(screenshots, options) {
102-
console.log("fetchDOM started")
101+
async function fetchDOM(screenshots, options, logger) {
102+
logger.debug("fetchDOM started")
103103
const createBrowser = require('browserless')
104104
const browser = createBrowser()
105105

106106
if (!fs.existsSync('doms')) {
107107
fs.mkdir('doms', (err) => {
108108
if (err) {
109-
console.error(err);
109+
logger.error(err);
110110
process.exit(constants.ERROR_CATCHALL);
111111
}
112112
});
113113
}
114114

115115
//TODO: Make this async
116116
for (const screenshot of screenshots) {
117-
console.log(screenshot)
117+
logger.debug(screenshot)
118118
let id = generateId(screenshot.name)
119-
console.log(id)
119+
logger.debug(id)
120120
screenshot.id = id
121121
const browserless = await browser.createContext()
122122

@@ -135,16 +135,16 @@ async function fetchDOM(screenshots, options) {
135135
let image = new URL(element.getAttribute('src'), `https://${host}`).href;
136136
element.setAttribute('src', image);
137137
} catch (e) {
138-
console.log(e);
138+
logger.error(e);
139139
}
140140
}
141141

142142
try {
143-
console.log("Creating CSS DOM")
143+
logger.debug("Creating CSS DOM")
144144
await serializeCSSOM(dom, clone);
145145
fs.writeFileSync(`doms/${id}.html`, clone.serialize());
146146
} catch (err) {
147-
console.error(err);
147+
logger.error(err);
148148
}
149149
await browserless.destroyContext();
150150
//Async upload
@@ -191,12 +191,12 @@ function generateId(str) {
191191
return noSpacesStr;
192192
}
193193

194-
async function upload(screenshots, options) {
194+
async function upload(screenshots, options,logger) {
195195
// Create form
196196
let commit = await getLastCommit();
197197
const form = new formData();
198-
console.log("Upload Started with ", screenshots)
199-
198+
logger.info("Upload screenshot started")
199+
logger.debug(screenshots)
200200
for (const screenshot of screenshots) {
201201
const file = fs.readFileSync(`doms/${screenshot.id}.html`);
202202
form.append('files', file, `${screenshot.name}.html`);
@@ -222,14 +222,14 @@ async function upload(screenshots, options) {
222222
...form.getHeaders()
223223
}
224224
}).then(async function (response) {
225-
console.log('[smartui] Build URL: ', response.data.buildURL);
226-
console.log('[smartui] Build in progress...');
225+
logger.info('[smartui] Build URL: '+ response.data.buildURL);
226+
logger.info('[smartui] Build in progress...');
227227
await shortPolling(response.data.buildId, 0, options);
228228
}).catch(function (error) {
229229
if (error.response) {
230-
console.log('[smartui] Build failed: Error: ', error.response.data.message);
230+
logger.error('[smartui] Build failed: Error: '+ error.response.data.message);
231231
} else {
232-
console.log('[smartui] Build failed: Error: ', error.message);
232+
logger.error('[smartui] Build failed: Error: '+ error.message);
233233
}
234234
});
235235
}

commands/utils/package.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,24 @@ const axios = require('axios');
22
var { constants } = require('./constants');
33

44
// Check for package updates
5-
function checkUpdate(version, options) {
5+
function checkUpdate(version, options, logger) {
66
return axios.get(new URL(constants[options.env].CHECK_UPDATE_PATH, constants[options.env].BASE_URL).href, {
77
params: {
88
packageName: 'smartui-storybook',
99
packageVersion: version
1010
}})
1111
.then(function (response) {
1212
if (response.data.data.deprecated) {
13-
console.log('v' + version + ' is deprecated. Please update to v' + response.data.data.latestVersion);
13+
logger.warn('v' + version + ' is deprecated. Please update to v' + response.data.data.latestVersion);
1414
} else if (response.data.data.latestVersion != version) {
15-
console.log('A newer version v' + response.data.data.latestVersion + ' is available.');
15+
logger.warn('A newer version v' + response.data.data.latestVersion + ' is available.');
1616
}
1717
})
1818
.catch(function (error) {
1919
if (error.response && error.response.data && error.response.data.error) {
20-
console.log('Cannot check for updates. Error: ' + error.response.data.error.message);
20+
logger.error('Cannot check for updates. Error: ' + error.response.data.error.message);
2121
} else {
22-
console.log('Cannot check for updates. Error: ' + error.message);
22+
logger.error('Cannot check for updates. Error: ' + error.message);
2323
}
2424
});
2525
};

commands/utils/validate.js

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,29 +17,30 @@ class ValidationError extends Error {
1717
}
1818
}
1919

20-
function validateProjectToken(options) {
21-
console.log("options", options);
22-
if (process.env.PROJECT_TOKEN) {
20+
function validateProjectToken(options, logger) {
21+
logger.debug("options", options);
22+
if (process.env.PROJECT_TOKEN) {
2323
return axios.get(constants[options.env].AUTH_URL, {
2424
headers: {
2525
projectToken: process.env.PROJECT_TOKEN
26-
}})
26+
}
27+
})
2728
.then(function (response) {
28-
console.log('[smartui] Project Token Validated');
29+
logger.info('[smartui] Project Token Validated');
2930
})
3031
.catch(function (error) {
3132
if (error.response) {
32-
console.log('[smartui] Error: Invalid Project Token');
33+
logger.error('[smartui] Error: Invalid Project Token');
3334
} else if (error.request) {
34-
console.log('[smartui] Project Token not validated. Error: ', error.message);
35+
logger.error('[smartui] Project Token not validated. Error: ', error.message);
3536
} else {
36-
console.log('[smartui] Project Token not validated. Error: ', error.message);
37+
logger.error('[smartui] Project Token not validated. Error: ', error.message);
3738
}
3839
process.exit(constants.ERROR_CATCHALL);
39-
});
40+
});
4041
}
41-
else {
42-
console.log('[smartui] Error: please set PROJECT_TOKEN key, refer to https://smartui.lambdatest.com');
42+
else {
43+
logger.error('[smartui] Error: please set PROJECT_TOKEN key, refer to https://smartui.lambdatest.com');
4344
process.exit(constants.ERROR_CATCHALL);
4445
}
4546
};
@@ -94,7 +95,8 @@ async function validateLatestBuild(options) {
9495
params: {
9596
branch: commit.branch,
9697
commitId: commit.shortHash
97-
}})
98+
}
99+
})
98100
.then(function (response) {
99101
if (response.data.status === 'Failure') {
100102
console.log(`[smartui] Build with commit '${commit.shortHash}' on branch '${commit.branch}' already exists.`);
@@ -198,12 +200,56 @@ function parse(file) {
198200
return JSON.parse(data);
199201
}
200202

201-
// Verify Screenshot config
202-
function validateScreenshotConfig(configFile) {
203-
// Verify config file exists
203+
// Verify Screenshot config
204+
function validateScreenshotConfig(configFile, logger) {
205+
// Check for JSON extension
206+
if (!isJSONFile(configFile)) {
207+
logger.error('capture command only supports json file');
208+
process.exit(constants.ERROR_CATCHALL);
209+
}
210+
211+
// Check if file exists
212+
if (configFile) {
213+
try {
214+
fs.accessSync(configFile, fs.constants.F_OK);
215+
} catch (error) {
216+
logger.error('Error: File does not exist ' + configFile);
217+
process.exit(constants.ERROR_CATCHALL);
218+
}
219+
220+
}
221+
222+
223+
let screenshots = {};
224+
// Check JSON Parse Error
225+
if (configFile) {
226+
try {
227+
screenshots = parse(configFile)
228+
} catch (error) {
229+
logger.error('Error: Invalid json file');
230+
process.exit(constants.ERROR_CATCHALL);
231+
}
232+
}
233+
234+
logger.debug(screenshots)
235+
236+
//Check for URLs should not be empty
237+
for (const screenshot of screenshots) {
238+
if(!screenshot.url || screenshot.url == ''){
239+
logger.error('Error: Missing required URL for screenshot');
240+
process.exit(constants.ERROR_CATCHALL);
241+
}
242+
//Check for URLs should valid (like abcd in URL)
243+
try {
244+
new URL(screenshot.url);
245+
} catch (error) {
246+
logger.error('Error: Invalid screenshot URL: '+screenshot.url);
247+
process.exit(constants.ERROR_CATCHALL);
248+
}
249+
}
204250
}
205251

206-
module.exports = {
252+
module.exports = {
207253
ValidationError,
208254
validateProjectToken,
209255
validateStorybookUrl,

0 commit comments

Comments
 (0)