Skip to content

Commit fc46a90

Browse files
committed
minor refactor
1 parent 8315ed6 commit fc46a90

File tree

2 files changed

+8
-270
lines changed

2 files changed

+8
-270
lines changed

bin/helpers/helper.js

Lines changed: 1 addition & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ exports.debug = (text, shouldReport = false, throwable = null) => {
2626
}
2727
}
2828

29-
const RequestQueueHandler = require('../testObservability/helper/requestQueueHandler');
30-
exports.requestQueueHandler = new RequestQueueHandler();
31-
3229
exports.getFileSeparatorData = () => {
3330
return /^win/.test(process.platform) ? "\\" : "/";
3431
}
@@ -89,7 +86,7 @@ exports.getPackageVersion = (package_, bsConfig = null) => {
8986
}
9087

9188
exports.getAgentVersion = () => {
92-
let _path = path.join(__dirname, '../../../package.json');
89+
let _path = path.join(__dirname, '../../package.json');
9390
if(fs.existsSync(_path))
9491
return require(_path).version;
9592
}
@@ -293,52 +290,3 @@ exports.getBuildDetails = (bsConfig) => {
293290
buildTags
294291
};
295292
}
296-
297-
const httpsScreenshotsKeepAliveAgent = new https.Agent({
298-
keepAlive: true,
299-
timeout: 60000,
300-
maxSockets: 2,
301-
maxTotalSockets: 2
302-
});
303-
304-
exports.httpsKeepAliveAgent = new https.Agent({
305-
keepAlive: true,
306-
timeout: 60000,
307-
maxSockets: 2,
308-
maxTotalSockets: 2
309-
});
310-
311-
exports.nodeRequest = (type, url, data, config, api_url) => {
312-
return new Promise(async (resolve, reject) => {
313-
const options = {...config,...{
314-
method: type,
315-
url: `${api_url}/${url}`,
316-
body: data,
317-
json: config.headers['Content-Type'] === 'application/json',
318-
agent: this.httpsKeepAliveAgent
319-
}};
320-
321-
if(url === exports.requestQueueHandler.screenshotEventUrl) {
322-
options.agent = httpsScreenshotsKeepAliveAgent;
323-
}
324-
325-
request(options, function callback(error, response, body) {
326-
if(error) {
327-
reject(error);
328-
} else if(response.statusCode != 200) {
329-
reject(response && response.body ? response.body : `Received response from BrowserStack Server with status : ${response.statusCode}`);
330-
} else {
331-
try {
332-
if(typeof(body) !== 'object') body = JSON.parse(body);
333-
} catch(e) {
334-
if(!url.includes('/stop')) {
335-
reject('Not a JSON response from BrowserStack Server');
336-
}
337-
}
338-
resolve({
339-
data: body
340-
});
341-
}
342-
});
343-
});
344-
}

bin/testObservability/helper/helper.js

Lines changed: 7 additions & 217 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ const pGitconfig = promisify(gitconfig);
1616

1717
const logger = require("../../helpers/logger").winstonLogger;
1818
const utils = require('../../helpers/utils');
19+
const helper = require('../../helpers/helper');
20+
1921
const CrashReporter = require('../crashReporter');
2022

2123
// Getting global packages path
@@ -181,178 +183,6 @@ exports.findGitConfig = (filePath) => {
181183
}
182184
}
183185

184-
const getGitMetaData = () => {
185-
return new Promise(async (resolve, reject) => {
186-
try {
187-
var info = getRepoInfo();
188-
if(!info.commonGitDir) {
189-
exports.debug(`Unable to find a Git directory`);
190-
resolve({});
191-
}
192-
if(!info.author && exports.findGitConfig(process.cwd())) {
193-
/* commit objects are packed */
194-
gitLastCommit.getLastCommit(async (err, commit) => {
195-
if(err) {
196-
exports.debug(`Exception in populating Git Metadata with error : ${err}`, true, err);
197-
return resolve({});
198-
}
199-
try {
200-
info["author"] = info["author"] || `${commit["author"]["name"].replace(/[]+/g, '')} <${commit["author"]["email"].replace(/[]+/g, '')}>`;
201-
info["authorDate"] = info["authorDate"] || commit["authoredOn"];
202-
info["committer"] = info["committer"] || `${commit["committer"]["name"].replace(/[]+/g, '')} <${commit["committer"]["email"].replace(/[]+/g, '')}>`;
203-
info["committerDate"] = info["committerDate"] || commit["committedOn"];
204-
info["commitMessage"] = info["commitMessage"] || commit["subject"];
205-
206-
const { remote } = await pGitconfig(info.commonGitDir);
207-
const remotes = Object.keys(remote).map(remoteName => ({name: remoteName, url: remote[remoteName]['url']}));
208-
resolve({
209-
"name": "git",
210-
"sha": info["sha"],
211-
"short_sha": info["abbreviatedSha"],
212-
"branch": info["branch"],
213-
"tag": info["tag"],
214-
"committer": info["committer"],
215-
"committer_date": info["committerDate"],
216-
"author": info["author"],
217-
"author_date": info["authorDate"],
218-
"commit_message": info["commitMessage"],
219-
"root": info["root"],
220-
"common_git_dir": info["commonGitDir"],
221-
"worktree_git_dir": info["worktreeGitDir"],
222-
"last_tag": info["lastTag"],
223-
"commits_since_last_tag": info["commitsSinceLastTag"],
224-
"remotes": remotes
225-
});
226-
} catch(e) {
227-
exports.debug(`Exception in populating Git Metadata with error : ${e}`, true, e);
228-
return resolve({});
229-
}
230-
}, {dst: exports.findGitConfig(process.cwd())});
231-
} else {
232-
const { remote } = await pGitconfig(info.commonGitDir);
233-
const remotes = Object.keys(remote).map(remoteName => ({name: remoteName, url: remote[remoteName]['url']}));
234-
resolve({
235-
"name": "git",
236-
"sha": info["sha"],
237-
"short_sha": info["abbreviatedSha"],
238-
"branch": info["branch"],
239-
"tag": info["tag"],
240-
"committer": info["committer"],
241-
"committer_date": info["committerDate"],
242-
"author": info["author"],
243-
"author_date": info["authorDate"],
244-
"commit_message": info["commitMessage"],
245-
"root": info["root"],
246-
"common_git_dir": info["commonGitDir"],
247-
"worktree_git_dir": info["worktreeGitDir"],
248-
"last_tag": info["lastTag"],
249-
"commits_since_last_tag": info["commitsSinceLastTag"],
250-
"remotes": remotes
251-
});
252-
}
253-
} catch(err) {
254-
exports.debug(`Exception in populating Git metadata with error : ${err}`, true, err);
255-
resolve({});
256-
}
257-
})
258-
}
259-
260-
const getCiInfo = () => {
261-
var env = process.env;
262-
// Jenkins
263-
if ((typeof env.JENKINS_URL === "string" && env.JENKINS_URL.length > 0) || (typeof env.JENKINS_HOME === "string" && env.JENKINS_HOME.length > 0)) {
264-
return {
265-
name: "Jenkins",
266-
build_url: env.BUILD_URL,
267-
job_name: env.JOB_NAME,
268-
build_number: env.BUILD_NUMBER
269-
}
270-
}
271-
// CircleCI
272-
if (env.CI === "true" && env.CIRCLECI === "true") {
273-
return {
274-
name: "CircleCI",
275-
build_url: env.CIRCLE_BUILD_URL,
276-
job_name: env.CIRCLE_JOB,
277-
build_number: env.CIRCLE_BUILD_NUM
278-
}
279-
}
280-
// Travis CI
281-
if (env.CI === "true" && env.TRAVIS === "true") {
282-
return {
283-
name: "Travis CI",
284-
build_url: env.TRAVIS_BUILD_WEB_URL,
285-
job_name: env.TRAVIS_JOB_NAME,
286-
build_number: env.TRAVIS_BUILD_NUMBER
287-
}
288-
}
289-
// Codeship
290-
if (env.CI === "true" && env.CI_NAME === "codeship") {
291-
return {
292-
name: "Codeship",
293-
build_url: null,
294-
job_name: null,
295-
build_number: null
296-
}
297-
}
298-
// Bitbucket
299-
if (env.BITBUCKET_BRANCH && env.BITBUCKET_COMMIT) {
300-
return {
301-
name: "Bitbucket",
302-
build_url: env.BITBUCKET_GIT_HTTP_ORIGIN,
303-
job_name: null,
304-
build_number: env.BITBUCKET_BUILD_NUMBER
305-
}
306-
}
307-
// Drone
308-
if (env.CI === "true" && env.DRONE === "true") {
309-
return {
310-
name: "Drone",
311-
build_url: env.DRONE_BUILD_LINK,
312-
job_name: null,
313-
build_number: env.DRONE_BUILD_NUMBER
314-
}
315-
}
316-
// Semaphore
317-
if (env.CI === "true" && env.SEMAPHORE === "true") {
318-
return {
319-
name: "Semaphore",
320-
build_url: env.SEMAPHORE_ORGANIZATION_URL,
321-
job_name: env.SEMAPHORE_JOB_NAME,
322-
build_number: env.SEMAPHORE_JOB_ID
323-
}
324-
}
325-
// GitLab
326-
if (env.CI === "true" && env.GITLAB_CI === "true") {
327-
return {
328-
name: "GitLab",
329-
build_url: env.CI_JOB_URL,
330-
job_name: env.CI_JOB_NAME,
331-
build_number: env.CI_JOB_ID
332-
}
333-
}
334-
// Buildkite
335-
if (env.CI === "true" && env.BUILDKITE === "true") {
336-
return {
337-
name: "Buildkite",
338-
build_url: env.BUILDKITE_BUILD_URL,
339-
job_name: env.BUILDKITE_LABEL || env.BUILDKITE_PIPELINE_NAME,
340-
build_number: env.BUILDKITE_BUILD_NUMBER
341-
}
342-
}
343-
// Visual Studio Team Services
344-
if (env.TF_BUILD === "True") {
345-
return {
346-
name: "Visual Studio Team Services",
347-
build_url: `${env.SYSTEM_TEAMFOUNDATIONSERVERURI}${env.SYSTEM_TEAMPROJECTID}`,
348-
job_name: env.SYSTEM_DEFINITIONID,
349-
build_number: env.BUILD_BUILDID
350-
}
351-
}
352-
// if no matches, return null
353-
return null;
354-
}
355-
356186
let packages = {};
357187

358188
exports.getPackageVersion = (package_, bsConfig = null) => {
@@ -394,12 +224,6 @@ exports.getPackageVersion = (package_, bsConfig = null) => {
394224
return packageVersion;
395225
}
396226

397-
exports.getAgentVersion = () => {
398-
let _path = path.join(__dirname, '../../../package.json');
399-
if(fs.existsSync(_path))
400-
return require(_path).version;
401-
}
402-
403227
const setEnvironmentVariablesForRemoteReporter = (BS_TESTOPS_JWT, BS_TESTOPS_BUILD_HASHED_ID, BS_TESTOPS_ALLOW_SCREENSHOTS, OBSERVABILITY_LAUNCH_SDK_VERSION) => {
404228
process.env.BS_TESTOPS_JWT = BS_TESTOPS_JWT;
405229
process.env.BS_TESTOPS_BUILD_HASHED_ID = BS_TESTOPS_BUILD_HASHED_ID;
@@ -442,47 +266,13 @@ const setEventListeners = () => {
442266
}
443267
}
444268

445-
const getBuildDetails = (bsConfig) => {
446-
const isTestObservabilityOptionsPresent = !utils.isUndefined(bsConfig["testObservabilityOptions"]);
447-
let buildName = '',
448-
projectName = '',
449-
buildDescription = '',
450-
buildTags = [];
451-
452-
/* Pick from environment variables */
453-
buildName = process.env.BROWSERSTACK_BUILD_NAME || buildName;
454-
projectName = process.env.BROWSERSTACK_PROJECT_NAME || projectName;
455-
456-
/* Pick from testObservabilityOptions */
457-
if(isTestObservabilityOptionsPresent) {
458-
buildName = buildName || bsConfig["testObservabilityOptions"]["buildName"];
459-
projectName = projectName || bsConfig["testObservabilityOptions"]["projectName"];
460-
if(!utils.isUndefined(bsConfig["testObservabilityOptions"]["buildTag"])) buildTags = [...buildTags, ...bsConfig["testObservabilityOptions"]["buildTag"]];
461-
buildDescription = buildDescription || bsConfig["testObservabilityOptions"]["buildDescription"];
462-
}
463-
464-
/* Pick from run settings */
465-
buildName = buildName || bsConfig["run_settings"]["build_name"];
466-
projectName = projectName || bsConfig["run_settings"]["project_name"];
467-
if(!utils.isUndefined(bsConfig["run_settings"]["build_tag"])) buildTags = [...buildTags, bsConfig["run_settings"]["build_tag"]];
468-
469-
buildName = buildName || path.basename(path.resolve(process.cwd()));
470-
471-
return {
472-
buildName,
473-
projectName,
474-
buildDescription,
475-
buildTags
476-
};
477-
}
478-
479269
const setBrowserstackCypressCliDependency = (bsConfig) => {
480270
const runSettings = bsConfig.run_settings;
481271
if (runSettings.npm_dependencies !== undefined &&
482272
typeof runSettings.npm_dependencies === 'object') {
483273
if (!("browserstack-cypress-cli" in runSettings.npm_dependencies)) {
484274
logger.warn("Missing browserstack-cypress-cli not found in npm_dependencies");
485-
runSettings.npm_dependencies['browserstack-cypress-cli'] = exports.getAgentVersion() || "latest";
275+
runSettings.npm_dependencies['browserstack-cypress-cli'] = helper.getAgentVersion() || "latest";
486276
logger.warn(`Adding browserstack-cypress-cli version ${runSettings.npm_dependencies['browserstack-cypress-cli']} in npm_dependencies`);
487277
}
488278
}
@@ -551,7 +341,7 @@ exports.launchTestSession = async (user_config, bsConfigPath) => {
551341
projectName,
552342
buildDescription,
553343
buildTags
554-
} = getBuildDetails(user_config);
344+
} = helper.getBuildDetails(user_config);
555345
const data = {
556346
'format': 'json',
557347
'project_name': projectName,
@@ -566,14 +356,14 @@ exports.launchTestSession = async (user_config, bsConfigPath) => {
566356
version: os.version(),
567357
arch: os.arch()
568358
},
569-
'ci_info': getCiInfo(),
359+
'ci_info': helper.getCiInfo(),
570360
'build_run_identifier': process.env.BROWSERSTACK_BUILD_RUN_IDENTIFIER,
571361
'failed_tests_rerun': process.env.BROWSERSTACK_RERUN || false,
572-
'version_control': await getGitMetaData(),
362+
'version_control': await helper.getGitMetaData(),
573363
'observability_version': {
574364
frameworkName: "Cypress",
575365
frameworkVersion: exports.getPackageVersion('cypress', user_config),
576-
sdkVersion: exports.getAgentVersion()
366+
sdkVersion: helper.getAgentVersion()
577367
}
578368
};
579369
const config = {

0 commit comments

Comments
 (0)