Skip to content
This repository was archived by the owner on Mar 25, 2021. It is now read-only.

Add action events #19

Merged
merged 4 commits into from
Dec 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/cli-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const PACKAGE_DISPLAY_HEADERS = [
'Smart Version',
'License',
'Description',
'Deprecated',
'My Usage',
'Score'
]
Expand Down Expand Up @@ -74,7 +73,6 @@ class Renderer {
`${style(data.recommendedVersion || 'No Insight')}`,
`${style(this.trimStringToLength(data.license, 4) || '')}`,
`${style(this.trimStringToLength(data.description, 20) || '')}`,
`${style(this.boolToString(data.deprecated) || '')}`,
`${style(this.fractionToPercentageString(data.usage) || 'No Insight')}`
]
if (hasHigherScore) style = style.bold.green
Expand All @@ -98,7 +96,7 @@ class Renderer {
let calculatedScore
if (Object.keys(weights).length > 0)
calculatedScore = score.calculatePackageScore(pkgData, weights, true)
else calculatedScore = pkgSet.source.score.final
else calculatedScore = pkgData.source.score.final
return (Number(calculatedScore) * 100).toFixed()
}

Expand Down Expand Up @@ -159,6 +157,7 @@ class Renderer {
}
} catch (err) {
this.logger.error(err)
throw err
}
}
renderVersionsTable({ data }) {
Expand All @@ -174,6 +173,7 @@ class Renderer {
this.renderLink('single', data)
} catch (err) {
this.logger.error(err)
throw err
}
}

Expand Down
73 changes: 63 additions & 10 deletions lib/insight.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,98 @@
require('babel-polyfill')

const request = require('request-promise-native')
const program = require('commander')
const auth = require('../lib/auth')
const weights = require('../lib/weights')
const loggerFactory = require('./loggerFactory')
const utils = require('./utils')

const getInsights = async function(data, token) {
const logger = loggerFactory.get('insight')
const BASE_URL = 'https://gateway.datree.io'

program
.option('-e, --event <event>', 'Event type')
.option('-d, --data <data>', 'The payload')
.parse(process.argv)

const makeRequest = async function({ uri, data, token }) {
const headers = {
'x-datree-sdk-type': 'nodejs',
'x-datree-sdk-version': utils.getVersion()
}
let options = {
headers: {},
uri: 'https://gateway.datree.io/packages/javascript',
headers,
uri,
body: data,
json: true
}
if (token) options.headers.Authorization = `Bearer ${token}`
return request.post(options)
}

const notifyUnInstall = async function(data, token) {
const uri = `${BASE_URL}/uninstall`
try {
await makeRequest({ uri, data, token })
} catch (err) {
logger.error(err)
}
}
const notifyInstall = async function(data, token) {
const uri = `${BASE_URL}/install`
try {
let res = await request.post(options)
await makeRequest({ uri, data, token })
} catch (err) {
logger.error(err)
}
}

const getInsights = async function(data, token) {
const uri = `${BASE_URL}/packages/javascript`

try {
const res = await makeRequest({ uri, data, token })
return res
} catch (err) {
logger.error(err)
return []
}
}

const main = async function() {
const info = JSON.parse(process.argv[2])
const token = auth.getToken()
const insight = await getInsights(info, token)
const userWeights = await weights.getWeights(token)

console.log(JSON.stringify({ insight, userWeights }))
const data = JSON.parse(program.data)
switch (program.event) {
case 'install':
await notifyInstall(data, token)
break
case 'uninstall':
await notifyUnInstall(data, token)
break
case 'insight':
const insight = await getInsights(data, token)
const userWeights = await weights.getWeights(token)
console.log(JSON.stringify({ insight, userWeights }))
break
default:
logger.error(`Unknown event ${program.event}`)
}
}

if (require.main === module) {
main()
.then(_ => {
process.exit(0)
})
.catch(_ => {
.catch(err => {
logger.error(err)
process.exit(1)
})
} else {
module.exports = {
getInsights
getInsights,
notifyInstall,
notifyUnInstall
}
}
28 changes: 23 additions & 5 deletions lib/install.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
const fs = require('fs-extra')
const fs = require('fs')
const childProcess = require('child_process')
const path = require('path')
const os = require('os')
const ini = require('ini')
const utils = require('../lib/utils')
const loggerFactory = require('./loggerFactory')
const logger = loggerFactory.get('install')

function enableHook(hookFullPath, homeDir) {
let npmrc = path.join(homeDir, '.npmrc')
if (!fs.pathExistsSync()) fs.createFileSync(npmrc)
const config = ini.parse(fs.readFileSync(npmrc).toString())
let config = {}
if (fs.existsSync(npmrc))
config = ini.parse(fs.readFileSync(npmrc).toString())

config['onload-script'] = `${hookFullPath}`
fs.writeFileSync(npmrc, ini.stringify(config))
}
Expand All @@ -21,9 +26,22 @@ function hookSetup() {
fs.mkdirSync(datreeioDir)
} catch (err) {}

fs.copySync(path.join(__dirname, 'hook.js'), hookFullPath)
fs.copyFileSync(path.join(__dirname, 'hook.js'), hookFullPath)
enableHook(hookFullPath, homeDir)
} catch (err) {}
const data = {
systeminfo: utils.getSystemInfo()
}

const insightsProcess = childProcess.spawnSync(`node`, [
`${__dirname}/insight.js`,
'-e',
'install',
'-d',
`${JSON.stringify(data)}`
])
} catch (err) {
logger.error(err)
}
}

hookSetup()
Expand Down
78 changes: 43 additions & 35 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,43 +29,51 @@ async function main() {
// If in npm install - parse installed packages
if (info.action === 'install' || info.action === 'i') {
info.installaction = argumentsExtractor.extractPackagesArgv()
}

// fetch insights
const insightsProcess = childProcess.spawnSync(`node`, [
`${__dirname}/insight.js`,
`${JSON.stringify(info)}`
])
const insightsResponse = JSON.parse(insightsProcess.stdout.toString('utf8'))
const insight = insightsResponse.insight
logger.info(insightsResponse)
const renderer = new Renderer({ logger })
renderer.renderSeparator()
renderer.renderLogo()
renderer.renderLegend(insight)
renderer.renderSeparator()
if (insight && insight.length > 0) {
let installType
if (info.installaction.length > 0) {
installType = 'alternative'
renderer.renderPackagesTable({
data: insight,
weights: insightsResponse.userWeights
})
} else {
installType = 'single'
insight.forEach(pkgSet => {
const pkgJsonVersion = node.getVersionFromDependencies(
info.packages,
pkgSet.source.name
)
pkgSet.source.pkgJsonVersion = pkgJsonVersion
})
renderer.renderVersionsTable({
data: insight
})
// fetch insights
const data = JSON.stringify(info)
const insightsProcess = childProcess.spawnSync(`node`, [
`${__dirname}/insight.js`,
'-e',
'insight',
'-d',
`${data}`
])

const insightsResponse = JSON.parse(
insightsProcess.stdout.toString('utf8')
)
const insight = insightsResponse.insight

if (insight && insight.length > 0) {
const renderer = new Renderer({ logger })
renderer.renderSeparator()
renderer.renderLogo()
renderer.renderLegend(insight)
renderer.renderSeparator()
let installType
if (info.installaction.length > 0) {
installType = 'alternative'
renderer.renderPackagesTable({
data: insight,
weights: insightsResponse.userWeights
})
} else {
installType = 'single'
insight.forEach(pkgSet => {
const pkgJsonVersion = node.getVersionFromDependencies(
info.packages,
pkgSet.source.name
)
pkgSet.source.pkgJsonVersion = pkgJsonVersion
})
renderer.renderVersionsTable({
data: insight
})
}

if (utils.isCI()) utils.writeToFile('debug.log', insight)
}
if (utils.isCI()) utils.writeToFile('test.log', insight)
}
} catch (err) {
logger.error(err)
Expand Down
26 changes: 22 additions & 4 deletions lib/uninstall.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,38 @@
const fs = require('fs-extra')
const fs = require('fs')
const childProcess = require('child_process')
const ini = require('ini')
const path = require('path')
const os = require('os')
const utils = require('../lib/utils')
const loggerFactory = require('./loggerFactory')
const logger = loggerFactory.get('uninstall')

function disableHook (homeDir) {
function disableHook(homeDir) {
let npmrc = path.join(homeDir, '.npmrc')
const config = ini.parse(fs.readFileSync(npmrc).toString())
config['onload-script'] = ''
fs.writeFileSync(npmrc, ini.stringify(config))
}

function uninstall () {
function uninstall() {
try {
const homeDir = os.homedir()
disableHook(homeDir)
} catch (err) {}
const data = {
systeminfo: utils.getSystemInfo(),
installDate: utils.getInstallDate()
}
const insightsProcess = childProcess.spawnSync(`node`, [
`${__dirname}/insight.js`,
'-e',
'uninstall',
'-d',
`${JSON.stringify(data)}`
])
console.log(insightsProcess.stdout.toString('utf8'))
} catch (err) {
logger.error(err)
}
}

uninstall()
Expand Down
25 changes: 20 additions & 5 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict'
const os = require('os')
const path = require('path')
const osName = require('os-name')
const fs = require('fs')
const pkgJson = require('../package.json')

function isDebug() {
return process.env.DATREE_ENV && process.env.DATREE_ENV !== 'ci'
Expand All @@ -15,7 +15,6 @@ function isCI() {
function getSystemInfo() {
return {
date_time: new Date().toISOString(),
user_id: getUserId(),
lang: 'nodejs',
lang_version: process.version,
os_platform: os.platform(),
Expand All @@ -24,9 +23,17 @@ function getSystemInfo() {
node_components: process.versions
}
}

function getUserId() {
return 'Anonymous' // TODO: DT-31
function setVersion() {
const versionPath = path.join(getDatreeioDir(), 'VERSION')
const version = pkgJson.version
fs.writeFileSync(versionPath, version)
}
function getVersion() {
const versionPath = path.join(getDatreeioDir(), 'VERSION')
return fs
.readFileSync(versionPath)
.toString('utf8')
.replace(/\n$/, '')
}

function getDatreeioDir() {
Expand All @@ -39,10 +46,18 @@ function writeToFile(fileName, data) {
fs.writeFileSync(fileLocation, JSON.stringify(data))
}

function getInstallDate() {
const datreeioDir = getDatreeioDir()
const stats = fs.statSync(datreeioDir)
return stats.birthtime
}

module.exports = {
getSystemInfo,
getDatreeioDir,
writeToFile,
getInstallDate,
getVersion,
isDebug,
isCI
}
5 changes: 4 additions & 1 deletion lib/weights.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const request = require('request-promise-native')
const utils = require('./utils')

const getWeights = async function (token) {
const getWeights = async function(token) {
let options = {
headers: {
'x-datree-sdk-type': 'nodejs',
'x-datree-sdk-version': utils.getVersion(),
Authorization: `Bearer ${token}`
},
uri: `https://gateway.datree.io/users/`,
Expand Down
Loading