Re-enable require-await

This commit is contained in:
Oliver Blanthorn 2020-06-19 13:48:22 +01:00
parent ab13c700ee
commit dee3b7e6c1
No known key found for this signature in database
GPG key ID: 2BB8C36BB504BFF3
6 changed files with 78 additions and 64 deletions

View file

@ -137,7 +137,7 @@ module.exports = {
"avoidEscape": true "avoidEscape": true
} }
], ],
"@typescript-eslint/require-await": "off", //"error", "@typescript-eslint/require-await": "error",
"@typescript-eslint/restrict-plus-operands": "off", //"error", // We use this a lot - fixing it is a problem for a rainy day "@typescript-eslint/restrict-plus-operands": "off", //"error", // We use this a lot - fixing it is a problem for a rainy day
"@typescript-eslint/restrict-template-expressions": "off", "@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/semi": [ "@typescript-eslint/semi": [
@ -252,11 +252,12 @@ module.exports = {
"use-isnan": "error", "use-isnan": "error",
"valid-typeof": "off" "valid-typeof": "off"
}, },
// // We ultimately didn't need this but I thought I should document it anyway "overrides": [{
// "overrides": [{ "files": ["src/completions/*.ts", "src/excmds.ts"],
// "files": ["src/completions/*.ts",], "rules": {
// "rules": { // We have methods that must be async in some classes but not in others
// "@typescript-eslint/no-empty-function": "off", // In src/excmds anything that crosses between content<->background must be async even if it looks like it isn't
// }, "@typescript-eslint/require-await": "off",
// }], },
}],
}; };

View file

@ -4,13 +4,14 @@
*/ */
import * as controller from "@src/lib/controller" import * as controller from "@src/lib/controller"
export async function inputEnteredListener( export function inputEnteredListener(
input: string, disposition: input: string,
browser.omnibox.OnInputEnteredDisposition) { disposition: browser.omnibox.OnInputEnteredDisposition,
) {
controller.acceptExCmd(input) controller.acceptExCmd(input)
} }
export async function init() { export function init() {
browser.omnibox.onInputEntered.addListener(inputEnteredListener) browser.omnibox.onInputEntered.addListener(inputEnteredListener)
browser.omnibox.setDefaultSuggestion({ browser.omnibox.setDefaultSuggestion({
description: `Execute a Tridactyl exstr (for example, "tabopen -c container www.google.com")`, description: `Execute a Tridactyl exstr (for example, "tabopen -c container www.google.com")`,

View file

@ -2620,9 +2620,7 @@ export async function qall() {
//#background //#background
export async function containerclose(name: string) { export async function containerclose(name: string) {
const containerId = await Container.getId(name) const containerId = await Container.getId(name)
return browser.tabs.query({ cookieStoreId: containerId }).then(tabs => browser.tabs.remove( return browser.tabs.query({ cookieStoreId: containerId }).then(tabs => browser.tabs.remove(tabs.map(tab => tab.id)))
tabs.map(tab => tab.id),
))
} }
/** Creates a new container. Note that container names must be unique and that the checks are case-insensitive. /** Creates a new container. Note that container names must be unique and that the checks are case-insensitive.
@ -2669,7 +2667,7 @@ export async function containerupdate(name: string, uname: string, ucolor: strin
logger.debug("containerupdate parameters: " + name + ", " + uname + ", " + ucolor + ", " + uicon) logger.debug("containerupdate parameters: " + name + ", " + uname + ", " + ucolor + ", " + uicon)
const containerId = await Container.fuzzyMatch(name) const containerId = await Container.fuzzyMatch(name)
const containerObj = Container.fromString(uname, ucolor, uicon) const containerObj = Container.fromString(uname, ucolor, uicon)
await Container.update(containerId, containerObj) Container.update(containerId, containerObj)
} }
/** Shows a list of the current containers in Firefox's native JSON viewer in the current tab. /** Shows a list of the current containers in Firefox's native JSON viewer in the current tab.
@ -3617,8 +3615,7 @@ export async function sanitise(...args: string[]) {
*/ */
} }
if (args.find(x => x === "all") !== undefined) { if (args.find(x => x === "all") !== undefined) {
for (const attr in dts) for (const attr in dts) if (Object.prototype.hasOwnProperty.call(dts, attr)) dts[attr] = true
if (Object.prototype.hasOwnProperty.call(dts, attr)) dts[attr] = true
} else { } else {
// We bother checking if dts[x] is false because // We bother checking if dts[x] is false because
// browser.browsingData.remove() is very strict on the format of the // browser.browsingData.remove() is very strict on the format of the

View file

@ -80,7 +80,7 @@ export async function remove(name: string) {
@param color the new color of the container @param color the new color of the container
@param icon the new icon of the container @param icon the new icon of the container
*/ */
export async function update( export function update(
containerId: string, containerId: string,
updateObj: { updateObj: {
name: string name: string
@ -88,7 +88,7 @@ export async function update(
icon: browser.contextualIdentities.IdentityIcon icon: browser.contextualIdentities.IdentityIcon
}, },
) { ) {
const {name, color, icon} = updateObj const { name, color, icon } = updateObj
if (!isValidColor(color)) { if (!isValidColor(color)) {
logger.debug(updateObj) logger.debug(updateObj)
throw new Error("[Container.update] invalid container color: " + color) throw new Error("[Container.update] invalid container color: " + color)
@ -97,7 +97,7 @@ export async function update(
logger.debug(updateObj) logger.debug(updateObj)
throw new Error("[Container.update] invalid container icon: " + icon) throw new Error("[Container.update] invalid container icon: " + icon)
} }
browser.contextualIdentities.update(containerId, {name, color, icon}) browser.contextualIdentities.update(containerId, { name, color, icon })
} }
/** Gets a container object from a supplied container id string. If no container corresponds to containerId, returns a default empty container. /** Gets a container object from a supplied container id string. If no container corresponds to containerId, returns a default empty container.
@ -122,7 +122,9 @@ export async function exists(cname: string): Promise<boolean> {
let exists = false let exists = false
try { try {
const containers = await getAll() const containers = await getAll()
const res = containers.filter(c => c.name.toLowerCase() === cname.toLowerCase()) const res = containers.filter(
c => c.name.toLowerCase() === cname.toLowerCase(),
)
if (res.length > 0) { if (res.length > 0) {
exists = true exists = true
} }

View file

@ -102,7 +102,8 @@ export async function getBestEditor(): Promise<string> {
const vim_positioning_arg = ` ${arg_quote}+normal!%lGzv%c|${arg_quote}` const vim_positioning_arg = ` ${arg_quote}+normal!%lGzv%c|${arg_quote}`
if (os === "mac") { if (os === "mac") {
gui_candidates = [ gui_candidates = [
"/Applications/MacVim.app/Contents/bin/mvim -f" + vim_positioning_arg, "/Applications/MacVim.app/Contents/bin/mvim -f" +
vim_positioning_arg,
"/usr/local/bin/vimr --wait --nvim +only", "/usr/local/bin/vimr --wait --nvim +only",
] ]
// if anyone knows of any "sensible" terminals that let you send them commands to run, // if anyone knows of any "sensible" terminals that let you send them commands to run,
@ -149,7 +150,12 @@ export async function getBestEditor(): Promise<string> {
] ]
} }
tui_editors = ["vim" + vim_positioning_arg, "nvim" + vim_positioning_arg, "nano %f", "emacs -nw %f"] tui_editors = [
"vim" + vim_positioning_arg,
"nvim" + vim_positioning_arg,
"nano %f",
"emacs -nw %f",
]
// Consider GUI editors // Consider GUI editors
let cmd = await firstinpath(gui_candidates) let cmd = await firstinpath(gui_candidates)
@ -246,12 +252,17 @@ export async function firstinpath(cmdarray) {
return cmd return cmd
} }
export async function editor(file: string, line: number, col: number, content?: string) { export async function editor(
file: string,
line: number,
col: number,
content?: string,
) {
if (content !== undefined) await write(file, content) if (content !== undefined) await write(file, content)
const editorcmd = const editorcmd = (config.get("editorcmd") === "auto"
(config.get("editorcmd") === "auto" ? await getBestEditor()
? await getBestEditor() : config.get("editorcmd")
: config.get("editorcmd")) )
.replace(/%l/, line) .replace(/%l/, line)
.replace(/%c/, col) .replace(/%c/, col)
let exec let exec
@ -260,8 +271,7 @@ export async function editor(file: string, line: number, col: number, content?:
} else { } else {
exec = await run(editorcmd + " " + file) exec = await run(editorcmd + " " + file)
} }
if (exec.code != 0) if (exec.code != 0) return exec
return exec
return read(file) return read(file)
} }
@ -371,9 +381,7 @@ export async function clipboard(
const result = await run(`${clipcmd} -i`, str) const result = await run(`${clipcmd} -i`, str)
if (result.code !== 0) if (result.code !== 0)
throw new Error( throw new Error(
`External command failed with code ${ `External command failed with code ${result.code}: ${clipcmd}`,
result.code
}: ${clipcmd}`,
) )
return "" return ""
} else { } else {
@ -448,9 +456,7 @@ export async function parseProfilesIni(content: string, basePath: string) {
} else if (profile.IsRelative === "0") { } else if (profile.IsRelative === "0") {
if (profile.Path.substring(0, basePath.length) !== basePath) { if (profile.Path.substring(0, basePath.length) !== basePath) {
throw new Error( throw new Error(
`Error parsing profiles ini: basePath "${basePath}" doesn't match profile path ${ `Error parsing profiles ini: basePath "${basePath}" doesn't match profile path ${profile.Path}`,
profile.Path
}`,
) )
} }
profile.relativePath = profile.Path.substring(basePath.length) profile.relativePath = profile.Path.substring(basePath.length)
@ -509,8 +515,7 @@ export async function getProfileUncached() {
// Then, try to find a profile path in the arguments given to Firefox // Then, try to find a profile path in the arguments given to Firefox
const cmdline = await ff_cmdline().catch(e => "") const cmdline = await ff_cmdline().catch(e => "")
let profile = cmdline.indexOf("--profile") let profile = cmdline.indexOf("--profile")
if (profile === -1) if (profile === -1) profile = cmdline.indexOf("-profile")
profile = cmdline.indexOf("-profile")
if (profile >= 0 && profile < cmdline.length - 1) { if (profile >= 0 && profile < cmdline.length - 1) {
const profilePath = cmdline[profile + 1] const profilePath = cmdline[profile + 1]
if (iniSucceeded) { if (iniSucceeded) {
@ -545,9 +550,7 @@ export async function getProfileUncached() {
} }
} }
throw new Error( throw new Error(
`native.ts:getProfile() : '${ `native.ts:getProfile() : '${cmdline[p]}' found in command line arguments but no matching profile name found in "${iniPath}"`,
cmdline[p]
}' found in command line arguments but no matching profile name found in "${iniPath}"`,
) )
} }
} }
@ -562,10 +565,7 @@ export async function getProfileUncached() {
profilecmd.content = profilecmd.content.trim() profilecmd.content = profilecmd.content.trim()
// If there's only one profile in use, use that to find the right profile // If there's only one profile in use, use that to find the right profile
if (profilecmd.content.split("\n").length === 1) { if (profilecmd.content.split("\n").length === 1) {
const path = profilecmd.content const path = profilecmd.content.split("/").slice(0, -1).join("/")
.split("/")
.slice(0, -1)
.join("/")
if (iniSucceeded) { if (iniSucceeded) {
for (const profileName of Object.keys(iniObject)) { for (const profileName of Object.keys(iniObject)) {
const profile = iniObject[profileName] const profile = iniObject[profileName]
@ -602,8 +602,7 @@ export async function getProfileUncached() {
// Disk operations are extremely slow on windows, let's cache our profile info // Disk operations are extremely slow on windows, let's cache our profile info
let cachedProfile let cachedProfile
export async function getProfile() { export async function getProfile() {
if (cachedProfile === undefined) if (cachedProfile === undefined) cachedProfile = await getProfileUncached()
cachedProfile = await getProfileUncached()
return cachedProfile return cachedProfile
} }
// It makes sense to pre-fetch this value in the background script because it's // It makes sense to pre-fetch this value in the background script because it's
@ -627,7 +626,7 @@ export async function getProfileDir() {
return getProfile().then(p => p.absolutePath) return getProfile().then(p => p.absolutePath)
} }
export async function parsePrefs(prefFileContent: string) { export function parsePrefs(prefFileContent: string) {
// This RegExp currently only deals with " but for correctness it should // This RegExp currently only deals with " but for correctness it should
// also deal with ' and ` // also deal with ' and `
// We could also just give up on parsing and eval() the whole thing // We could also just give up on parsing and eval() the whole thing
@ -790,17 +789,23 @@ export async function unfixamo() {
const tridactylPref2 = "tridactyl.unfixedamo_removed" const tridactylPref2 = "tridactyl.unfixedamo_removed"
const restricted = "extensions.webextensions.restrictedDomains" const restricted = "extensions.webextensions.restrictedDomains"
const amoblocker = "privacy.resistFingerprinting.block_mozAddonManager" const amoblocker = "privacy.resistFingerprinting.block_mozAddonManager"
const restrictedDomains = '"accounts-static.cdn.mozilla.net,accounts.firefox.com,addons.cdn.mozilla.net,addons.mozilla.org,api.accounts.firefox.com,content.cdn.mozilla.net,discovery.addons.mozilla.org,install.mozilla.org,oauth.accounts.firefox.com,profile.accounts.firefox.com,support.mozilla.org,sync.services.mozilla.com"' const restrictedDomains =
'"accounts-static.cdn.mozilla.net,accounts.firefox.com,addons.cdn.mozilla.net,addons.mozilla.org,api.accounts.firefox.com,content.cdn.mozilla.net,discovery.addons.mozilla.org,install.mozilla.org,oauth.accounts.firefox.com,profile.accounts.firefox.com,support.mozilla.org,sync.services.mozilla.com"'
// Exit if we've already run this once // Exit if we've already run this once
if (userjs[tridactylPref2] === "true") return if (userjs[tridactylPref2] === "true") return
if (userjs[restricted] === "" || userjs[restricted] === restrictedDomains) { if (
userjs[restricted] === "" ||
userjs[restricted] === restrictedDomains
) {
await removePref(tridactylPref) // Clean up after first attempt if it exists await removePref(tridactylPref) // Clean up after first attempt if it exists
await removePref(restricted) await removePref(restricted)
await removePref(amoblocker) await removePref(amoblocker)
await writePref(tridactylPref2, "true") await writePref(tridactylPref2, "true")
browserBg.tabs.create({url: browserBg.runtime.getURL("static/unfixamo.html")}) browserBg.tabs.create({
url: browserBg.runtime.getURL("static/unfixamo.html"),
})
} }
return return

View file

@ -39,10 +39,12 @@ export const browserBg = inContentScript() ? browserProxy : browser
* *
*/ */
export async function activeTab() { export async function activeTab() {
return (await browserBg.tabs.query({ return (
active: true, await browserBg.tabs.query({
currentWindow: true, active: true,
}))[0] currentWindow: true,
})
)[0]
} }
export async function activeTabId() { export async function activeTabId() {
@ -122,9 +124,11 @@ export async function openInNewTab(
break break
case "last": case "last":
// Infinity can't be serialised, apparently. // Infinity can't be serialised, apparently.
options.index = (await browserBg.tabs.query({ options.index = (
currentWindow: true, await browserBg.tabs.query({
})).length currentWindow: true,
})
).length
break break
case "related": case "related":
if (await firefoxVersionAtLeast(57)) { if (await firefoxVersionAtLeast(57)) {
@ -135,16 +139,20 @@ export async function openInNewTab(
break break
} }
if (kwargs.active === false) { // load in background if (kwargs.active === false) {
// load in background
return browserBg.tabs.create(options) return browserBg.tabs.create(options)
} else { // load in background and then activate, per issue #1993 } else {
return browserBg.tabs.create(options).then(newtab => browserBg.tabs.update(newtab.id, { active: true })) // load in background and then activate, per issue #1993
return browserBg.tabs
.create(options)
.then(newtab => browserBg.tabs.update(newtab.id, { active: true }))
} }
} }
// lazily copied from excmds.ts' winopen - forceURI really ought to be moved to lib/webext // lazily copied from excmds.ts' winopen - forceURI really ought to be moved to lib/webext
// Should consider changing interface of this to match openInNewTab or vice versa // Should consider changing interface of this to match openInNewTab or vice versa
export async function openInNewWindow(createData = {}) { export function openInNewWindow(createData = {}) {
browserBg.windows.create(createData) browserBg.windows.create(createData)
} }
@ -254,5 +262,5 @@ export async function openInTab(tab, opts = {}, strarr: string[]) {
// No search engine has been defined in Tridactyl, let's use firefox's default search engine // No search engine has been defined in Tridactyl, let's use firefox's default search engine
browserBg.search.search({ tabId: tab.id, query: queryString }) browserBg.search.search({ tabId: tab.id, query: queryString })
return tab; return tab
} }