Skip to content

Commit

Permalink
[UP] Repo command update is added
Browse files Browse the repository at this point in the history
  • Loading branch information
mostafabarmshory committed Feb 3, 2025
1 parent d5e38d0 commit 40964e8
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 26 deletions.
9 changes: 5 additions & 4 deletions src/otoolbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from otoolbox import workspace
from otoolbox import developer
from otoolbox import maintainer
from otoolbox import repositories
from otoolbox import env
from otoolbox import utils

Expand Down Expand Up @@ -136,10 +136,11 @@ def result_callback(*args, **kargs):

# Launch the CLI application
app = typer.Typer(
callback=callback_common_arguments,
result_callback=result_callback
callback=callback_common_arguments,
result_callback=result_callback,
pretty_exceptions_show_locals=False
)
app.add_typer(workspace.app, name="workspace")
app.add_typer(repositories.app, name="repo")
app.add_typer(developer.app, name="dev")
app.add_typer(maintainer.app, name="admin")
app()
1 change: 1 addition & 0 deletions src/otoolbox/addons/repositories/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def _load_repositories():
],
destructors=[],
validators=[],
tags=['git', item["workspace"], *item.get('tags', [])]
)
if item["workspace"] not in workspaces:
workspaces.append(item["workspace"])
Expand Down
42 changes: 35 additions & 7 deletions src/otoolbox/addons/repositories/git.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,40 @@

import os
import logging

from otoolbox import env
from otoolbox import utils

_logger = logging.getLogger(__name__)

GIT_ERROR_TABLE = {
2: {
'level': 'fatal',
'message': "Resource {path}, doese not exist or is not a git repository."
},
128: {
'level': 'fatal',
'message': "Destination path '{path}' already exists and is not an empty directory."
}
}

def _rais_git_error(context, error_code):
if not error_code:
return
error = GIT_ERROR_TABLE.get(error_code, {
'level': 'fatal',
'message': "Unknown GIT error for distination path {path}. Error code is {error_code}. "
"See .otoolbox/logs.text for more information."
})
message = error['message'].format(error_code=error_code,**context.__dict__)
if env.context.get('continue_on_exception'):
_logger.error(message)
env.errors.append(message)
else:
raise RuntimeError(
error['message'].format(error_code=error_code,**context.__dict__)
)


def git_clone(context):
"""Clone the git repository from github
Expand All @@ -20,20 +51,17 @@ def git_clone(context):
f"[email protected]:{context.path}.git"
], cwd=cwd)

if result != 0:
raise AssertionError("Fail to update the repository")
_rais_git_error(context=context, error_code=result)



def git_pull(context):
"""Pull the git repository from github
"""
cwd = os.path.dirname(context.path)
cwd = env.get_workspace_path(context.path)
result = utils.call_process_safe([
'git',
'pull',
f"[email protected]:{context.path}.git"
'pull'
], cwd=cwd)

if result != 0:
raise AssertionError("Fail to update the repository")
_rais_git_error(context=context, error_code=result)
39 changes: 36 additions & 3 deletions src/otoolbox/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,37 @@ def set_validator_failed(self, validator, exception):
def clean_validator_failer(self):
self.validation_errors.clear()

def has_tag(self, *args):
"""Check if it has any tags from arguments.
# git or github
flag = resource.has_tag('git', 'github')
"""
for arg in args:
if arg in self.tags:
return True

class WorkspaceResourceGroup(WorkspaceResource):
"""Group of resources
If there are many resources that are related to each other, it is possible to group them in a group.
"""

def __init__(self, **kargs):
super().__init__(**kargs)
self.resources = kargs.get('resources', [])
def __init__(self,
path,
resources=None,
root=None,
**kargs):
super().__init__(path, **kargs)
self.resources = resources if resources else []
self.validators_len = 0
self.root = root

def append(self, resource: WorkspaceResource):
"""Appends new resource to the group"""
if self.root:
raise RuntimeError("Imposible to modifie virtual resource")
self.resources.append(resource)
self.resources = sorted(self.resources, key=lambda x: x.priority, reverse=True)
self.priority = self.resources[0].priority
Expand Down Expand Up @@ -120,5 +138,20 @@ def verify(self, **kargs):
verified += super().verify(**kargs)
return verified

def update(self, **kargs):
for resource in self.resources:
resource.update(**kargs)
super().update(**kargs)

def get_validators_len(self) -> int:
return self.validators_len

def has_tag(self, *args):
for resource in self.resources:
if resource.has_tag(*args):
return True
return super().has_tag(*args)

def filter(self, filter_function):
resources = list(filter(filter_function, self.resources))
return WorkspaceResourceGroup(self.path, root=self, resources=resources)
3 changes: 3 additions & 0 deletions src/otoolbox/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
)
}

# list of errors and warnings
errors = []


def resource_string(resource_name:str, packag_name:str="otoolbox", encoding:str="utf-8"):
"""Load resource"""
Expand Down
21 changes: 19 additions & 2 deletions src/otoolbox/maintainer.py → src/otoolbox/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,37 @@
"""
import typer

# from otoolbox.args import common


from otoolbox import env
# from otoolbox.repositories import admin


app = typer.Typer()


def _filter_resources():
resources = (
env.context
.get('resources')
.filter(lambda resource: resource.has_tag('git'))
)
return resources;

@app.command()
def info():
"""Display information about the workspace"""
pass

@app.command()
def init():
"""Initialize all resources from addons into the current workspace"""
return _filter_resources().build()

@app.command()
def update():
pass
"""Updates current workspace to the latest version"""
return _filter_resources().update()



Expand Down
20 changes: 11 additions & 9 deletions src/otoolbox/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,20 @@ def verify_all_resource(should_exit=True):
###################################################################
# constructors
###################################################################
def call_process_safe(command, shell=False, cwd='.'):
def call_process_safe(command, shell=False, cwd=None):
"""Execute a command in a subprocess and log the output"""
try:
if not cwd:
cwd = env.get_workspace()
with open(get_workspace_path(".otoolbox/logs.txt"), "a", encoding="utf8") as log:
ret = subprocess.call(command, shell=shell,
cwd=cwd, stdout=log, stderr=log)
if ret != 0:
if ret < 0:
print("Killed by signal")
else:
print("Command failed with return code")
return ret
ret = subprocess.call(
command,
shell=shell,
cwd=cwd,
stdout=log,
stderr=log
)
return ret
except Exception as e:
_logger.error('Failed to execute command: %s', e)
return 2
Expand Down
25 changes: 24 additions & 1 deletion src/otoolbox/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from otoolbox import utils


app = typer.Typer()
app = typer.Typer(
pretty_exceptions_show_locals=False
)

@app.command()
def init():
Expand All @@ -29,6 +31,27 @@ def delete():
resources.destroy()


# TODO: maso, 2025: add info command
#
# Info command displayes information about the current workspace such as
# - version
# - creation time
# - last update time
# - acvite moduals
#
# @app.command()
# def info():
# """Display information about the workspace"""
# pass

@app.command()
def update():
"""Updates current workspace to the latest version"""
resources = env.context.get('resources')
resources.update()



# def init_cli(parent_parser):
# """Init CLI to support maintainer tools
# """
Expand Down

0 comments on commit 40964e8

Please sign in to comment.