Improve raw command handlers and remove dayjs dependency (switched to native Intl.DateTimeFormat API)

This commit is contained in:
lowlighter
2021-02-09 18:50:25 +01:00
parent 7d9d259f23
commit b80eecc3f5
10 changed files with 37 additions and 21 deletions

View File

@@ -3,6 +3,7 @@ repository:
- .github/** - .github/**
- .gitignore - .gitignore
- .gitattributes - .gitattributes
- .eslintrc.yml
- SECURITY.md - SECURITY.md
- LICENSE - LICENSE
- CONTRIBUTING.md - CONTRIBUTING.md

5
package-lock.json generated
View File

@@ -2185,11 +2185,6 @@
"whatwg-url": "^8.0.0" "whatwg-url": "^8.0.0"
} }
}, },
"dayjs": {
"version": "1.10.4",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.10.4.tgz",
"integrity": "sha512-RI/Hh4kqRc1UKLOAf/T5zdMMX5DQIlDxwUe3wSyMMnEbGunnpENCdbUgM+dW7kXidZqCttBrmw7BhN4TMddkCw=="
},
"debug": { "debug": {
"version": "2.6.9", "version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",

View File

@@ -28,7 +28,6 @@
"@octokit/rest": "^18.0.15", "@octokit/rest": "^18.0.15",
"axios": "^0.21.1", "axios": "^0.21.1",
"compression": "^1.7.4", "compression": "^1.7.4",
"dayjs": "^1.10.4",
"ejs": "^3.1.5", "ejs": "^3.1.5",
"express": "^4.17.1", "express": "^4.17.1",
"express-rate-limit": "^5.2.3", "express-rate-limit": "^5.2.3",

View File

@@ -60,10 +60,8 @@
if (!account) if (!account)
logger(`metrics/inputs > account type not set for plugin ${name}!`) logger(`metrics/inputs > account type not set for plugin ${name}!`)
if (account !== "bypass") { if (account !== "bypass") {
if (!meta.supports?.includes(account)) if (!meta.supports?.includes(q.repo ? "repository" : account))
throw {error:{message:`Not supported for: ${account}`, instance:new Error()}} throw {error:{message:`Not supported for: ${account}`, instance:new Error()}}
if ((q.repo)&&(!meta.supports?.includes("repository")))
throw {error:{message:`Not supported for: ${account} repositories`, instance:new Error()}}
} }
//Inputs checks //Inputs checks
const result = Object.fromEntries(Object.entries(inputs).map(([key, {type, format, default:defaulted, min, max, values}]) => [ const result = Object.fromEntries(Object.entries(inputs).map(([key, {type, format, default:defaulted, min, max, values}]) => [

View File

@@ -8,11 +8,9 @@
import axios from "axios" import axios from "axios"
import puppeteer from "puppeteer" import puppeteer from "puppeteer"
import imgb64 from "image-to-base64" import imgb64 from "image-to-base64"
import dayjs from "dayjs" import git from "simple-git"
import utc from "dayjs/plugin/utc.js"
dayjs.extend(utc)
export {fs, os, paths, url, util, processes, axios, puppeteer, imgb64, dayjs} export {fs, os, paths, url, util, processes, axios, puppeteer, imgb64, git}
/**Returns module __dirname */ /**Returns module __dirname */
export function __module(module) { export function __module(module) {
@@ -60,6 +58,12 @@
} }
format.ellipsis = ellipsis format.ellipsis = ellipsis
/**Date formatter */
export function date(string, options) {
return new Intl.DateTimeFormat("en-GB", options).format(new Date(string))
}
format.date = date
/**Array shuffler */ /**Array shuffler */
export function shuffle(array) { export function shuffle(array) {
for (let i = array.length-1; i > 0; i--) { for (let i = array.length-1; i > 0; i--) {
@@ -90,7 +94,9 @@
} }
/**Run command */ /**Run command */
export async function run(command, options) { export async function run(command, options, {prefixed = true} = {}) {
const prefix = {win32:"wsl"}[process.platform] ?? ""
command = `${prefixed ? prefix : ""} ${command}`.trim()
return new Promise((solve, reject) => { return new Promise((solve, reject) => {
console.debug(`metrics/command > ${command}`) console.debug(`metrics/command > ${command}`)
const child = processes.exec(command, options) const child = processes.exec(command, options)
@@ -104,6 +110,19 @@
}) })
} }
/**Check command existance */
export async function which(command) {
try {
console.debug(`metrics/command > checking existence of ${command}`)
await run(`which ${command}`)
return true
}
catch {
console.debug(`metrics/command > checking existence of ${command} > failed`)
}
return false
}
/**Render svg */ /**Render svg */
export async function svgresize(svg, {paddings = ["6%"], convert} = {}) { export async function svgresize(svg, {paddings = ["6%"], convert} = {}) {
//Instantiate browser if needed //Instantiate browser if needed

View File

@@ -42,6 +42,7 @@ query BaseRepositories {
} }
forkCount forkCount
licenseInfo { licenseInfo {
name
spdxId spdxId
} }
} }

View File

@@ -41,6 +41,7 @@ query BaseRepository {
} }
forkCount forkCount
licenseInfo { licenseInfo {
name
spdxId spdxId
} }
} }

View File

@@ -83,8 +83,7 @@
if (charts) { if (charts) {
//Check if linguist exists //Check if linguist exists
console.debug(`metrics/compute/${login}/plugins > habits > searching recently used languages using linguist`) console.debug(`metrics/compute/${login}/plugins > habits > searching recently used languages using linguist`)
const prefix = {win32:"wsl"}[process.platform] ?? "" if ((patches.length)&&(await imports.which("github-linguist"))) {
if ((patches.length)&&(await imports.run(`${prefix} which github-linguist`))) {
//Setup for linguist //Setup for linguist
habits.linguist.available = true habits.linguist.available = true
const path = imports.paths.join(imports.os.tmpdir(), `${commits[0]?.actor?.id ?? 0}`) const path = imports.paths.join(imports.os.tmpdir(), `${commits[0]?.actor?.id ?? 0}`)
@@ -94,15 +93,18 @@
await Promise.all(patches.map(({name, patch}, i) => imports.fs.writeFile(imports.paths.join(path, `${i}${imports.paths.extname(name)}`), patch))) await Promise.all(patches.map(({name, patch}, i) => imports.fs.writeFile(imports.paths.join(path, `${i}${imports.paths.extname(name)}`), patch)))
//Create temporary git repository //Create temporary git repository
console.debug(`metrics/compute/${login}/plugins > habits > creating temp git repository`) console.debug(`metrics/compute/${login}/plugins > habits > creating temp git repository`)
await imports.run('git init && git add . && git config user.name "linguist" && git config user.email "<>" && git commit -m "linguist"', {cwd:path}).catch(console.debug) const git = await imports.git(path)
await imports.run("git status", {cwd:path}) await git.init().add(".").addConfig("user.name", "linguist").addConfig("user.email", "<>").commit("linguist").status()
//Spawn linguist process //Spawn linguist process
console.debug(`metrics/compute/${login}/plugins > habits > running linguist`) console.debug(`metrics/compute/${login}/plugins > habits > running linguist`)
;(await imports.run(`${prefix} github-linguist --breakdown`, {cwd:path})) ;(await imports.run("github-linguist --breakdown", {cwd:path}))
//Parse linguist result //Parse linguist result
.split("\n").map(line => line.match(/(?<value>[\d.]+)%\s+(?<language>[\s\S]+)$/)?.groups).filter(line => line) .split("\n").map(line => line.match(/(?<value>[\d.]+)%\s+(?<language>[\s\S]+)$/)?.groups).filter(line => line)
.map(({value, language}) => habits.linguist.languages[language] = (habits.linguist.languages[language] ?? 0) + value/100) .map(({value, language}) => habits.linguist.languages[language] = (habits.linguist.languages[language] ?? 0) + value/100)
habits.linguist.ordered = Object.entries(habits.linguist.languages).sort(([_an, a], [_bn, b]) => b - a) habits.linguist.ordered = Object.entries(habits.linguist.languages).sort(([_an, a], [_bn, b]) => b - a)
//Cleaning
console.debug(`metrics/compute/${login}/plugins > habits > cleaning temp dir ${path}`)
await imports.fs.rmdir(path, {recursive:true})
} }
else else
console.debug(`metrics/compute/${login}/plugins > habits > linguist not available`) console.debug(`metrics/compute/${login}/plugins > habits > linguist not available`)

View File

@@ -154,7 +154,7 @@
name:track.name, name:track.name,
artist:track.artists[0].name, artist:track.artists[0].name,
artwork:track.album.images[0].url, artwork:track.album.images[0].url,
played_at:played_at ? imports.dayjs(played_at).format("[played at] HH:MM on DD/MM/YYYY") : null, played_at:played_at ? `${imports.date(played_at, {timeStyle:"short", timeZone:data.config.timezone?.name})} on ${imports.date(played_at, {dateStyle:"short", timeZone:data.config.timezone?.name})}` : null,
})) }))
//Ensure no duplicate are added //Ensure no duplicate are added
for (const track of loaded) { for (const track of loaded) {

View File

@@ -27,7 +27,7 @@
<div class="name"><%= name %></div> <div class="name"><%= name %></div>
<div class="artist"><%= artist %></div> <div class="artist"><%= artist %></div>
<% if (plugins.music.played_at) { %> <% if (plugins.music.played_at) { %>
<div class="played-at"><%= played_at %></div> <div class="played-at">[played at] <%= played_at %></div>
<% } %> <% } %>
</div> </div>
</div> </div>