Skip to content

Commit

Permalink
read http iface settings from $XDG_CONFIG_HOME/brotab/brotab.env
Browse files Browse the repository at this point in the history
  • Loading branch information
balta2ar committed May 29, 2022
1 parent 557183f commit 1bf040c
Show file tree
Hide file tree
Showing 11 changed files with 88 additions and 179 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
* Support config file in `$XDG_CONFIG_HOME/brotab/brotab.env`:
```env
HTTP_IFACE=0.0.0.0
MIN_HTTP_PORT=4625
MAX_HTTP_PORT=4635
```
This is useful if you want to change interface mediator is binding to.

1.4.1 (2022-05-29)

* Better syntax for navigate and update:
Expand Down
5 changes: 3 additions & 2 deletions brotab/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
from urllib.request import Request
from urllib.request import urlopen

from brotab.env import http_iface
from brotab.inout import MultiPartForm
from brotab.inout import edit_tabs_in_editor
from brotab.mediator.const import DEFAULT_HTTP_IFACE
from brotab.operations import infer_all_commands
from brotab.parallel import call_parallel
from brotab.tab import parse_tab_lines
Expand Down Expand Up @@ -302,7 +302,7 @@ def api_must_ready(port: int, browser: str,
prefix='a',
client_timeout: float = 0.1,
startup_timeout: float = 1.0) -> SingleMediatorAPI:
client = HttpClient(DEFAULT_HTTP_IFACE, port, timeout=client_timeout)
client = HttpClient(http_iface(), port, timeout=client_timeout)
api = SingleMediatorAPI(prefix=prefix, port=port, startup_timeout=startup_timeout, client=client)
assert api.browser == browser
return api
Expand All @@ -312,6 +312,7 @@ def int_tab_id(tab_id: str) -> int:
"""Convert from str(b.20.123) to int(123)"""
return int(tab_id.split('.')[-1])


class MultipleMediatorsAPI(object):
"""
This API is designed to work with multiple mediators.
Expand Down
36 changes: 36 additions & 0 deletions brotab/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from os import environ
from os.path import exists
from os.path import expanduser

from brotab.files import slurp_lines
from brotab.mediator.const import DEFAULT_HTTP_IFACE
from brotab.mediator.const import DEFAULT_MAX_HTTP_PORT
from brotab.mediator.const import DEFAULT_MIN_HTTP_PORT
from brotab.mediator.log import mediator_logger

CONFIG = environ.get('XDG_CONFIG_HOME', expanduser('~/.config'))
DEFAULT_FILENAME = '{0}/brotab/brotab.env'.format(CONFIG)


def http_iface():
return environ.get('HTTP_IFACE', DEFAULT_HTTP_IFACE)


def min_http_port():
return environ.get('MIN_HTTP_PORT', DEFAULT_MIN_HTTP_PORT)


def max_http_port():
return environ.get('MAX_HTTP_PORT', DEFAULT_MAX_HTTP_PORT)


def load_dotenv(filename=None):
if filename is None: filename = DEFAULT_FILENAME
mediator_logger.info('Loading .env file: %s', filename)
if not exists(filename):
mediator_logger.info('No .env file found: %s', filename)
return
for line in slurp_lines(filename):
if not line or line.startswith('#'): continue
key, value = line.split('=', 1)
environ[key] = value
22 changes: 22 additions & 0 deletions brotab/files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import os
import tempfile


def slurp(filename):
with open(filename) as file_:
return file_.read()


def slurp_lines(filename):
with open(filename) as file_:
return [line.strip() for line in file_.readlines()]


def spit(filename, contents):
with open(filename, 'w', encoding='utf-8') as file_:
file_.write(contents)


def in_temp_dir(filename) -> str:
temp_dir = tempfile.gettempdir()
return os.path.join(temp_dir, filename)
31 changes: 4 additions & 27 deletions brotab/inout.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,22 @@
import os
import socket
import sys
import tempfile
import uuid
from select import select
from subprocess import CalledProcessError
from subprocess import check_call
from tempfile import NamedTemporaryFile
from typing import BinaryIO
from typing import Iterable
from typing import Union

from select import select

from brotab.env import max_http_port
from brotab.env import min_http_port
from brotab.platform import get_editor

MIN_MEDIATOR_PORT = 4625
MAX_MEDIATOR_PORT = MIN_MEDIATOR_PORT + 10


def slurp(filename):
with open(filename) as file_:
return file_.read()


def slurp_lines(filename):
with open(filename) as file_:
return [line.strip() for line in file_.readlines()]


def spit(filename, contents):
with open(filename, 'w', encoding='utf-8') as file_:
file_.write(contents)


def in_temp_dir(filename) -> str:
temp_dir = tempfile.gettempdir()
return os.path.join(temp_dir, filename)


def get_mediator_ports() -> Iterable:
return range(MIN_MEDIATOR_PORT, MAX_MEDIATOR_PORT)
return range(min_http_port(), max_http_port())


def get_available_tcp_port(start=1025, end=65536, host='127.0.0.1'):
Expand Down
2 changes: 1 addition & 1 deletion brotab/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
from brotab.const import DEFAULT_GET_WORDS_JOIN_WITH
from brotab.const import DEFAULT_GET_WORDS_MATCH_REGEX
from brotab.inout import get_mediator_ports
from brotab.inout import in_temp_dir
from brotab.files import in_temp_dir
from brotab.inout import is_port_accepting_connections
from brotab.inout import marshal
from brotab.inout import read_stdin
Expand Down
6 changes: 4 additions & 2 deletions brotab/mediator/brotab_mediator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
import re
import socket

from brotab.env import http_iface
from brotab.env import load_dotenv
from brotab.inout import get_mediator_ports
from brotab.inout import is_port_accepting_connections
from brotab.mediator import sig
from brotab.mediator.const import DEFAULT_HTTP_IFACE
from brotab.mediator.const import DEFAULT_SHUTDOWN_POLL_INTERVAL
from brotab.mediator.http_server import MediatorHttpServer
from brotab.mediator.log import disable_click_echo
Expand Down Expand Up @@ -66,12 +67,13 @@ def mediator_main():
monkeypatch_socket_bind_allow_port_reuse()
disable_click_echo()

load_dotenv()
port_range = list(get_mediator_ports())
transport = default_transport()
# transport = transport_with_timeout(sys.stdin.buffer, sys.stdout.buffer, DEFAULT_TRANSPORT_TIMEOUT)
# transport = transport_with_timeout(sys.stdin.buffer, sys.stdout.buffer, 1.0)
remote_api = default_remote_api(transport)
host = DEFAULT_HTTP_IFACE
host = http_iface()
poll_interval = DEFAULT_SHUTDOWN_POLL_INTERVAL

for port in port_range:
Expand Down
2 changes: 1 addition & 1 deletion brotab/mediator/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging.handlers
from traceback import format_stack

from brotab.inout import in_temp_dir
from brotab.files import in_temp_dir


def _init_logger(tag, filename: str):
Expand Down
3 changes: 2 additions & 1 deletion brotab/tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import pytest

from brotab.api import api_must_ready
from brotab.env import min_http_port
from brotab.inout import get_available_tcp_port
from brotab.inout import wait_net_service
from brotab.mediator.const import DEFAULT_MIN_HTTP_PORT
Expand Down Expand Up @@ -144,7 +145,7 @@ def __init__(self):
self._browser = Popen(self.CMD, shell=True,
cwd=self.CWD, preexec_fn=os.setsid)
print('PID', self._browser.pid)
wait_net_service('localhost', DEFAULT_MIN_HTTP_PORT, TIMEOUT)
wait_net_service('localhost', min_http_port(), TIMEOUT)
print('init done PID', self._browser.pid)

def stop(self):
Expand Down
14 changes: 7 additions & 7 deletions brotab/tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
from uuid import uuid4

from brotab.api import SingleMediatorAPI
from brotab.inout import MIN_MEDIATOR_PORT
from brotab.env import http_iface
from brotab.env import min_http_port
from brotab.files import in_temp_dir
from brotab.files import spit
from brotab.inout import get_available_tcp_port
from brotab.inout import in_temp_dir
from brotab.inout import spit
from brotab.main import create_clients
from brotab.main import run_commands
from brotab.mediator.const import DEFAULT_HTTP_IFACE
from brotab.mediator.http_server import MediatorHttpServer
from brotab.mediator.remote_api import default_remote_api
from brotab.mediator.transport import Transport
Expand Down Expand Up @@ -59,7 +59,7 @@ def __init__(self, prefix='a', port=None, remote_api=None):
self.port = get_available_tcp_port() if port is None else port
self.transport = MockedLoggingTransport()
self.remote_api = default_remote_api(self.transport) if remote_api is None else remote_api
self.server = MediatorHttpServer(DEFAULT_HTTP_IFACE, self.port, self.remote_api, 0.050)
self.server = MediatorHttpServer(http_iface(), self.port, self.remote_api, 0.050)
self.thread = self.server.run.in_thread()
self.transport.received_extend(['mocked'])
self.api = SingleMediatorAPI(prefix, port=self.port, startup_timeout=1)
Expand Down Expand Up @@ -128,7 +128,7 @@ def run_mocked_mediators(count, default_port_offset, delay):
"""
assert count > 0
print('Creating %d mediators' % count)
start_port = MIN_MEDIATOR_PORT + default_port_offset
start_port = min_http_port() + default_port_offset
ports = range(start_port, start_port + count)
mediators = [MockedMediator(letter, port, DummyBrowserRemoteAPI())
for i, letter, port in zip(range(count), ascii_letters, ports)]
Expand All @@ -147,7 +147,7 @@ def run_mocked_mediator_current_thread(port):
"""
remote_api = DummyBrowserRemoteAPI()
port = get_available_tcp_port() if port is None else port
server = MediatorHttpServer(DEFAULT_HTTP_IFACE, port, remote_api, 0.050)
server = MediatorHttpServer(http_iface(), port, remote_api, 0.050)
server.run.here()


Expand Down
138 changes: 0 additions & 138 deletions brotab/tests/test_mediator.py

This file was deleted.

0 comments on commit 1bf040c

Please sign in to comment.