Skip to content

Commit f73cd76

Browse files
authored
Merge pull request datreeio#19 from datreeio/add-action-events
Add action events
2 parents fc798bb + 42ac3e4 commit f73cd76

File tree

11 files changed

+216
-84
lines changed

11 files changed

+216
-84
lines changed

lib/cli-renderer.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ const PACKAGE_DISPLAY_HEADERS = [
99
'Smart Version',
1010
'License',
1111
'Description',
12-
'Deprecated',
1312
'My Usage',
1413
'Score'
1514
]
@@ -74,7 +73,6 @@ class Renderer {
7473
`${style(data.recommendedVersion || 'No Insight')}`,
7574
`${style(this.trimStringToLength(data.license, 4) || '')}`,
7675
`${style(this.trimStringToLength(data.description, 20) || '')}`,
77-
`${style(this.boolToString(data.deprecated) || '')}`,
7876
`${style(this.fractionToPercentageString(data.usage) || 'No Insight')}`
7977
]
8078
if (hasHigherScore) style = style.bold.green
@@ -98,7 +96,7 @@ class Renderer {
9896
let calculatedScore
9997
if (Object.keys(weights).length > 0)
10098
calculatedScore = score.calculatePackageScore(pkgData, weights, true)
101-
else calculatedScore = pkgSet.source.score.final
99+
else calculatedScore = pkgData.source.score.final
102100
return (Number(calculatedScore) * 100).toFixed()
103101
}
104102

@@ -159,6 +157,7 @@ class Renderer {
159157
}
160158
} catch (err) {
161159
this.logger.error(err)
160+
throw err
162161
}
163162
}
164163
renderVersionsTable({ data }) {
@@ -174,6 +173,7 @@ class Renderer {
174173
this.renderLink('single', data)
175174
} catch (err) {
176175
this.logger.error(err)
176+
throw err
177177
}
178178
}
179179

lib/insight.js

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,98 @@
11
require('babel-polyfill')
22

33
const request = require('request-promise-native')
4+
const program = require('commander')
45
const auth = require('../lib/auth')
56
const weights = require('../lib/weights')
7+
const loggerFactory = require('./loggerFactory')
8+
const utils = require('./utils')
69

7-
const getInsights = async function(data, token) {
10+
const logger = loggerFactory.get('insight')
11+
const BASE_URL = 'https://gateway.datree.io'
12+
13+
program
14+
.option('-e, --event <event>', 'Event type')
15+
.option('-d, --data <data>', 'The payload')
16+
.parse(process.argv)
17+
18+
const makeRequest = async function({ uri, data, token }) {
19+
const headers = {
20+
'x-datree-sdk-type': 'nodejs',
21+
'x-datree-sdk-version': utils.getVersion()
22+
}
823
let options = {
9-
headers: {},
10-
uri: 'https://gateway.datree.io/packages/javascript',
24+
headers,
25+
uri,
1126
body: data,
1227
json: true
1328
}
1429
if (token) options.headers.Authorization = `Bearer ${token}`
30+
return request.post(options)
31+
}
1532

33+
const notifyUnInstall = async function(data, token) {
34+
const uri = `${BASE_URL}/uninstall`
35+
try {
36+
await makeRequest({ uri, data, token })
37+
} catch (err) {
38+
logger.error(err)
39+
}
40+
}
41+
const notifyInstall = async function(data, token) {
42+
const uri = `${BASE_URL}/install`
1643
try {
17-
let res = await request.post(options)
44+
await makeRequest({ uri, data, token })
45+
} catch (err) {
46+
logger.error(err)
47+
}
48+
}
49+
50+
const getInsights = async function(data, token) {
51+
const uri = `${BASE_URL}/packages/javascript`
52+
53+
try {
54+
const res = await makeRequest({ uri, data, token })
1855
return res
1956
} catch (err) {
57+
logger.error(err)
2058
return []
2159
}
2260
}
2361

2462
const main = async function() {
25-
const info = JSON.parse(process.argv[2])
2663
const token = auth.getToken()
27-
const insight = await getInsights(info, token)
28-
const userWeights = await weights.getWeights(token)
2964

30-
console.log(JSON.stringify({ insight, userWeights }))
65+
const data = JSON.parse(program.data)
66+
switch (program.event) {
67+
case 'install':
68+
await notifyInstall(data, token)
69+
break
70+
case 'uninstall':
71+
await notifyUnInstall(data, token)
72+
break
73+
case 'insight':
74+
const insight = await getInsights(data, token)
75+
const userWeights = await weights.getWeights(token)
76+
console.log(JSON.stringify({ insight, userWeights }))
77+
break
78+
default:
79+
logger.error(`Unknown event ${program.event}`)
80+
}
3181
}
3282

3383
if (require.main === module) {
3484
main()
3585
.then(_ => {
3686
process.exit(0)
3787
})
38-
.catch(_ => {
88+
.catch(err => {
89+
logger.error(err)
3990
process.exit(1)
4091
})
4192
} else {
4293
module.exports = {
43-
getInsights
94+
getInsights,
95+
notifyInstall,
96+
notifyUnInstall
4497
}
4598
}

lib/install.js

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1-
const fs = require('fs-extra')
1+
const fs = require('fs')
2+
const childProcess = require('child_process')
23
const path = require('path')
34
const os = require('os')
45
const ini = require('ini')
56
const utils = require('../lib/utils')
7+
const loggerFactory = require('./loggerFactory')
8+
const logger = loggerFactory.get('install')
69

710
function enableHook(hookFullPath, homeDir) {
811
let npmrc = path.join(homeDir, '.npmrc')
9-
if (!fs.pathExistsSync()) fs.createFileSync(npmrc)
10-
const config = ini.parse(fs.readFileSync(npmrc).toString())
12+
let config = {}
13+
if (fs.existsSync(npmrc))
14+
config = ini.parse(fs.readFileSync(npmrc).toString())
15+
1116
config['onload-script'] = `${hookFullPath}`
1217
fs.writeFileSync(npmrc, ini.stringify(config))
1318
}
@@ -21,9 +26,22 @@ function hookSetup() {
2126
fs.mkdirSync(datreeioDir)
2227
} catch (err) {}
2328

24-
fs.copySync(path.join(__dirname, 'hook.js'), hookFullPath)
29+
fs.copyFileSync(path.join(__dirname, 'hook.js'), hookFullPath)
2530
enableHook(hookFullPath, homeDir)
26-
} catch (err) {}
31+
const data = {
32+
systeminfo: utils.getSystemInfo()
33+
}
34+
35+
const insightsProcess = childProcess.spawnSync(`node`, [
36+
`${__dirname}/insight.js`,
37+
'-e',
38+
'install',
39+
'-d',
40+
`${JSON.stringify(data)}`
41+
])
42+
} catch (err) {
43+
logger.error(err)
44+
}
2745
}
2846

2947
hookSetup()

lib/main.js

Lines changed: 43 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -29,43 +29,51 @@ async function main() {
2929
// If in npm install - parse installed packages
3030
if (info.action === 'install' || info.action === 'i') {
3131
info.installaction = argumentsExtractor.extractPackagesArgv()
32-
}
3332

34-
// fetch insights
35-
const insightsProcess = childProcess.spawnSync(`node`, [
36-
`${__dirname}/insight.js`,
37-
`${JSON.stringify(info)}`
38-
])
39-
const insightsResponse = JSON.parse(insightsProcess.stdout.toString('utf8'))
40-
const insight = insightsResponse.insight
41-
logger.info(insightsResponse)
42-
const renderer = new Renderer({ logger })
43-
renderer.renderSeparator()
44-
renderer.renderLogo()
45-
renderer.renderLegend(insight)
46-
renderer.renderSeparator()
47-
if (insight && insight.length > 0) {
48-
let installType
49-
if (info.installaction.length > 0) {
50-
installType = 'alternative'
51-
renderer.renderPackagesTable({
52-
data: insight,
53-
weights: insightsResponse.userWeights
54-
})
55-
} else {
56-
installType = 'single'
57-
insight.forEach(pkgSet => {
58-
const pkgJsonVersion = node.getVersionFromDependencies(
59-
info.packages,
60-
pkgSet.source.name
61-
)
62-
pkgSet.source.pkgJsonVersion = pkgJsonVersion
63-
})
64-
renderer.renderVersionsTable({
65-
data: insight
66-
})
33+
// fetch insights
34+
const data = JSON.stringify(info)
35+
const insightsProcess = childProcess.spawnSync(`node`, [
36+
`${__dirname}/insight.js`,
37+
'-e',
38+
'insight',
39+
'-d',
40+
`${data}`
41+
])
42+
43+
const insightsResponse = JSON.parse(
44+
insightsProcess.stdout.toString('utf8')
45+
)
46+
const insight = insightsResponse.insight
47+
48+
if (insight && insight.length > 0) {
49+
const renderer = new Renderer({ logger })
50+
renderer.renderSeparator()
51+
renderer.renderLogo()
52+
renderer.renderLegend(insight)
53+
renderer.renderSeparator()
54+
let installType
55+
if (info.installaction.length > 0) {
56+
installType = 'alternative'
57+
renderer.renderPackagesTable({
58+
data: insight,
59+
weights: insightsResponse.userWeights
60+
})
61+
} else {
62+
installType = 'single'
63+
insight.forEach(pkgSet => {
64+
const pkgJsonVersion = node.getVersionFromDependencies(
65+
info.packages,
66+
pkgSet.source.name
67+
)
68+
pkgSet.source.pkgJsonVersion = pkgJsonVersion
69+
})
70+
renderer.renderVersionsTable({
71+
data: insight
72+
})
73+
}
74+
75+
if (utils.isCI()) utils.writeToFile('debug.log', insight)
6776
}
68-
if (utils.isCI()) utils.writeToFile('test.log', insight)
6977
}
7078
} catch (err) {
7179
logger.error(err)

lib/uninstall.js

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,38 @@
1-
const fs = require('fs-extra')
1+
const fs = require('fs')
2+
const childProcess = require('child_process')
23
const ini = require('ini')
34
const path = require('path')
45
const os = require('os')
6+
const utils = require('../lib/utils')
7+
const loggerFactory = require('./loggerFactory')
8+
const logger = loggerFactory.get('uninstall')
59

6-
function disableHook (homeDir) {
10+
function disableHook(homeDir) {
711
let npmrc = path.join(homeDir, '.npmrc')
812
const config = ini.parse(fs.readFileSync(npmrc).toString())
913
config['onload-script'] = ''
1014
fs.writeFileSync(npmrc, ini.stringify(config))
1115
}
1216

13-
function uninstall () {
17+
function uninstall() {
1418
try {
1519
const homeDir = os.homedir()
1620
disableHook(homeDir)
17-
} catch (err) {}
21+
const data = {
22+
systeminfo: utils.getSystemInfo(),
23+
installDate: utils.getInstallDate()
24+
}
25+
const insightsProcess = childProcess.spawnSync(`node`, [
26+
`${__dirname}/insight.js`,
27+
'-e',
28+
'uninstall',
29+
'-d',
30+
`${JSON.stringify(data)}`
31+
])
32+
console.log(insightsProcess.stdout.toString('utf8'))
33+
} catch (err) {
34+
logger.error(err)
35+
}
1836
}
1937

2038
uninstall()

lib/utils.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
'use strict'
21
const os = require('os')
32
const path = require('path')
43
const osName = require('os-name')
54
const fs = require('fs')
5+
const pkgJson = require('../package.json')
66

77
function isDebug() {
88
return process.env.DATREE_ENV && process.env.DATREE_ENV !== 'ci'
@@ -15,7 +15,6 @@ function isCI() {
1515
function getSystemInfo() {
1616
return {
1717
date_time: new Date().toISOString(),
18-
user_id: getUserId(),
1918
lang: 'nodejs',
2019
lang_version: process.version,
2120
os_platform: os.platform(),
@@ -24,9 +23,17 @@ function getSystemInfo() {
2423
node_components: process.versions
2524
}
2625
}
27-
28-
function getUserId() {
29-
return 'Anonymous' // TODO: DT-31
26+
function setVersion() {
27+
const versionPath = path.join(getDatreeioDir(), 'VERSION')
28+
const version = pkgJson.version
29+
fs.writeFileSync(versionPath, version)
30+
}
31+
function getVersion() {
32+
const versionPath = path.join(getDatreeioDir(), 'VERSION')
33+
return fs
34+
.readFileSync(versionPath)
35+
.toString('utf8')
36+
.replace(/\n$/, '')
3037
}
3138

3239
function getDatreeioDir() {
@@ -39,10 +46,18 @@ function writeToFile(fileName, data) {
3946
fs.writeFileSync(fileLocation, JSON.stringify(data))
4047
}
4148

49+
function getInstallDate() {
50+
const datreeioDir = getDatreeioDir()
51+
const stats = fs.statSync(datreeioDir)
52+
return stats.birthtime
53+
}
54+
4255
module.exports = {
4356
getSystemInfo,
4457
getDatreeioDir,
4558
writeToFile,
59+
getInstallDate,
60+
getVersion,
4661
isDebug,
4762
isCI
4863
}

lib/weights.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
const request = require('request-promise-native')
2+
const utils = require('./utils')
23

3-
const getWeights = async function (token) {
4+
const getWeights = async function(token) {
45
let options = {
56
headers: {
7+
'x-datree-sdk-type': 'nodejs',
8+
'x-datree-sdk-version': utils.getVersion(),
69
Authorization: `Bearer ${token}`
710
},
811
uri: `https://gateway.datree.io/users/`,

0 commit comments

Comments
 (0)