Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create package Lint Reporter #1835

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ repopack-output.txt
repopack.config.json
.repopackignore

**/umd/index.js
**/umd/*.js
4,286 changes: 1,112 additions & 3,174 deletions package-lock.json

Large diffs are not rendered by default.

136 changes: 136 additions & 0 deletions packages/lint-reporters/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# CHANGELOG

# 1.18.0 (2024-08-26)


### Features

* adopt metric service v2 version ([55591a6](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/55591a61266feb12a079d1072def8c912facea44))
* use https protocal ([daa6883](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/daa688344a54cad9cb90f4bec3b541a988362dcc))



# 1.17.0 (2024-06-20)


### Features

* remove unnecessary await ([7937b4a](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/7937b4a971e8942147c523471e00da11f65a7d4e))
* send org name ([2d78ec4](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/2d78ec4241da4a1f11dc0cbe1a880fcfb655b79f))
* use default env variable ([76754d6](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/76754d60d810a02322fc2d5c2eb3582bf1c09711))



# 1.16.0 (2024-06-03)


### Features

* remove dedent ([7dab9f4](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/7dab9f4371600acc95dfaca295cd56d3de9dbdde))



# 1.15.0 (2024-06-03)


### Features

* add decorators report ([3ea3763](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/3ea3763249b090e4759be38c0287ecac8f962d16))



# 1.14.0 (2024-05-28)


### Features

* Avoid send a empty array of metrics ([f5ca649](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/f5ca649af7947849bd34689b26f6de47129bf9cb))



# 1.13.0 (2024-05-23)


### Features

* fix array indentation ([aff1602](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/aff16022449e4af8ff63c2cb9c79f145babf76fc))



# 1.12.0 (2024-05-23)


### Bug Fixes

* fix async function ([a6807b8](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/a6807b8724cec317c2bf9f3f8759d008dc65f56f))



# 1.11.0 (2024-05-23)


### Features

* Send signals as arrays ([d383b4a](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/d383b4a97cda6c37f9dded9a9b3eedbe254f67df))



# 1.10.0 (2024-05-23)


### Features

* Fix content length ([ace0fce](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/ace0fceaef66db0d133add1ae893c9b427a59d81))



# 1.9.0 (2024-05-23)


### Features

* Send Repository ID ([7ba23dd](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/7ba23dd1ff3ccec1ac3d5a81fb297fd668a6643f))



# 1.8.0 (2024-05-22)


### Features

* fix payload ([1d8e315](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/1d8e3151beee33bf83004021735d3ce5a1e2bcbc))



# 1.7.0 (2024-05-22)


### Features

* add type of signal ([7714a2b](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/7714a2b573056368f08b72a0698d3b1681ec87f2))



# 1.6.0 (2024-05-22)



# 1.5.0 (2024-05-22)



# 1.4.0 (2024-05-22)


### Bug Fixes

* Fix console.log error ([85dfc39](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/85dfc3959b1be899c7ac2dc53631e07f486a1ab8))


### Features

* check until log ([da0e777](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/da0e777df41e7934d8d9490a7c2b9c7587f1a079))
* Create package and add fake tests ([b4ee7e1](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/b4ee7e1717c2edce5896f6eff0b508fa674a0a02))
* Send metric using the new microservice ([d1a2187](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/d1a2187bbe892b47aa799d665fbb84443826fb52))
* Send reports only in master branch ([7460cd5](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/7460cd58f198d51b101dc789e025eae3906f91a1))
* Send reports only in master or main branch ([9afe39f](https://github.mpi-internal.com/scmspain/frontend-common--lib-adv/commit/9afe39f06afda758ea6da42433f758548f0fad53))
34 changes: 34 additions & 0 deletions packages/lint-reporters/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
.PHONY: lib umd
OWNER=Web Platform <[email protected]>

SHELL := /bin/bash
.DEFAULT_GOAL := help

TEST_FLAG ?=
TEST_FLAG_SERVER ?=

lib: ## Build the library
@rm -Rf ./lib
@npx sui-js-compiler

umd: ## Bundle the reporter scripts to send sui-lint metrics to DD
rm -Rf ./umd && mkdir ./umd
npx esbuild ./src/sui-lint-js-reporter.js --bundle --platform=node --target=node10.4 > ./umd/sui-lint-js-reporter.bundle.js
npx esbuild ./src/sui-lint-repository-reporter.js --bundle --platform=node --target=node10.4 > ./umd/sui-lint-repository-reporter.bundle.js

prepublishOnly: lib umd ## Build the Library before publish the package

lint: ## Lint and fix JS/TS code
npx sui-lint js --fix

test: test_server ## Run client and server tests

test_server: ## run server tests
STAGE=test npx sui-test server $(TEST_FLAG) $(TEST_FLAG_SERVER)

test_server_watch: ## run server test in watch mode
TEST_FLAG=--watch $(MAKE) test_server

help: ## show help
@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

41 changes: 41 additions & 0 deletions packages/lint-reporters/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "@s-ui/lint-reporters",
"version": "1.0.0-beta.0",
"description": "Send lint errors and golden path metrics to DataDog",
"author": "Web Platform <[email protected]> (https://github.mpi-internal.com/scmspain/es-td-agreements/tree/master/30-Frontend)",
"license": "MIT",
"keywords": [
"DataDog",
"lint",
"eslint"
],
"files": [
"umd",
"lib"
],
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"scripts": {
"lib": "make lib",
"umd": "make umd",
"prepublishOnly": "make prepublishOnly",
"lint": "make lint",
"test": "make test"
},
"devDependencies": {
"@s-ui/js-compiler": "1",
"@s-ui/test": "8",
"@types/chai": "4.3.6",
"@types/chai-dom": "1.11.3",
"@types/globrex": "0.1.4",
"@types/mocha": "10.0.2",
"@types/sinon": "17.0.3",
"chai": "4.3.10",
"sinon": "18.0.0"
},
"dependencies": {
"@s-ui/lint": "4",
"globrex": "0.1.2",
"ts-pattern": "5.1.1"
}
}
40 changes: 40 additions & 0 deletions packages/lint-reporters/src/Reporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {exec as execNode} from 'child_process'
import {promisify} from 'util'

import {HTTPSender} from './Sender/HTTPSender'
import type {Sender} from './Sender/Sender'

const exec = promisify(execNode)
type Repository = string

export class Reporter {
sender: Sender = HTTPSender.create()

async _isMaster(): Promise<boolean> {
let branch = await exec('git rev-parse --abbrev-ref HEAD').catch(() => 'UNKNOW_BRANCH')

if (typeof branch !== 'string') {
branch = branch.stdout
}

return branch.trim() === 'master' || branch.trim() === 'main'
}

async _getRepository(): Promise<Repository> {
let url = await exec('git config --get remote.origin.url').catch(() => '[email protected]:sui/remote-url.git')

if (typeof url !== 'string') {
url = url.stdout
}

const cleanUrl = url.trim().replace('\n', '')
const isHttp = cleanUrl.startsWith('https://')

if (isHttp) {
return cleanUrl.split('/')[4]?.replace('.git', '')
} else {
const [, address] = cleanUrl.split('@')
return address.split('/')[1].replace('.git', '')
}
}
}
122 changes: 122 additions & 0 deletions packages/lint-reporters/src/Sender/HTTPSender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/* eslint @typescript-eslint/no-non-null-assertion:0 */
/* eslint @typescript-eslint/strict-boolean-expressions:0 */

import https from 'node:https'
import {match} from 'ts-pattern'

import type {Sender, Signal} from './Sender'

const ONE_SECOND = 1000
const delay = async (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

const {MS_URL = 'ms-common--metrics.es-global-pro.schip.io', BASIC_AUTH} = process.env

export class HTTPSender implements Sender {
static create() {
return new HTTPSender()
}

async send(signals: Signal[]): Promise<void> {
if (!signals || signals.length === 0) return this.log('😡 Sorry but there are not signals to send')

const body = signals.map(signal =>
match(signal)
.with({type: 'repository'}, p => ({rule: p.rule, value: p.value, type: p.type}))
.with({type: 'js'}, p => ({rule: p.ruleName, value: p.numberOfFails, type: p.type}))
.exhaustive()
)

this.log('🚀 Sending the metric to the microservice.')
const ok = await this.request(body)

if (ok) this.log('🤓 The metric has been successfully sent to the microservice.')

if (!ok) {
this.log('😅 The initial attempt to send the metric has failed. We will retry in 1 second.')
await delay(ONE_SECOND)
match(await this.request(body))
.with(true, () => this.log('😏 The retry attempt to send the metric has worked successfully.'))
.with(false, () =>
this.log(
'😡 Sorry, but the second retry attempt to send the metric has also failed. We will not attempt again, and the metric will be lost forever.'
)
) // eslint-disable-line
}

return undefined
}

private log(...msg: string[]): void {
console.log.apply(console, msg) // eslint-disable-line
}

private async request(
body: Array<{
rule: string
value: unknown
type: Signal['type']
}>
): Promise<boolean> {
if (BASIC_AUTH === undefined) {
this.log('❌ BASIC_AUTH env var shouldnt be undefined')
process.exit(1)
}

const bodyReq = {
metrics: [
{
name: 'metrics.frontend.discipline',
organisationName: process.env.GITHUB_REPOSITORY_OWNER,
repositoryId: process.env.GITHUB_REPOSITORY_ID,
tags: body.map(bodyJSON => ({
tagSetId: match(bodyJSON.type)
.with('repository', p => 'global.metrics.frontend.repository')
.with('js', p => 'global.metrics.frontend.code')
.exhaustive(),
key: bodyJSON.rule,
value: bodyJSON.value
}))
}
]
}

return new Promise((resolve, _reject) => {
const options = {
hostname: MS_URL,
port: 443,
path: '/v2/ci-metrics',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(JSON.stringify(bodyReq)),
Authorization: 'Basic ' + BASIC_AUTH
}
}

const req = https.request(options, res => {
this.log(`STATUS: ${res.statusCode! as unknown as string}`)
this.log(`HEADERS: ${JSON.stringify(res.headers)}`)
res.setEncoding('utf8')
res.on('data', chunk => {
this.log(`BODY: ${chunk as string}`)
})
res.on('end', () => {
this.log('No more data in response.')
const isSuccess = res.statusCode && res.statusCode >= 200 && res.statusCode < 300
resolve(Boolean(isSuccess))
})
})

req.on('error', e => {
this.log(`problem with request: ${e.message}`)
resolve(false)
})

this.log('Body:\n\n', JSON.stringify(bodyReq, null, 2), '\n\n')

// Write data to request body
req.write(JSON.stringify(bodyReq))
req.end()
})
}
}
7 changes: 7 additions & 0 deletions packages/lint-reporters/src/Sender/Sender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type Signal =
| {type: 'repository'; rule: string; value: string | number | boolean; repository?: string}
| {type: 'js'; ruleName: string; numberOfFails: number; repository?: string}

export interface Sender {
send: (signal: Signal[]) => Promise<void>
}
Loading