Example #1
0
    def __init__(self,
                 sub_path: pathlib.Path,
                 clear_content: bool = False) -> None:
        """Initialize a create path action.

        It creates all the missing directories in the path.
        If it is a file, then it also creates an empty file with the name provided

        Arguments:
            sub_path: this is the desired file or directory path that needs to be created under the project root
        """
        sub_path = sub_path.resolve()

        self._trestle_project_root = file_utils.extract_trestle_project_root(
            sub_path)
        if self._trestle_project_root is None:
            raise TrestleError(
                f'Sub path "{sub_path}" should be child of a valid trestle project'
            )

        self._sub_path = sub_path
        self._created_paths: List[pathlib.Path] = []

        # variables for handling with file content
        self._clear_content = clear_content
        self._old_file_content = None

        super().__init__(ActionType.CREATE_PATH, True)
Example #2
0
    def get_models_of_type(model_type: str, root: pathlib.Path) -> List[str]:
        """Get list of model names for requested type in trestle directory."""
        if model_type not in const.MODEL_TYPE_LIST:
            raise err.TrestleError(f'Model type {model_type} is not supported')
        # search relative to project root
        trestle_root = extract_trestle_project_root(root)
        if not trestle_root:
            logger.error(
                f'Given directory {root} is not within a trestle project.')
            raise err.TrestleError(
                'Given directory is not within a trestle project.')

        # contruct path to the model file name
        model_dir_name = ModelUtils.model_type_to_model_dir(model_type)
        root_model_dir = trestle_root / model_dir_name
        model_list = []
        for f in root_model_dir.glob('*/'):
            # only look for proper json and yaml files
            if not ModelUtils._should_ignore(f.stem):
                if not f.is_dir():
                    logger.warning(
                        f'Ignoring validation of misplaced file {f.name} ' +
                        f'found in the model directory, {model_dir_name}.')
                else:
                    model_list.append(f.stem)
        return model_list
Example #3
0
def to_origin_dir_path(trash_dir_path: pathlib.Path) -> pathlib.Path:
    """Convert trash content path to origin path."""
    if trash_dir_path.suffix != '' and trash_dir_path.suffix.endswith(
            TRESTLE_TRASH_FILE_EXT):
        raise AssertionError(
            f'Given path "{trash_dir_path}" is a trash file, not a valid trash directory'
        )

    trestle_root = file_utils.extract_trestle_project_root(trash_dir_path)
    if trestle_root is None:
        raise AssertionError(
            f'Directory path "{trash_dir_path}" is not in a valid trestle project path'
        )

    trash_root = get_trash_root(trash_dir_path)
    if trash_root is None:
        raise AssertionError(
            f'Directory path "{trash_dir_path}" is not in a valid trestle trash path'
        )

    if not has_parent_path(trash_dir_path, trash_root):
        raise AssertionError(
            f'Directory path "{trash_dir_path}" is not a valid trash dir path')

    relative_path = trash_dir_path.relative_to(str(trash_root))

    origin_path_parts: List[str] = []
    for item in relative_path.parts:
        parts = item.split(TRESTLE_TRASH_DIR_EXT)
        origin_path_parts.append(parts[0])

    origin_relative_path = pathlib.Path('/'.join(origin_path_parts))
    origin_path = trestle_root / origin_relative_path
    return origin_path
Example #4
0
 def _validate_arguments(self, args):
     """Check trestle-root argument is a valid trestle root directory."""
     root = file_utils.extract_trestle_project_root(args.trestle_root)
     if root is None:
         logger.error(f'Given directory {args.trestle_root} is not in a valid trestle root directory')
         return CmdReturnCodes.TRESTLE_ROOT_ERROR.value
     is_oscal_dir_valid = file_utils.check_oscal_directories(args.trestle_root)
     if not is_oscal_dir_valid:
         return CmdReturnCodes.TRESTLE_ROOT_ERROR.value
     args.trestle_root = root
     return CmdReturnCodes.SUCCESS.value
Example #5
0
def test_get_trestle_project_root(tmp_path: pathlib.Path,
                                  rand_str: str) -> None:
    """Test get_trestle_project_root  method."""
    project_path: pathlib.Path = pathlib.Path.joinpath(tmp_path, rand_str)
    sub_path: pathlib.Path = project_path.joinpath('samples2')
    sub_path.mkdir(exist_ok=True, parents=True)
    assert sub_path.exists() and sub_path.is_dir()

    # create a file
    sub_path.joinpath('readme.md').touch()

    # create a data-dir and a file
    sub_data_dir = pathlib.Path.joinpath(sub_path, 'data')
    sub_data_dir.mkdir(exist_ok=True, parents=True)
    sub_data_dir.joinpath('readme.md').touch()

    assert file_utils.extract_trestle_project_root(sub_data_dir) is None

    test_utils.ensure_trestle_config_dir(project_path)
    assert file_utils.extract_trestle_project_root(
        sub_data_dir) == project_path
    assert file_utils.extract_trestle_project_root(
        sub_data_dir.joinpath('readme.md')) == project_path
    assert file_utils.extract_trestle_project_root(
        sub_path.joinpath('readme.md')) == project_path
    assert file_utils.extract_trestle_project_root(sub_path) == project_path
    assert file_utils.extract_trestle_project_root(project_path.parent) is None
Example #6
0
def to_trash_dir_path(dir_path: pathlib.Path) -> pathlib.Path:
    """Construct the path to the trashed file."""
    absolute_path = dir_path.resolve()
    root_path = file_utils.extract_trestle_project_root(absolute_path)
    if root_path is None:
        raise AssertionError(
            f'Directory path "{absolute_path}" is not in a valid trestle project'
        )

    trestle_trash_path = root_path / TRESTLE_TRASH_DIR

    relative_path = absolute_path.relative_to(str(root_path))
    if len(relative_path.parts) == 0:
        trash_dir = trestle_trash_path
    else:
        trash_dir = trestle_trash_path / f'{relative_path}{TRESTLE_TRASH_DIR_EXT}'

    return trash_dir
Example #7
0
    def __init__(self, sub_path: pathlib.Path) -> None:
        """Initialize a remove path action.

        It removes the file or directory recursively into trash.

        Arguments:
            sub_path: this is the desired file or directory path that needs to be removed under the project root
        """
        if not isinstance(sub_path, pathlib.Path):
            raise TrestleError('Sub path must be of type pathlib.Path')

        self._trestle_project_root = file_utils.extract_trestle_project_root(
            sub_path)
        if self._trestle_project_root is None:
            raise TrestleError(
                f'Sub path "{sub_path}" should be child of a valid trestle project.'
            )

        self._sub_path = sub_path

        super().__init__(ActionType.REMOVE_PATH, True)