Add source for RC files, source_quiet at startup

Commit attributed to Isaac as he was instrumental to getting this in.
@bovine3dom added all of the bugs.
This commit is contained in:
Isaac Khor 2018-05-10 21:22:14 +01:00 committed by Oliver Blanthorn
parent d0ca2cf770
commit 5a7c786840
No known key found for this signature in database
GPG key ID: 2BB8C36BB504BFF3
6 changed files with 1931 additions and 1816 deletions

View file

@ -8,7 +8,7 @@ import struct
import subprocess
import tempfile
VERSION = "0.1.2"
VERSION = "0.1.3"
class NoConnectionError(Exception):
""" Exception thrown when stdin cannot be read """
@ -64,6 +64,43 @@ def sendMessage(encodedMessage):
sys.stdout.buffer.flush()
def findUserConfigFile():
""" Find a user config file, if it exists. Return the file path, or None
if not found
"""
home = os.path.expanduser('~')
config_dir = getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
# Will search for files in this order
candidate_files = [
os.path.join(config_dir, "tridactyl", "tridactylrc"),
os.path.join(home, '.tridactylrc')
]
config_path = None
# find the first path in the list that exists
for path in candidate_files:
if os.path.isfile(path):
config_path = path
break
return config_path
def getUserConfig():
# look it up freshly each time - the user could have moved or killed it
cfg_file = findUserConfigFile()
# no file, return
if not cfg_file:
return None
# for now, this is a simple file read, but if the files can
# include other files, that will need more work
return open(cfg_file, 'r').read()
def handleMessage(message):
""" Generate reply from incoming message. """
cmd = message["cmd"]
@ -72,6 +109,13 @@ def handleMessage(message):
if cmd == 'version':
reply = {'version': VERSION}
elif cmd == 'getconfig':
file_content = getUserConfig()
if file_content:
reply['content'] = file_content
else:
reply['code'] = 'File not found'
elif cmd == 'run':
commands = message["command"]

3631
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -79,3 +79,6 @@ browser.storage.onChanged.addListener((changes, areaname) => {
// Prevent Tridactyl from being updated while it is running in the hope of fixing #290
browser.runtime.onUpdateAvailable.addListener(_ => {})
// Try to load an RC file
excmds.source_quiet()

28
src/config_rc.ts Normal file
View file

@ -0,0 +1,28 @@
import * as Controller from "./controller"
import * as Native from "./native_background"
import Logger from "./logging"
const logger = new Logger("rc")
export async function source(filename = "auto") {
let rctext = ""
if (filename == "auto") {
rctext = await Native.getrc()
} else {
rctext = (await Native.read(filename)).content
}
runRc(rctext)
}
export async function runRc(rc: string) {
for (let cmd of rcFileToExCmds(rc)) {
await Controller.acceptExCmd(cmd)
}
}
export function rcFileToExCmds(rcText: string): string[] {
const excmds = rcText.split("\n")
// Remove comment lines
return excmds.filter(x => x != "" && !x.trim().startsWith('"'))
}

View file

@ -117,6 +117,7 @@ import { ModeName } from "./state"
import * as keydown from "./keydown_background"
import { activeTab, firefoxVersionAtLeast, openInNewTab } from "./lib/webext"
import * as CommandLineBackground from "./commandline_background"
import * as rc from "./config_rc"
//#background_helper
import * as Native from "./native_background"
@ -311,6 +312,32 @@ export async function installnative() {
fillcmdline("# Installation command copied to clipboard. Please paste and run it in your shell to install the native messenger.")
}
/**
* Runs an RC file from disk.
*
* If no argument given, it will try to open ~/.tridactylrc, ~/.config/tridactylrc or $XDG_CONFIG_HOME/tridactyl/tridactylrc in reverse order.
*
* @param fileArr the file to open. Must be an absolute path and can't contain magic strings like ~.
*/
//#background
export async function source(...fileArr: string[]) {
const file = fileArr.join(" ") || undefined
if (await Native.nativegate("0.1.3")) rc.source(file)
}
/**
* Same as [[source]] but suppresses all errors
*/
//#background
export async function source_quiet(...fileArr: string[]) {
try {
const file = fileArr.join(" ") || undefined
if (await Native.nativegate("0.1.3", false)) rc.source(file)
} catch (e) {
logger.info("Automatic loading of RC file failed.")
}
}
/**
* Updates the native messenger if it is installed, using our GitHub repo. This is run every time Tridactyl is updated.
*

View file

@ -17,6 +17,7 @@ type MessageCommand =
| "temp"
| "mkdir"
| "eval"
| "getconfig"
| "env"
interface MessageResp {
cmd: string
@ -50,6 +51,17 @@ async function sendNativeMsg(
}
}
export async function getrc(): Promise<string> {
const res = await sendNativeMsg("getconfig", {})
if (res.content && !res.error) {
logger.info(`Successfully retrieved fs config:\n${res.content}`)
return res.content
} else {
logger.error(`Error in retrieving config: ${res.error}`)
}
}
export async function getNativeMessengerVersion(
quiet = false,
): Promise<number> {