provide hostname hint in editor temporary files

when calling an external editor, include the hostname of the remote
site in the generated temporary filename.

Closes #495
This commit is contained in:
Lars Kellogg-Stedman 2018-05-11 10:20:22 -04:00
parent e23e972da4
commit 861110a76d
3 changed files with 26 additions and 4 deletions

View file

@ -4,12 +4,15 @@
import sys
import os
import json
import re
import struct
import subprocess
import tempfile
import unicodedata
VERSION = "0.1.3"
class NoConnectionError(Exception):
""" Exception thrown when stdin cannot be read """
@ -25,6 +28,7 @@ def getenv(variable, default):
""" Get an environment variable value, or use the default provided """
return os.environ.get(variable) or default
def getMessage():
"""Read a message from stdin and decode it.
@ -101,6 +105,19 @@ def getUserConfig():
return open(cfg_file, 'r').read()
def sanitizeFilename(fn):
""" Transform a string to make it suitable for use as a filename.
From https://stackoverflow.com/a/295466/147356"""
fn = unicodedata.normalize('NFKD', fn).encode(
'ascii', 'ignore').decode('ascii')
fn = re.sub('[^\w\s/.-]', '', fn).strip().lower()
fn = re.sub('\.\.+', '', fn)
fn = re.sub('[-/\s]+', '-', fn)
return fn
def handleMessage(message):
""" Generate reply from incoming message. """
cmd = message["cmd"]
@ -153,7 +170,11 @@ def handleMessage(message):
file.write(message["content"])
elif cmd == 'temp':
(handle, filepath) = tempfile.mkstemp()
prefix = message.get('prefix')
if prefix is not None:
prefix = 'tmp_{}_'.format(sanitizeFilename(prefix))
(handle, filepath) = tempfile.mkstemp(prefix=prefix)
with os.fdopen(handle, "w") as file:
file.write(message["content"])
reply['content'] = filepath

View file

@ -167,8 +167,9 @@ export async function getinput() {
*/
//#background
export async function editor() {
let url = new URL((await activeTab()).url)
if (!await Native.nativegate()) return
const file = (await Native.temp(await getinput())).content
const file = (await Native.temp(await getinput(), url.hostname)).content
fillinput((await Native.editor(file)).content)
// TODO: add annoying "This message was written with [Tridactyl](https://addons.mozilla.org/en-US/firefox/addon/tridactyl-vim/)"
// to everything written using editor

View file

@ -238,8 +238,8 @@ export async function mkdir(dir: string, exist_ok: boolean) {
return sendNativeMsg("mkdir", { dir, exist_ok })
}
export async function temp(content: string) {
return sendNativeMsg("temp", { content })
export async function temp(content: string, prefix: string) {
return sendNativeMsg("temp", { content, prefix })
}
export async function run(command: string) {