Skip to content

Commit 0350476

Browse files
authored
Merge pull request #3 from ika-rwth-aachen/improvement/small-improvements
Small improvements
2 parents 4b532c9 + 9300a79 commit 0350476

File tree

7 files changed

+43
-13
lines changed

7 files changed

+43
-13
lines changed

docker-run-cli/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "docker-run-cli"
7-
version = "0.9.2"
7+
version = "0.9.3"
88
description = "'docker run' and 'docker exec' with useful defaults"
99
license = {file = "LICENSE"}
1010
readme = "README.md"
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
__name__ = "docker-run"
2-
__version__ = "0.9.2"
2+
__version__ = "0.9.3"

docker-run-cli/src/docker_run/core.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from typing import Any, Dict, List, Tuple
88

99
import docker_run
10-
from docker_run.utils import log, runCommand
10+
from docker_run.utils import log, runCommand, validDockerContainerName
1111
from docker_run.plugins.plugin import Plugin
1212

1313
# automatically load all available plugins inheriting from `Plugin`
@@ -21,6 +21,7 @@
2121
if isinstance(cls, type) and issubclass(cls, Plugin) and cls is not Plugin:
2222
PLUGINS.append(cls)
2323

24+
DEFAULT_CONTAINER_NAME = validDockerContainerName(os.path.basename(os.getcwd()))
2425

2526
def parseArguments() -> Tuple[argparse.Namespace, List[str], List[str]]:
2627

@@ -45,7 +46,7 @@ def format_help(self):
4546

4647
parser.add_argument("--help", action="help", default=argparse.SUPPRESS, help="show this help message and exit")
4748
parser.add_argument("--image", help="image name (may also be specified without --image as last argument before command)")
48-
parser.add_argument("--name", default=os.path.basename(os.getcwd()), help="container name; generates `docker exec` command if already running")
49+
parser.add_argument("--name", default=DEFAULT_CONTAINER_NAME, help="container name; generates `docker exec` command if already running")
4950
parser.add_argument("--no-name", action="store_true", help="disable automatic container name (current directory)")
5051
parser.add_argument("--verbose", action="store_true", help="print generated command")
5152
parser.add_argument("--version", action="store_true", help="show program's version number and exit")
@@ -88,14 +89,19 @@ def buildDockerCommand(args: Dict[str, Any], unknown_args: List[str] = [], cmd_a
8889
# check for running container
8990
if args["no_name"]:
9091
args["name"] = None
91-
new_container = False
92-
running_containers = runCommand('docker ps --format "{{.Names}}"')[0].split('\n')
93-
new_container = not (args["name"] in running_containers)
92+
new_container = True
93+
else:
94+
new_container = False
95+
running_containers = runCommand('docker ps --format "{{.Names}}"')[0].split('\n')
96+
new_container = not (args["name"] in running_containers)
97+
if not new_container and args["image"] is not None and len(args["image"]) > 0:
98+
args["name"] = None if args["name"] == DEFAULT_CONTAINER_NAME else args["name"]
99+
new_container = True
94100

95101
if new_container: # docker run
96102

97103
log_msg = f"Starting new container "
98-
if not args["no_name"]:
104+
if args["name"] is not None:
99105
log_msg += f"'{args['name']}'"
100106
log(log_msg + " ...")
101107
docker_cmd = ["docker", "run"]

docker-run-cli/src/docker_run/plugins/core.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ def x11GuiForwardingFlags(cls, docker_network: str = "bridge") -> List[str]:
9292
display = os.environ.get("DISPLAY")
9393
if display is None:
9494
return []
95+
96+
if cls.OS == "Darwin":
97+
runCommand(f"xhost +local:")
9598

9699
xsock = "/tmp/.X11-unix"
97100
xauth = tempfile.NamedTemporaryFile(prefix='.docker.xauth.', delete=False).name
@@ -101,9 +104,9 @@ def x11GuiForwardingFlags(cls, docker_network: str = "bridge") -> List[str]:
101104
os.chmod(xauth, 0o777)
102105

103106
if docker_network != "host" and not display.startswith(":"):
104-
display="172.17.0.1:" + display.split(":")[1]
107+
display = "172.17.0.1:" + display.split(":")[1]
105108
if cls.OS == "Darwin":
106-
display="host.docker.internal:" + display.split(":")[1]
109+
display = "host.docker.internal:" + display.split(":")[1]
107110

108111
flags = []
109112
flags.append(f"--env DISPLAY={display}")

docker-run-cli/src/docker_run/utils.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
import subprocess
23
import sys
34
from typing import Tuple
@@ -28,3 +29,21 @@ def runCommand(cmd: str, *args, **kwargs) -> Tuple[str, str]:
2829
raise RuntimeError(f"System command '{cmd}' failed: {exc.stderr.decode()}")
2930

3031
return output.stdout.decode(), output.stderr.decode()
32+
33+
34+
def validDockerContainerName(name: str) -> str:
35+
"""Cleans a string such that it is a valid Docker container name.
36+
37+
[a-zA-Z0-9][a-zA-Z0-9_.-]
38+
39+
Args:
40+
name (str): raw name
41+
42+
Returns:
43+
str: valid container name
44+
"""
45+
46+
name = re.sub('[^a-zA-Z0-9_.-]', '-', name)
47+
name = re.sub('^[^a-zA-Z0-9]+', '', name)
48+
49+
return name

docker-run-docker-ros/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "docker-run-docker-ros"
7-
version = "1.0.1"
7+
version = "1.0.2"
88
description = "docker-run plugin for Docker images built by docker-ros"
99
license = {file = "LICENSE"}
1010
readme = "README.md"

docker-run-docker-ros/src/docker_run/plugins/docker_ros.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from docker_run.plugins.plugin import Plugin
77

88

9-
__version__ = "1.0.1"
9+
__version__ = "1.0.2"
1010

1111

1212
class DockerRosPlugin(Plugin):
@@ -33,7 +33,9 @@ def getRunFlags(cls, args: Dict[str, Any], unknown_args: List[str]) -> List[str]
3333
@classmethod
3434
def getExecFlags(cls, args: Dict[str, Any], unknown_args: List[str]) -> List[str]:
3535
flags = []
36-
if not args["no_user"] and runCommand(f"docker exec {args['name']} sh -c 'echo $DOCKER_ROS'")[0][:-1] == "1":
36+
is_docker_ros = (runCommand(f"docker exec {args['name']} printenv DOCKER_ROS")[0][:-1] == "1")
37+
is_non_root = (len(runCommand(f"docker exec {args['name']} printenv DOCKER_UID")[0][:-1]) > 0)
38+
if not args["no_user"] and is_docker_ros and is_non_root:
3739
flags += cls.userExecFlags()
3840
return flags
3941

0 commit comments

Comments
 (0)