Exemplo n.º 1
0
    def get(self,
            id: Union[str, int],
            lazy: bool = False,
            **kwargs: Any) -> base.RESTObject:
        """Retrieve a single object.

        Args:
            id: ID of the object to retrieve
            lazy: If True, don't request the server, but create a
                         shallow object giving access to the managers. This is
                         useful if you want to avoid useless calls to the API.
            **kwargs: Extra options to send to the server (e.g. sudo)

        Returns:
            The generated RESTObject.

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the server cannot perform the request
        """
        if not isinstance(id, int):
            id = utils._url_encode(id)
        path = f"{self.path}/{id}"
        if TYPE_CHECKING:
            assert self._obj_cls is not None
        if lazy is True:
            if TYPE_CHECKING:
                assert self._obj_cls._id_attr is not None
            return self._obj_cls(self, {self._obj_cls._id_attr: id})
        server_data = self.gitlab.http_get(path, **kwargs)
        if TYPE_CHECKING:
            assert not isinstance(server_data, requests.Response)
        return self._obj_cls(self, server_data)
Exemplo n.º 2
0
    def update(  # type: ignore
            self,
            file_path: str,
            new_data: Optional[Dict[str, Any]] = None,
            **kwargs: Any) -> Dict[str, Any]:
        """Update an object on the server.

        Args:
            id: ID of the object to update (can be None if not required)
            new_data: the update data for the object
            **kwargs: Extra options to send to the server (e.g. sudo)

        Returns:
            The new object data (*not* a RESTObject)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """
        new_data = new_data or {}
        data = new_data.copy()
        file_path = utils._url_encode(file_path)
        data["file_path"] = file_path
        path = f"{self.path}/{file_path}"
        self._check_missing_update_attrs(data)
        result = self.gitlab.http_put(path, post_data=data, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(result, dict)
        return result
Exemplo n.º 3
0
    def save(self, **kwargs: Any) -> Optional[Dict[str, Any]]:
        """Save the changes made to the object to the server.

        The object is updated to match what the server returns.

        Args:
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raise:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """
        updated_data = self._get_updated_data()
        # Nothing to update. Server fails if sent an empty dict.
        if not updated_data:
            return None

        # call the manager
        obj_id = self.get_id()
        if TYPE_CHECKING:
            assert isinstance(self.manager, UpdateMixin)
        if isinstance(obj_id, str):
            obj_id = utils._url_encode(obj_id)
        server_data = self.manager.update(obj_id, updated_data, **kwargs)
        if server_data is not None:
            self._update_attrs(server_data)
        return server_data
Exemplo n.º 4
0
    def create(self,
               data: Optional[Dict[str, Any]] = None,
               **kwargs: Any) -> ProjectFile:
        """Create a new object.

        Args:
            data: parameters to send to the server to create the
                         resource
            **kwargs: Extra options to send to the server (e.g. sudo)

        Returns:
            a new instance of the managed object class built with
                the data sent by the server

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabCreateError: If the server cannot perform the request
        """

        if TYPE_CHECKING:
            assert data is not None
        self._check_missing_create_attrs(data)
        new_data = data.copy()
        file_path = utils._url_encode(new_data.pop("file_path"))
        path = f"{self.path}/{file_path}"
        server_data = self.gitlab.http_post(path, post_data=new_data, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        return self._obj_cls(self, server_data)
Exemplo n.º 5
0
def test_url_encode():
    src = "nothing_special"
    dest = "nothing_special"
    assert dest == utils._url_encode(src)

    src = "foo#bar/baz/"
    dest = "foo%23bar%2Fbaz%2F"
    assert dest == utils._url_encode(src)

    src = "foo%bar/baz/"
    dest = "foo%25bar%2Fbaz%2F"
    assert dest == utils._url_encode(src)

    # periods/dots should not be modified
    src = "docs/README.md"
    dest = "docs%2FREADME.md"
    assert dest == utils._url_encode(src)
Exemplo n.º 6
0
    def delete(  # type: ignore
            self, branch: str, commit_message: str, **kwargs: Any) -> None:
        """Delete the file from the server.

        Args:
            branch: Branch from which the file will be removed
            commit_message: Commit message for the deletion
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server cannot perform the request
        """
        file_path = utils._url_encode(self.get_id())
        self.manager.delete(file_path, branch, commit_message, **kwargs)
Exemplo n.º 7
0
    def delete(self, id: Union[str, int], **kwargs: Any) -> None:
        """Delete an object on the server.

        Args:
            id: ID of the object to delete
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server cannot perform the request
        """
        if id is None:
            path = self.path
        else:
            if not isinstance(id, int):
                id = utils._url_encode(id)
            path = f"{self.path}/{id}"
        self.gitlab.http_delete(path, **kwargs)
Exemplo n.º 8
0
    def save(  # type: ignore
            self, branch: str, commit_message: str, **kwargs: Any) -> None:
        """Save the changes made to the file to the server.

        The object is updated to match what the server returns.

        Args:
            branch: Branch in which the file will be updated
            commit_message: Message to send with the commit
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabUpdateError: If the server cannot perform the request
        """
        self.branch = branch
        self.commit_message = commit_message
        self.file_path = utils._url_encode(self.file_path)
        super(ProjectFile, self).save(**kwargs)
Exemplo n.º 9
0
    def delete(  # type: ignore
            self, file_path: str, branch: str, commit_message: str,
            **kwargs: Any) -> None:
        """Delete a file on the server.

        Args:
            file_path: Path of the file to remove
            branch: Branch from which the file will be removed
            commit_message: Commit message for the deletion
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabDeleteError: If the server cannot perform the request
        """
        file_path = utils._url_encode(file_path)
        path = f"{self.path}/{file_path}"
        data = {"branch": branch, "commit_message": commit_message}
        self.gitlab.http_delete(path, query_data=data, **kwargs)
Exemplo n.º 10
0
    def set(
        self,
        name: str,
        value: Union[bool, int],
        feature_group: Optional[str] = None,
        user: Optional[str] = None,
        group: Optional[str] = None,
        project: Optional[str] = None,
        **kwargs: Any,
    ) -> Feature:
        """Create or update the object.

        Args:
            name: The value to set for the object
            value: The value to set for the object
            feature_group: A feature group name
            user: A GitLab username
            group: A GitLab group
            project: A GitLab project in form group/project
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabSetError: If an error occurred

        Returns:
            The created/updated attribute
        """
        name = utils._url_encode(name)
        path = f"{self.path}/{name}"
        data = {
            "value": value,
            "feature_group": feature_group,
            "user": user,
            "group": group,
            "project": project,
        }
        data = utils.remove_none_from_dict(data)
        server_data = self.gitlab.http_post(path, post_data=data, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(server_data, dict)
        return self._obj_cls(self, server_data)
Exemplo n.º 11
0
    def raw(
        self,
        file_path: str,
        ref: str,
        streamed: bool = False,
        action: Optional[Callable[..., Any]] = None,
        chunk_size: int = 1024,
        **kwargs: Any,
    ) -> Optional[bytes]:
        """Return the content of a file for a commit.

        Args:
            ref: ID of the commit
            filepath: Path of the file to return
            streamed: If True the data will be processed by chunks of
                `chunk_size` and each chunk is passed to `action` for
                treatment
            action: Callable responsible of dealing with chunk of
                data
            chunk_size: Size of each chunk
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabGetError: If the file could not be retrieved

        Returns:
            The file content
        """
        file_path = utils._url_encode(file_path)
        path = f"{self.path}/{file_path}/raw"
        query_data = {"ref": ref}
        result = self.gitlab.http_get(path,
                                      query_data=query_data,
                                      streamed=streamed,
                                      raw=True,
                                      **kwargs)
        if TYPE_CHECKING:
            assert isinstance(result, requests.Response)
        return utils.response_content(result, streamed, action, chunk_size)
Exemplo n.º 12
0
    def update_submodule(
            self, submodule: str, branch: str, commit_sha: str,
            **kwargs: Any) -> Union[Dict[str, Any], requests.Response]:
        """Update a project submodule

        Args:
            submodule: Full path to the submodule
            branch: Name of the branch to commit into
            commit_sha: Full commit SHA to update the submodule to
            commit_message: Commit message. If no message is provided, a
                default one will be set (optional)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabPutError: If the submodule could not be updated
        """

        submodule = utils._url_encode(submodule)
        path = f"/projects/{self.get_id()}/repository/submodules/{submodule}"
        data = {"branch": branch, "commit_sha": commit_sha}
        if "commit_message" in kwargs:
            data["commit_message"] = kwargs["commit_message"]
        return self.manager.gitlab.http_put(path, post_data=data)
Exemplo n.º 13
0
    def blame(self, file_path: str, ref: str,
              **kwargs: Any) -> List[Dict[str, Any]]:
        """Return the content of a file for a commit.

        Args:
            file_path: Path of the file to retrieve
            ref: Name of the branch, tag or commit
            **kwargs: Extra options to send to the server (e.g. sudo)

        Raises:
            GitlabAuthenticationError: If authentication is not correct
            GitlabListError:  If the server failed to perform the request

        Returns:
            A list of commits/lines matching the file
        """
        file_path = utils._url_encode(file_path)
        path = f"{self.path}/{file_path}/blame"
        query_data = {"ref": ref}
        result = self.gitlab.http_list(path, query_data, **kwargs)
        if TYPE_CHECKING:
            assert isinstance(result, list)
        return result