Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Added formatting rules to js folder (#90)
Ulan Rakymzhanovaa3f4846611d
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex f4c808860..8d51adce3 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -1,4 +1,4 @@-exclude: Pipfile\.lock|migrations|\.idea+exclude: Pipfile\.lock|migrations|\.idea|node_modulesrepos:- repo: https://github.com/pre-commit/pre-commit-hooks@@ -20,7 +20,7 @@ repos:args:- --remove- id: pretty-format-json- exclude: package-lock\.json+ exclude: package(-lock)?\.jsonargs:- --autofix- id: requirements-txt-fixer@@ -51,3 +51,18 @@ repos:- id: blackargs:- --safe++ - repo: https://github.com/pre-commit/mirrors-eslint+ rev: v8.3.0+ hooks:+ - id: eslint+ files: ^js/.*$+ additional_dependencies:++ - repo: https://github.com/pre-commit/mirrors-prettier+ rev: v2.5.0+ hooks:+ - id: prettier+ files: ^js/.*$diff --git a/js/.eslintrc.js b/js/.eslintrc.jsnew file mode 100644index 000000000..c3b6d660e--- /dev/null+++ b/js/.eslintrc.js@@ -0,0 +1,14 @@+module.exports = {+ env: {+ node: true,+ es6: true,+ },+ parserOptions: {+ ecmaVersion: 'latest',+ },+ extends: ['eslint:recommended', 'prettier'],+ rules: {+ semi: [2, 'never'],+ 'no-console': 'off',+ },+}diff --git a/js/.prettierrc b/js/.prettierrcdeleted file mode 100644index 01e96eb7d..000000000--- a/js/.prettierrc+++ /dev/null@@ -1,7 +0,0 @@-{- "tabWidth": 2,- "useTabs": false,- "semi": false,- "arrowParens": "avoid",- "singleQuote": true-}diff --git a/js/prettier.config.js b/js/prettier.config.jsnew file mode 100644index 000000000..0614ee70c--- /dev/null+++ b/js/prettier.config.js@@ -0,0 +1,6 @@+module.exports = {+ trailingComma: 'es5',+ tabWidth: 2,+ semi: false,+ singleQuote: true,+}diff --git a/js/src/last_week_tonight.js b/js/src/last_week_tonight.jsindex 4bb837bb2..6ea42f6c1 100644--- a/js/src/last_week_tonight.js+++ b/js/src/last_week_tonight.js@@ -3,53 +3,57 @@* Openverse repos.*/-const fs = require('fs');-const path = require('path');+const fs = require('fs')+const path = require('path')-const yaml = require('js-yaml');-const fetch = require('node-fetch');-const {Octokit} = require('@octokit/rest');+const yaml = require('js-yaml')+const fetch = require('node-fetch')+const { Octokit } = require('@octokit/rest')/* Environment variables *//** the personal access token for the GitHub API */-const pat = process.env.ACCESS_TOKEN;+const pat = process.env.ACCESS_TOKEN/** the username for the Make site account making the post */-const username = process.env.MAKE_USERNAME;+const username = process.env.MAKE_USERNAME/** the application password for the Make site */-const password = process.env.MAKE_PASSWORD;--if (!pat) console.log('GitHub personal access token "ACCESS_TOKEN" is required.')-if (!username) console.log('Make site username "MAKE_USERNAME" is required.')-if (!password) console.log('Make site application password "MAKE_PASSWORD" is required.')+const password = process.env.MAKE_PASSWORD++if (!pat) {+ console.log('GitHub personal access token "ACCESS_TOKEN" is required.')+}+if (!username) {+ console.log('Make site username "MAKE_USERNAME" is required.')+}+if (!password) {+ console.log('Make site application password "MAKE_PASSWORD" is required.')+}if (!(pat && username && password)) process.exit(1)/* Read GitHub information from the data files */-const githubDataFile = path.resolve(__dirname, '../../data/github.yml');-const githubInfo = yaml.load(fs.readFileSync(githubDataFile));-const org = githubInfo.org;-const repos = Object.values(githubInfo.repos);+const githubDataFile = path.resolve(__dirname, '../../data/github.yml')+const githubInfo = yaml.load(fs.readFileSync(githubDataFile))+const org = githubInfo.org+const repos = Object.values(githubInfo.repos)/* Time period */-const msInWeeks = (weeks) => weeks * 7 * 24 * 60 * 60 * 1e3;+const msInWeeks = (weeks) => weeks * 7 * 24 * 60 * 60 * 1e3// End date is always today-const [endDate] = new Date()- .toISOString()- .split('T');+const [endDate] = new Date().toISOString().split('T')// Start date is one week before todayconst [startDate] = new Date(new Date().getTime() - msInWeeks(1))- .toISOString()- .split('T');+ .toISOString()+ .split('T')/* GitHub API */-const octokit = new Octokit({auth: pat});-const mergedPrsQ = repo =>- `repo:${org}/${repo} is:pr is:merged merged:>=${startDate}`;-const closedIssuesQ = repo =>- `repo:${org}/${repo} is:issue is:closed closed:>=${startDate}`;+const octokit = new Octokit({ auth: pat })+const mergedPrsQ = (repo) =>+ `repo:${org}/${repo} is:pr is:merged merged:>=${startDate}`+const closedIssuesQ = (repo) =>+ `repo:${org}/${repo} is:issue is:closed closed:>=${startDate}`/* Format issues, PRs and repos as HTML */@@ -60,17 +64,18 @@ const closedIssuesQ = repo =>* @returns {string[]} - lines of HTML*/const getItemsHtml = (title, items) => {- if (!items.length) return [];-- return [- `<h3>${title}</h3>`,- '<ul>',- ...items.map(item =>- `<li><a href="${item.html_url}">#${item.number}</a>: ${item.title}`,- ),- '</ul>',- ];-};+ if (!items.length) return []++ return [+ `<h3>${title}</h3>`,+ '<ul>',+ ...items.map(+ (item) =>+ `<li><a href="${item.html_url}">#${item.number}</a>: ${item.title}`+ ),+ '</ul>',+ ]+}/*** Generate the HTML for the closed issues or merged PRs of one repository.* @param {string} repo - the name of the repository@@ -78,17 +83,17 @@ const getItemsHtml = (title, items) => {* @param {{html_url: string, number: int, title: string}[]} closedIssues - the list of issues* @returns {string[]} - lines of HTML*/-const getRepoHtml = ({repo, mergedPrs, closedIssues}) => {- return [- `<h2><a href="https://github.com/${org}/${repo}">${repo}</a></h2>`,- ...getItemsHtml('Merged PRs', mergedPrs),- ...getItemsHtml('Closed issues', closedIssues),- ]-};+const getRepoHtml = ({ repo, mergedPrs, closedIssues }) => {+ return [+ `<h2><a href="https://github.com/${org}/${repo}">${repo}</a></h2>`,+ ...getItemsHtml('Merged PRs', mergedPrs),+ ...getItemsHtml('Closed issues', closedIssues),+ ]+}// Create post on Make site-const MAKE_SITE_API = 'https://make.wordpress.org/openverse/wp-json/wp/v2';-const token = Buffer.from(`${username}:${password}`).toString('base64');+const MAKE_SITE_API = 'https://make.wordpress.org/openverse/wp-json/wp/v2'+const token = Buffer.from(`${username}:${password}`).toString('base64')/*** Post the activities to the Make site.* @param {{@@ -99,55 +104,57 @@ const token = Buffer.from(`${username}:${password}`).toString('base64');* @returns {Promise} - the response for the POST request*/const postActivities = (activities) => {- const report = activities.map(getRepoHtml).flat().join('\n');- return fetch(`${MAKE_SITE_API}/posts`, {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- Authorization: `Basic ${token}`,- },- body: JSON.stringify({- title: `A week in Openverse: ${startDate} - ${endDate}`,- slug: `last-week-openverse-${startDate}-${endDate}`,- excerpt: `The developments in Openverse between ${startDate} and ${endDate}`,- content: report,- status: 'publish',- tags: [- 3, // openverse- 5, // week-in-openverse- ],- }),- });-};+ const report = activities.map(getRepoHtml).flat().join('\n')+ return fetch(`${MAKE_SITE_API}/posts`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Basic ${token}`,+ },+ body: JSON.stringify({+ title: `A week in Openverse: ${startDate} - ${endDate}`,+ slug: `last-week-openverse-${startDate}-${endDate}`,+ excerpt: `The developments in Openverse between ${startDate} and ${endDate}`,+ content: report,+ status: 'publish',+ tags: [+ 3, // openverse+ 5, // week-in-openverse+ ],+ }),+ })+}// Entry pointPromise.all(- repos.map((repo) => Promise.all([- octokit.rest.search.issuesAndPullRequests({q: closedIssuesQ(repo)})- .then(res => res.data.items),- octokit.rest.search.issuesAndPullRequests({q: mergedPrsQ(repo)})- .then(res => res.data.items),- ])- .then(([closedIssues, mergedPrs]) => {- if (closedIssues.length || mergedPrs.length) {- return {- repo: repo,- closedIssues,- mergedPrs,- };- }- return null;- }),- ),-)- .then((activities) => activities.filter(activity => Boolean(activity)))- .then(postActivities)- .then(res => {- if (res.status !== 201) {- console.error('Create post request failed. See the logs.')- process.exitCode = 1+ repos.map((repo) =>+ Promise.all([+ octokit.rest.search+ .issuesAndPullRequests({ q: closedIssuesQ(repo) })+ .then((res) => res.data.items),+ octokit.rest.search+ .issuesAndPullRequests({ q: mergedPrsQ(repo) })+ .then((res) => res.data.items),+ ]).then(([closedIssues, mergedPrs]) => {+ if (closedIssues.length || mergedPrs.length) {+ return {+ repo: repo,+ closedIssues,+ mergedPrs,}- return res.json()+ }+ return null})- .then(data => JSON.stringify(data, null, 2))- .then(console.log)+ )+)+ .then((activities) => activities.filter((activity) => Boolean(activity)))+ .then(postActivities)+ .then((res) => {+ if (res.status !== 201) {+ console.error('Create post request failed. See the logs.')+ process.exitCode = 1+ }+ return res.json()+ })+ .then((data) => JSON.stringify(data, null, 2))+ .then(console.log)diff --git a/js/src/migrate_issues.js b/js/src/migrate_issues.jsindex 6eecd847b..9c9d7103b 100644--- a/js/src/migrate_issues.js+++ b/js/src/migrate_issues.js@@ -1,5 +1,6 @@-import { Octokit } from '@octokit/rest'-import fs from 'fs'+const fs = require('fs')++const { Octokit } = require('@octokit/rest')// TODO: add auth tokenconst octokit = new Octokit({@@ -8,11 +9,11 @@ const octokit = new Octokit({})async function getTargetIssues(previousOwner, targetLabel, repos) {- const parseComments = comments => {+ const parseComments = (comments) => {if (comments.length === 0) {return []}- return comments.map(comment => {+ return comments.map((comment) => {// Add a `>` symbol at the beginning of a new line// in comments to make them look like a quotecomment.body@@ -29,11 +30,11 @@ async function getTargetIssues(previousOwner, targetLabel, repos) {function parseIssues(issues) {return issues- .filter(issue =>- issue.labels.map(label => label.name).includes(targetLabel)+ .filter((issue) =>+ issue.labels.map((label) => label.name).includes(targetLabel))- .map(issue => {- const labelNames = issue.labels.map(label => label.name)+ .map((issue) => {+ const labelNames = issue.labels.map((label) => label.name)const repoNameParts = issue.repository_url.split('/')const repoName = repoNameParts[repoNameParts.length - 1]return {@@ -53,7 +54,7 @@ async function getTargetIssues(previousOwner, targetLabel, repos) {const addIssueComments = async (issuesToProcess, previousOwner) => {return await Promise.all(- issuesToProcess.map(async issue => {+ issuesToProcess.map(async (issue) => {let issueCommentstry {issueComments = await octokit.rest.issues.listComments({@@ -99,8 +100,8 @@ async function transferIssues(REPOS, previousOwner, newOwner, targetLabel) {? JSON.parse(fs.readFileSync('issues.json', 'utf-8')): await getTargetIssues(previousOwner, targetLabel, REPOS)- repos.forEach(repo => {- repo.issues.forEach(async issue => {+ repos.forEach((repo) => {+ repo.issues.forEach(async (issue) => {const issueMeta = `${issue.migrationNotice}\n\`\`\`\n${[issue.author,issue.date,@@ -149,4 +150,5 @@ const LABEL = '🙅 status: discontinued'// The issues will be transferred from `OLD_ORG` organization to the `NEW_ORG` organizationconst OLD_ORG = 'creativecommons'const NEW_ORG = 'Automattic'-await transferIssues(REPOS, OLD_ORG, NEW_ORG, LABEL)++transferIssues(REPOS, OLD_ORG, NEW_ORG, LABEL)diff --git a/js/src/utils.js b/js/src/utils.jsindex 37f86b930..c4a81e37a 100644--- a/js/src/utils.js+++ b/js/src/utils.js@@ -4,23 +4,23 @@ const compose = (...fns) =>(...args) =>f(g(...args)))-const map = fn => arr => arr.map(fn)-const fmap = fn => arr => arr.flatMap(fn)-const tap = fn => value => {+const map = (fn) => (arr) => arr.map(fn)+const fmap = (fn) => (arr) => arr.flatMap(fn)+const tap = (fn) => (value) => {fn(value)return value}-const filter = fn => arr => arr.filter(fn)+const filter = (fn) => (arr) => arr.filter(fn)const tapLog = tap(console.log)-const prop = prop => obj => obj[prop]-const fromPairs = pairs =>+const prop = (prop) => (obj) => obj[prop]+const fromPairs = (pairs) =>pairs.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {})-const zip = a => b => a.map((a, i) => [a, b[i]])-const zipObj = a => compose(fromPairs, zip(a))-const mapAwait = fn => data => Promise.all(map(fn)(data))-const gt = test => value => value > test-const gte = test => value => value >= test-const entries = obj => Object.entries(obj)+const zip = (a) => (b) => a.map((a, i) => [a, b[i]])+const zipObj = (a) => compose(fromPairs, zip(a))+const mapAwait = (fn) => (data) => Promise.all(map(fn)(data))+const gt = (test) => (value) => value > test+const gte = (test) => (value) => value >= test+const entries = (obj) => Object.entries(obj)const branch =(left, right) =>([a, b]) => {diff --git a/js/src/weekly_report.js b/js/src/weekly_report.jsindex 2eb1579ea..f1fafd9ad 100644--- a/js/src/weekly_report.js+++ b/js/src/weekly_report.js@@ -3,9 +3,7 @@ const fetch = require('node-fetch')const {compose,zipObj,- tap,mapAwait,- tapLog,prop,gte,map,@@ -32,11 +30,11 @@ const repos = [// internalsconst API_ROOT = `https://api.github.com`-const makeIssueUrl = owner => repo =>+const makeIssueUrl = (owner) => (repo) =>`${API_ROOT}/repos/${owner}/${repo}/issues?state=closed&since=${date}&per_page=10000`const makeWpIssueUrl = makeIssueUrl('wordpress')// this key only has public repo access, i don't care about showing it-const authFetch = url =>+const authFetch = (url) =>fetch(url, {headers: {Authorization:@@ -44,11 +42,11 @@ const authFetch = url =>},})const fetchRepoIssues = compose(authFetch, makeWpIssueUrl)-const getJSON = i => i.json()+const getJSON = (i) => i.json()const filterClosed = compose(gte(date), prop('closed_at'))-const logRepo = repo =>+const logRepo = (repo) =>console.log(`\n## [${repo}](https://github.com/wordpress/${repo}) \n`)-const logIssue = issue =>+const logIssue = (issue) =>console.log(`- [#${issue.number} ${issue.title}](${issue.html_url})`)// run it