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.port = utils.get_socket_port()['url'] = f"http://{}:{self.port}""Using site url: {['url']}")
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
super().serve(*args, **kwargs)
except OSError as e:
# get a free random port number
log.debug(e)"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'] =
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 default port 5500
s.bind(('', 5500))
except OSError:'Port 5500 is in use, trying an arbitrary port')
s.bind(('', 0))
port = s.getsockname()[1]
return port
......@@ -101,3 +101,9 @@ def test_clean_project(tmp_path):
assert project_dir.is_dir() is False
# FileNotFoundError
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