You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@devlake.apache.org by "mappjzc (via GitHub)" <gi...@apache.org> on 2023/02/13 09:21:03 UTC

[GitHub] [incubator-devlake] mappjzc commented on a diff in pull request #4397: Gitlab remote api

mappjzc commented on code in PR #4397:
URL: https://github.com/apache/incubator-devlake/pull/4397#discussion_r1104186953


##########
backend/plugins/gitlab/api/remote.go:
##########
@@ -0,0 +1,376 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package api
+
+import (
+	"context"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"net/url"
+	"strconv"
+
+	"github.com/apache/incubator-devlake/core/errors"
+	"github.com/apache/incubator-devlake/core/plugin"
+	"github.com/apache/incubator-devlake/helpers/pluginhelper/api"
+	"github.com/apache/incubator-devlake/plugins/gitlab/models"
+	"github.com/apache/incubator-devlake/plugins/gitlab/tasks"
+)
+
+type RemoteScopesChild struct {
+	Type     string      `json:"type"`
+	ParentId *string     `json:"parentId"`
+	Id       string      `json:"id"`
+	Data     interface{} `json:"data"`
+}
+
+type RemoteScopesOutput struct {
+	Children      []RemoteScopesChild `json:"children"`
+	NextPageToken string              `json:"nextPageToken"`
+}
+
+type PageData struct {
+	Page    int    `json:"page"`
+	PerPage int    `json:"per_page"`
+	Tag     string `json:"tag"`
+}
+
+type GroupResponse struct {
+	Id                   int    `json:"id"`
+	WebUrl               string `json:"web_url"`
+	Name                 string `json:"name"`
+	Path                 string `json:"path"`
+	Description          string `json:"description"`
+	Visibility           string `json:"visibility"`
+	LfsEnabled           bool   `json:"lfs_enabled"`
+	AvatarUrl            string `json:"avatar_url"`
+	RequestAccessEnabled bool   `json:"request_access_enabled"`
+	FullName             string `json:"full_name"`
+	FullPath             string `json:"full_path"`
+	ParentId             *int   `json:"parent_id"`
+	LdapCN               string `json:"ldap_cn"`
+	LdapAccess           string `json:"ldap_access"`
+}
+
+const GitlabRemoteScoopesPerPage int = 100
+const TypeProject string = "scope"
+const TypeGroup string = "group"
+
+// RemoteScopes list all available scope for users
+// @Summary list all available scope for users
+// @Description list all available scope for users
+// @Tags plugins/gitlab
+// @Accept application/json
+// @Param connectionId path int false "connection ID"
+// @Param groupId body string false "group ID"
+// @Param pageToken body string false "page Token"
+// @Success 200  {object} []models.GitlabProject
+// @Failure 400  {object} shared.ApiBody "Bad Request"
+// @Failure 500  {object} shared.ApiBody "Internal Error"
+// @Router /plugins/gitlab/connections/{connectionId}/remote-scopes [GET]
+func RemoteScopes(input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, errors.Error) {
+	connectionId, _ := extractParam(input.Params)
+	if connectionId == 0 {
+		return nil, errors.BadInput.New("invalid connectionId")
+	}
+
+	connection := &models.GitlabConnection{}
+	err := connectionHelper.First(connection, input.Params)
+	if err != nil {
+		return nil, err
+	}
+
+	groupId, ok := input.Query["groupId"]
+	if !ok || len(groupId) == 0 {
+		groupId = []string{""}
+	}
+
+	pageToken, ok := input.Query["pageToken"]
+	if !ok || len(pageToken) == 0 {
+		pageToken = []string{""}
+	}
+
+	// get gid and pageData
+	gid := groupId[0]
+	pageData, err := GetPageDataFromPageToken(pageToken[0])
+	if err != nil {
+		return nil, errors.BadInput.New("failed to get paget token")
+	}
+
+	// create api client
+	apiClient, err := api.NewApiClientFromConnection(context.TODO(), basicRes, connection)
+	if err != nil {
+		return nil, err
+	}
+
+	query, err := GetQueryFromPageData(pageData)
+	if err != nil {
+		return nil, err
+	}
+
+	var res *http.Response
+	outputBody := &RemoteScopesOutput{}
+
+	query.Set("top_level_only", "true")
+
+	// list groups part
+	if pageData.Tag == TypeGroup {
+		if gid == "" {
+			res, err = apiClient.Get("groups", query, nil)
+		} else {
+			res, err = apiClient.Get(fmt.Sprintf("groups/%s/subgroups", gid), query, nil)
+		}
+		if err != nil {
+			return nil, err
+		}
+
+		resBody := []GroupResponse{}
+		err = api.UnmarshalResponse(res, &resBody)
+
+		// append group to output
+		for _, group := range resBody {
+			child := RemoteScopesChild{
+				Type: TypeGroup,
+				Id:   strconv.Itoa(group.Id),
+				// don't need to save group into data
+				Data: nil,
+			}
+
+			// ignore not top_level
+			if group.ParentId == nil {
+				if gid != "" {
+					continue
+				}
+			} else {
+				if strconv.Itoa(*group.ParentId) != gid {
+					continue
+				}
+			}
+
+			child.ParentId = &gid
+			if *child.ParentId == "" {
+				child.ParentId = nil
+			}
+
+			outputBody.Children = append(outputBody.Children, child)
+		}
+
+		// check groups count
+		if err != nil {
+			return nil, err
+		}
+		if len(resBody) < pageData.PerPage {
+			pageData.Tag = TypeProject
+			pageData.Page = 1
+			pageData.PerPage = pageData.PerPage - len(resBody)
+		}
+	}
+
+	query, err = GetQueryFromPageData(pageData)
+	if err != nil {
+		return nil, err
+	}
+
+	// list projects part
+	if pageData.Tag == TypeProject {
+		if gid == "" {
+			res, err = apiClient.Get(fmt.Sprintf("users/%d/projects", apiClient.GetData(models.GitlabApiClientData_UserId)), query, nil)
+		} else {
+			query.Set("with_shared", "false")
+			res, err = apiClient.Get(fmt.Sprintf("/groups/%s/projects", gid), query, nil)

Review Comment:
   > I find the change `subgroup -> projects` is fixed after the pre-review. Have you tested all main paths(if)?
   
   added the new testing



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@devlake.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org