Commit 376071fd authored by Matthieu Boileau's avatar Matthieu Boileau
Browse files

Add a get_socket_port function

parent c8f08727
"""Provide an http server and watch for changes using livereload"""
from livereload import Server
import socket
import logging
from . import sgelt, config
from . import sgelt, config, utils
log = logging.getLogger(__name__)
......@@ -12,27 +11,22 @@ log = logging.getLogger(__name__)
class MyServer(Server):
"""A livereload server capable of rebuilding the site"""
def __init__(self, conf, *args, **kwargs):
def __init__(self, conf: config.Config):
self.conf = conf
super().__init__(*args, **kwargs)
self.host = "127.0.0.1"
self.port = utils.get_socket_port()
self.conf.site['url'] = f"http://{self.host}:{self.port}"
log.info(f"Using site url: {self.conf.site['url']}")
super().__init__()
def serve(self, browser: bool, *args, **kwargs):
"""Serve and open browser if browser == True"""
if browser:
kwargs['open_url_delay'] = 0
kwargs['root'] = self.conf.output_path
try:
super().serve(*args, **kwargs)
except OSError as e:
# get a free random port number
log.debug(e)
log.info("Default port 5500 seems to be occupied: "
"trying a random port number")
s = socket.socket()
s.bind(('', 0))
kwargs['port'] = s.getsockname()[1]
super().serve(*args, **kwargs)
kwargs['host'] = self.host
kwargs['port'] = self.port
super().serve(*args, **kwargs)
def watch(self):
"""Watch for directories and rebuild site"""
......
......@@ -11,6 +11,7 @@ import logging
import markdown
from markdown_link_attr_modifier import LinkAttrModifierExtension
import frontmatter
import socket
import yaml
from .mdextend import TableExtension
......@@ -183,3 +184,17 @@ def override_default(paths: list, dcmp):
# Recursive call to subdirectories
for sub_dcmp in dcmp.subdirs.values():
override_default(paths, sub_dcmp)
def get_socket_port() -> int:
"""Return 5500 or an arbitrary unused port"""
s = socket.socket()
try:
# Try default port 5500
s.bind(('', 5500))
except OSError:
log.info('Port 5500 is in use, trying an arbitrary port')
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
......@@ -101,3 +101,9 @@ def test_clean_project(tmp_path):
assert project_dir.is_dir() is False
# FileNotFoundError
utils.clean_project(project_dir)
def test_get_socket_port():
port = utils.get_socket_port()
# port number depends on currently open sockets on the system
assert port >= 5500
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment