#!/usr/bin/env -S python3 -u # Note that running python with the `-u` flag is required on Windows, # in order to ensure that stdin and stdout are opened in binary, rather # than text, mode. import sys import json import struct import os from platform import system as platform repo_map = { "gitlab.otters.xyz": "~/git/Cabify" } # Read a message from stdin and decode it. def getMessage(): rawLength = sys.stdin.buffer.read(4) if len(rawLength) == 0: sys.exit(0) messageLength = struct.unpack('@I', rawLength)[0] message = sys.stdin.buffer.read(messageLength).decode('utf-8') return json.loads(message) # Encode a message for transmission, # given its content. def encodeMessage(messageContent): # https://docs.python.org/3/library/json.html#basic-usage # To get the most compact JSON representation, you should specify # (',', ':') to eliminate whitespace. # We want the most compact representation because the browser rejects # messages that exceed 1 MB. encodedContent = json.dumps(messageContent, separators=(',', ':')).encode('utf-8') encodedLength = struct.pack('@I', len(encodedContent)) return {'length': encodedLength, 'content': encodedContent} # Send an encoded message to stdout def sendMessage(encodedMessage): sys.stdout.buffer.write(encodedMessage['length']) sys.stdout.buffer.write(encodedMessage['content']) sys.stdout.buffer.flush() while True: receivedMessage = getMessage() if repo_map.get(receivedMessage["host"]): path_prefix = os.path.expanduser(repo_map[receivedMessage["host"]]) path = os.path.join(path_prefix, receivedMessage["repo"]) if not os.path.exists(path): sendMessage(encodeMessage(json.dumps({"error": "repo not found"}))) # tmux new-window -t 0 -n "$repo_path" "cd ~/git/Cabify/$repo_path && nvim ." os.system("/opt/homebrew/bin/tmux new-window -t 0 -n \"{}\" \"cd {} && nvim .\"".format(receivedMessage["repo"], path)) os.system("/usr/bin/osascript -e 'activate application \"Alacritty\"'") sendMessage(encodeMessage(json.dumps(receivedMessage))) else: sendMessage(encodeMessage(json.dumps({"error": "host not found in map"})))