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/**
- .gitignore
- .gitattributes
- .eslintrc.yml
- SECURITY.md
- LICENSE
- CONTRIBUTING.md

5
package-lock.json generated
View File

@@ -2185,11 +2185,6 @@
"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": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",

View File

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

View File

@@ -60,10 +60,8 @@
if (!account)
logger(`metrics/inputs > account type not set for plugin ${name}!`)
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()}}
if ((q.repo)&&(!meta.supports?.includes("repository")))
throw {error:{message:`Not supported for: ${account} repositories`, instance:new Error()}}
}
//Inputs checks
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 puppeteer from "puppeteer"
import imgb64 from "image-to-base64"
import dayjs from "dayjs"
import utc from "dayjs/plugin/utc.js"
dayjs.extend(utc)
import git from "simple-git"
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 */
export function __module(module) {
@@ -60,6 +58,12 @@
}
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 */
export function shuffle(array) {
for (let i = array.length-1; i > 0; i--) {
@@ -90,7 +94,9 @@
}
/**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) => {
console.debug(`metrics/command > ${command}`)
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 */
export async function svgresize(svg, {paddings = ["6%"], convert} = {}) {
//Instantiate browser if needed

View File

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

View File

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

View File

@@ -83,8 +83,7 @@
if (charts) {
//Check if linguist exists
console.debug(`metrics/compute/${login}/plugins > habits > searching recently used languages using linguist`)
const prefix = {win32:"wsl"}[process.platform] ?? ""
if ((patches.length)&&(await imports.run(`${prefix} which github-linguist`))) {
if ((patches.length)&&(await imports.which("github-linguist"))) {
//Setup for linguist
habits.linguist.available = true
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)))
//Create temporary 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)
await imports.run("git status", {cwd:path})
const git = await imports.git(path)
await git.init().add(".").addConfig("user.name", "linguist").addConfig("user.email", "<>").commit("linguist").status()
//Spawn linguist process
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
.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)
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
console.debug(`metrics/compute/${login}/plugins > habits > linguist not available`)

View File

@@ -154,7 +154,7 @@
name:track.name,
artist:track.artists[0].name,
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
for (const track of loaded) {

View File

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