From b0eda8e28ec9481dc09e6ce9b4598d990ab5da6c Mon Sep 17 00:00:00 2001 From: trickypr Date: Sat, 2 Oct 2021 12:06:01 +1000 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A8=20Fix=20eslint=20warnings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc.json | 1 - docs/static/js.js | 92 ++++++++++++++---------------- src/commands/bootstrap.ts | 3 +- src/commands/build.ts | 18 +++--- src/commands/discard.ts | 2 +- src/commands/download-artifacts.ts | 6 +- src/commands/download.ts | 10 ++-- src/commands/export-file.ts | 6 +- src/commands/export-patches.ts | 22 +++---- src/commands/import-patches.ts | 10 ++-- src/commands/license-check.ts | 10 ++-- src/commands/reset.ts | 4 +- src/commands/run.ts | 4 +- src/commands/setupProject.ts | 2 +- src/constants/index.ts | 13 ++++- src/controllers/patch.ts | 20 ++++--- src/index.ts | 17 +++--- src/log.ts | 32 ++++++----- src/manual-patches.ts | 2 +- src/middleware/patch-check.ts | 2 +- src/middleware/sha-check.ts | 2 +- src/middleware/update-check.ts | 12 ++-- src/utils/delay.ts | 5 +- src/utils/dispatch.ts | 13 ++--- src/utils/error-handler.ts | 9 ++- src/utils/import.ts | 12 ++-- src/utils/version.ts | 2 +- src/utils/write-metadata.ts | 7 +-- tsconfig.json | 4 +- 29 files changed, 175 insertions(+), 167 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index f78130c..9aef33e 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -6,7 +6,6 @@ "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended", - "airbnb", "eslint-config-prettier" ], "parser": "@typescript-eslint/parser", diff --git a/docs/static/js.js b/docs/static/js.js index 4769a10..06223ba 100644 --- a/docs/static/js.js +++ b/docs/static/js.js @@ -1,14 +1,14 @@ // search script, borrowed from book theme function debounce(func, wait) { - var timeout; + let timeout; return function () { - var context = this; - var args = arguments; + const context = this; + const args = arguments; clearTimeout(timeout); - timeout = setTimeout(function () { + timeout = setTimeout(() => { timeout = null; func.apply(context, args); }, wait); @@ -26,30 +26,28 @@ function debounce(func, wait) { // maximum sum. If there are multiple maximas, then get the last one. // Enclose the terms in . function makeTeaser(body, terms) { - var TERM_WEIGHT = 40; - var NORMAL_WORD_WEIGHT = 2; - var FIRST_WORD_WEIGHT = 8; - var TEASER_MAX_WORDS = 30; + const TERM_WEIGHT = 40; + const NORMAL_WORD_WEIGHT = 2; + const FIRST_WORD_WEIGHT = 8; + const TEASER_MAX_WORDS = 30; - var stemmedTerms = terms.map(function (w) { - return elasticlunr.stemmer(w.toLowerCase()); - }); - var termFound = false; - var index = 0; - var weighted = []; // contains elements of ["word", weight, index_in_document] + const stemmedTerms = terms.map((w) => elasticlunr.stemmer(w.toLowerCase())); + let termFound = false; + let index = 0; + const weighted = []; // contains elements of ["word", weight, index_in_document] // split in sentences, then words - var sentences = body.toLowerCase().split(". "); + const sentences = body.toLowerCase().split(". "); for (var i in sentences) { - var words = sentences[i].split(" "); - var value = FIRST_WORD_WEIGHT; + const words = sentences[i].split(" "); + let value = FIRST_WORD_WEIGHT; - for (var j in words) { + for (const j in words) { var word = words[j]; if (word.length > 0) { - for (var k in stemmedTerms) { + for (const k in stemmedTerms) { if (elasticlunr.stemmer(word).startsWith(stemmedTerms[k])) { value = TERM_WEIGHT; termFound = true; @@ -70,10 +68,10 @@ function debounce(func, wait) { return body; } - var windowWeights = []; - var windowSize = Math.min(weighted.length, TEASER_MAX_WORDS); + const windowWeights = []; + const windowSize = Math.min(weighted.length, TEASER_MAX_WORDS); // We add a window with all the weights first - var curSum = 0; + let curSum = 0; for (var i = 0; i < windowSize; i++) { curSum += weighted[i][1]; } @@ -86,9 +84,9 @@ function debounce(func, wait) { } // If we didn't find the term, just pick the first window - var maxSumIndex = 0; + let maxSumIndex = 0; if (termFound) { - var maxFound = 0; + let maxFound = 0; // backwards for (var i = windowWeights.length - 1; i >= 0; i--) { if (windowWeights[i] > maxFound) { @@ -98,8 +96,8 @@ function debounce(func, wait) { } } - var teaser = []; - var startIndex = weighted[maxSumIndex][2]; + const teaser = []; + let startIndex = weighted[maxSumIndex][2]; for (var i = maxSumIndex; i < maxSumIndex + windowSize; i++) { var word = weighted[i]; if (startIndex < word[2]) { @@ -124,7 +122,7 @@ function debounce(func, wait) { } function formatSearchResultItem(item, terms) { - var li = document.createElement("li"); + const li = document.createElement("li"); li.classList.add("search-results__item"); li.innerHTML = `${item.doc.title}`; li.innerHTML += `
${makeTeaser(item.doc.body, terms)}
`; @@ -133,9 +131,9 @@ function debounce(func, wait) { // Go from the book view to the search view function toggleSearchMode() { - var $wrapContent = document.querySelector("#wrap"); - var $searchIcon = document.querySelector("#search-ico"); - var $searchContainer = document.querySelector(".search-container"); + const $wrapContent = document.querySelector("#wrap"); + const $searchIcon = document.querySelector("#search-ico"); + const $searchContainer = document.querySelector(".search-container"); if ($searchContainer.classList.contains("search-container--is-visible")) { $searchContainer.classList.remove("search-container--is-visible"); $wrapContent.style.display = ""; @@ -149,30 +147,30 @@ function debounce(func, wait) { } function initSearch() { - var $searchInput = document.getElementById("search"); + const $searchInput = document.getElementById("search"); if (!$searchInput) { return; } - var $searchIcon = document.querySelector("#search-ico"); + const $searchIcon = document.querySelector("#search-ico"); $searchIcon.addEventListener("click", toggleSearchMode); - var $searchResults = document.querySelector(".search-results"); - var $searchResultsHeader = document.querySelector(".search-results__header"); - var $searchResultsItems = document.querySelector(".search-results__items"); - var MAX_ITEMS = 100; + const $searchResults = document.querySelector(".search-results"); + const $searchResultsHeader = document.querySelector(".search-results__header"); + const $searchResultsItems = document.querySelector(".search-results__items"); + const MAX_ITEMS = 100; - var options = { + const options = { bool: "AND", fields: { title: {boost: 2}, body: {boost: 1}, } }; - var currentTerm = ""; - var index = elasticlunr.Index.load(window.searchIndex); + let currentTerm = ""; + const index = elasticlunr.Index.load(window.searchIndex); - $searchInput.addEventListener("keyup", debounce(function() { - var term = $searchInput.value.trim(); + $searchInput.addEventListener("keyup", debounce(() => { + const term = $searchInput.value.trim(); if (term === currentTerm || !index) { return; } @@ -182,9 +180,7 @@ function debounce(func, wait) { return; } - var results = index.search(term, options).filter(function (r) { - return r.doc.body !== ""; - }); + const results = index.search(term, options).filter((r) => r.doc.body !== ""); if (results.length === 0) { $searchResultsHeader.innerText = `Nothing like «${term}»`; return; @@ -192,7 +188,7 @@ function debounce(func, wait) { currentTerm = term; $searchResultsHeader.innerText = `${results.length} found for «${term}»:`; - for (var i = 0; i < Math.min(results.length, MAX_ITEMS); i++) { + for (let i = 0; i < Math.min(results.length, MAX_ITEMS); i++) { if (!results[i].doc.body) { continue; } @@ -215,8 +211,8 @@ function debounce(func, wait) { // mobile function burger() { - let x = document.querySelector("#trees"); - let y = document.querySelector("#mobile"); + const x = document.querySelector("#trees"); + const y = document.querySelector("#mobile"); if (x.style.display === "block") { x.style.display = "none"; @@ -277,7 +273,7 @@ function copyCodeBlockExecCommand(codeToCopy, highlightDiv) { function codeWasCopied(button) { button.blur(); button.innerHTML = ""; - setTimeout(function () { + setTimeout(() => { button.innerHTML = ""; }, 2000); } diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts index bb68457..b675b65 100644 --- a/src/commands/bootstrap.ts +++ b/src/commands/bootstrap.ts @@ -1,8 +1,7 @@ /// import distro from 'linus' -import { bin_name } from '..' -import { log } from '../' +import { bin_name , log } from '..' import { ENGINE_DIR } from '../constants' import { dispatch } from '../utils' import { pacmanInstall } from './bootstrap/arch' diff --git a/src/commands/build.ts b/src/commands/build.ts index e088458..1f2d1e2 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -99,14 +99,14 @@ const genericBuild = async (os: string, tier: string) => { } const parseDate = (d: number) => { - d = d / 1000 - var h = Math.floor(d / 3600) - var m = Math.floor((d % 3600) / 60) - var s = Math.floor((d % 3600) % 60) + d /= 1000 + const h = Math.floor(d / 3600) + const m = Math.floor((d % 3600) / 60) + const s = Math.floor((d % 3600) % 60) - var hDisplay = h > 0 ? h + (h == 1 ? ' hour, ' : ' hours, ') : '' - var mDisplay = m > 0 ? m + (m == 1 ? ' minute, ' : ' minutes, ') : '' - var sDisplay = s > 0 ? s + (s == 1 ? ' second' : ' seconds') : '' + const hDisplay = h > 0 ? h + (h == 1 ? ' hour, ' : ' hours, ') : '' + const mDisplay = m > 0 ? m + (m == 1 ? ' minute, ' : ' minutes, ') : '' + const sDisplay = s > 0 ? s + (s == 1 ? ' second' : ' seconds') : '' return hDisplay + mDisplay + sDisplay } @@ -121,7 +121,7 @@ interface Options { } export const build = async (tier: string, options: Options) => { - let d = Date.now() + const d = Date.now() // Host build @@ -139,7 +139,7 @@ export const build = async (tier: string, options: Options) => { ARCHITECTURE )}.` ) - else arch = options.arch + arch = options.arch } await patchCheck() diff --git a/src/commands/discard.ts b/src/commands/discard.ts index 9cb2466..1569291 100644 --- a/src/commands/discard.ts +++ b/src/commands/discard.ts @@ -39,7 +39,7 @@ export const discard = async (file: string, options: Options) => { const patchFile = resolve( PATCHES_DIR, - file.replace(/\//g, '-').replace(/\./g, '-') + '.patch' + `${file.replace(/\//g, '-').replace(/\./g, '-') }.patch` ) if (!existsSync(patchFile)) diff --git a/src/commands/download-artifacts.ts b/src/commands/download-artifacts.ts index b9d3d37..2784ae7 100644 --- a/src/commands/download-artifacts.ts +++ b/src/commands/download-artifacts.ts @@ -20,7 +20,7 @@ export const downloadArtifacts = async () => { let home = homedir().split(sep).join(posix.sep) if (process.platform == 'win32') { - home = '/' + home.replace(/\:/, '').replace(/\\/g, '/').toLowerCase() + home = `/${ home.replace(/\:/, '').replace(/\\/g, '/').toLowerCase()}` } log.info(`Downloading Windows artifacts...`) @@ -38,10 +38,10 @@ export const downloadArtifacts = async () => { data.on('data', (chunk: any) => { receivedBytes += chunk.length - let rand = Math.floor(Math.random() * 1000 + 1) + const rand = Math.floor(Math.random() * 1000 + 1) if (rand > 999.5) { - let percentCompleted = parseInt( + const percentCompleted = parseInt( Math.round((receivedBytes * 100) / length).toFixed(0) ) if (percentCompleted % 2 == 0 || percentCompleted >= 100) return diff --git a/src/commands/download.ts b/src/commands/download.ts index 0d0b400..e729a59 100644 --- a/src/commands/download.ts +++ b/src/commands/download.ts @@ -28,7 +28,7 @@ const onData = (data: any) => { d.split('\n').forEach((line: any) => { if (line.trim().length !== 0) { - let t = line.split(' ') + const t = line.split(' ') t.shift() initProgressText = t.join(' ') } @@ -58,7 +58,7 @@ const unpack = async (name: string, version: string) => { } catch (e) {} ensureDirSync(ENGINE_DIR) - let tarProc = execa('tar', [ + const tarProc = execa('tar', [ '--transform', `s,firefox-${gFFVersion},engine,`, `--show-transformed`, @@ -161,7 +161,7 @@ export const download = async (firefoxVersion?: string) => { ) ) || fs.existsSync( - resolve(process.cwd(), 'firefox', 'firefox-' + version.split('b')[0]) + resolve(process.cwd(), 'firefox', `firefox-${ version.split('b')[0]}`) ) ) log.error( @@ -187,10 +187,10 @@ export const download = async (firefoxVersion?: string) => { data.on('data', (chunk: any) => { receivedBytes += chunk.length - let rand = Math.floor(Math.random() * 1000 + 1) + const rand = Math.floor(Math.random() * 1000 + 1) if (rand > 999.5) { - let percentCompleted = parseInt( + const percentCompleted = parseInt( Math.round((receivedBytes * 100) / length).toFixed(0) ) if (percentCompleted % 2 == 0 || percentCompleted >= 100) return diff --git a/src/commands/export-file.ts b/src/commands/export-file.ts index f4e8fdf..53fd7c6 100644 --- a/src/commands/export-file.ts +++ b/src/commands/export-file.ts @@ -29,10 +29,10 @@ export const exportFile = async (file: string) => { } ) const name = - file + `${file .split('/') - [file.replace(/\./g, '-').split('/').length - 1].replace(/\./g, '-') + - '.patch' + [file.replace(/\./g, '-').split('/').length - 1].replace(/\./g, '-') + }.patch` const patchPath = file.replace(/\./g, '-').split('/').slice(0, -1) diff --git a/src/commands/export-patches.ts b/src/commands/export-patches.ts index 0ec7246..ccf2aa5 100644 --- a/src/commands/export-patches.ts +++ b/src/commands/export-patches.ts @@ -22,27 +22,25 @@ const flags: { } const getFiles = async (flags: string, cwd: string) => { - let { stdout: ignored } = await execa( + const { stdout: ignored } = await execa( 'git', ['ls-files', `-${flags.toLowerCase()}`, '-i', '-o', '--exclude-standard'], { cwd } ) - let { stdout: fls } = await execa( + const { stdout: fls } = await execa( 'git', ['diff', `--diff-filter=${flags}`, '--name-only', '--ignore-space-at-eol'], { cwd } ) - const files = fls.split('\n').filter((i: any) => { - return !(ignored.split('\n').includes(i) || i == '.gitignore') - }) // this filters out the manual patches + const files = fls.split('\n').filter((i: any) => !(ignored.split('\n').includes(i) || i == '.gitignore')) // this filters out the manual patches log.info(`Ignoring ${ignored.split('\n').length} files...`) const fileNames: any = files.map((f: any) => { if (f.length !== 0) { - return f.replace(/\//g, '-').replace(/\./g, '-') + '.patch' + return `${f.replace(/\//g, '-').replace(/\./g, '-') }.patch` } }) @@ -52,7 +50,7 @@ const getFiles = async (flags: string, cwd: string) => { const exportModified = async (patchesDir: string, cwd: string) => { const { files, fileNames } = await getFiles('M', cwd) - var filesWritten = 0 + let filesWritten = 0 await Promise.all( files.map(async (file: any, i: any) => { @@ -81,7 +79,7 @@ const exportModified = async (patchesDir: string, cwd: string) => { ++filesWritten } catch (e) { log.error(e) - return + } } }) @@ -101,11 +99,10 @@ const exportFlag = async (flag: string, cwd: string, actions: any[]) => { return actions } -const exportManual = async (cwd: string) => { - return new Promise(async (resol) => { +const exportManual = async (cwd: string) => new Promise(async (resol) => { manualPatches.forEach((patch) => { if (patch.action == 'copy') { - if (typeof patch.src == 'string') { + if (typeof patch.src === 'string') { const inSrc = resolve(cwd, patch.src) const outsideSrc = resolve(COMMON_DIR, patch.src) @@ -129,14 +126,13 @@ const exportManual = async (cwd: string) => { } }) }) -} export const exportPatches = async () => { throw new Error( 'export-patches has been deprecated in favour of export-file. This change has been made to limit the amount of active patches we have in the tree.' ) - let actions: any[] = [] + const actions: any[] = [] log.info(`Wiping patches directory...`) console.log() diff --git a/src/commands/import-patches.ts b/src/commands/import-patches.ts index 44fe0c0..e45188b 100644 --- a/src/commands/import-patches.ts +++ b/src/commands/import-patches.ts @@ -19,11 +19,11 @@ const importManual = async (minimal?: boolean, noIgnore?: boolean) => { if (!minimal) console.log() return new Promise(async (res, rej) => { - var total = 0 + const total = 0 - var i = 0 + let i = 0 - for await (let { name, action, src } of manualPatches) { + for await (const { name, action, src } of manualPatches) { ++i const patch = new ManualPatch( @@ -69,7 +69,7 @@ const importPatchFiles = async (minimal?: boolean, noIgnore?: boolean) => { await delay(100) - var i = 0 + let i = 0 for await (const patchName of patches) { ++i @@ -108,7 +108,7 @@ const importMelonPatches = async (minimal?: boolean, noIgnore?: boolean) => { await delay(100) - var i = 0 + let i = 0 for await (const patch of patches) { ++i diff --git a/src/commands/license-check.ts b/src/commands/license-check.ts index a135d8b..5a5726d 100644 --- a/src/commands/license-check.ts +++ b/src/commands/license-check.ts @@ -19,9 +19,9 @@ export const licenseCheck = async () => { return data.split('diff --git a/')[1].split(' b/')[0] }) - let passed: string[] = [] - let failed: string[] = [] - let ignored: string[] = [] + const passed: string[] = [] + const failed: string[] = [] + const ignored: string[] = [] originalPaths.forEach((p) => { const data = readFileSync(resolve(ENGINE_DIR, p), 'utf-8') @@ -32,7 +32,7 @@ export const licenseCheck = async () => { headerRegion.includes('This Source Code Form') && headerRegion.includes('copy of the MPL') - const isIgnored = ignoredExt.find((i) => p.endsWith(i)) ? true : false + const isIgnored = !!ignoredExt.find((i) => p.endsWith(i)) isIgnored && ignored.push(p) if (!isIgnored) { @@ -41,7 +41,7 @@ export const licenseCheck = async () => { } }) - let maxPassed = 5 + const maxPassed = 5 let i = 0 for (const p of passed) { diff --git a/src/commands/reset.ts b/src/commands/reset.ts index 81755c2..e6f1b7e 100644 --- a/src/commands/reset.ts +++ b/src/commands/reset.ts @@ -25,7 +25,7 @@ export const reset = async () => { const { src, action } = patch if (action == 'copy') { - if (typeof src == 'string') { + if (typeof src === 'string') { const path = resolve(ENGINE_DIR, src) if (path !== ENGINE_DIR) { @@ -51,7 +51,7 @@ export const reset = async () => { } }) - let leftovers = new Set() + const leftovers = new Set() const { stdout: origFiles } = await execa( 'git', diff --git a/src/commands/run.ts b/src/commands/run.ts index ebe87e4..ef53c57 100644 --- a/src/commands/run.ts +++ b/src/commands/run.ts @@ -6,9 +6,7 @@ import { dispatch } from '../utils' export const run = async (chrome?: string) => { const dirs = readdirSync(ENGINE_DIR) - const objDirname: any = dirs.find((dir) => { - return dir.startsWith('obj-') - }) + const objDirname: any = dirs.find((dir) => dir.startsWith('obj-')) if (!objDirname) { throw new Error('Dot Browser needs to be built before you can do this.') diff --git a/src/commands/setupProject.ts b/src/commands/setupProject.ts index fd22ffe..6183cbd 100644 --- a/src/commands/setupProject.ts +++ b/src/commands/setupProject.ts @@ -61,7 +61,7 @@ export async function setupProject() { ], }) - if (typeof product == 'undefined') return + if (typeof product === 'undefined') return const productVersion = await getLatestFF(product) diff --git a/src/constants/index.ts b/src/constants/index.ts index d0f5d59..e46ab39 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -1,5 +1,6 @@ import execa from 'execa' import { resolve } from 'path' +import { log } from '..' export const BUILD_TARGETS = ['linux', 'windows', 'macos'] @@ -17,15 +18,21 @@ export const PATCHES_DIR = resolve(process.cwd(), 'patches') export const COMMON_DIR = resolve(process.cwd(), 'common') export const CONFIGS_DIR = resolve(process.cwd(), 'configs') -export let CONFIG_GUESS: any = null +export let CONFIG_GUESS: string try { CONFIG_GUESS = execa.commandSync('./build/autoconf/config.guess', { cwd: ENGINE_DIR, }).stdout -} catch (e) {} +} catch (e) { + log.warning('An error occurred running engine/build/autoconf/config.guess') + log.warning(e) + log.askForReport() + + process.exit(1) +} export const OBJ_DIR = resolve(ENGINE_DIR, `obj-${CONFIG_GUESS}`) export const FTL_STRING_LINE_REGEX = - /(([a-zA-Z0-9\-]*|\.[a-z\-]*) =(.*|\.)|\[[a-zA-Z0-9]*\].*(\n\s?\s?})?|\*\[[a-zA-Z0-9]*\] .*(\n\s?\s?})?)/gm + /(([a-zA-Z0-9-]*|\.[a-z-]*) =(.*|\.)|\[[a-zA-Z0-9]*\].*(\n\s?\s?})?|\*\[[a-zA-Z0-9]*\] .*(\n\s?\s?})?)/gm diff --git a/src/controllers/patch.ts b/src/controllers/patch.ts index 41810f7..315bf29 100644 --- a/src/controllers/patch.ts +++ b/src/controllers/patch.ts @@ -14,7 +14,7 @@ import { dirname, join, resolve } from 'path' import readline from 'readline' import sharp from 'sharp' import { log } from '..' -import { CONFIGS_DIR, ENGINE_DIR, PATCH_ARGS, SRC_DIR } from '../constants' +import { CONFIGS_DIR, ENGINE_DIR, PATCH_ARGS } from '../constants' import { copyManual, walkDirectory } from '../utils' export interface IPatchApplier { @@ -24,13 +24,16 @@ export interface IPatchApplier { export class PatchBase { protected name: string + protected status: number[] + protected options: { minimal?: boolean noIgnore?: boolean } private _done = false + protected error: Error | unknown constructor( @@ -46,11 +49,11 @@ export class PatchBase { this.options = options } - protected get done() { + protected get done(): boolean { return this._done } - protected set done(_: any) { + protected set done(_: boolean) { this._done = _ if (this.options.minimal) return @@ -74,7 +77,7 @@ export class PatchBase { } } - protected start() { + protected start(): void { if (this.options.minimal) return log.info( @@ -86,13 +89,14 @@ export class PatchBase { public async applyWithStatus(status: [number, number]): Promise { this.status = status - if (!(this as any).apply) return - await (this as any as IPatchApplier).apply() + if (!(this as unknown as IPatchApplier).apply) return + await (this as unknown as IPatchApplier).apply() } } export class ManualPatch extends PatchBase implements IPatchApplier { private action: 'copy' | 'delete' + private src: string | string[] constructor( @@ -199,7 +203,7 @@ export class PatchFile extends PatchBase implements IPatchApplier { try { try { - await execa('git', ['apply', '-R', ...PATCH_ARGS, this.src as any], { + await execa('git', ['apply', '-R', ...PATCH_ARGS, this.src], { cwd: ENGINE_DIR, }) } catch (e) { @@ -208,7 +212,7 @@ export class PatchFile extends PatchBase implements IPatchApplier { const { stdout, exitCode } = await execa( 'git', - ['apply', ...PATCH_ARGS, this.src as any], + ['apply', ...PATCH_ARGS, this.src], { cwd: ENGINE_DIR } ) diff --git a/src/index.ts b/src/index.ts index c90fe48..40bee87 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,27 +1,26 @@ -import Log from './log' - -// The logger must be initialized before the config generator, otherwise reference -// errors occur -export let log = new Log() - import chalk from 'chalk' import commander, { Command } from 'commander' import { existsSync, readFileSync } from 'fs' import { resolve } from 'path' +import Log from './log' import { errorHandler, getConfig } from './utils' import { commands } from './cmds' import { ENGINE_DIR } from './constants' import { shaCheck } from './middleware/sha-check' import { updateCheck } from './middleware/update-check' +import { version as melon } from '../package.json' + +// The logger must be initialized before the config generator, otherwise reference +// errors occur +export const log = new Log() + export const config = getConfig() const program = new Command() program.storeOptionsAsProperties(false).passCommandToAction(false) -const { version: melon } = require('../package.json') - let reportedFFVersion if (existsSync(resolve(ENGINE_DIR, 'browser', 'config', 'version.txt'))) { @@ -74,7 +73,7 @@ commands.forEach((command) => { _cmd.option(opt.arg, opt.description) }) - _cmd.action(async (...args: any) => { + _cmd.action(async (...args: unknown[]) => { await shaCheck(command.cmd) await updateCheck() diff --git a/src/log.ts b/src/log.ts index 233b214..e1b5250 100644 --- a/src/log.ts +++ b/src/log.ts @@ -9,45 +9,49 @@ class Log { this.startTime = d.getTime() } - getDiff() { + getDiff(): string { const d = new Date() const currentTime = d.getTime() const elapsedTime = currentTime - this.startTime - var secs = Math.floor((elapsedTime / 1000) % 60) - var mins = Math.floor((elapsedTime / (60 * 1000)) % 60) - var hours = Math.floor((elapsedTime / (60 * 60 * 1000)) % 24) + const secs = Math.floor((elapsedTime / 1000) % 60) + const mins = Math.floor((elapsedTime / (60 * 1000)) % 60) + const hours = Math.floor((elapsedTime / (60 * 60 * 1000)) % 24) - const format = (r: number) => { - return r.toString().length == 1 ? '0' + r : r - } + const format = (r: number) => (r.toString().length == 1 ? `0${r}` : r) return `${format(hours)}:${format(mins)}:${format(secs)}` } - info(...args: any[]) { + info(...args: unknown[]): void { console.info(chalk.blueBright.bold(this.getDiff()), ...args) } - warning(...args: any[]) { + warning(...args: unknown[]): void { console.info(chalk.yellowBright.bold(' WARNING'), ...args) } - hardWarning(...args: any[]) { + hardWarning(...args: unknown[]): void { console.info('', chalk.bgRed.bold('WARNING'), ...args) } - success(...args: any[]) { + success(...args: unknown[]): void { console.log(`\n${chalk.greenBright.bold('SUCCESS')}`, ...args) } - error(...args: any[]) { - throw new Error(...args) + error(...args: unknown[]): void { + if (args[0] instanceof Error) { + throw args[0] + } + + throw new Error( + ...args.map((a) => (typeof a !== 'undefined' ? a.toString() : a)) + ) } - askForReport() { + askForReport(): void { console.info( 'The following error is a bug. Please open an issue on the melon issue structure with a link to your repository and the output from this command.' ) diff --git a/src/manual-patches.ts b/src/manual-patches.ts index bcb2332..a73d23c 100644 --- a/src/manual-patches.ts +++ b/src/manual-patches.ts @@ -2,7 +2,7 @@ import { sync } from 'glob' import { SRC_DIR } from './constants' import { IPatch } from './interfaces/patch' -let files = sync('**/*', { +const files = sync('**/*', { nodir: true, cwd: SRC_DIR, }).filter( diff --git a/src/middleware/patch-check.ts b/src/middleware/patch-check.ts index 3aed4c8..f02f6f7 100644 --- a/src/middleware/patch-check.ts +++ b/src/middleware/patch-check.ts @@ -9,7 +9,7 @@ import { walkDirectory } from '../utils' export const patchCountFile = resolve(process.cwd(), '.dotbuild', 'patchCount') -export const patchCheck = async () => { +export const patchCheck = async (): Promise => { const fileList = await walkDirectory(resolve(process.cwd(), 'src')) const patchCount = fileList.length diff --git a/src/middleware/sha-check.ts b/src/middleware/sha-check.ts index e7e7ebc..1ed2e5b 100644 --- a/src/middleware/sha-check.ts +++ b/src/middleware/sha-check.ts @@ -5,7 +5,7 @@ import { bin_name, log } from '..' const blacklistedCommands = ['reset', 'init', 'set-branch'] -export const shaCheck = async (command: string) => { +export const shaCheck = async (command: string): Promise => { if ( blacklistedCommands.filter((c) => command.startsWith(c)).length !== 0 || !existsSync(resolve(process.cwd(), '.dotbuild', 'metadata')) diff --git a/src/middleware/update-check.ts b/src/middleware/update-check.ts index 5f26c10..c923b0f 100644 --- a/src/middleware/update-check.ts +++ b/src/middleware/update-check.ts @@ -1,7 +1,7 @@ import axios from 'axios' -import { config, log } from '../' +import { config, log } from '..' -export const updateCheck = async () => { +export const updateCheck = async (): Promise => { const firefoxVersion = config.version.version try { @@ -11,12 +11,16 @@ export const updateCheck = async () => { ) if (data) { - let version = Object.keys(data)[Object.keys(data).length - 1] + const version = Object.keys(data)[Object.keys(data).length - 1] if (firefoxVersion && version !== firefoxVersion) log.warning( `Latest version of Firefox (${version}) does not match frozen version (${firefoxVersion}).` ) } - } catch (e) {} + } catch (e) { + log.warning(`Failed to check for updates.`) + log.warning(e) + log.askForReport() + } } diff --git a/src/utils/delay.ts b/src/utils/delay.ts index 6ce370a..b089d49 100644 --- a/src/utils/delay.ts +++ b/src/utils/delay.ts @@ -1,5 +1,4 @@ -export const delay = (delay: number) => { - return new Promise((resolve) => { +export const delay = (delay: number): Promise => + new Promise((resolve) => { setTimeout(() => resolve(true), delay) }) -} diff --git a/src/utils/dispatch.ts b/src/utils/dispatch.ts index 6993c3f..2e38fca 100644 --- a/src/utils/dispatch.ts +++ b/src/utils/dispatch.ts @@ -1,10 +1,10 @@ import execa from 'execa' import { log } from '..' -const handle = (data: any, killOnError?: boolean) => { +const handle = (data: string | Error, killOnError?: boolean) => { const d = data.toString() - d.split('\n').forEach((line: any) => { + d.split('\n').forEach((line: string) => { if (line.length !== 0) log.info(line.replace(/\s\d{1,5}:\d\d\.\d\d /g, '')) }) @@ -16,16 +16,16 @@ const handle = (data: any, killOnError?: boolean) => { export const dispatch = ( cmd: string, - args?: any[], + args?: string[], cwd?: string, noLog?: boolean, killOnError?: boolean -) => { - return new Promise((resolve, reject) => { +): Promise => + new Promise((resolve) => { process.env.MACH_USE_SYSTEM_PYTHON = 'true' const proc = execa(cmd, args, { - cwd: cwd ? cwd : process.cwd(), + cwd: cwd || process.cwd(), env: process.env, }) @@ -39,4 +39,3 @@ export const dispatch = ( resolve(true) }) }) -} diff --git a/src/utils/error-handler.ts b/src/utils/error-handler.ts index f1bf9d1..dff32bd 100644 --- a/src/utils/error-handler.ts +++ b/src/utils/error-handler.ts @@ -3,7 +3,7 @@ import { readFileSync } from 'fs-extra' import { resolve } from 'path' import { log } from '..' -export const errorHandler = (err: Error, isUnhandledRej: boolean) => { +export const errorHandler = (err: Error, isUnhandledRej: boolean): void => { let cc = readFileSync(resolve(process.cwd(), '.dotbuild', 'command'), 'utf-8') cc = cc.replace(/(\r\n|\n|\r)/gm, '') @@ -21,7 +21,10 @@ export const errorHandler = (err: Error, isUnhandledRej: boolean) => { : err.message.replace(/\n/g, '\n\t ') ) if (err.stack || isUnhandledRej) { - const stack: any = err.stack?.split('\n') + const stack: string[] | undefined = err.stack?.split('\n') + + if (!stack) return + stack.shift() stack.shift() console.log( @@ -29,7 +32,7 @@ export const errorHandler = (err: Error, isUnhandledRej: boolean) => { stack .join('\n') .replace(/(\r\n|\n|\r)/gm, '') - .replace(/ at /g, '\n\t • ') + .replace(/ {4}at /g, '\n\t • ') ) } diff --git a/src/utils/import.ts b/src/utils/import.ts index 86638bb..d1d9dd7 100644 --- a/src/utils/import.ts +++ b/src/utils/import.ts @@ -6,13 +6,12 @@ import { } from 'fs-extra' import { resolve } from 'path' import rimraf from 'rimraf' +import { log } from '..' import { ENGINE_DIR, SRC_DIR } from '../constants' -const getChunked = (location: string) => { - return location.replace(/\\/g, '/').split('/') -} +const getChunked = (location: string) => location.replace(/\\/g, '/').split('/') -export const copyManual = (name: string, noIgnore?: boolean) => { +export const copyManual = (name: string, noIgnore?: boolean): void => { try { try { if ( @@ -20,7 +19,9 @@ export const copyManual = (name: string, noIgnore?: boolean) => { ) { rimraf.sync(resolve(ENGINE_DIR, ...getChunked(name))) } - } catch (e) {} + } catch (e) { + log.error(e) + } ensureSymlink( resolve(SRC_DIR, ...getChunked(name)), @@ -41,6 +42,5 @@ export const copyManual = (name: string, noIgnore?: boolean) => { } catch (e) { console.log(e) process.exit(0) - // return e; } } diff --git a/src/utils/version.ts b/src/utils/version.ts index be39009..3836bad 100644 --- a/src/utils/version.ts +++ b/src/utils/version.ts @@ -12,7 +12,7 @@ const firefoxTargets = JSON.parse(`{ export const getLatestFF = async ( product: SupportedProducts = SupportedProducts.Firefox -) => { +): Promise => { const { data } = await axios.get( 'https://product-details.mozilla.org/1.0/firefox_versions.json' ) diff --git a/src/utils/write-metadata.ts b/src/utils/write-metadata.ts index 7c34af4..049e2d4 100644 --- a/src/utils/write-metadata.ts +++ b/src/utils/write-metadata.ts @@ -1,10 +1,9 @@ import execa from 'execa' import { writeFileSync } from 'fs-extra' import { resolve } from 'path' +import { config } from '..' -const pjson = require('../../package.json') - -export const writeMetadata = async () => { +export const writeMetadata = async (): Promise => { const { stdout: sha } = await execa('git', ['rev-parse', 'HEAD']) const { stdout: branch } = await execa('git', ['branch', '--show-current']) @@ -14,7 +13,7 @@ export const writeMetadata = async () => { sha, branch, birth: Date.now(), - versions: pjson.versions, + versions: config.version, }) ) } diff --git a/tsconfig.json b/tsconfig.json index c919474..f4e3880 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -58,7 +58,9 @@ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true /* Skip type checking of declaration files. */, - "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */, + + "resolveJsonModule": true }, "exclude": [ "node_modules/**/*",