Skip to content

Commit

Permalink
added feature to automatically change port (#2867)
Browse files Browse the repository at this point in the history
  • Loading branch information
wassafshahzad committed Mar 26, 2024
1 parent 8a2b92f commit 15dc7f4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 27 deletions.
4 changes: 2 additions & 2 deletions reflex/reflex.py
Expand Up @@ -169,10 +169,10 @@ def _run(

# If something is running on the ports, ask the user if they want to kill or change it.
if frontend and processes.is_process_on_port(frontend_port):
frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
frontend_port = processes.change_port(frontend_port, "frontend")

if backend and processes.is_process_on_port(backend_port):
backend_port = processes.change_or_terminate_port(backend_port, "backend")
backend_port = processes.change_port(backend_port, "backend")

# Apply the new ports to the config.
if frontend_port != str(config.frontend_port):
Expand Down
33 changes: 8 additions & 25 deletions reflex/utils/processes.py
Expand Up @@ -87,41 +87,24 @@ def kill_process_on_port(port):
get_process_on_port(port).kill() # type: ignore


def change_or_terminate_port(port, _type) -> str:
"""Terminate or change the port.
def change_port(port: str, _type: str) -> str:
"""Change the port.
Args:
port: The port.
_type: The type of the port.
Returns:
The new port or the current one.
The new port.
Raises:
Exit: If the user wants to exit.
"""
new_port = str(int(port) + 1)
if is_process_on_port(new_port):
return change_port(new_port, _type)
console.info(
f"Something is already running on port [bold underline]{port}[/bold underline]. This is the port the {_type} runs on."
f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
)
frontend_action = console.ask("Kill or change it?", choices=["k", "c", "n"])
if frontend_action == "k":
kill_process_on_port(port)
return port
elif frontend_action == "c":
new_port = console.ask("Specify the new port")

# Check if also the new port is used
if is_process_on_port(new_port):
return change_or_terminate_port(new_port, _type)
else:
console.info(
f"The {_type} will run on port [bold underline]{new_port}[/bold underline]."
)
return new_port
else:
console.log("Exiting...")
raise typer.Exit()
return new_port


def new_process(args, run: bool = False, show_logs: bool = False, **kwargs):
Expand Down

0 comments on commit 15dc7f4

Please sign in to comment.