Skip to content

Commit

Permalink
Implement get_path and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
basicthinker committed Aug 20, 2023
1 parent 3705c0d commit 4019c42
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
31 changes: 31 additions & 0 deletions devchat/namespace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import os
from typing import List, Optional


class Namespace:
def __init__(self, root_path: str,
branches: List[str] = None):
"""
:param root_path: The root path of the namespace.
:param branches: The hidden branches with descending order of priority.
"""
self.root_path = root_path
self.branches = branches if branches else ['usr', 'org', 'sys']

def get_path(self, name: str) -> Optional[str]:
"""
:param name: The command name in the namespace.
:return: The relative path of the command directory.
"""
if not name:
return None
# Convert the dot-separated name to a path
path = os.path.join(*name.split('.'))

for branch in self.branches:
full_path = os.path.join(self.root_path, branch, path)
if os.path.exists(full_path):
# If it exists, return the branch/path part
return os.path.join(branch, path)
# If no existing path is found, return None
return None
26 changes: 26 additions & 0 deletions tests/test_namespace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import os
from devchat.namespace import Namespace


def test_get_path(tmp_path):
# Create a Namespace instance with the temporary directory as the root path
namespace = Namespace(str(tmp_path))

# Test case 1: a path that exists
# Create a file in the 'usr' branch
os.makedirs(os.path.join(tmp_path, 'usr', 'a', 'b', 'c'), exist_ok=True)
assert namespace.get_path('a.b.c') == os.path.join('usr', 'a', 'b', 'c')

# Test case 2: a path that doesn't exist
assert namespace.get_path('d.e.f') is None

# Test case 3: a path that exists in a later branch
# Create a file in the 'sys' branch
os.makedirs(os.path.join(tmp_path, 'sys', 'g', 'h', 'i'), exist_ok=True)
assert namespace.get_path('g.h.i') == os.path.join('sys', 'g', 'h', 'i')

# Test case 4: a path in 'usr' overwrites the same in 'sys'
# Create the same file in the 'usr' and 'sys' branches
os.makedirs(os.path.join(tmp_path, 'usr', 'j', 'k', 'l'), exist_ok=True)
os.makedirs(os.path.join(tmp_path, 'sys', 'j', 'k', 'l'), exist_ok=True)
assert namespace.get_path('j.k.l') == os.path.join('usr', 'j', 'k', 'l')

0 comments on commit 4019c42

Please sign in to comment.