Add support to generate charts in habits plugin (#26)

* Add charts to habits plugin
* Dockerfile update
* Add support for dflags
This commit is contained in:
Simon Lecoq authored and GitHub committed 2020-12-23 00:10:46 +01:00
1 parent 5335ef69a1
commit 25a82b319b
13 files changed
+341 -73

No files matched your search

+15
View File
@@ -165,6 +165,21 @@ jobs:
base: ""
plugins_errors_fatal: yes
plugin_habits: yes
plugin_habits_from: 5
- name: ${{ matrix.template }} > Plugin > Habits (charts)
uses: lowlighter/metrics@master
with:
token: ${{ secrets.METRICS_TOKEN }}
dryrun: yes
repositories: 1
template: ${{ matrix.template }}
base: ""
plugins_errors_fatal: yes
plugin_habits: yes
plugin_habits_from: 5
plugin_habits_facts: no
plugin_habits_charts: yes
- name: ${{ matrix.template }} > Plugin > Languages
uses: lowlighter/metrics@master
+17 -13
View File
@@ -1,25 +1,29 @@
# Based on https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md#running-puppeteer-in-docker
# Base image
FROM node:15-slim
FROM node:15-buster-slim
# Install latest chrome dev package and fonts to support major charsets
RUN apt-get update \
# Copy GitHub action
COPY action/dist/index.js /index.js
# Setup
RUN chmod +x /index.js \
# Install latest chrome dev package, fonts to support major charsets and skip chromium download on puppeteer install
# Based on https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md#running-puppeteer-in-docker
&& apt-get update \
&& apt-get install -y wget gnupg ca-certificates libgconf-2-4 \
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libxss1 \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# Uncomment to skip the chromium download when installing puppeteer
&& rm -rf /var/lib/apt/lists/* \
# Install ruby to support linguist
# Based on https://github.com/github/linguist
&& apt-get update \
&& apt-get install -y ruby-full \
&& apt-get install -y git g++ cmake pkg-config libicu-dev zlib1g-dev libcurl4-openssl-dev libssl-dev ruby-dev \
&& gem install github-linguist
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true
ENV PUPPETEER_BROWSER_PATH "google-chrome-stable"
# Copy action
COPY action/dist/index.js /index.js
RUN chmod +x /index.js
# Execute action
# Execute GitHub action
ENTRYPOINT node /index.js
+34 -13
View File
@@ -98,16 +98,32 @@ inputs:
default: no
# Coding habits plugin
# Search in your recent activity what've recently did and deduce tidbits like if you're using spaces or tabs as indents, etc.
# Search in your recent activity what've recently did and deduce facts/charts
plugin_habits:
description: Enable coding habits metrics
default: no
# Number of activity events to base habits on
# Maximum number of events is capped to 100
# Capped to 1000
plugin_habits_from:
description: Number of activity events to use
default: 100
default: 200
# Number of days to base habits on (older events will be discarded)
# Capped to 30
plugin_habits_days:
description: Number of days to use
default: 14
# Display tidbits about your active hours/days, indent used (spaces/tabs), etc. deduced from recent activity
plugin_habits_facts:
description: Display habits facts based on recent activity
default: yes
# Display charts of most active time of the day and languages recently used
plugin_habits_charts:
description: Display recent coding activity charts
default: no
# Languages plugins
# Compute the most used programming languages on your repositories
@@ -266,10 +282,10 @@ inputs:
description: Number of tweets to display
default: 2
# Enable debug mode
# Ensure you correctly put all sensitive informations in your repository secrets before !
debug:
description: Enable debug logs
# When enabled, any plugins errors will throw
# By default, metrics are still generated with an error message
plugins_errors_fatal:
description: Die on plugins errors
default: no
# Verify SVG after generation
@@ -278,14 +294,19 @@ inputs:
description: Verify SVG after genaration
default: no
# Enable debug mode
# Ensure you correctly put all sensitive informations in your repository secrets before !
debug:
description: Enable debug logs
default: no
# Debug flags (used for testing)
debug_flags:
description: Debug flags
default: ""
# Enable dry-run mode
# Generate image but does not push it (used for testing)
dryrun:
description: Enable dry-run
default: no
# When enabled, any plugins errors will throw
# By default, metrics are still generated with an error message
plugins_errors_fatal:
description: Die on plugins errors
default: no
+5 -5
View File
@@ -1,4 +1,4 @@
module.exports=(()=>{var _Mathhypot=Math.hypot,_Mathacos=Math.acos,_Mathtan=Math.tan,_Mathasin=Math.asin,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathsqrt=Math.sqrt,_NumberisInteger=Number.isInteger,_Stringprototype=String.prototype,_NumberPOSITIVE_INFINITY=Number.POSITIVE_INFINITY,_NumberNEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,_NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,_Mathround=Math.round,_StringfromCharCode=String.fromCharCode,_Mathabs=Math.abs,_Mathpow=Math.pow,_Mathceil=Math.ceil,_Mathfloor=Math.floor,_Mathmax=Math.max,_Mathmin=Math.min;function __webpack_require__(e){if(__webpack_module_cache__[e])return __webpack_module_cache__[e].exports;var t=__webpack_module_cache__[e]={exports:{}},r=!0;try{__webpack_modules__[e].call(t.exports,t,t.exports,__webpack_require__),r=!1}finally{r&&delete __webpack_module_cache__[e]}return t.exports}var __webpack_modules__={19935:(e,t,r)=>{"use strict";async function n({log:e=!0}={}){const t=e?console.debug:()=>null;t(`metrics/setup > setup`);const n="src/templates",a={templates:{},settings:{},statics:r.ab+"html",node_modules:y.resolve("node_modules")};if(t(`metrics/setup > load settings.json`),f.existsSync(r.ab+"settings.json")?(a.settings=JSON.parse(`${await f.promises.readFile(y.resolve("settings.json"))}`),t(`metrics/setup > load settings.json > success`)):t(`metrics/setup > load settings.json > (missing)`),a.settings.templates||(a.settings.templates={default:"classic",enabled:[]}),a.settings.plugins||(a.settings.plugins={}),a.settings.plugins.base={parts:["header","activity","community","repositories","metadata"]},a.settings.debug&&t(a.settings),t(`metrics/setup > load package.json`),f.existsSync(r.ab+"package.json")?(a.package=JSON.parse(`${await f.promises.readFile(y.resolve("package.json"))}`),t(`metrics/setup > load package.json > success`)):(t(`metrics/setup > load package.json > (missing)`),a.package={version:"2.9.0-beta",author:"lowlighter"}),f.existsSync(r.ab+"templates"))for(const e of await f.promises.readdir(n)){if(/.*[.]mjs$/.test(e))continue;t(`metrics/setup > load template [${e}]`);const r=[`${n}/${e}/query.graphql`,`${n}/${e}/image.svg`,`${n}/${e}/style.css`,`${n}/${e}/fonts.css`],[o,i,s,l]=await Promise.all(r.map(async e=>`${await f.promises.readFile(y.resolve(e))}`));a.templates[e]={query:o,image:i,style:s,fonts:l},t(`metrics/setup > load template [${e}] > success`),a.settings.debug&&Object.defineProperty(a.templates,e,{get(){t(`metrics/setup > reload template [${e}]`);const[n,a,o,i]=r.map(e=>`${f.readFileSync(y.resolve(e))}`);return t(`metrics/setup > reload template [${e}] > success`),{query:n,image:a,style:o,fonts:i}}})}else t(`metrics/setup > load templates from build`),a.templates=JSON.parse(Buffer.from(`eyJjbGFzc2ljIjp7InF1ZXJ5IjoicXVlcnkgTWV0cmljcyB7XHJcbiAgdXNlcihsb2dpbjogJGxvZ2luKSB7XHJcbiAgICBkYXRhYmFzZUlkXHJcbiAgICBuYW1lXHJcbiAgICBsb2dpblxyXG4gICAgY3JlYXRlZEF0XHJcbiAgICBhdmF0YXJVcmxcclxuICAgIHdlYnNpdGVVcmxcclxuICAgIGlzSGlyZWFibGVcclxuICAgIHR3aXR0ZXJVc2VybmFtZVxyXG4gICAgZ2lzdHMge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICByZXBvc2l0b3JpZXMobGFzdDogJHJlcG9zaXRvcmllcywgaXNGb3JrOiBmYWxzZSwgb3duZXJBZmZpbGlhdGlvbnM6IE9XTkVSKSB7XHJcbiAgICAgIHRvdGFsQ291bnRcclxuICAgICAgdG90YWxEaXNrVXNhZ2VcclxuICAgICAgbm9kZXMge1xyXG4gICAgICAgIG5hbWVcclxuICAgICAgICB3YXRjaGVycyB7XHJcbiAgICAgICAgICB0b3RhbENvdW50XHJcbiAgICAgICAgfVxyXG4gICAgICAgIHN0YXJnYXplcnMge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBsYW5ndWFnZXMoZmlyc3Q6IDQpIHtcclxuICAgICAgICAgIGVkZ2VzIHtcclxuICAgICAgICAgICAgc2l6ZVxyXG4gICAgICAgICAgICBub2RlIHtcclxuICAgICAgICAgICAgICBjb2xvclxyXG4gICAgICAgICAgICAgIG5hbWVcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBpc3N1ZXNfb3BlbjogaXNzdWVzKHN0YXRlczogT1BFTikge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBpc3N1ZXNfY2xvc2VkOiBpc3N1ZXMoc3RhdGVzOiBDTE9TRUQpIHtcclxuICAgICAgICAgIHRvdGFsQ291bnRcclxuICAgICAgICB9XHJcbiAgICAgICAgcHJfb3BlbjogcHVsbFJlcXVlc3RzKHN0YXRlczogT1BFTikge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBwcl9tZXJnZWQ6IHB1bGxSZXF1ZXN0cyhzdGF0ZXM6IE1FUkdFRCkge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICByZWxlYXNlcyB7XHJcbiAgICAgICAgICB0b3RhbENvdW50XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGZvcmtDb3VudFxyXG4gICAgICAgIGxpY2Vuc2VJbmZvIHtcclxuICAgICAgICAgIHNwZHhJZFxyXG4gICAgICAgIH1cclxuICAgICAgfVxyXG4gICAgfVxyXG4gICAgcGFja2FnZXMge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzdGFycmVkUmVwb3NpdG9yaWVzIHtcclxuICAgICAgdG90YWxDb3VudFxyXG4gICAgfVxyXG4gICAgd2F0Y2hpbmcge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzcG9uc29yc2hpcHNBc1Nwb25zb3Ige1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzcG9uc29yc2hpcHNBc01haW50YWluZXIge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBjb250cmlidXRpb25zQ29sbGVjdGlvbiB7XHJcbiAgICAgIHRvdGFsUmVwb3NpdG9yaWVzV2l0aENvbnRyaWJ1dGVkQ29tbWl0c1xyXG4gICAgICB0b3RhbENvbW1pdENvbnRyaWJ1dGlvbnNcclxuICAgICAgcmVzdHJpY3RlZENvbnRyaWJ1dGlvbnNDb3VudFxyXG4gICAgICB0b3RhbElzc3VlQ29udHJpYnV0aW9uc1xyXG4gICAgICB0b3RhbFB1b Line truncated
module.exports=(()=>{var _Mathhypot=Math.hypot,_Mathacos=Math.acos,_Mathtan=Math.tan,_Mathasin=Math.asin,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathsqrt=Math.sqrt,_NumberisInteger=Number.isInteger,_Stringprototype=String.prototype,_NumberPOSITIVE_INFINITY=Number.POSITIVE_INFINITY,_NumberNEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,_NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,_Mathround=Math.round,_StringfromCharCode=String.fromCharCode,_Mathabs=Math.abs,_Mathpow=Math.pow,_Mathfloor=Math.floor,_Mathceil=Math.ceil,_Mathmax=Math.max,_Mathmin=Math.min;function __webpack_require__(e){if(__webpack_module_cache__[e])return __webpack_module_cache__[e].exports;var t=__webpack_module_cache__[e]={exports:{}},r=!0;try{__webpack_modules__[e].call(t.exports,t,t.exports,__webpack_require__),r=!1}finally{r&&delete __webpack_module_cache__[e]}return t.exports}var __webpack_modules__={45274:(e,t,r)=>{"use strict";async function n({log:e=!0}={}){const t=e?console.debug:()=>null;t(`metrics/setup > setup`);const n="src/templates",a={templates:{},settings:{},statics:r.ab+"html",node_modules:b.resolve("node_modules")};if(t(`metrics/setup > load settings.json`),y.existsSync(r.ab+"settings.json")?(a.settings=JSON.parse(`${await y.promises.readFile(b.resolve("settings.json"))}`),t(`metrics/setup > load settings.json > success`)):t(`metrics/setup > load settings.json > (missing)`),a.settings.templates||(a.settings.templates={default:"classic",enabled:[]}),a.settings.plugins||(a.settings.plugins={}),a.settings.plugins.base={parts:["header","activity","community","repositories","metadata"]},a.settings.debug&&t(a.settings),t(`metrics/setup > load package.json`),y.existsSync(r.ab+"package.json")?(a.package=JSON.parse(`${await y.promises.readFile(b.resolve("package.json"))}`),t(`metrics/setup > load package.json > success`)):(t(`metrics/setup > load package.json > (missing)`),a.package={version:"2.9.0-beta",author:"lowlighter"}),y.existsSync(r.ab+"templates"))for(const e of await y.promises.readdir(n)){if(/.*[.]mjs$/.test(e))continue;t(`metrics/setup > load template [${e}]`);const r=[`${n}/${e}/query.graphql`,`${n}/${e}/image.svg`,`${n}/${e}/style.css`,`${n}/${e}/fonts.css`],[o,i,s,l]=await Promise.all(r.map(async e=>`${await y.promises.readFile(b.resolve(e))}`));a.templates[e]={query:o,image:i,style:s,fonts:l},t(`metrics/setup > load template [${e}] > success`),a.settings.debug&&Object.defineProperty(a.templates,e,{get(){t(`metrics/setup > reload template [${e}]`);const[n,a,o,i]=r.map(e=>`${y.readFileSync(b.resolve(e))}`);return t(`metrics/setup > reload template [${e}] > success`),{query:n,image:a,style:o,fonts:i}}})}else t(`metrics/setup > load templates from build`),a.templates=JSON.parse(Buffer.from(`eyJjbGFzc2ljIjp7InF1ZXJ5IjoicXVlcnkgTWV0cmljcyB7XHJcbiAgdXNlcihsb2dpbjogJGxvZ2luKSB7XHJcbiAgICBkYXRhYmFzZUlkXHJcbiAgICBuYW1lXHJcbiAgICBsb2dpblxyXG4gICAgY3JlYXRlZEF0XHJcbiAgICBhdmF0YXJVcmxcclxuICAgIHdlYnNpdGVVcmxcclxuICAgIGlzSGlyZWFibGVcclxuICAgIHR3aXR0ZXJVc2VybmFtZVxyXG4gICAgZ2lzdHMge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICByZXBvc2l0b3JpZXMobGFzdDogJHJlcG9zaXRvcmllcywgaXNGb3JrOiBmYWxzZSwgb3duZXJBZmZpbGlhdGlvbnM6IE9XTkVSKSB7XHJcbiAgICAgIHRvdGFsQ291bnRcclxuICAgICAgdG90YWxEaXNrVXNhZ2VcclxuICAgICAgbm9kZXMge1xyXG4gICAgICAgIG5hbWVcclxuICAgICAgICB3YXRjaGVycyB7XHJcbiAgICAgICAgICB0b3RhbENvdW50XHJcbiAgICAgICAgfVxyXG4gICAgICAgIHN0YXJnYXplcnMge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBsYW5ndWFnZXMoZmlyc3Q6IDQpIHtcclxuICAgICAgICAgIGVkZ2VzIHtcclxuICAgICAgICAgICAgc2l6ZVxyXG4gICAgICAgICAgICBub2RlIHtcclxuICAgICAgICAgICAgICBjb2xvclxyXG4gICAgICAgICAgICAgIG5hbWVcclxuICAgICAgICAgICAgfVxyXG4gICAgICAgICAgfVxyXG4gICAgICAgIH1cclxuICAgICAgICBpc3N1ZXNfb3BlbjogaXNzdWVzKHN0YXRlczogT1BFTikge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBpc3N1ZXNfY2xvc2VkOiBpc3N1ZXMoc3RhdGVzOiBDTE9TRUQpIHtcclxuICAgICAgICAgIHRvdGFsQ291bnRcclxuICAgICAgICB9XHJcbiAgICAgICAgcHJfb3BlbjogcHVsbFJlcXVlc3RzKHN0YXRlczogT1BFTikge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICBwcl9tZXJnZWQ6IHB1bGxSZXF1ZXN0cyhzdGF0ZXM6IE1FUkdFRCkge1xyXG4gICAgICAgICAgdG90YWxDb3VudFxyXG4gICAgICAgIH1cclxuICAgICAgICByZWxlYXNlcyB7XHJcbiAgICAgICAgICB0b3RhbENvdW50XHJcbiAgICAgICAgfVxyXG4gICAgICAgIGZvcmtDb3VudFxyXG4gICAgICAgIGxpY2Vuc2VJbmZvIHtcclxuICAgICAgICAgIHNwZHhJZFxyXG4gICAgICAgIH1cclxuICAgICAgfVxyXG4gICAgfVxyXG4gICAgcGFja2FnZXMge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzdGFycmVkUmVwb3NpdG9yaWVzIHtcclxuICAgICAgdG90YWxDb3VudFxyXG4gICAgfVxyXG4gICAgd2F0Y2hpbmcge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzcG9uc29yc2hpcHNBc1Nwb25zb3Ige1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBzcG9uc29yc2hpcHNBc01haW50YWluZXIge1xyXG4gICAgICB0b3RhbENvdW50XHJcbiAgICB9XHJcbiAgICBjb250cmlidXRpb25zQ29sbGVjdGlvbiB7XHJcbiAgICAgIHRvdGFsUmVwb3NpdG9yaWVzV2l0aENvbnRyaWJ1dGVkQ29tbWl0c1xyXG4gICAgICB0b3RhbENvbW1pdENvbnRyaWJ1dGlvbnNcclxuICAgICAgcmVzdHJpY3RlZENvbnRyaWJ1dGlvbnNDb3VudFxyXG4gICAgICB0b3RhbElzc3VlQ29udHJpYnV0aW9uc1xyXG4gICAgICB0b3RhbFB1b Line truncated
query Gists {
user(login: "${e}") {
gists(last: 100) {
@@ -16,7 +16,7 @@ module.exports=(()=>{var _Mathhypot=Math.hypot,_Mathacos=Math.acos,_Mathtan=Math
}
}
}
`);let o=0,i=0,s=0;for(const e of a.nodes)e.isFork||(o+=e.stargazerCount,i+=e.forks.totalCount,s+=e.comments.totalCount);return{totalCount:a.totalCount,stargazers:o,forks:i,comments:s}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},habits:async function({login:e,rest:t,q:r},{enabled:n=!1,from:a=100}={}){try{if(!n||!r.habits)return null;let{"habits.from":o=a.from??100}=r;o=_Mathmax(1,_Mathmin(100,+o));const i={commits:{hour:NaN,hours:{}},indents:{style:"",spaces:0,tabs:0}},s=await t.activity.listEventsForAuthenticatedUser({username:e,per_page:o}),l=s.data.filter(({type:e})=>"PushEvent"===e).filter(({actor:t})=>t.login===e);{const e=l.map(({created_at:e})=>new Date(e).getHours());for(const t of e)i.commits.hours[t]=(i.commits.hours[t]??0)+1;i.commits.hour=e.length?`${Object.entries(i.commits.hours).sort(([e,t],[r,n])=>n-t).map(([e,t])=>e)[0]}`.padStart(2,"0"):NaN}{const e=await Promise.allSettled(l.flatMap(({payload:e})=>e.commits).map(e=>e.url).map(async e=>(await t.request(e)).data.files));e.filter(({status:e})=>"fulfilled"===e).map(({value:e})=>e).flatMap(e=>e.flatMap(e=>(e.patch??"").match(/(?<=^[+])((?:\t)|(?: )) /gm)??[])).forEach(e=>i.indents[/^\t/.test(e)?"tabs":"spaces"]++),i.indents.style=i.indents.spaces>i.indents.tabs?"spaces":i.indents.tabs>i.indents.spaces?"tabs":""}return i}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},isocalendar:async function({login:e,graphql:t,q:r},{enabled:n=!1}={}){try{if(!n||!r.isocalendar)return null;let{"isocalendar.duration":a="half-year"}=r;a=["full-year","half-year"].includes(a)?a:"full-year";const o=new Date,s=new Date(o);"full-year"===a?s.setFullYear(o.getFullYear()-1):s.setHours(-4320);const l=new Date(s);l.setHours(-336);const d={};for(const[r,n,a]of[["padding",l,s],["weeks",s,o]]){console.debug(`metrics/compute/${e}/plugins > isocalendar > loading "${r}" from "${n.toISOString()}" to "${a.toISOString()}"`);const{user:{calendar:{contributionCalendar:{weeks:o}}}}=await t(`
`);let o=0,i=0,s=0;for(const e of a.nodes)e.isFork||(o+=e.stargazerCount,i+=e.forks.totalCount,s+=e.comments.totalCount);return{totalCount:a.totalCount,stargazers:o,forks:i,comments:s}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},habits:async function({login:e,rest:t,imports:r,q:n},{enabled:a=!1,from:o=100}={}){try{if(!a||!n.habits)return null;let{"habits.from":i=o.from??500,"habits.days":s=30,"habits.facts":l=!0,"habits.charts":d=!1}=n;i=_Mathmax(1,_Mathmin(1e3,+i)),s=_Mathmax(1,_Mathmin(30,+i));const p={facts:l,charts:d,commits:{hour:NaN,hours:{},day:NaN,days:{}},indents:{style:"",spaces:0,tabs:0},linguist:{available:!1,ordered:[],languages:{}}},c=_Mathceil(i/100),u=[];try{for(let r=0;r<c;r++)console.debug(`metrics/compute/${e}/plugins > habits > loaded page ${r}`),u.push(...(await t.activity.listEventsForAuthenticatedUser({username:e,per_page:100,page:r})).data)}catch{console.debug(`metrics/compute/${e}/plugins > habits > no more events to load`)}console.debug(`metrics/compute/${e}/plugins > habits > no more events to load (${u.length} loaded)`);const m=u.filter(({type:e})=>"PushEvent"===e).filter(({actor:t})=>t.login===e).filter(({created_at:e})=>new Date(e)>new Date(Date.now()-1e3*(60*(60*(24*s)))));console.debug(`metrics/compute/${e}/plugins > habits > filtered out ${m.length} commits`);const g=m[0]?.actor?.id??0,h=[...(await Promise.allSettled(m.flatMap(({payload:e})=>e.commits).map(e=>e.url).map(async e=>(await t.request(e)).data.files)))].filter(({status:e})=>"fulfilled"===e).map(({value:e})=>e).flatMap(e=>e.map(e=>({name:r.paths.basename(e.filename),patch:e.patch??""}))).map(({name:e,patch:t})=>({name:e,patch:t.split("\n").filter(e=>/^[-+]/.test(e)).map(e=>e.substring(1)).join("\n")}));{const e=m.map(({created_at:e})=>new Date(e).getDay());for(const t of e)p.commits.days[t]=(p.commits.days[t]??0)+1;p.commits.days.max=_Mathmax(...Object.values(p.commits.days)),p.commits.day=e.length?["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][Object.entries(p.commits.days).sort(([e,t],[r,n])=>n-t).map(([e,t])=>e)[0]]??NaN:NaN}{const e=m.map(({created_at:e})=>new Date(e).getHours());for(const t of e)p.commits.hours[t]=(p.commits.hours[t]??0)+1;p.commits.hours.max=_Mathmax(...Object.values(p.commits.hours)),p.commits.hour=e.length?`${Object.entries(p.commits.hours).sort(([e,t],[r,n])=>n-t).map(([e,t])=>e)[0]}`.padStart(2,"0"):NaN}if(h.map(({patch:e})=>e.match(/((?:\t)|(?: )) /gm)??[]).forEach(e=>p.indents[/^\t/.test(e)?"tabs":"spaces"]++),p.indents.style=p.indents.spaces>p.indents.tabs?"spaces":p.indents.tabs>p.indents.spaces?"tabs":"",d){const t={win32:"wsl"}[process.platform]??"";if(await r.run(`${t} which github-linguist`)){p.linguist.available=!0;const n=r.paths.join(r.os.tmpdir(),`${g}`);await r.fs.mkdir(n,{recursive:!0}),await Promise.all(h.map(async({name:e,patch:t},a)=>await r.fs.writeFile(r.paths.join(n,`${a}${r.paths.extname(e)}`),t))),console.debug(`metrics/compute/${e}/plugins > habits > created temp dir ${n} with ${h.length} files`),await r.run(`git init && git add . && git config user.name "linguist" && git config user.email "null@github.com" && git commit -m "linguist"`,{cwd:n}).catch(console.debug),await r.run(`git status`,{cwd:n}),console.debug(`metrics/compute/${e}/plugins > habits > created temp git repository`),console.debug(`metrics/compute/${e}/plugins > habits > running linguist`),(await r.run(`${t} github-linguist`,{cwd:n})).split("\n").map(e=>e.match(/(?<value>[\d.]+)%\s+(?<language>\w+)/)?.groups).filter(e=>e).map(({value:e,language:t})=>p.linguist.languages[t]=(p.linguist.languages[t]??0)+e/100),p.linguist.ordered=Object.entries(p.linguist.languages).sort(([e,t],[r,n])=>n-t)}else console.debug(`metrics/compute/${e}/plugins > habits > linguist is not available`)}return p}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},isocalendar:async function({login:e,graphql:t,q:r},{enabled:n=!1}={}){try{if(!n||!r.isocalendar)return null;let{"isocalendar.duration":a="half-year"}=r;a=["full-year","half-year"].includes(a)?a:"full-year";const o=new Date,s=new Date(o);"full-year"===a?s.setFullYear(o.getFullYear()-1):s.setHours(-4320);const l=new Date(s);l.setHours(-336);const d={};for(const[r,n,a]of[["padding",l,s],["weeks",s,o]]){console.debug(`metrics/compute/${e}/plugins > isocalendar > loading "${r}" from "${n.toISOString()}" to "${a.toISOString()}"`);const{user:{calendar:{contributionCalendar:{weeks:o}}}}=await t(`
query Calendar {
user(login: "${e}") {
calendar:contributionsCollection(from: "${n.toISOString()}", to: "${a.toISOString()}") {
@@ -63,13 +63,13 @@ module.exports=(()=>{var _Mathhypot=Math.hypot,_Mathacos=Math.acos,_Mathtan=Math
}
}
}
`),i=[];for(const e of o.nodes){const t=(Date.now()-new Date(e.updatedAt).getTime())/86400000;let r=1>t?"less than 1 day ago":30>t?`${_Mathfloor(t)} day${2<=t?"s":""} ago`:new Date(e.updatedAt).toDateString().substring(4);const{enabled:n,todoCount:a,inProgressCount:o,doneCount:s}=e.progress;i.push({name:e.name,updated:r,progress:{enabled:n,todo:a,doing:o,done:s,total:a+o+s}})}return{list:i,totalCount:o.totalCount}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},topics:async function({login:e,imports:t,q:r},{enabled:n=!1}={}){try{if(!n||!r.topics)return null;let{"topics.sort":a="stars","topics.limit":o=15}=r;const i="random"===a;a={starred:"created",activity:"updated",stars:"stars",random:"created"}[a]??"starred",o=_Mathmax(1,_Mathmin(20,+o));let s=[];console.debug(`metrics/compute/${e}/plugins > topics > starting browser`);const l=await t.puppeteer.launch({headless:!0,executablePath:process.env.PUPPETEER_BROWSER_PATH,args:["--no-sandbox","--disable-extensions","--disable-setuid-sandbox","--disable-dev-shm-usage"]});console.debug(`metrics/compute/${e}/plugins > topics > loaded ${await l.version()}`);const d=await l.newPage();for(let t=1;100>=t;t++){console.debug(`metrics/compute/${e}/plugins > topics > loading page ${t}`),await d.goto(`https://github.com/stars/${e}/topics?direction=desc&page=${t}&sort=${a}`);const r=d.mainFrame();await Promise.race([r.waitForSelector("ul.repo-list"),r.waitForSelector(".blankslate")]);const n=await r.evaluate(()=>[...document.querySelectorAll("ul.repo-list li")].map(e=>({name:e.querySelector(".f3").innerText,description:e.querySelector(".f5").innerText,icon:e.querySelector("img")?.src??null})));if(!n.length)break;s.push(...n)}if(console.debug(`metrics/compute/${e}/plugins > music > closing browser`),await l.close(),i&&(s=t.shuffle(s)),0<o){console.debug(`metrics/compute/${e}/plugins > topics > keeping only ${o} topics`);const t=s.slice(o);s=s.slice(0,o),s.push({name:`And ${t.length} more...`,description:t.map(({name:e})=>e).join(", "),icon:null})}for(const r of s)r.icon&&(console.debug(`metrics/compute/${e}/plugins > topics > processing ${r.name}`),r.icon=await t.imgb64(r.icon)),r.description=t.htmlescape(r.description);return{list:s}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},traffic:async function({login:e,imports:t,data:r,rest:n,q:a},{enabled:o=!1}={}){try{if(!o||!a.traffic)return null;const i=r.user.repositories.nodes.map(({name:e})=>e)??[],s={count:0,uniques:0},l=await Promise.all(i.map(async t=>await n.repos.getViews({owner:e,repo:t})));return l.filter(({data:e})=>e).map(({data:{count:e,uniques:t}})=>(s.count+=e,s.uniques+=t)),s.count=t.format(s.count),s.uniques=t.format(s.uniques),{views:s}}catch(e){if(403===e.status)throw{error:{message:`Insufficient token rights`}};throw console.debug(e),{error:{message:`An error occured`}}}},tweets:async function({login:e,imports:t,data:r,q:n},{enabled:a=!1,token:o=null}={}){try{if(!a||!n.tweets)return null;let{"tweets.limit":i=2}=n;i=_Mathmax(1,_Mathmin(10,+i));const s=r.user.twitterUsername;console.debug(`metrics/compute/${e}/plugins > tweets > loading twitter profile (@${s})`);const{data:{data:l=null}}=await t.axios.get(`https://api.twitter.com/2/users/by/username/${s}?user.fields=profile_image_url,verified`,{headers:{Authorization:`Bearer ${o}`}});console.debug(`metrics/compute/${e}/plugins > tweets > loading tweets`);const{data:{data:d=[]}}=await t.axios.get(`https://api.twitter.com/2/tweets/search/recent?query=from:${s}&tweet.fields=created_at&expansions=entities.mentions.username`,{headers:{Authorization:`Bearer ${o}`}});return l?.profile_image_url&&(console.debug(`metrics/compute/${e}/plugins > tweets > loading profile image`),l.profile_image=await t.imgb64(l.profile_image_url)),0<i&&(console.debug(`metrics/compute/${e}/plugins > tweets > keeping only ${i} tweets`),d.splice(i)),await Promise.all(d.map(async r=>{r.mentions=r.entities?.mentions.map(({username:e})=>e)??[],console.debug(`metrics/compute/${e}/plugins > tweets > formatting tweet ${r.id}`),r.text=t.htmlescape(t.htmlescape(r.text,{"<":!0,">":!0}).replace(new RegExp(`@(${r.mentions.join("|")})`,"gi"),` <span class="mention">@$1</span> `).replace(/(?<!&)[#|#]([a-z0-9_\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0300-\u036f\u1e00-\u1eff\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05d0-\u05ea\u05f0-\u05f4\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u0750-\u077f\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c-\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u Line truncated
`),i=[];for(const e of o.nodes){const t=(Date.now()-new Date(e.updatedAt).getTime())/86400000;let r=1>t?"less than 1 day ago":30>t?`${_Mathfloor(t)} day${2<=t?"s":""} ago`:new Date(e.updatedAt).toDateString().substring(4);const{enabled:n,todoCount:a,inProgressCount:o,doneCount:s}=e.progress;i.push({name:e.name,updated:r,progress:{enabled:n,todo:a,doing:o,done:s,total:a+o+s}})}return{list:i,totalCount:o.totalCount}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},topics:async function({login:e,imports:t,q:r},{enabled:n=!1}={}){try{if(!n||!r.topics)return null;let{"topics.sort":a="stars","topics.limit":o=15}=r;const i="random"===a;a={starred:"created",activity:"updated",stars:"stars",random:"created"}[a]??"starred",o=_Mathmax(1,_Mathmin(20,+o));let s=[];console.debug(`metrics/compute/${e}/plugins > topics > starting browser`);const l=await t.puppeteer.launch({headless:!0,executablePath:process.env.PUPPETEER_BROWSER_PATH,args:["--no-sandbox","--disable-extensions","--disable-setuid-sandbox","--disable-dev-shm-usage"]});console.debug(`metrics/compute/${e}/plugins > topics > loaded ${await l.version()}`);const d=await l.newPage();for(let t=1;100>=t;t++){console.debug(`metrics/compute/${e}/plugins > topics > loading page ${t}`),await d.goto(`https://github.com/stars/${e}/topics?direction=desc&page=${t}&sort=${a}`);const r=d.mainFrame();await Promise.race([r.waitForSelector("ul.repo-list"),r.waitForSelector(".blankslate")]);const n=await r.evaluate(()=>[...document.querySelectorAll("ul.repo-list li")].map(e=>({name:e.querySelector(".f3").innerText,description:e.querySelector(".f5").innerText,icon:e.querySelector("img")?.src??null})));if(!n.length)break;s.push(...n)}if(console.debug(`metrics/compute/${e}/plugins > music > closing browser`),await l.close(),i&&(s=t.shuffle(s)),0<o){console.debug(`metrics/compute/${e}/plugins > topics > keeping only ${o} topics`);const t=s.slice(o);s=s.slice(0,o),s.push({name:`And ${t.length} more...`,description:t.map(({name:e})=>e).join(", "),icon:null})}for(const r of s)r.icon&&(console.debug(`metrics/compute/${e}/plugins > topics > processing ${r.name}`),r.icon=await t.imgb64(r.icon)),r.description=t.htmlescape(r.description);return{list:s}}catch(e){throw console.debug(e),{error:{message:`An error occured`}}}},traffic:async function({login:e,imports:t,data:r,rest:n,q:a},{enabled:o=!1}={}){try{if(!o||!a.traffic)return null;const i=r.user.repositories.nodes.map(({name:e})=>e)??[],s={count:0,uniques:0},l=await Promise.all(i.map(async t=>await n.repos.getViews({owner:e,repo:t})));return l.filter(({data:e})=>e).map(({data:{count:e,uniques:t}})=>(s.count+=e,s.uniques+=t)),s.count=t.format(s.count),s.uniques=t.format(s.uniques),{views:s}}catch(e){if(403===e.status)throw{error:{message:`Insufficient token rights`}};throw console.debug(e),{error:{message:`An error occured`}}}},tweets:async function({login:e,imports:t,data:r,q:n},{enabled:a=!1,token:o=null}={}){try{if(!a||!n.tweets)return null;let{"tweets.limit":i=2}=n;i=_Mathmax(1,_Mathmin(10,+i));const s=r.user.twitterUsername;console.debug(`metrics/compute/${e}/plugins > tweets > loading twitter profile (@${s})`);const{data:{data:l=null}}=await t.axios.get(`https://api.twitter.com/2/users/by/username/${s}?user.fields=profile_image_url,verified`,{headers:{Authorization:`Bearer ${o}`}});console.debug(`metrics/compute/${e}/plugins > tweets > loading tweets`);const{data:{data:d=[]}}=await t.axios.get(`https://api.twitter.com/2/tweets/search/recent?query=from:${s}&tweet.fields=created_at&expansions=entities.mentions.username`,{headers:{Authorization:`Bearer ${o}`}});return l?.profile_image_url&&(console.debug(`metrics/compute/${e}/plugins > tweets > loading profile image`),l.profile_image=await t.imgb64(l.profile_image_url)),0<i&&(console.debug(`metrics/compute/${e}/plugins > tweets > keeping only ${i} tweets`),d.splice(i)),await Promise.all(d.map(async r=>{r.mentions=r.entities?.mentions.map(({username:e})=>e)??[],console.debug(`metrics/compute/${e}/plugins > tweets > formatting tweet ${r.id}`),r.text=t.htmlescape(t.htmlescape(r.text,{"<":!0,">":!0}).replace(new RegExp(`@(${r.mentions.join("|")})`,"gi"),` <span class="mention">@$1</span> `).replace(/(?<!&)[#|#]([a-z0-9_\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0300-\u036f\u1e00-\u1eff\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05d0-\u05ea\u05f0-\u05f4\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u0750-\u077f\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c-\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u Line truncated
query Sha {
repository(owner: "${t.context.repo.owner}", name: "${t.context.repo.repo}") {
object(expression: "${r}:${m}") { ... on Blob { oid } }
}
}
`);o=e}catch(e){console.debug(e)}console.log(`Previous render sha | ${o||"none"}`),await a.repos.createOrUpdateFileContents({...t.context.repo,path:m,message:`Update ${m} - [Skip GitHub Action]`,content:Buffer.from(_).toString("base64"),...(o?{sha:o}:{})}),console.log(`Commit to repo | ok`)}console.log(`Success !`),process.exit(0)}catch(t){console.error(t),i(e.getInput("debug"))||console.log("An error occured, logging debug message :",...s),e.setFailed(t.message),process.exit(1)}})().catch(()=>process.exit(1))},12541:function(e,t,r){"use strict";function n(e,t,r){const n=new p(e,t,r);process.stdout.write(n.toString()+s.EOL)}function a(e){return l.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function o(e){return l.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const s=i(r(12087)),l=r(74332);t.issueCommand=n,t.issue=function(e,t=""){n(e,{},t)};const d="::";class p{constructor(e,t,r){e||(e="missing.command"),this.command=e,this.properties=t,this.message=r}toString(){let e=d+this.command;if(this.properties&&0<Object.keys(this.properties).length){e+=" ";let t=!0;for(const r in this.properties)if(this.properties.hasOwnProperty(r)){const n=this.properties[r];n&&(t?t=!1:e+=",",e+=`${r}=${o(n)}`)}}return e+=`${d}${a(this.message)}`,e}}},32882:function(e,t,r){"use strict";function n(e){process.exitCode=g.Failure,a(e)}function a(e){d.issue("error",e instanceof Error?e.toString():e)}function o(e){d.issue("group",e)}function i(){d.issue("endgroup")}var s=this&&this.__awaiter||function(e,t,r,n){function a(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,o){function i(e){try{l(n.next(e))}catch(t){o(t)}}function s(e){try{l(n["throw"](e))}catch(t){o(t)}}function l(e){e.done?r(e.value):a(e.value).then(i,s)}l((n=n.apply(e,t||[])).next())})},l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const d=r(12541),p=r(29582),c=r(74332),u=l(r(12087)),m=l(r(85622));var g;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(g=t.ExitCode||(t.ExitCode={})),t.exportVariable=function(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env.GITHUB_ENV||"";if(n){const t=`${e}<<${"_GitHubActionsFileCommandDelimeter_"}${u.EOL}${r}${u.EOL}${"_GitHubActionsFileCommandDelimeter_"}`;p.issueCommand("ENV",t)}else d.issueCommand("set-env",{name:e},r)},t.setSecret=function(e){d.issueCommand("add-mask",{},e)},t.addPath=function(e){const t=process.env.GITHUB_PATH||"";t?p.issueCommand("PATH",e):d.issueCommand("add-path",{},e),process.env.PATH=`${e}${m.delimiter}${process.env.PATH}`},t.getInput=function(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r)throw new Error(`Input required and not supplied: ${e}`);return r.trim()},t.setOutput=function(e,t){d.issueCommand("set-output",{name:e},t)},t.setCommandEcho=function(e){d.issue("echo",e?"on":"off")},t.setFailed=n,t.isDebug=function(){return"1"===process.env.RUNNER_DEBUG},t.debug=function(e){d.issueCommand("debug",{},e)},t.error=a,t.warning=function(e){d.issue("warning",e instanceof Error?e.toString():e)},t.info=function(e){process.stdout.write(e+u.EOL)},t.startGroup=o,t.endGroup=i,t.group=function(e,t){return s(this,void 0,void 0,function*(){o(e);let r;try{r=yield t()}finally{i()}return r})},t.saveState=function(e,t){d.issueCommand("save-state",{name:e},t)},t.getState=function(e){return process.env[`STATE_${e}`]||""}},29582:function(e,t,r){"use strict";var n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const a=n(r(35747)),o=n(r(12087)),i=r(74332);t.issueCommand=function(e,t){const r=process.env[`GITHUB_${e}`];if(!r)throw new Error(`Unable to find environment variable for file command ${e}`);if(!a.existsSync(r))throw new Error(`Missing file at path: ${r}`);a.appendFileSync(r,`${i.toCommandValue(t)}${o.EOL}`,{encoding:"utf8"})}},74332:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toCommandValue=function(e){return null===e||void 0===e?"":"string"==typeof e||e instanceof String?e:JSON.stringify(e)}},84873:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Context=void 0;const n=r(35747),a=r(12087);class o{constructor(){if(this.payload={},process.env.GITHUB_EVENT_PATH)if(n.existsSync(process.env.GITHUB_EVENT_PATH))this.payload=JSON.parse(n.readFileSync(pro Line truncated
`);o=e}catch(e){console.debug(e)}console.log(`Previous render sha | ${o||"none"}`),await a.repos.createOrUpdateFileContents({...t.context.repo,path:m,message:`Update ${m} - [Skip GitHub Action]`,content:Buffer.from(w).toString("base64"),...(o?{sha:o}:{})}),console.log(`Commit to repo | ok`)}console.log(`Success !`),process.exit(0)}catch(t){console.error(t),i(e.getInput("debug"))||console.log("An error occured, logging debug message :",...s),e.setFailed(t.message),process.exit(1)}})().catch(()=>process.exit(1))},12541:function(e,t,r){"use strict";function n(e,t,r){const n=new p(e,t,r);process.stdout.write(n.toString()+s.EOL)}function a(e){return l.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function o(e){return l.toCommandValue(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}var i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const s=i(r(12087)),l=r(74332);t.issueCommand=n,t.issue=function(e,t=""){n(e,{},t)};const d="::";class p{constructor(e,t,r){e||(e="missing.command"),this.command=e,this.properties=t,this.message=r}toString(){let e=d+this.command;if(this.properties&&0<Object.keys(this.properties).length){e+=" ";let t=!0;for(const r in this.properties)if(this.properties.hasOwnProperty(r)){const n=this.properties[r];n&&(t?t=!1:e+=",",e+=`${r}=${o(n)}`)}}return e+=`${d}${a(this.message)}`,e}}},32882:function(e,t,r){"use strict";function n(e){process.exitCode=g.Failure,a(e)}function a(e){d.issue("error",e instanceof Error?e.toString():e)}function o(e){d.issue("group",e)}function i(){d.issue("endgroup")}var s=this&&this.__awaiter||function(e,t,r,n){function a(e){return e instanceof r?e:new r(function(t){t(e)})}return new(r||(r=Promise))(function(r,o){function i(e){try{l(n.next(e))}catch(t){o(t)}}function s(e){try{l(n["throw"](e))}catch(t){o(t)}}function l(e){e.done?r(e.value):a(e.value).then(i,s)}l((n=n.apply(e,t||[])).next())})},l=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const d=r(12541),p=r(29582),c=r(74332),u=l(r(12087)),m=l(r(85622));var g;(function(e){e[e.Success=0]="Success",e[e.Failure=1]="Failure"})(g=t.ExitCode||(t.ExitCode={})),t.exportVariable=function(e,t){const r=c.toCommandValue(t);process.env[e]=r;const n=process.env.GITHUB_ENV||"";if(n){const t=`${e}<<${"_GitHubActionsFileCommandDelimeter_"}${u.EOL}${r}${u.EOL}${"_GitHubActionsFileCommandDelimeter_"}`;p.issueCommand("ENV",t)}else d.issueCommand("set-env",{name:e},r)},t.setSecret=function(e){d.issueCommand("add-mask",{},e)},t.addPath=function(e){const t=process.env.GITHUB_PATH||"";t?p.issueCommand("PATH",e):d.issueCommand("add-path",{},e),process.env.PATH=`${e}${m.delimiter}${process.env.PATH}`},t.getInput=function(e,t){const r=process.env[`INPUT_${e.replace(/ /g,"_").toUpperCase()}`]||"";if(t&&t.required&&!r)throw new Error(`Input required and not supplied: ${e}`);return r.trim()},t.setOutput=function(e,t){d.issueCommand("set-output",{name:e},t)},t.setCommandEcho=function(e){d.issue("echo",e?"on":"off")},t.setFailed=n,t.isDebug=function(){return"1"===process.env.RUNNER_DEBUG},t.debug=function(e){d.issueCommand("debug",{},e)},t.error=a,t.warning=function(e){d.issue("warning",e instanceof Error?e.toString():e)},t.info=function(e){process.stdout.write(e+u.EOL)},t.startGroup=o,t.endGroup=i,t.group=function(e,t){return s(this,void 0,void 0,function*(){o(e);let r;try{r=yield t()}finally{i()}return r})},t.saveState=function(e,t){d.issueCommand("save-state",{name:e},t)},t.getState=function(e){return process.env[`STATE_${e}`]||""}},29582:function(e,t,r){"use strict";var n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t};Object.defineProperty(t,"__esModule",{value:!0});const a=n(r(35747)),o=n(r(12087)),i=r(74332);t.issueCommand=function(e,t){const r=process.env[`GITHUB_${e}`];if(!r)throw new Error(`Unable to find environment variable for file command ${e}`);if(!a.existsSync(r))throw new Error(`Missing file at path: ${r}`);a.appendFileSync(r,`${i.toCommandValue(t)}${o.EOL}`,{encoding:"utf8"})}},74332:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.toCommandValue=function(e){return null===e||void 0===e?"":"string"==typeof e||e instanceof String?e:JSON.stringify(e)}},84873:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Context=void 0;const n=r(35747),a=r(12087);class o{constructor(){if(this.payload={},process.env.GITHUB_EVENT_PATH)if(n.existsSync(process.env.GITHUB_EVENT_PATH))this.payload=JSON.parse(n.readFileSync(pro Line truncated
* @file Embedded JavaScript templating engine. {@link http://ejs.co}
* @author Matthew Eernisse <mde@fleegix.org>
* @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
@@ -172,4 +172,4 @@ If you think this is a bug, please report it on the Puppeteer issue tracker.`}\n
* ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО
* ОБЕСПЕЧЕНИЯ
* ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/function n(e,t){return e.renameElem("use"),e.removeAttr("d"),e.removeAttr("stroke"),e.removeAttr("fill"),e.addAttr({name:"xlink:href",local:"xlink:href",prefix:"none",value:"#"+t}),delete e.pathJS,e}function a(e,t){if(!e.isEmpty())for(let r of e.content)t(r),a(r,t)}var o=r(71921);t.type="full",t.active=!1,t.description="Finds <path> elements with the same d, fill, and stroke, and converts them to <use> elements referencing a single <path> def.",t.fn=function(e){const t=new Map;let r=0;const i=[];a(e,e=>{if(!e.isElem("path")||!e.hasAttr("d"))return;const a=e.attr("d").value,o=e.hasAttr("fill")&&e.attr("fill").value||"",s=e.hasAttr("stroke")&&e.attr("stroke").value||"",l=a+";s:"+s+";f:"+o,d=t.get(l);return d?void(!d.reused&&(d.reused=!0,!d.elem.hasAttr("id")&&d.elem.addAttr({name:"id",local:"id",prefix:"",value:"reuse-"+r++}),i.push(d.elem)),e=n(e,d.elem.attr("id").value)):void t.set(l,{elem:e,reused:!1})});const s=new o({elem:"defs",prefix:"",local:"defs",content:[],attrs:[]},e);e.content[0].spliceContent(0,0,s);for(let t of i){const e=t.style,r=t.class;delete t.style,delete t.class;const a=t.clone();t.style=e,t.class=r,a.removeAttr("transform"),s.spliceContent(0,0,a),t=n(t,a.attr("id").value),t.removeAttr("id")}return e}},17549:(e,t)=>{"use strict";t.type="perItem",t.active=!1,t.description="sorts element attributes (disabled by default)",t.params={order:["id","width","height","x","x1","x2","y","y1","y2","cx","cy","r","fill","stroke","marker","d","points"]},t.fn=function(e,t){var r=[],n={},o=t.order.length+1,i=t.xmlnsOrder||"front";e.elem&&(e.eachAttr(function(e){r.push(e)}),r.sort(function(e,r){if(e.prefix!=r.prefix){if("front"==i){if("xmlns"==e.prefix)return-1;if("xmlns"==r.prefix)return 1}return e.prefix<r.prefix?-1:1}for(var n=o,a=o,s=0;s<t.order.length;s++)e.name==t.order[s]?n=s:0===e.name.indexOf(t.order[s]+"-")&&(n=s+.5),r.name==t.order[s]?a=s:0===r.name.indexOf(t.order[s]+"-")&&(a=s+.5);return n==a?e.name<r.name?-1:1:n-a}),r.forEach(function(e){n[e.name]=e}),e.attrs=n)}},5681:(e,t)=>{"use strict";t.type="perItem",t.active=!0,t.description="Sorts children of <defs> to improve compression",t.fn=function(e){if(e.isElem("defs")){if(e.content){var t=e.content.reduce(function(e,t){return t.elem in e?e[t.elem]++:e[t.elem]=1,e},{});e.content.sort(function(e,r){var n=t[r.elem]-t[e.elem];if(0!=n)return n;var a=r.elem.length-e.elem.length;return 0==a?e.elem==r.elem?0:e.elem>r.elem?-1:1:a})}return!0}}},16974:(e,t,r)=>{function n(e,t,r,a){return t===r?a(null,!0):void e.lstat(t,function(o,i){return o&&"ENOENT"!==o.code?a(o):o||i.isDirectory()?n(e,p.join(t,".."),r,a):void a(null,!1)})}function a(e,t,r){l(e,{fs:t.fs},function(e,n){!e&&n&&t.own?o(n,t.uid,t.gid,r):r(e)})}var o=r(28729),i=r(15283),s=r(537),l=r(23607),d=r(35747),p=r(85622),c=r(12087),u="win32"===c.platform(),m=function(){},g=function(e){return e},h=u?function(e){return e.replace(/\\/g,"/").replace(/[:?<>|]/g,"_")}:g,f=function(e,t,r,n,a,o){var s=a||["."];return function(a){if(!s.length)return a();var l=s.shift(),d=p.join(r,l);t.call(e,d,function(t,c){return t?a(t):c.isDirectory()?void e.readdir(d,function(e,t){if(e)return a(e);o&&t.sort();for(var d=0;d<t.length;d++)n(p.join(r,l,t[d]))||s.push(p.join(l,t[d]));a(null,l,c)}):a(null,l,c)})}},y=function(e,t){return function(r){r.name=r.name.split("/").slice(t).join("/");var n=r.linkname;return n&&("link"===r.type||p.isAbsolute(n))&&(r.linkname=n.split("/").slice(t).join("/")),e(r)}};t.pack=function(e,t){e||(e="."),t||(t={});var r=t.fs||d,n=t.ignore||t.filter||m,a=t.map||m,o=t.mapStream||g,l=f(r,t.dereference?r.stat:r.lstat,e,n,t.entries,t.sort),c=!1!==t.strict,u="number"==typeof t.umask?~t.umask:~x(),b="number"==typeof t.dmode?t.dmode:0,S="number"==typeof t.fmode?t.fmode:0,v=t.pack||i.pack(),k=t.finish||m;t.strip&&(a=y(a,t.strip)),t.readable&&(b|=parseInt(555,8),S|=parseInt(444,8)),t.writable&&(b|=parseInt(333,8),S|=parseInt(222,8));var C=function(t,n){r.readlink(p.join(e,t),function(e,t){return e?v.destroy(e):void(n.linkname=h(t),v.entry(n,w))})},_=function(n,i,l){if(n)return v.destroy(n);if(!i)return!1!==t.finalize&&v.finalize(),k(v);if(l.isSocket())return w();var d={name:h(i),mode:(l.mode|(l.isDirectory()?b:S))&u,mtime:l.mtime,size:l.size,type:"file",uid:l.uid,gid:l.gid};if(l.isDirectory())return d.size=0,d.type="directory",d=a(d)||d,v.entry(d,w);if(l.isSymbolicLink())return d.size=0,d.type="symlink",d=a(d)||d,C(i,d);if(d=a(d)||d,!l.isFile())return c?v.destroy(new Error("unsupported type for "+i)):w();var m=v.entry(d,w);if(m){var g=o(r.createReadStream(p.join(e,i),{start:0,end:0<d.size?d.size-1:d.size}),d);g.on("error",function(e){m.destroy(e)}),s(g,m)}},w=function(e){return e?v.destroy(e):void l(_)};return w(),v};var b=function(e){return e.length?e[e.length-1]:null},S=function(){return process.getuid?process.getuid():-1},x=function(){return process.umask?process.umask():0};t.extract=function(e,t){e||(e="."),t||(t={});var r=t.fs||d,o=t.ignore||t.filter||m,l=t.map||m,c=t.mapStream||g,f=!1!==t.chown&&!Line truncated
*/function n(e,t){return e.renameElem("use"),e.removeAttr("d"),e.removeAttr("stroke"),e.removeAttr("fill"),e.addAttr({name:"xlink:href",local:"xlink:href",prefix:"none",value:"#"+t}),delete e.pathJS,e}function a(e,t){if(!e.isEmpty())for(let r of e.content)t(r),a(r,t)}var o=r(71921);t.type="full",t.active=!1,t.description="Finds <path> elements with the same d, fill, and stroke, and converts them to <use> elements referencing a single <path> def.",t.fn=function(e){const t=new Map;let r=0;const i=[];a(e,e=>{if(!e.isElem("path")||!e.hasAttr("d"))return;const a=e.attr("d").value,o=e.hasAttr("fill")&&e.attr("fill").value||"",s=e.hasAttr("stroke")&&e.attr("stroke").value||"",l=a+";s:"+s+";f:"+o,d=t.get(l);return d?void(!d.reused&&(d.reused=!0,!d.elem.hasAttr("id")&&d.elem.addAttr({name:"id",local:"id",prefix:"",value:"reuse-"+r++}),i.push(d.elem)),e=n(e,d.elem.attr("id").value)):void t.set(l,{elem:e,reused:!1})});const s=new o({elem:"defs",prefix:"",local:"defs",content:[],attrs:[]},e);e.content[0].spliceContent(0,0,s);for(let t of i){const e=t.style,r=t.class;delete t.style,delete t.class;const a=t.clone();t.style=e,t.class=r,a.removeAttr("transform"),s.spliceContent(0,0,a),t=n(t,a.attr("id").value),t.removeAttr("id")}return e}},17549:(e,t)=>{"use strict";t.type="perItem",t.active=!1,t.description="sorts element attributes (disabled by default)",t.params={order:["id","width","height","x","x1","x2","y","y1","y2","cx","cy","r","fill","stroke","marker","d","points"]},t.fn=function(e,t){var r=[],n={},o=t.order.length+1,i=t.xmlnsOrder||"front";e.elem&&(e.eachAttr(function(e){r.push(e)}),r.sort(function(e,r){if(e.prefix!=r.prefix){if("front"==i){if("xmlns"==e.prefix)return-1;if("xmlns"==r.prefix)return 1}return e.prefix<r.prefix?-1:1}for(var n=o,a=o,s=0;s<t.order.length;s++)e.name==t.order[s]?n=s:0===e.name.indexOf(t.order[s]+"-")&&(n=s+.5),r.name==t.order[s]?a=s:0===r.name.indexOf(t.order[s]+"-")&&(a=s+.5);return n==a?e.name<r.name?-1:1:n-a}),r.forEach(function(e){n[e.name]=e}),e.attrs=n)}},5681:(e,t)=>{"use strict";t.type="perItem",t.active=!0,t.description="Sorts children of <defs> to improve compression",t.fn=function(e){if(e.isElem("defs")){if(e.content){var t=e.content.reduce(function(e,t){return t.elem in e?e[t.elem]++:e[t.elem]=1,e},{});e.content.sort(function(e,r){var n=t[r.elem]-t[e.elem];if(0!=n)return n;var a=r.elem.length-e.elem.length;return 0==a?e.elem==r.elem?0:e.elem>r.elem?-1:1:a})}return!0}}},16974:(e,t,r)=>{function n(e,t,r,a){return t===r?a(null,!0):void e.lstat(t,function(o,i){return o&&"ENOENT"!==o.code?a(o):o||i.isDirectory()?n(e,p.join(t,".."),r,a):void a(null,!1)})}function a(e,t,r){l(e,{fs:t.fs},function(e,n){!e&&n&&t.own?o(n,t.uid,t.gid,r):r(e)})}var o=r(28729),i=r(15283),s=r(537),l=r(23607),d=r(35747),p=r(85622),c=r(12087),u="win32"===c.platform(),m=function(){},g=function(e){return e},h=u?function(e){return e.replace(/\\/g,"/").replace(/[:?<>|]/g,"_")}:g,f=function(e,t,r,n,a,o){var s=a||["."];return function(a){if(!s.length)return a();var l=s.shift(),d=p.join(r,l);t.call(e,d,function(t,c){return t?a(t):c.isDirectory()?void e.readdir(d,function(e,t){if(e)return a(e);o&&t.sort();for(var d=0;d<t.length;d++)n(p.join(r,l,t[d]))||s.push(p.join(l,t[d]));a(null,l,c)}):a(null,l,c)})}},y=function(e,t){return function(r){r.name=r.name.split("/").slice(t).join("/");var n=r.linkname;return n&&("link"===r.type||p.isAbsolute(n))&&(r.linkname=n.split("/").slice(t).join("/")),e(r)}};t.pack=function(e,t){e||(e="."),t||(t={});var r=t.fs||d,n=t.ignore||t.filter||m,a=t.map||m,o=t.mapStream||g,l=f(r,t.dereference?r.stat:r.lstat,e,n,t.entries,t.sort),c=!1!==t.strict,u="number"==typeof t.umask?~t.umask:~x(),b="number"==typeof t.dmode?t.dmode:0,S="number"==typeof t.fmode?t.fmode:0,v=t.pack||i.pack(),k=t.finish||m;t.strip&&(a=y(a,t.strip)),t.readable&&(b|=parseInt(555,8),S|=parseInt(444,8)),t.writable&&(b|=parseInt(333,8),S|=parseInt(222,8));var C=function(t,n){r.readlink(p.join(e,t),function(e,t){return e?v.destroy(e):void(n.linkname=h(t),v.entry(n,w))})},_=function(n,i,l){if(n)return v.destroy(n);if(!i)return!1!==t.finalize&&v.finalize(),k(v);if(l.isSocket())return w();var d={name:h(i),mode:(l.mode|(l.isDirectory()?b:S))&u,mtime:l.mtime,size:l.size,type:"file",uid:l.uid,gid:l.gid};if(l.isDirectory())return d.size=0,d.type="directory",d=a(d)||d,v.entry(d,w);if(l.isSymbolicLink())return d.size=0,d.type="symlink",d=a(d)||d,C(i,d);if(d=a(d)||d,!l.isFile())return c?v.destroy(new Error("unsupported type for "+i)):w();var m=v.entry(d,w);if(m){var g=o(r.createReadStream(p.join(e,i),{start:0,end:0<d.size?d.size-1:d.size}),d);g.on("error",function(e){m.destroy(e)}),s(g,m)}},w=function(e){return e?v.destroy(e):void l(_)};return w(),v};var b=function(e){return e.length?e[e.length-1]:null},S=function(){return process.getuid?process.getuid():-1},x=function(){return process.umask?process.umask():0};t.extract=function(e,t){e||(e="."),t||(t={});var r=t.fs||d,o=t.ignore||t.filter||m,l=t.map||m,c=t.mapStream||g,f=!1!==t.chown&&!Line truncated
+13 -2
View File
@@ -71,6 +71,8 @@
if (!debug)
console.debug = message => debugged.push(message)
console.log(`Debug mode | ${debug}`)
const dflags = (core.getInput("debug_flags") ?? "").split(" ").filter(flag => flag)
console.log(`Debug flags | ${dflags.join(" ")}`)
//Base elements
const base = {}
@@ -84,7 +86,7 @@
lines:{enabled:bool(core.getInput("plugin_lines"))},
traffic:{enabled:bool(core.getInput("plugin_traffic"))},
pagespeed:{enabled:bool(core.getInput("plugin_pagespeed"))},
habits:{enabled:bool(core.getInput("plugin_habits")), from:Number(core.getInput("plugin_habits_from")) || 100},
habits:{enabled:bool(core.getInput("plugin_habits"))},
languages:{enabled:bool(core.getInput("plugin_languages"))},
followup:{enabled:bool(core.getInput("plugin_followup"))},
music:{enabled:bool(core.getInput("plugin_music"))},
@@ -112,6 +114,15 @@
console.log(`Languages ignored | ${q["languages.ignored"]}`)
console.log(`Languages skipped repos | ${q["languages.skipped"]}`)
}
//Habits
if (plugins.habits.enabled) {
for (const option of ["from", "days", "facts", "charts"])
q[`habits.${option}`] = core.getInput(`plugin_habits_${option}`) || null
console.log(`Habits facts | ${q["habits.facts"]}`)
console.log(`Habits charts | ${q["habits.charts"]}`)
console.log(`Habits events to use | ${q["habits.from"]}`)
console.log(`Habits days to keep | ${q["habits.days"]}`)
}
//Music
if (plugins.music.enabled) {
plugins.music.token = core.getInput("plugin_music_token") || ""
@@ -169,7 +180,7 @@
q = {...q, base:false, ...base, repositories, template}
//Render metrics
const rendered = await metrics({login:user, q}, {graphql, rest, plugins, conf, die})
const rendered = await metrics({login:user, q, dflags}, {graphql, rest, plugins, conf, die})
console.log(`Render | complete`)
//Verify svg
+3
View File
@@ -48,6 +48,9 @@
"languages.skipped":"",
"pagespeed.detailed":false,
"habits.from":100,
"habits.days":14,
"habits.facts":true,
"habits.charts":false,
"music.playlist":"",
"music.limit":4,
"posts.limit":4,
+13 -1
View File
@@ -94,7 +94,19 @@
<h4>{{ plugins.descriptions.habits }}</h4>
<label>
Number of events for habits
<input type="number" v-model="plugins.options['habits.from']" min="1" max="100">
<input type="number" v-model="plugins.options['habits.from']" min="1" max="1000">
</label>
<label>
Number of days for habits
<input type="number" v-model="plugins.options['habits.days']" min="1" max="30">
</label>
<label>
Display tidbits
<input type="checkbox" v-model="plugins.options['habits.facts']" @change="load">
</label>
<label>
Display activity charts
<input type="checkbox" v-model="plugins.options['habits.charts']" @change="load">
</label>
</div>
<div class="options-group" v-if="plugins.enabled.posts">
+22 -3
View File
@@ -7,9 +7,13 @@
import Templates from "./templates/index.mjs"
import puppeteer from "puppeteer"
import url from "url"
import processes from "child_process"
import fs from "fs/promises"
import os from "os"
import paths from "path"
//Setup
export default async function metrics({login, q}, {graphql, rest, plugins, conf, die = false}) {
export default async function metrics({login, q, dflags = []}, {graphql, rest, plugins, conf, die = false}) {
//Compute rendering
try {
@@ -49,7 +53,7 @@
//Compute metrics
console.debug(`metrics/compute/${login} > compute`)
const computer = Templates[template].default || Templates[template]
await computer({login, q}, {conf, data, rest, graphql, plugins}, {s, pending, imports:{plugins:Plugins, url, imgb64, axios, puppeteer, format, bytes, shuffle, htmlescape, urlexpand}})
await computer({login, q, dflags}, {conf, data, rest, graphql, plugins}, {s, pending, imports:{plugins:Plugins, url, imgb64, axios, puppeteer, run, fs, os, paths, format, bytes, shuffle, htmlescape, urlexpand}})
const promised = await Promise.all(pending)
//Check plugins errors
@@ -133,6 +137,21 @@
}
}
/** Run command */
async function run(command, options) {
return await new Promise((solve, reject) => {
console.debug(`metrics/command > ${command}`)
const child = processes.exec(command, options)
let [stdout, stderr] = ["", ""]
child.stdout.on("data", data => stdout += data)
child.stderr.on("data", data => stderr += data)
child.on("close", code => {
console.debug(`metrics/command > ${command} > exited with code ${code}`)
return code === 0 ? solve(stdout) : reject(stderr)
})
})
}
/** Placeholder generator */
function placeholder({data, conf, q}) {
//Proxifier
@@ -175,7 +194,7 @@
music:{provider:"########", tracks:new Array("music.limit" in q ? Math.max(Number(q["music.limit"])||0, 0) : 4).fill({name:"##########", artist:"######", artwork:"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mOcOnfpfwAGfgLYttYINwAAAABJRU5ErkJggg=="})},
pagespeed:{detailed:!!q["pagespeed.detailed"], scores:["Performance", "Accessibility", "Best Practices", "SEO"].map(title => ({title, score:NaN}))},
followup:{issues:{count:0}, pr:{count:0}},
habits:{indents:{style:`########`}},
habits:{facts:!!(q["habits.facts"] ?? 1), charts:!!q["habits.charts"], indents:{style:`########`}, commits:{day:"####"}, linguist:{ordered:[]}},
languages:{favorites:new Array(7).fill(null).map((_, x) => ({x, name:"######", color:"#ebedf0", value:1/(x+1)}))},
topics:{list:[...new Array("topics.limit" in q ? Math.max(Number(q["topics.limit"])||0, 0) : 12).fill(null).map(() => ({name:"######", description:"", icon:null})), {name:`And ## more...`, description:"", icon:null}]},
projects:{list:[...new Array("projects.limit" in q ? Math.max(Number(q["projects.limit"])||0, 0) : 4).fill(null).map(() => ({name:"########", updated:"########", progress:{enabled:true, todo:"##", doing:"##", done:"##", total:"##"}}))]},
+71 -18
View File
@@ -1,46 +1,99 @@
//Setup
export default async function ({login, rest, q}, {enabled = false, from:defaults = 100} = {}) {
export default async function ({login, rest, imports, q}, {enabled = false, from:defaults = 100} = {}) {
//Plugin execution
try {
//Check if plugin is enabled and requirements are met
if ((!enabled)||(!q.habits))
return null
//Parameters override
let {"habits.from":from = defaults.from ?? 100} = q
let {"habits.from":from = defaults.from ?? 500, "habits.days":days = 30, "habits.facts":facts = true, "habits.charts":charts = false} = q
//Events
from = Math.max(1, Math.min(100, Number(from)))
from = Math.max(1, Math.min(1000, Number(from)))
//Days
days = Math.max(1, Math.min(30, Number(from)))
//Initialization
const habits = {commits:{hour:NaN, hours:{}}, indents:{style:"", spaces:0, tabs:0}}
//Get user recent commits from events
const events = await rest.activity.listEventsForAuthenticatedUser({username:login, per_page:from})
const commits = events.data
const habits = {facts, charts, commits:{hour:NaN, hours:{}, day:NaN, days:{}}, indents:{style:"", spaces:0, tabs:0}, linguist:{available:false, ordered:[], languages:{}}}
const pages = Math.ceil(from/100)
//Get user recent activity
const events = []
try {
for (let page = 0; page < pages; page++) {
console.debug(`metrics/compute/${login}/plugins > habits > loaded page ${page}`)
events.push(...(await rest.activity.listEventsForAuthenticatedUser({username:login, per_page:100, page})).data)
}
} catch { console.debug(`metrics/compute/${login}/plugins > habits > no more events to load`) }
console.debug(`metrics/compute/${login}/plugins > habits > no more events to load (${events.length} loaded)`)
//Get user recent commits
const commits = events
.filter(({type}) => type === "PushEvent")
.filter(({actor}) => actor.login === login)
.filter(({created_at}) => new Date(created_at) > new Date(Date.now()-days*24*60*60*1000))
console.debug(`metrics/compute/${login}/plugins > habits > filtered out ${commits.length} commits`)
const actor = commits[0]?.actor?.id ?? 0
//Retrieve edited files and filter edited lines (those starting with +/-) from patches
const patches = [...await Promise.allSettled(commits
.flatMap(({payload}) => payload.commits).map(commit => commit.url)
.map(async commit => (await rest.request(commit)).data.files)
)]
.filter(({status}) => status === "fulfilled")
.map(({value}) => value)
.flatMap(files => files.map(file => ({name:imports.paths.basename(file.filename), patch:file.patch ?? ""})))
.map(({name, patch}) => ({name, patch:patch.split("\n").filter(line => /^[-+]/.test(line)).map(line => line.substring(1)).join("\n")}))
//Commit day
{
//Compute commit days
const days = commits.map(({created_at}) => (new Date(created_at)).getDay())
for (const day of days)
habits.commits.days[day] = (habits.commits.days[day] ?? 0) + 1
habits.commits.days.max = Math.max(...Object.values(habits.commits.days))
//Compute day with most commits
habits.commits.day = days.length ? ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][Object.entries(habits.commits.days).sort(([an, a], [bn, b]) => b - a).map(([day, occurence]) => day)[0]] ?? NaN : NaN
}
//Commit hour
{
//Compute commit hours
const hours = commits.map(({created_at}) => (new Date(created_at)).getHours())
for (const hour of hours)
habits.commits.hours[hour] = (habits.commits.hours[hour] ?? 0) + 1
habits.commits.hours.max = Math.max(...Object.values(habits.commits.hours))
//Compute hour with most commits
habits.commits.hour = hours.length ? `${Object.entries(habits.commits.hours).sort(([an, a], [bn, b]) => b - a).map(([hour, occurence]) => hour)[0]}`.padStart(2, "0") : NaN
}
//Indent style
{
//Retrieve edited files
const edited = await Promise.allSettled(commits
.flatMap(({payload}) => payload.commits).map(commit => commit.url)
.map(async commit => (await rest.request(commit)).data.files)
)
//Attemp to guess whether tabs or spaces are used from patch
edited
.filter(({status}) => status === "fulfilled")
.map(({value}) => value)
.flatMap(files => files.flatMap(file => (file.patch ?? "").match(/(?<=^[+])((?:\t)|(?: )) /gm) ?? []))
//Attempt to guess whether tabs or spaces are used in patches
patches
.map(({patch}) => patch.match(/((?:\t)|(?: )) /gm) ?? [])
.forEach(indent => habits.indents[/^\t/.test(indent) ? "tabs" : "spaces"]++)
//Compute indent style
habits.indents.style = habits.indents.spaces > habits.indents.tabs ? "spaces" : habits.indents.tabs > habits.indents.spaces ? "tabs" : ""
}
//Linguist
if (charts) {
//Check if linguist exists
const prefix = {win32:"wsl"}[process.platform] ?? ""
if (await imports.run(`${prefix} which github-linguist`)) {
//Setup for linguist
habits.linguist.available = true
const path = imports.paths.join(imports.os.tmpdir(), `${actor}`)
//Create temporary directory and save patches
await imports.fs.mkdir(path, {recursive:true})
await Promise.all(patches.map(async ({name, patch}, i) => await imports.fs.writeFile(imports.paths.join(path, `${i}${imports.paths.extname(name)}`), patch)))
console.debug(`metrics/compute/${login}/plugins > habits > created temp dir ${path} with ${patches.length} files`)
//Create temporary git repository
await imports.run(`git init && git add . && git config user.name "linguist" && git config user.email "null@github.com" && git commit -m "linguist"`, {cwd:path}).catch(console.debug)
await imports.run(`git status`, {cwd:path})
console.debug(`metrics/compute/${login}/plugins > habits > created temp git repository`)
//Spawn linguist process
console.debug(`metrics/compute/${login}/plugins > habits > running linguist`)
;(await imports.run(`${prefix} github-linguist`, {cwd:path}))
//Parse linguist result
.split("\n").map(line => line.match(/(?<value>[\d.]+)%\s+(?<language>\w+)/)?.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)
}
else
console.debug(`metrics/compute/${login}/plugins > habits > linguist is not available`)
}
//Results
return habits
}
+70 -17
View File
@@ -6,7 +6,7 @@
+ ((!!base.repositories)*((!!plugins.traffic)||(!!plugins.lines)))*16
+ (!!plugins.followup)*68
+ (!!plugins.pagespeed)*126 + (plugins.pagespeed?.detailed ?? 0)*6*20
+ (!!plugins.habits)*68
+ (!!plugins.habits)*28 + (!!plugins.habits?.facts)*58 + (!!plugins.habits?.charts)*226
+ (!!plugins.languages)*96
+ (!!plugins.music)*64 + (plugins.music?.tracks?.length ? 14+Math.max(0, plugins.music.tracks.length-1)*36 : 0)
+ (!!plugins.posts)*64 + (plugins.posts?.list?.length ?? 0)*40
@@ -504,28 +504,81 @@
<section>
<h2 class="field">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M8 1.5c-2.363 0-4 1.69-4 3.75 0 .984.424 1.625.984 2.304l.214.253c.223.264.47.556.673.848.284.411.537.896.621 1.49a.75.75 0 01-1.484.211c-.04-.282-.163-.547-.37-.847a8.695 8.695 0 00-.542-.68c-.084-.1-.173-.205-.268-.32C3.201 7.75 2.5 6.766 2.5 5.25 2.5 2.31 4.863 0 8 0s5.5 2.31 5.5 5.25c0 1.516-.701 2.5-1.328 3.259-.095.115-.184.22-.268.319-.207.245-.383.453-.541.681-.208.3-.33.565-.37.847a.75.75 0 01-1.485-.212c.084-.593.337-1.078.621-1.489.203-.292.45-.584.673-.848.075-.088.147-.173.213-.253.561-.679.985-1.32.985-2.304 0-2.06-1.637-3.75-4-3.75zM6 15.25a.75.75 0 01.75-.75h2.5a.75.75 0 010 1.5h-2.5a.75.75 0 01-.75-.75zM5.75 12a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-4.5z"></path></svg>
Coding habits
Coding habits and recent activity
</h2>
<% if (plugins.habits.facts) { %>
<div class="row">
<% if (plugins.habits.error) { %>
<section>
<div class="field error">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M2.343 13.657A8 8 0 1113.657 2.343 8 8 0 012.343 13.657zM6.03 4.97a.75.75 0 00-1.06 1.06L6.94 8 4.97 9.97a.75.75 0 101.06 1.06L8 9.06l1.97 1.97a.75.75 0 101.06-1.06L9.06 8l1.97-1.97a.75.75 0 10-1.06-1.06L8 6.94 6.03 4.97z"></path></svg>
<%= plugins.habits.error.message %>
</div>
</section>
<% } else { %>
<ul class="habits">
<% if (plugins.habits.indents.style) { %>
<li>Use <%= plugins.habits.indents.style %> for indents</li>
<% } %>
<% if (!Number.isNaN(plugins.habits.commits.hour)) { %>
<li>Mostly push code around <%= plugins.habits.commits.hour %>:00</li>
<% } %>
<% if (plugins.habits.commits.day) { %>
<li>Mostly active on <%= plugins.habits.commits.day.toLocaleLowerCase() %></li>
<% } %>
</ul>
<% } %>
</div>
<% } %>
</section>
<% if (plugins.habits.charts) { %>
<% if (!Number.isNaN(plugins.habits.commits.hour)) { %>
<section class="column chart">
<h3>Commit activity per time of the day</h3>
<div class="chart-bars">
<% for (let h = 0; h < 24; h++) { const p = (plugins.habits.commits.hours[h]??0)/(plugins.habits.commits.hours.max??1); %>
<div class="entry">
<span class="value"><%= plugins.habits.commits.hours[h] %></span>
<div class="bar" style="height: <%= p*50 %>px; background-color: var(--color-calendar-graph-day-L<%= Math.ceil(p/0.25) %>-bg)"></div>
<%= `${h}`.padStart(2, 0) %>
</div>
<% } %>
</div>
</section>
<% } %>
<div class="row">
<% if (plugins.habits.error) { %>
<section>
<div class="field error">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M2.343 13.657A8 8 0 1113.657 2.343 8 8 0 012.343 13.657zM6.03 4.97a.75.75 0 00-1.06 1.06L6.94 8 4.97 9.97a.75.75 0 101.06 1.06L8 9.06l1.97 1.97a.75.75 0 101.06-1.06L9.06 8l1.97-1.97a.75.75 0 10-1.06-1.06L8 6.94 6.03 4.97z"></path></svg>
<%= plugins.habits.error.message %>
<% if (!Number.isNaN(plugins.habits.commits.day)) { %>
<section class="column chart">
<h3>Commit activity per day</h3>
<div class="chart-bars">
<% for (let d = 0; d < 7; d++) { const p = (plugins.habits.commits.days[d]??0)/(plugins.habits.commits.days.max??1); %>
<div class="entry">
<span class="value"><%= plugins.habits.commits.days[d] %></span>
<div class="bar" style="height: <%= p*50 %>px; background-color: var(--color-calendar-graph-day-L<%= Math.ceil(p/0.25) %>-bg)"></div>
<%= ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][d] %>
</div>
<% } %>
</div>
</section>
<% } %>
<% if (plugins.habits.linguist.available) { %>
<section class="column chart">
<h3>Language activity</h3>
<div class="chart-bars horizontal">
<% for (const [language, p] of plugins.habits.linguist.ordered) { %>
<div class="entry">
<span class="name"><%= language %></span>
<div class="bar" style="width: <%= p*80 %>%; background-color: var(--color-calendar-graph-day-L<%= Math.ceil(p/0.25) %>-bg)"></div>
<span class="value"><%= Math.round(100*p) %>%</span>
</div>
<% } %>
</div>
</section>
<% } else { %>
<ul class="habits">
<% if (plugins.habits.indents.style) { %>
<li>Use <%= plugins.habits.indents.style %> for indents</li>
<% } %>
<% if (!Number.isNaN(plugins.habits.commits.hour)) { %>
<li>Mostly push code around <%= plugins.habits.commits.hour %>:00</li>
<% } %>
</ul>
<% } %>
</div>
</section>
<% } %>
<% } %>
<% if (plugins.topics) { %>

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 73 KiB

+57
View File
@@ -304,6 +304,63 @@
color: #666666;
}
/* Charts and graphs */
.chart {
padding: 0 8px;
}
.chart-bars {
display: flex;
justify-content: space-between;
align-items: flex-end;
width: 100%;
margin: 8px 0 4px;
}
.chart-bars .entry {
flex: 1 1 0;
display: flex;
flex-direction: column;
align-items: center;
font-size: 10px;
color: #666666;
}
.chart-bars .entry .value {
font-size: 9px;
}
.chart-bars .bar {
width: 7px;
background-color: var(--color-calendar-graph-day-bg);
border: 1px solid var(--color-calendar-graph-day-border);
border-radius: 5px;
}
.chart-bars.horizontal {
flex-direction: column;
align-items: space-between;
height: 100%;
}
.chart-bars.horizontal .entry {
align-items: center;
flex-direction: row;
width: 100%;
}
.chart-bars.horizontal .entry .name {
flex-shrink: 0;
text-align: right;
min-width: 30%;
}
.chart-bars.horizontal .bar {
height: 7px;
width: auto;
margin: 0 6px;
}
/* Fade animation */
.af {
opacity: 0;
+11 -1
View File
@@ -1,5 +1,5 @@
/** Template common processor */
export default async function ({login, q}, {conf, data, rest, graphql, plugins}, {s, pending, imports}) {
export default async function ({login, q, dflags}, {conf, data, rest, graphql, plugins}, {s, pending, imports}) {
//Init
const computed = data.computed = {commits:0, sponsorships:0, licenses:{favorite:"", used:{}}, token:{}, repositories:{watchers:0, stargazers:0, issues_open:0, issues_closed:0, pr_open:0, pr_merged:0, forks:0, releases:0}}
@@ -61,4 +61,14 @@
//Meta
data.meta = {version:conf.package.version, author:conf.package.author}
//Debug flags
if (dflags.includes("--cakeday")||q["dflag.cakeday"]) {
console.debug(`metrics/compute/${login} > applying dflag --cakeday`)
computed.cakeday = true
}
if (dflags.includes("--hireable")||q["dflag.hireable"]) {
console.debug(`metrics/compute/${login} > applying dflag --hireable`)
data.user.isHireable = true
}
}
+10
View File
@@ -115,6 +115,16 @@ jobs:
uses: lowlighter/metrics@<%- release %>
<%- testcase({
plugin_habits: true,
plugin_habits_from: 5,
}) %>
- name: ${{ matrix.template }} > Plugin > Habits (charts)
uses: lowlighter/metrics@<%- release %>
<%- testcase({
plugin_habits: true,
plugin_habits_from: 5,
plugin_habits_facts: false,
plugin_habits_charts: true,
}) %>
- name: ${{ matrix.template }} > Plugin > Languages