How to use FetchURI method of content Package

Best Testkube code snippet using content.FetchURI

gitlab.go

Source:gitlab.go Github

copy

Full Screen

1package gitlab2import (3 "encoding/json"4 "errors"5 "fmt"6 "strings"7 "github.com/go-resty/resty/v2"8 "github.com/sirupsen/logrus"9)10type GitlabClient interface {11 GetProperty(property string) string12 SetProperty(property string, value string) string13 Get(uri string) (string, error)14 Delete(uri string) (string, error)15 GetUsers(search string) (string, error)16 GetGroup(groupID int) (Group, error)17 GetGroups(search string) (GroupList, error)18 GetSubGroups(groupID int) (GroupList, error)19 GetDescendantGroups(groupID int) (GroupList, error)20 GetGroupProjects(groupID int) (ProjectList, error)21 GetGroupMembers(group int) (string, error)22 AddGroupMember(groupID, userID, accessLevel int) (string, error)23 GetForcePushSetting(projectID int, protectedBranch string) (bool, error)24 GetProjectID(projectPath string) (int, error)25 GetProject(projectID int) (Project, error)26 GetProjectMembers(project int) (string, error)27 AddProjectMember(projectID, userID, accessLevel int) (string, error)28 DeleteProject(projectID int) error29 GetProjectMirrors(projectID int) (ProjectMirrors, error)30 GetGroupID(groupPath string) (int, error)31 CreateProject(groupID int, projectPath string, visibility string) (Project, error)32 DeleteProtectedBranch(projectID int, protectedBranch string) (bool, error)33 ProtectBranch(projectID int, protectedBranch string) (bool, error)34 CreateProjectMirror(projectID int, mirrorURL string) (ProjectMirror, error)35 UpdateProjectMirror(projectID int, mirrorID int) (ProjectMirror, error)36 CreateMergeRequest(projectID int, title string, sourceBranch string, targetBranch string) (string, error)37 GetPipelines(projectID int, user string) (Pipelines, error)38 GetPipeline(projectID int, pipelineID int) (Pipeline, error)39 GetCicdVariables(projectdID int) (Variables, error)40 GetCicdVariablesFromGroup(groupID int, includeProjects bool) (Variables, error)41}42type gitlabClient struct {43 BaseUrl string44 ApiPath string45 RepoFeedPath string46 Token string47 Client *resty.Client48}49// New generate a new gitlab client50func New(baseUrl, apiPath, token string) GitlabClient {51 // TODO: Add TLS Insecure && Pass in CA CRT for authentication52 restClient := resty.New()53 if apiPath == "" {54 apiPath = "/api/v4"55 }56 return &gitlabClient{57 BaseUrl: baseUrl,58 ApiPath: apiPath,59 Token: token,60 Client: restClient,61 }62}63func (r *gitlabClient) GetProperty(property string) string {64 switch property {65 case "BaseUrl":66 return r.BaseUrl67 case "ApiPath":68 return r.ApiPath69 case "Token":70 return r.Token71 }72 return ""73}74func (r *gitlabClient) SetProperty(property string, value string) string {75 switch property {76 case "BaseUrl":77 r.BaseUrl = value78 return r.BaseUrl79 case "ApiPath":80 r.ApiPath = value81 return r.ApiPath82 case "Token":83 r.Token = value84 return r.Token85 }86 return ""87}88func (r *gitlabClient) Get(uri string) (string, error) {89 nextPage := "1"90 combinedResults := ""91 for {92 // TODO: detect if there are no options passed in, ? verus & for page option93 fetchUri := fmt.Sprintf("https://%s%s%s&page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)94 // logrus.Warn(fetchUri)95 resp, resperr := r.Client.R().96 SetHeader("PRIVATE-TOKEN", r.Token).97 Get(fetchUri)98 if resperr != nil {99 logrus.WithError(resperr).Error("Oops")100 return "", resperr101 }102 items := strings.TrimPrefix(string(resp.Body()[:]), "[")103 items = strings.TrimSuffix(items, "]")104 if combinedResults == "" {105 combinedResults += items106 } else {107 combinedResults += fmt.Sprintf(", %s", items)108 }109 currentPage := resp.Header().Get("X-Page")110 nextPage = resp.Header().Get("X-Next-Page")111 totalPages := resp.Header().Get("X-Total-Pages")112 if currentPage == totalPages {113 break114 }115 }116 return fmt.Sprintf("[%s]", combinedResults), nil117}118func (r *gitlabClient) Delete(uri string) (string, error) {119 // https://git.alteryx.com/api/v4/projects/5784/releases/v0.0.6120 // GL_PAT=$(get-gitlab-api-pat)121 // curl --request DELETE --header "PRIVATE-TOKEN: ${GL_PAT}" "https://git.alteryx.com/api/v4/projects/5784/releases/v0.0.6"122 deleteUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)123 // logrus.Warn(fetchUri)124 resp, resperr := r.Client.R().125 SetHeader("PRIVATE-TOKEN", r.Token).126 Delete(deleteUri)127 if resperr != nil {128 logrus.WithError(resperr).Error("Oops")129 return "", resperr130 }131 return string(resp.Body()[:]), nil132}133// CreateMergeRequest creates a new merge request.134//135// GitLab API docs:136// https://docs.gitlab.com/ce/api/merge_requests.html#create-mr137func (r *gitlabClient) CreateMergeRequest(projectID int, title string, sourceBranch string, targetBranch string) (string, error) {138 // https://git.alteryx.com/api/v4/projects/5701 /merge_requests139 // curl --request POST https://gitlab.com /api/v4/projects/${project_id}/merge_requests --header "PRIVATE-TOKEN: ${mytoken}" \140 // --header 'Content-Type: application/json' \141 // --data "{142 // \"id\": \"${project_id}\",143 // \"title\": \"m2d\",144 // \"source_branch\": \"m2d\",145 // \"target_branch\": \"develop\"146 // }"147 uri := fmt.Sprintf("/projects/%d/merge_requests", projectID)148 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)149 mrTemplate := `{150 "id": "%d",151 "title": "%s",152 "source_branch": "%s",153 "target_branch": "%s"154 }`155 body := fmt.Sprintf(mrTemplate, projectID, title, sourceBranch, targetBranch)156 resp, resperr := r.Client.R().157 SetHeader("PRIVATE-TOKEN", r.Token).158 SetHeader("Content-Type", "application/json").159 SetBody(body).160 Post(fetchUri)161 if resperr != nil {162 logrus.WithError(resperr).Error("Oops")163 return "", resperr164 }165 return string(resp.Body()[:]), nil166}167// GetProjectID - returns the project ID based on the group/project path (slug)168//169// GitLab API docs:170// https://docs.gitlab.com/ee/api/projects.html#get-single-project171func (r *gitlabClient) GetProjectID(projectPath string) (int, error) {172 uri := fmt.Sprintf("/projects/%s", projectPath)173 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)174 // fmt.Printf("fetchUri: %s\n", fetchUri)175 resp, resperr := r.Client.R().176 SetHeader("PRIVATE-TOKEN", r.Token).177 SetHeader("Content-Type", "application/json").178 Get(fetchUri)179 if resperr != nil {180 logrus.WithError(resperr).Error("Oops")181 return 0, resperr182 }183 var pi ProjectInfo184 marshErr := json.Unmarshal(resp.Body(), &pi)185 if marshErr != nil {186 logrus.Fatal("Cannot marshall Pipeline", marshErr)187 }188 return pi.ID, nil189}190// GetProject - returns the full project based on the project ID191//192// GitLab API docs:193// https://docs.gitlab.com/ee/api/projects.html#get-single-project194func (r *gitlabClient) GetProject(projectID int) (Project, error) {195 uri := fmt.Sprintf("/projects/%d", projectID)196 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)197 // fmt.Printf("fetchUri: %s\n", fetchUri)198 resp, resperr := r.Client.R().199 SetHeader("PRIVATE-TOKEN", r.Token).200 SetHeader("Content-Type", "application/json").201 Get(fetchUri)202 if resperr != nil {203 logrus.WithError(resperr).Error("Oops")204 return Project{}, resperr205 }206 var pi Project207 marshErr := json.Unmarshal(resp.Body(), &pi)208 if marshErr != nil {209 logrus.Fatal("Cannot marshall Pipeline", marshErr)210 return Project{}, resperr211 }212 return pi, nil213}214// GetProjectMirrors - returns the full project based on the project ID215//216// GitLab API docs:217func (r *gitlabClient) GetProjectMirrors(projectID int) (ProjectMirrors, error) {218 // curl -Ls "https://git.alteryx.com/api/v4/projects/${PR_ID}/remote_mirrors" \219 // --header "PRIVATE-TOKEN: ${PRIV_TOKEN}" | jq -r '.[] | ([.id,.url,.enabled,.only_protected_branches]220 uri := fmt.Sprintf("/projects/%d/remote_mirrors", projectID)221 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)222 // fmt.Printf("fetchUri: %s\n", fetchUri)223 resp, resperr := r.Client.R().224 SetHeader("PRIVATE-TOKEN", r.Token).225 SetHeader("Content-Type", "application/json").226 Get(fetchUri)227 if resperr != nil {228 logrus.WithError(resperr).Error("Oops")229 return ProjectMirrors{}, resperr230 }231 var prm ProjectMirrors232 marshErr := json.Unmarshal(resp.Body(), &prm)233 if marshErr != nil {234 logrus.Fatal("Cannot marshall Pipeline", marshErr)235 return ProjectMirrors{}, resperr236 }237 return prm, nil238}239// CreateProject creates a new gitlab project (git repository)240//241// GitLab API docs:242// https://docs.gitlab.com/ee/api/projects.html#create-project243func (r *gitlabClient) CreateProject(groupID int, projectPath string, visibility string) (Project, error) {244 // curl -Ls --request POST https://gitlab.com/api/v4/projects --header "PRIVATE-TOKEN: ${mytoken}" \245 // --header 'Content-Type: application/json' \246 // --data "{247 // \"path\": \"${new_ring}\",248 // \"default_branch\": \"master\",249 // \"initialize_with_readme\": \"true\",250 // \"visibility\": \"private\",251 // \"namespace_id\": \"${group_id}\"252 // }"253 uri := "/projects"254 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)255 // logrus.Info(fmt.Sprintf("fetchUri: %s", fetchUri))256 projectTemplate := `{257 "path": "%s",258 "default_branch": "master",259 "initialize_with_readme": "true",260 "visibility": "%s",261 "namespace_id": "%d"262 }`263 body := fmt.Sprintf(projectTemplate, projectPath, visibility, groupID)264 // logrus.Info(fmt.Sprintf("body: %s", body))265 resp, resperr := r.Client.R().266 SetHeader("PRIVATE-TOKEN", r.Token).267 SetHeader("Content-Type", "application/json").268 SetBody(body).269 Post(fetchUri)270 if resperr != nil {271 logrus.WithError(resperr).Error("Oops")272 return Project{}, resperr273 }274 logrus.Info(fmt.Sprintf("%s", string(resp.Body()[:])))275 var prj Project276 marshErr := json.Unmarshal(resp.Body(), &prj)277 if marshErr != nil {278 logrus.Fatal("Cannot marshall Pipeline", marshErr)279 return Project{}, marshErr280 }281 return prj, nil282}283// ProtectBranch284//285// GitLab API docs:286func (r *gitlabClient) ProtectBranch(projectID int, protectedBranch string) (bool, error) {287 // curl -Ls --request POST "https://gitlab.com/api/v4/projects/${PR_ID}/protected_branches" \288 // --header "PRIVATE-TOKEN: ${PUB_TOKEN}" \289 // --header 'Content-Type: application/json' \290 // --data "{291 // \"name\": \"master\",292 // \"push_access_levels\": [293 // {294 // \"access_level\": 40,295 // \"access_level_description\": \"Maintainers\",296 // \"user_id\": null,297 // \"group_id\": null298 // }299 // ],300 // \"merge_access_levels\": [301 // {302 // \"access_level\": 40,303 // \"access_level_description\": \"Maintainers\",304 // \"user_id\": null,305 // \"group_id\": null306 // }307 // ],308 // \"allow_force_push\": true,309 // \"unprotect_access_levels\": [],310 // \"code_owner_approval_required\": false311 // }" | jq '.allow_force_push'312 uri := fmt.Sprintf("/projects/%d/protected_branches", projectID)313 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)314 pbTemplate := `{315 "name": "%s",316 "push_access_levels": [317 {318 "access_level": 40,319 "access_level_description": "Maintainers",320 "user_id": null,321 "group_id": null322 }323 ],324 "merge_access_levels": [325 {326 "access_level": 40,327 "access_level_description": "Maintainers",328 "user_id": null,329 "group_id": null330 }331 ],332 "allow_force_push": true,333 "unprotect_access_levels": [],334 "code_owner_approval_required": false335 }`336 body := fmt.Sprintf(pbTemplate, protectedBranch)337 resp, resperr := r.Client.R().338 SetHeader("PRIVATE-TOKEN", r.Token).339 SetHeader("Content-Type", "application/json").340 SetBody(body).341 Post(fetchUri)342 if resperr != nil {343 logrus.WithError(resperr).Error("Oops")344 return false, resperr345 }346 var pbs ProtectedBranchSettings347 marshErr := json.Unmarshal(resp.Body(), &pbs)348 if marshErr != nil {349 logrus.Fatal("Cannot marshall Pipeline", marshErr)350 return false, resperr351 }352 return pbs.AllowForcePush, nil353}354// CreateProjectMirror creates a new mirror for a gitlab project (git repository)355//356// GitLab API docs:357func (r *gitlabClient) CreateProjectMirror(projectID int, mirrorURL string) (ProjectMirror, error) {358 // curl -Ls --request POST "https://git.alteryx.com/api/v4/projects/${PR_ID}/remote_mirrors" \359 // --header "PRIVATE-TOKEN: ${PRIV_TOKEN}" \360 // --header 'Content-Type: application/json' \361 // --data "{362 // \"url\": \"https://falkor_sync:${ENC_SYNC_PW}@gitlab.com/${PROJECT_PATH}\",363 // \"enabled\": \"true\",364 // \"only_protected_branches\": \"true\"365 // }" | jq -r '([.id,.url,.enabled,.only_protected_branches]) | @csv')366 uri := fmt.Sprintf("/projects/%d/remote_mirrors", projectID)367 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)368 // logrus.Info(fmt.Sprintf("fetchUri: %s", fetchUri))369 mirrorTemplate := `{370 "url": "%s",371 "enabled": "true",372 "only_protected_branches": "true"373 }`374 body := fmt.Sprintf(mirrorTemplate, mirrorURL)375 // logrus.Info(fmt.Sprintf("body: %s", body))376 resp, resperr := r.Client.R().377 SetHeader("PRIVATE-TOKEN", r.Token).378 SetHeader("Content-Type", "application/json").379 SetBody(body).380 Post(fetchUri)381 if resperr != nil {382 logrus.WithError(resperr).Error("Oops")383 return ProjectMirror{}, resperr384 }385 // logrus.Info(fmt.Sprintf("%s", string(resp.Body()[:])))386 var pm ProjectMirror387 marshErr := json.Unmarshal(resp.Body(), &pm)388 if marshErr != nil {389 logrus.Fatal("Cannot marshall Pipeline", marshErr)390 return ProjectMirror{}, resperr391 }392 return pm, nil393}394// UpdateProjectMirror update a project mirror settings for a gitlab project (git repository)395//396// GitLab API docs:397func (r *gitlabClient) UpdateProjectMirror(projectID int, mirrorID int) (ProjectMirror, error) {398 // curl -Ls --request PUT https://git.alteryx.com/api/v4/projects/${PR_ID}/remote_mirrors/${m_id} \399 // --header "PRIVATE-TOKEN: ${PRIV_TOKEN}" \400 // --header 'Content-Type: application/json' \401 // --data "{402 // \"enabled\": \"true\",403 // \"only_protected_branches\": \"true\"404 // }" | jq -r '([.id,.url,.enabled,.only_protected_branches]) | @csv')405 uri := fmt.Sprintf("/projects/%d/remote_mirrors/%d", projectID, mirrorID)406 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)407 // logrus.Info(fmt.Sprintf("fetchUri: %s", fetchUri))408 mirrorTemplate := "enabled=true&only_protected_branches=true"409 resp, resperr := r.Client.R().410 SetHeader("PRIVATE-TOKEN", r.Token).411 SetHeader("Content-Type", "application/x-www-form-urlencoded").412 SetBody(mirrorTemplate).413 Put(fetchUri)414 if resperr != nil {415 logrus.WithError(resperr).Error("Oops")416 return ProjectMirror{}, resperr417 }418 // logrus.Info(fmt.Sprintf("%s", string(resp.Body()[:])))419 var pm ProjectMirror420 marshErr := json.Unmarshal(resp.Body(), &pm)421 if marshErr != nil {422 logrus.Fatal("Cannot marshall Pipeline", marshErr)423 return ProjectMirror{}, resperr424 }425 return pm, nil426}427// DeleteProject - Delete the project by ProjectID428//429// GitLab API docs:430// https://docs.gitlab.com/ee/api/projects.html#delete-project431func (r *gitlabClient) DeleteProject(projectID int) error {432 uri := fmt.Sprintf("/projects/%d", projectID)433 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)434 resp, resperr := r.Client.R().435 SetHeader("PRIVATE-TOKEN", r.Token).436 SetHeader("Content-Type", "application/json").437 Delete(fetchUri)438 if resperr != nil {439 return resperr440 }441 var msg Message442 marshErr := json.Unmarshal(resp.Body(), &msg)443 if marshErr != nil {444 return marshErr445 }446 if msg.Message == "202 Accepted" {447 return nil448 }449 return errors.New(strings.ToLower(msg.Message))450}451// DeleteProtectedBranch - delete the specified branch from the protected list452//453// GitLab API docs:454func (r *gitlabClient) DeleteProtectedBranch(projectID int, protectedBranch string) (bool, error) {455 // curl -Ls --request DELETE "https://gitlab.com/api/v4/projects/${PR_ID}/protected_branches/master" \456 // --header "PRIVATE-TOKEN: ${PUB_TOKEN}" | jq -r '.message'457 uri := fmt.Sprintf("/projects/%d/protected_branches/%s", projectID, protectedBranch)458 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)459 // fmt.Printf("fetchUri: %s\n", fetchUri)460 resp, resperr := r.Client.R().461 SetHeader("PRIVATE-TOKEN", r.Token).462 SetHeader("Content-Type", "application/json").463 Delete(fetchUri)464 if resperr != nil {465 logrus.WithError(resperr).Error("Oops")466 return false, resperr467 }468 return resp.IsSuccess(), nil469}470// GetForcePushSetting -471//472// GitLab API docs:473// https://docs.gitlab.com/ee/api/projects.html#get-single-project474func (r *gitlabClient) GetForcePushSetting(projectID int, protectedBranch string) (bool, error) {475 // curl -Ls --header "PRIVATE-TOKEN: ${PUB_TOKEN}" "https://gitlab.com/api/v4/projects/${PR_ID}/protected_branches/master" | jq '.allow_force_push'476 uri := fmt.Sprintf("/projects/%d/protected_branches/%s", projectID, protectedBranch)477 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)478 // fmt.Printf("fetchUri: %s\n", fetchUri)479 resp, resperr := r.Client.R().480 SetHeader("PRIVATE-TOKEN", r.Token).481 SetHeader("Content-Type", "application/json").482 Get(fetchUri)483 if resperr != nil {484 logrus.WithError(resperr).Error("Oops")485 return false, resperr486 }487 var pbs ProtectedBranchSettings488 marshErr := json.Unmarshal(resp.Body(), &pbs)489 if marshErr != nil {490 logrus.Fatal("Cannot marshall Pipeline", marshErr)491 return false, resperr492 }493 return pbs.AllowForcePush, nil494}495// GetGroupID - returns the group ID based on the namespace/group path (slug)496//497// GitLab API docs:498// https://docs.gitlab.com/ee/api/groups.html#details-of-a-group499func (r *gitlabClient) GetGroupID(groupPath string) (int, error) {500 uri := fmt.Sprintf("/groups/%s", groupPath)501 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)502 // fmt.Printf("fetchUri: %s\n", fetchUri)503 resp, resperr := r.Client.R().504 SetHeader("PRIVATE-TOKEN", r.Token).505 SetHeader("Content-Type", "application/json").506 Get(fetchUri)507 if resperr != nil {508 logrus.WithError(resperr).Error("Oops")509 return 0, resperr510 }511 var pi ProjectInfo512 marshErr := json.Unmarshal(resp.Body(), &pi)513 if marshErr != nil {514 logrus.Fatal("Cannot marshall Pipeline", marshErr)515 return 0, resperr516 }517 return pi.ID, nil518}519func (r *gitlabClient) GetUsers(search string) (string, error) {520 nextPage := "1"521 combinedResults := ""522 uri := "/users?active=true"523 for {524 // TODO: detect if there are no options passed in, ? verus & for page option525 fetchUri := fmt.Sprintf("https://%s%s%s&search=%s&page=%s", r.BaseUrl, r.ApiPath, uri, search, nextPage)526 // logrus.Warn(fetchUri)527 resp, resperr := r.Client.R().528 SetHeader("PRIVATE-TOKEN", r.Token).529 Get(fetchUri)530 if resperr != nil {531 logrus.WithError(resperr).Error("Oops")532 return "", resperr533 }534 items := strings.TrimPrefix(string(resp.Body()[:]), "[")535 items = strings.TrimSuffix(items, "]")536 if combinedResults == "" {537 combinedResults += items538 } else {539 combinedResults += fmt.Sprintf(", %s", items)540 }541 currentPage := resp.Header().Get("X-Page")542 nextPage = resp.Header().Get("X-Next-Page")543 totalPages := resp.Header().Get("X-Total-Pages")544 if currentPage == totalPages {545 break546 }547 }548 return fmt.Sprintf("[%s]", combinedResults), nil549}550// GetGroup - returns the full group based on the group ID551//552// GitLab API docs:553func (r *gitlabClient) GetGroup(groupID int) (Group, error) {554 uri := fmt.Sprintf("/groups/%d", groupID)555 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)556 // fmt.Printf("fetchUri: %s\n", fetchUri)557 resp, resperr := r.Client.R().558 SetHeader("PRIVATE-TOKEN", r.Token).559 SetHeader("Content-Type", "application/json").560 Get(fetchUri)561 if resperr != nil {562 logrus.WithError(resperr).Error("Oops")563 return Group{}, resperr564 }565 var gr Group566 marshErr := json.Unmarshal(resp.Body(), &gr)567 if marshErr != nil {568 logrus.Fatal("Cannot marshall Pipeline", marshErr)569 return Group{}, resperr570 }571 return gr, nil572}573// GetGroups- returns a list of groups574//575// GitLab API docs:576// https://docs.gitlab.com/ee/api/projects.html#get-single-project577func (r *gitlabClient) GetGroups(search string) (GroupList, error) {578 nextPage := "1"579 combinedResults := ""580 uri := "/groups?per_page=100&all_available=true"581 for {582 fetchUri := fmt.Sprintf("https://%s%s%s&page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)583 // fmt.Printf("fetchUri: %s\n", fetchUri)584 resp, resperr := r.Client.R().585 SetHeader("PRIVATE-TOKEN", r.Token).586 SetHeader("Content-Type", "application/json").587 Get(fetchUri)588 if resperr != nil {589 logrus.WithError(resperr).Error("Oops")590 return GroupList{}, resperr591 }592 items := strings.TrimPrefix(string(resp.Body()[:]), "[")593 items = strings.TrimSuffix(items, "]")594 if combinedResults == "" {595 combinedResults += items596 } else {597 combinedResults += fmt.Sprintf(", %s", items)598 }599 currentPage := resp.Header().Get("X-Page")600 nextPage = resp.Header().Get("X-Next-Page")601 totalPages := resp.Header().Get("X-Total-Pages")602 if currentPage == totalPages {603 break604 }605 }606 surroundArray := fmt.Sprintf("[%s]", combinedResults)607 var gl GroupList608 marshErr := json.Unmarshal([]byte(surroundArray), &gl)609 if marshErr != nil {610 logrus.Fatal("Cannot marshall Pipeline", marshErr)611 return GroupList{}, marshErr612 }613 return gl, nil614}615// GetSubGroups- returns a list of subgroups for a given group id616//617// GitLab API docs:618// https://docs.gitlab.com/ee/api/groups.html#list-a-groups-subgroups619func (r *gitlabClient) GetSubGroups(groupID int) (GroupList, error) {620 nextPage := "1"621 combinedResults := ""622 uri := fmt.Sprintf("/groups/%d/subgroups", groupID)623 for {624 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)625 // fmt.Printf("fetchUri: %s\n", fetchUri)626 resp, resperr := r.Client.R().627 SetHeader("PRIVATE-TOKEN", r.Token).628 SetHeader("Content-Type", "application/json").629 Get(fetchUri)630 if resperr != nil {631 logrus.WithError(resperr).Error("Oops")632 return GroupList{}, resperr633 }634 items := strings.TrimPrefix(string(resp.Body()[:]), "[")635 items = strings.TrimSuffix(items, "]")636 if combinedResults == "" {637 combinedResults += items638 } else {639 combinedResults += fmt.Sprintf(", %s", items)640 }641 currentPage := resp.Header().Get("X-Page")642 nextPage = resp.Header().Get("X-Next-Page")643 totalPages := resp.Header().Get("X-Total-Pages")644 if currentPage == totalPages {645 break646 }647 }648 surroundArray := fmt.Sprintf("[%s]", combinedResults)649 var gl GroupList650 marshErr := json.Unmarshal([]byte(surroundArray), &gl)651 if marshErr != nil {652 logrus.Fatal("Cannot marshall Pipeline", marshErr)653 return GroupList{}, marshErr654 }655 return gl, nil656}657// GetDescendantGroups - returns a list of descendant_groups for a groupID658//659// GitLab API docs:660// https://docs.gitlab.com/ee/api/groups.html#list-a-groups-descendant-groups661func (r *gitlabClient) GetDescendantGroups(groupID int) (GroupList, error) {662 nextPage := "1"663 combinedResults := ""664 uri := fmt.Sprintf("/groups/%d/descendant_groups", groupID)665 for {666 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)667 // fmt.Printf("fetchUri: %s\n", fetchUri)668 resp, resperr := r.Client.R().669 SetHeader("PRIVATE-TOKEN", r.Token).670 SetHeader("Content-Type", "application/json").671 Get(fetchUri)672 if resperr != nil {673 logrus.WithError(resperr).Error("Oops")674 return GroupList{}, resperr675 }676 items := strings.TrimPrefix(string(resp.Body()[:]), "[")677 items = strings.TrimSuffix(items, "]")678 if combinedResults == "" {679 combinedResults += items680 } else {681 combinedResults += fmt.Sprintf(", %s", items)682 }683 currentPage := resp.Header().Get("X-Page")684 nextPage = resp.Header().Get("X-Next-Page")685 totalPages := resp.Header().Get("X-Total-Pages")686 if currentPage == totalPages {687 break688 }689 }690 surroundArray := fmt.Sprintf("[%s]", combinedResults)691 var gl GroupList692 marshErr := json.Unmarshal([]byte(surroundArray), &gl)693 if marshErr != nil {694 logrus.Fatal("Cannot marshall Pipeline", marshErr)695 return GroupList{}, marshErr696 }697 return gl, nil698}699// GetGroupProjects- returns a list of projects for a given group id700//701// GitLab API docs:702// https://docs.gitlab.com/ee/api/groups.html#list-a-groups-projects703func (r *gitlabClient) GetGroupProjects(groupID int) (ProjectList, error) {704 nextPage := "1"705 combinedResults := ""706 uri := fmt.Sprintf("/groups/%d/projects", groupID)707 for {708 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)709 // fmt.Printf("fetchUri: %s\n", fetchUri)710 resp, resperr := r.Client.R().711 SetHeader("PRIVATE-TOKEN", r.Token).712 SetHeader("Content-Type", "application/json").713 Get(fetchUri)714 if resperr != nil {715 logrus.WithError(resperr).Error("Oops")716 return ProjectList{}, resperr717 }718 items := strings.TrimPrefix(string(resp.Body()[:]), "[")719 items = strings.TrimSuffix(items, "]")720 if combinedResults == "" {721 combinedResults += items722 } else {723 combinedResults += fmt.Sprintf(", %s", items)724 }725 currentPage := resp.Header().Get("X-Page")726 nextPage = resp.Header().Get("X-Next-Page")727 totalPages := resp.Header().Get("X-Total-Pages")728 if currentPage == totalPages {729 break730 }731 }732 surroundArray := fmt.Sprintf("[%s]", combinedResults)733 var pl ProjectList734 marshErr := json.Unmarshal([]byte(surroundArray), &pl)735 if marshErr != nil {736 logrus.Fatal("Cannot marshall Pipeline", marshErr)737 return ProjectList{}, marshErr738 }739 return pl, nil740}741// https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project742func (r *gitlabClient) GetGroupMembers(group int) (string, error) {743 nextPage := "1"744 combinedResults := ""745 uri := fmt.Sprintf("/groups/%d/members", group)746 for {747 // TODO: detect if there are no options passed in, ? verus & for page option748 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)749 // logrus.Warn(fetchUri)750 resp, resperr := r.Client.R().751 SetHeader("PRIVATE-TOKEN", r.Token).752 Get(fetchUri)753 if resperr != nil {754 logrus.WithError(resperr).Error("Oops")755 return "", resperr756 }757 items := strings.TrimPrefix(string(resp.Body()[:]), "[")758 items = strings.TrimSuffix(items, "]")759 if combinedResults == "" {760 combinedResults += items761 } else {762 combinedResults += fmt.Sprintf(", %s", items)763 }764 currentPage := resp.Header().Get("X-Page")765 nextPage = resp.Header().Get("X-Next-Page")766 totalPages := resp.Header().Get("X-Total-Pages")767 if currentPage == totalPages {768 break769 }770 }771 return fmt.Sprintf("[%s]", combinedResults), nil772}773// AddGroupMember774//775// GitLab API docs:776// https://docs.gitlab.com/ee/api/members.html#add-a-member-to-a-group-or-project777func (r *gitlabClient) AddGroupMember(groupID, userID, accessLevel int) (string, error) {778 uri := fmt.Sprintf("/groups/%d/members", groupID)779 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)780 memberTemplate := `{781 "user_id": "%d",782 "access_level": "%d"783 }`784 body := fmt.Sprintf(memberTemplate, userID, accessLevel)785 resp, resperr := r.Client.R().786 SetHeader("PRIVATE-TOKEN", r.Token).787 SetHeader("Content-Type", "application/json").788 SetBody(body).789 Post(fetchUri)790 if resperr != nil {791 logrus.WithError(resperr).Error("Oops")792 return "", resperr793 }794 return string(resp.Body()[:]), nil795}796// https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project797func (r *gitlabClient) GetProjectMembers(project int) (string, error) {798 nextPage := "1"799 combinedResults := ""800 uri := fmt.Sprintf("/projects/%d/members", project)801 for {802 // TODO: detect if there are no options passed in, ? verus & for page option803 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)804 // logrus.Warn(fetchUri)805 resp, resperr := r.Client.R().806 SetHeader("PRIVATE-TOKEN", r.Token).807 Get(fetchUri)808 if resperr != nil {809 logrus.WithError(resperr).Error("Oops")810 return "", resperr811 }812 items := strings.TrimPrefix(string(resp.Body()[:]), "[")813 items = strings.TrimSuffix(items, "]")814 if combinedResults == "" {815 combinedResults += items816 } else {817 combinedResults += fmt.Sprintf(", %s", items)818 }819 currentPage := resp.Header().Get("X-Page")820 nextPage = resp.Header().Get("X-Next-Page")821 totalPages := resp.Header().Get("X-Total-Pages")822 if currentPage == totalPages {823 break824 }825 }826 return fmt.Sprintf("[%s]", combinedResults), nil827}828// AddProjectMember829//830// GitLab API docs:831// https://docs.gitlab.com/ee/api/members.html#add-a-member-to-a-group-or-project832func (r *gitlabClient) AddProjectMember(projectID, userID, accessLevel int) (string, error) {833 uri := fmt.Sprintf("/projects/%d/members", projectID)834 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)835 memberTemplate := `{836 "user_id": "%d",837 "access_level": "%d"838 }`839 body := fmt.Sprintf(memberTemplate, userID, accessLevel)840 resp, resperr := r.Client.R().841 SetHeader("PRIVATE-TOKEN", r.Token).842 SetHeader("Content-Type", "application/json").843 SetBody(body).844 Post(fetchUri)845 if resperr != nil {846 logrus.WithError(resperr).Error("Oops")847 return "", resperr848 }849 return string(resp.Body()[:]), nil850}851// GetPipelines returns a list of pipelines for the project852//853// GitLab API docs:854// https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines855func (r *gitlabClient) GetPipelines(projectID int, user string) (Pipelines, error) {856 nextPage := "1"857 combinedResults := ""858 uri := ""859 if len(user) > 0 {860 uri = fmt.Sprintf("/projects/%d/pipelines?per_page=100&username=%s", projectID, user)861 } else {862 uri = fmt.Sprintf("/projects/%d/pipelines?per_page=100", projectID)863 }864 for {865 fetchUri := fmt.Sprintf("https://%s%s%s&page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)866 // fmt.Printf("fetchUri: %s\n", fetchUri)867 resp, resperr := r.Client.R().868 SetHeader("PRIVATE-TOKEN", r.Token).869 SetHeader("Content-Type", "application/json").870 Get(fetchUri)871 if resperr != nil {872 logrus.WithError(resperr).Error("Oops")873 return Pipelines{}, resperr874 }875 items := strings.TrimPrefix(string(resp.Body()[:]), "[")876 items = strings.TrimSuffix(items, "]")877 if combinedResults == "" {878 combinedResults += items879 } else {880 combinedResults += fmt.Sprintf(", %s", items)881 }882 currentPage := resp.Header().Get("X-Page")883 nextPage = resp.Header().Get("X-Next-Page")884 totalPages := resp.Header().Get("X-Total-Pages")885 if currentPage == totalPages {886 break887 }888 }889 surroundArray := fmt.Sprintf("[%s]", combinedResults)890 var pipelines Pipelines891 marshErr := json.Unmarshal([]byte(surroundArray), &pipelines)892 if marshErr != nil {893 logrus.Fatal("Cannot marshall Pipeline", marshErr)894 return Pipelines{}, marshErr895 }896 return pipelines, nil897}898// GetPipeline - Returns a single pipeline899//900// GitLab API docs:901// https://docs.gitlab.com/ee/api/pipelines.html#get-a-single-pipeline902func (r *gitlabClient) GetPipeline(projectID int, pipelineID int) (Pipeline, error) {903 uri := fmt.Sprintf("/projects/%d/pipelines/%d", projectID, pipelineID)904 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)905 // fmt.Printf("fetchUri: %s\n", fetchUri)906 resp, resperr := r.Client.R().907 SetHeader("PRIVATE-TOKEN", r.Token).908 SetHeader("Content-Type", "application/json").909 Get(fetchUri)910 if resperr != nil {911 logrus.WithError(resperr).Error("Oops")912 return Pipeline{}, resperr913 }914 var pipeline Pipeline915 marshErr := json.Unmarshal(resp.Body(), &pipeline)916 if marshErr != nil {917 logrus.Fatal("Cannot marshall Pipeline", marshErr)918 return Pipeline{}, resperr919 }920 return pipeline, nil921}922func getVariablesFrom(r *gitlabClient, id int, resource string) (Variables, error) {923 nextPage := "1"924 combinedResults := ""925 for {926 uri := fmt.Sprintf("/%s/%d/variables", resource, id)927 fetchUri := fmt.Sprintf("https://%s%s%s?page=%s", r.BaseUrl, r.ApiPath, uri, nextPage)928 resp, resperr := r.Client.R().929 SetHeader("PRIVATE-TOKEN", r.Token).930 SetHeader("Content-Type", "application/json").931 Get(fetchUri)932 if resperr != nil {933 logrus.WithError(resperr).Error("Oops")934 return Variables{}, resperr935 }936 items := strings.TrimPrefix(string(resp.Body()[:]), "[")937 items = strings.TrimSuffix(items, "]")938 if combinedResults == "" {939 combinedResults += items940 } else {941 combinedResults += fmt.Sprintf(", %s", items)942 }943 currentPage := resp.Header().Get("X-Page")944 nextPage = resp.Header().Get("X-Next-Page")945 totalPages := resp.Header().Get("X-Total-Pages")946 if currentPage == totalPages {947 break948 }949 }950 surroundArray := fmt.Sprintf("[%s]", combinedResults)951 var variables Variables952 marshErr := json.Unmarshal([]byte(surroundArray), &variables)953 if marshErr != nil {954 logrus.Fatal("Cannot marshall Pipeline", marshErr)955 return Variables{}, marshErr956 }957 if resource == "projects" {958 projectInfo, perr := r.GetProject(id)959 if perr != nil {960 logrus.Error("Cannot marshall Pipeline", marshErr)961 return variables, perr962 }963 // for _, v := range variables {964 for k := range variables {965 // v.Source = projectInfo.Path966 variables[k].Source = projectInfo.PathWithNamespace967 }968 }969 if resource == "groups" {970 groupInfo, gerr := r.GetGroup(id)971 if gerr != nil {972 logrus.Error("Cannot marshall Pipeline", marshErr)973 return variables, gerr974 }975 for k := range variables {976 // variables[k].Source = groupInfo.Path977 variables[k].Source = groupInfo.FullPath978 }979 }980 return variables, nil981}982// GetCicdVariables - Returns all CICD Variables for a ProjectID983//984// GitLab API docs:985// https://docs.gitlab.com/ee/api/project_level_variables.html986// https://docs.gitlab.com/ee/api/group_level_variables.html987func (r *gitlabClient) GetCicdVariables(projectID int) (Variables, error) {988 // curl -Ls --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" "https://git.alteryx.com/api/v4/projects/5844/variables" | jq .989 // Fetch the ProjectID, extract .namespace.id (this is the immediate containing group)990 // Fetch the GroupID, extract .parent_id until 'null'991 uri := fmt.Sprintf("/projects/%d/variables", projectID)992 fetchUri := fmt.Sprintf("https://%s%s%s", r.BaseUrl, r.ApiPath, uri)993 resp, resperr := r.Client.R().994 SetHeader("PRIVATE-TOKEN", r.Token).995 SetHeader("Content-Type", "application/json").996 Get(fetchUri)997 if resperr != nil {998 logrus.WithError(resperr).Error("Oops")999 return Variables{}, resperr1000 }1001 var variables Variables1002 marshErr := json.Unmarshal(resp.Body(), &variables)1003 if marshErr != nil {1004 logrus.Fatal("Cannot marshall Pipeline", marshErr)1005 return Variables{}, resperr1006 }1007 projectInfo, perr := r.GetProject(projectID)1008 if perr != nil {1009 logrus.Error("Cannot marshall Pipeline", marshErr)1010 return variables, perr1011 }1012 for k := range variables {1013 variables[k].Source = projectInfo.PathWithNamespace1014 }1015 if projectInfo.Namespace.ID > 0 {1016 groupID := projectInfo.Namespace.ID1017 for {1018 parentVariables, verr := getVariablesFrom(r, groupID, "groups")1019 if verr != nil {1020 logrus.Error("Cannot marshall Pipeline", marshErr)1021 return variables, resperr1022 }1023 variables = append(variables, parentVariables...)1024 groupInfo, gerr := r.GetGroup(groupID)1025 if gerr != nil {1026 logrus.Error("Cannot marshall Pipeline", marshErr)1027 return variables, gerr1028 }1029 if groupInfo.ParentID == 0 {1030 break1031 }1032 groupID = groupInfo.ParentID1033 }1034 }1035 return variables, nil1036}1037// GetCicdVariablesFromGroup - Returns all CICD Variables for a ProjectID1038//1039// GitLab API docs:1040// https://docs.gitlab.com/ee/api/project_level_variables.html1041// https://docs.gitlab.com/ee/api/group_level_variables.html1042func (r *gitlabClient) GetCicdVariablesFromGroup(groupID int, includeProjects bool) (Variables, error) {1043 // curl -Ls --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" "https://git.alteryx.com/api/v4/projects/5844/variables" | jq .1044 // Fetch the ProjectID, extract .namespace.id (this is the immediate containing group)1045 // Fetch the GroupID, extract .parent_id until 'null'1046 var variables Variables1047 topVariables, verr := getVariablesFrom(r, groupID, "groups")1048 if verr != nil {1049 logrus.Error("Cannot marshall Pipeline", verr)1050 return variables, verr1051 }1052 variables = append(variables, topVariables...)1053 if includeProjects {1054 topProjects, perr := r.GetGroupProjects(groupID)1055 if perr != nil {1056 logrus.Error("Failed to get top level group Projects", perr)1057 return variables, perr1058 }1059 for _, v := range topProjects {1060 projVariables, verr := getVariablesFrom(r, v.ID, "projects")1061 if verr != nil {1062 logrus.Error("Failed to get variables from topProjects ", verr)1063 return variables, verr1064 }1065 variables = append(variables, projVariables...)1066 }1067 }1068 subGroups, gerr := r.GetDescendantGroups(groupID)1069 if gerr != nil {1070 logrus.Error("Failed to get Top Project SubGroups", gerr)1071 return variables, gerr1072 }1073 for _, v := range subGroups {1074 grpVariables, verr := getVariablesFrom(r, v.ID, "groups")1075 if verr != nil {1076 logrus.Error("Failed to get variables from subGroups ", verr)1077 return variables, verr1078 }1079 variables = append(variables, grpVariables...)1080 if includeProjects {1081 grpProjects, perr := r.GetGroupProjects(v.ID)1082 if perr != nil {1083 logrus.Error("Failed to get Projects for SubGroup ", perr)1084 return variables, perr1085 }1086 for _, p := range grpProjects {1087 projVariables, verr := getVariablesFrom(r, p.ID, "projects")1088 if verr != nil {1089 logrus.Error("Failed to get variables from topProjects ", verr)1090 return variables, verr1091 }1092 variables = append(variables, projVariables...)1093 }1094 }1095 }1096 return variables, nil1097}...

Full Screen

Full Screen

bitwarden.go

Source:bitwarden.go Github

copy

Full Screen

1package bitwarden2import (3 "encoding/json"4 "fmt"5 "github.com/go-resty/resty/v2"6 "github.com/sirupsen/logrus"7)8type BitwardenClient interface {9 GetProperty(property string) string10 SetProperty(property string, value string) string11 GetItems(folder string) (Items, error)12 GetItem(itemID string) (Item, error)13 FindItem(name string) (string, error)14 GetUsername(itemID string) (string, error)15 GetPassword(itemID string) (string, error)16 GetTOTP(itemID string) (string, error)17 NewItem(newlogin Newlogin) (ReturnStatus, error)18 UpdateItem(id string, updatelogin ItemData) (ReturnStatus, error)19 DeleteItem(itemID string) (bool, error)20 GetFolders() (Folders, error)21 GetFolder(folderID string) (Folder, error)22 NewFolder(newfolder Newfolder) (ReturnStatus, error)23 FindFolder(name string) (string, error)24 Sync() (SyncReturn, error)25}26type bitwardenClient struct {27 BaseUrl string28 Port string29 Client *resty.Client30}31// New generate a new gitlab client32func New(baseUrl string, port string) BitwardenClient {33 // TODO: Add TLS Insecure && Pass in CA CRT for authentication34 restClient := resty.New()35 if port == "" {36 port = "7787"37 }38 return &bitwardenClient{39 BaseUrl: baseUrl,40 Port: port,41 Client: restClient,42 }43}44func (r *bitwardenClient) GetProperty(property string) string {45 switch property {46 case "BaseUrl":47 return r.BaseUrl48 case "Port":49 return r.Port50 }51 return ""52}53func (r *bitwardenClient) SetProperty(property string, value string) string {54 switch property {55 case "BaseUrl":56 r.BaseUrl = value57 return r.BaseUrl58 case "Port":59 r.Port = value60 return r.Port61 }62 return ""63}64func (r *bitwardenClient) GetItems(folder string) (Items, error) {65 // TODO: detect if there are no options passed in, ? verus & for page option66 fetchUri := fmt.Sprintf("http://localhost:%s/list/object/items", r.Port)67 // logrus.Warn(fetchUri)68 resp, resperr := r.Client.R().69 Get(fetchUri)70 if resperr != nil {71 logrus.WithError(resperr).Error("Oops")72 return Items{}, resperr73 }74 var items Items75 marshErr := json.Unmarshal(resp.Body(), &items)76 if marshErr != nil {77 logrus.Fatal("Cannot marshall Pipeline", marshErr)78 return Items{}, resperr79 }80 return items, nil81}82func (r *bitwardenClient) GetItem(itemID string) (Item, error) {83 // TODO: detect if there are no options passed in, ? verus & for page option84 fetchUri := fmt.Sprintf("http://localhost:%s/object/item/%s", r.Port, itemID)85 // logrus.Warn(fetchUri)86 resp, resperr := r.Client.R().87 Get(fetchUri)88 if resperr != nil {89 logrus.WithError(resperr).Error("Oops")90 return Item{}, resperr91 }92 var item Item93 marshErr := json.Unmarshal(resp.Body(), &item)94 if marshErr != nil {95 logrus.Fatal("Cannot marshall Pipeline", marshErr)96 return Item{}, resperr97 }98 return item, nil99}100func (r *bitwardenClient) FindItem(name string) (string, error) {101 fetchUri := fmt.Sprintf("http://localhost:%s/list/object/items", r.Port)102 // logrus.Warn(fetchUri)103 resp, resperr := r.Client.R().104 Get(fetchUri)105 if resperr != nil {106 logrus.WithError(resperr).Error("Oops")107 return "", resperr108 }109 var items Items110 marshErr := json.Unmarshal(resp.Body(), &items)111 if marshErr != nil {112 logrus.Fatal("Cannot marshall Pipeline", marshErr)113 return "", resperr114 }115 for _, v := range items.Data.Data {116 if v.Name == name {117 return v.ID, nil118 }119 }120 return "", nil121}122func (r *bitwardenClient) GetUsername(itemID string) (string, error) {123 // TODO: detect if there are no options passed in, ? verus & for page option124 fetchUri := fmt.Sprintf("http://localhost:%s/object/username/%s", r.Port, itemID)125 // logrus.Warn(fetchUri)126 resp, resperr := r.Client.R().127 Get(fetchUri)128 if resperr != nil {129 logrus.WithError(resperr).Error("Oops")130 return "", resperr131 }132 var pw Password133 marshErr := json.Unmarshal(resp.Body(), &pw)134 if marshErr != nil {135 logrus.Fatal("Cannot marshall Pipeline", marshErr)136 return "", resperr137 }138 return pw.Data.Data, nil139}140func (r *bitwardenClient) GetPassword(itemID string) (string, error) {141 // TODO: detect if there are no options passed in, ? verus & for page option142 fetchUri := fmt.Sprintf("http://localhost:%s/object/password/%s", r.Port, itemID)143 // logrus.Warn(fetchUri)144 resp, resperr := r.Client.R().145 Get(fetchUri)146 if resperr != nil {147 logrus.WithError(resperr).Error("Oops")148 return "", resperr149 }150 var pw Password151 marshErr := json.Unmarshal(resp.Body(), &pw)152 if marshErr != nil {153 logrus.Fatal("Cannot marshall Pipeline", marshErr)154 return "", resperr155 }156 return pw.Data.Data, nil157}158func (r *bitwardenClient) GetTOTP(itemID string) (string, error) {159 // TODO: detect if there are no options passed in, ? verus & for page option160 fetchUri := fmt.Sprintf("http://localhost:%s/object/totp/%s", r.Port, itemID)161 // logrus.Warn(fetchUri)162 resp, resperr := r.Client.R().163 Get(fetchUri)164 if resperr != nil {165 logrus.WithError(resperr).Error("Oops")166 return "", resperr167 }168 var totp Totp169 marshErr := json.Unmarshal(resp.Body(), &totp)170 if marshErr != nil {171 logrus.Fatal("Cannot marshall Pipeline", marshErr)172 return "", resperr173 }174 return totp.Data.Data, nil175}176func (r *bitwardenClient) NewItem(newlogin Newlogin) (ReturnStatus, error) {177 newLoginJSON, merr := json.Marshal(newlogin)178 if merr != nil {179 logrus.WithError(merr).Error("Oops")180 return ReturnStatus{}, merr181 }182 // fmt.Println(string(newLoginJSON[:]))183 fetchUri := fmt.Sprintf("http://localhost:%s/object/item", r.Port)184 // logrus.Warn(fetchUri)185 resp, resperr := r.Client.R().186 SetHeader("Content-Type", "application/json").187 SetBody(string(newLoginJSON[:])).188 Post(fetchUri)189 if resperr != nil {190 logrus.WithError(resperr).Error("Oops")191 return ReturnStatus{}, resperr192 }193 var status ReturnStatus194 marshErr := json.Unmarshal(resp.Body(), &status)195 if marshErr != nil {196 logrus.Fatal("Cannot marshall Pipeline", marshErr)197 return ReturnStatus{}, resperr198 }199 return status, nil200}201func (r *bitwardenClient) UpdateItem(id string, updatelogin ItemData) (ReturnStatus, error) {202 newLoginJSON, merr := json.Marshal(updatelogin)203 if merr != nil {204 logrus.WithError(merr).Error("Oops")205 return ReturnStatus{}, merr206 }207 fetchUri := fmt.Sprintf("http://localhost:%s/object/item/%s", r.Port, id)208 // logrus.Warn(fetchUri)209 resp, resperr := r.Client.R().210 SetHeader("Content-Type", "application/json").211 SetBody(string(newLoginJSON[:])).212 Put(fetchUri)213 if resperr != nil {214 logrus.WithError(resperr).Error("Oops")215 return ReturnStatus{}, resperr216 }217 var status ReturnStatus218 marshErr := json.Unmarshal(resp.Body(), &status)219 if marshErr != nil {220 logrus.Fatal("Cannot marshall Pipeline", marshErr)221 return ReturnStatus{}, resperr222 }223 return status, nil224}225func (r *bitwardenClient) DeleteItem(itemID string) (bool, error) {226 fetchUri := fmt.Sprintf("http://localhost:%s/object/item/%s", r.Port, itemID)227 resp, resperr := r.Client.R().228 Delete(fetchUri)229 if resperr != nil {230 logrus.WithError(resperr).Error("Oops")231 return false, resperr232 }233 var success Success234 marshErr := json.Unmarshal(resp.Body(), &success)235 if marshErr != nil {236 logrus.Fatal("Cannot marshall Pipeline", marshErr)237 return false, resperr238 }239 return success.Success, nil240}241func (r *bitwardenClient) GetFolders() (Folders, error) {242 // TODO: detect if there are no options passed in, ? verus & for page option243 fetchUri := fmt.Sprintf("http://localhost:%s/list/object/folders", r.Port)244 // logrus.Warn(fetchUri)245 resp, resperr := r.Client.R().246 Get(fetchUri)247 if resperr != nil {248 logrus.WithError(resperr).Error("Oops")249 return Folders{}, resperr250 }251 var folders Folders252 marshErr := json.Unmarshal(resp.Body(), &folders)253 if marshErr != nil {254 logrus.Fatal("Cannot marshall Pipeline", marshErr)255 return Folders{}, resperr256 }257 return folders, nil258}259func (r *bitwardenClient) GetFolder(folderID string) (Folder, error) {260 // TODO: detect if there are no options passed in, ? verus & for page option261 fetchUri := fmt.Sprintf("http://localhost:%s/object/folder/%s", r.Port, folderID)262 // logrus.Warn(fetchUri)263 resp, resperr := r.Client.R().264 Get(fetchUri)265 if resperr != nil {266 logrus.WithError(resperr).Error("Oops")267 return Folder{}, resperr268 }269 var folder Folder270 marshErr := json.Unmarshal(resp.Body(), &folder)271 if marshErr != nil {272 logrus.Fatal("Cannot marshall Pipeline", marshErr)273 return Folder{}, resperr274 }275 return folder, nil276}277func (r *bitwardenClient) NewFolder(newfolder Newfolder) (ReturnStatus, error) {278 newFolderJSON, merr := json.Marshal(newfolder)279 if merr != nil {280 logrus.WithError(merr).Error("Oops")281 return ReturnStatus{}, merr282 }283 // fmt.Println(string(newFolderJSON[:]))284 fetchUri := fmt.Sprintf("http://localhost:%s/object/folder", r.Port)285 // logrus.Warn(fetchUri)286 resp, resperr := r.Client.R().287 SetHeader("Content-Type", "application/json").288 SetBody(string(newFolderJSON[:])).289 Post(fetchUri)290 if resperr != nil {291 logrus.WithError(resperr).Error("Oops")292 return ReturnStatus{}, resperr293 }294 var status ReturnStatus295 marshErr := json.Unmarshal(resp.Body(), &status)296 if marshErr != nil {297 logrus.Fatal("Cannot marshall Pipeline", marshErr)298 return ReturnStatus{}, resperr299 }300 return status, nil301}302func (r *bitwardenClient) FindFolder(name string) (string, error) {303 fetchUri := fmt.Sprintf("http://localhost:%s/list/object/folders", r.Port)304 // logrus.Warn(fetchUri)305 resp, resperr := r.Client.R().306 Get(fetchUri)307 if resperr != nil {308 logrus.WithError(resperr).Error("Oops")309 return "", resperr310 }311 var folders Folders312 marshErr := json.Unmarshal(resp.Body(), &folders)313 if marshErr != nil {314 logrus.Fatal("Cannot marshall Pipeline", marshErr)315 return "", resperr316 }317 for _, v := range folders.Data.Data {318 if v.Name == name {319 return v.ID, nil320 }321 }322 return "", nil323}324func (r *bitwardenClient) Sync() (SyncReturn, error) {325 fetchUri := fmt.Sprintf("http://localhost:%s/sync", r.Port)326 resp, resperr := r.Client.R().327 SetHeader("Content-Type", "application/json").328 Post(fetchUri)329 if resperr != nil {330 logrus.WithError(resperr).Error("Oops")331 return SyncReturn{}, resperr332 }333 var status SyncReturn334 marshErr := json.Unmarshal(resp.Body(), &status)335 if marshErr != nil {336 logrus.Fatal("Cannot marshall Pipeline", marshErr)337 return SyncReturn{}, resperr338 }339 return status, nil340}...

Full Screen

Full Screen

jira.go

Source:jira.go Github

copy

Full Screen

1package jira2import (3 "encoding/json"4 "fmt"5 "github.com/go-resty/resty/v2"6 "github.com/sirupsen/logrus"7)8type Jira struct {9 BaseUrl string10 ApiPath string11 AgilePath string12 User string13 Token string14 Client *resty.Client15}16type Boards struct {17 MaxResults int `json:"maxResults"`18 StartAt int `json:"startAt"`19 Total int `json:"total"`20 IsLast bool `json:"isLast"`21 Values []BoardValues `json:"values"`22}23type Location struct {24 ProjectID int `json:"projectId"`25 DisplayName string `json:"displayName"`26 ProjectName string `json:"projectName"`27 ProjectKey string `json:"projectKey"`28 ProjectTypeKey string `json:"projectTypeKey"`29 AvatarURI string `json:"avatarURI"`30 Name string `json:"name"`31}32type BoardValues struct {33 ID int `json:"id"`34 Self string `json:"self"`35 Name string `json:"name"`36 Type string `json:"type"`37 Location Location `json:"location"`38}39type SprintIssues struct {40 Expand string `json:"expand"`41 StartAt int `json:"startAt"`42 MaxResults int `json:"maxResults"`43 IsLast bool `json:"isLast"`44 Total int `json:"total"`45 Issues []interface{} `json:"issues"`46}47// New generate a new jira client48func New(baseUrl, apiPath, agilePath, user, token string) *Jira {49 restClient := resty.New()50 if apiPath == "" {51 apiPath = "/rest/api/3"52 }53 if agilePath == "" {54 agilePath = "/rest/agile/1.0"55 }56 restClient.SetBasicAuth(user, token)57 return &Jira{58 BaseUrl: baseUrl,59 ApiPath: apiPath,60 AgilePath: agilePath,61 Token: token,62 Client: restClient,63 }64}65func (r *Jira) GetIssue(issue string) (string, error) {66 fetchUri := fmt.Sprintf("%s%s/issue/%s", r.BaseUrl, r.ApiPath, issue)67 // logrus.Warn(fetchUri)68 resp, resperr := r.Client.R().69 SetHeader("Content-Type", "application/json").70 Get(fetchUri)71 if resperr != nil {72 logrus.WithError(resperr).Error("Oops")73 return "", resperr74 }75 return string(resp.Body()[:]), nil76}77func (r *Jira) AddComment(issue string, comment string) (string, error) {78 fetchUri := fmt.Sprintf("%s%s/issue/%s/comment", r.BaseUrl, r.ApiPath, issue)79 // logrus.Warn(fetchUri)80 commentTemplate := `{81 "body": {82 "type": "doc",83 "version": 1,84 "content": [85 {86 "type": "paragraph",87 "content": [88 {89 "text": "%s",90 "type": "text"91 }92 ]93 }94 ]95 }96 }`97 body := fmt.Sprintf(commentTemplate, comment)98 resp, resperr := r.Client.R().99 SetHeader("Content-Type", "application/json").100 SetBody(body).101 Post(fetchUri)102 if resperr != nil {103 logrus.WithError(resperr).Error("Oops")104 return "", resperr105 }106 return string(resp.Body()[:]), nil107}108func (r *Jira) AssignIssue(issue string, account string) error {109 var body string110 fetchUri := fmt.Sprintf("%s%s/issue/%s/assignee", r.BaseUrl, r.ApiPath, issue)111 // logrus.Warn(fetchUri)112 if account == "null" {113 body = fmt.Sprintf("{ \"accountId\": %s }", account)114 } else {115 body = fmt.Sprintf("{ \"accountId\": \"%s\" }", account)116 }117 resp, resperr := r.Client.R().118 SetHeader("Content-Type", "application/json").119 SetBody(body).120 Put(fetchUri)121 if resperr != nil {122 logrus.WithError(resperr).Error("Oops", resp.Body()[:])123 return resperr124 }125 return nil126}127func (r *Jira) GetAccount(search string) (string, error) {128 fetchUri := fmt.Sprintf("%s%s/user/search?query=%s", r.BaseUrl, r.ApiPath, search)129 // logrus.Warn(fetchUri)130 resp, resperr := r.Client.R().131 SetHeader("Content-Type", "application/json").132 Get(fetchUri)133 if resperr != nil {134 logrus.WithError(resperr).Error("Oops", resp.Body()[:])135 return "", resperr136 }137 return string(resp.Body()[:]), nil138}139func (r *Jira) GetTransitions(issue string) (string, error) {140 fetchUri := fmt.Sprintf("%s%s/issue/%s/transitions", r.BaseUrl, r.ApiPath, issue)141 // logrus.Warn(fetchUri)142 resp, resperr := r.Client.R().143 SetHeader("Content-Type", "application/json").144 Get(fetchUri)145 if resperr != nil {146 logrus.WithError(resperr).Error("Oops")147 return "", resperr148 }149 return string(resp.Body()[:]), nil150}151func (r *Jira) TransitionIssue(issue string, transitionId string) (string, error) {152 fetchUri := fmt.Sprintf("%s%s/issue/%s/transitions", r.BaseUrl, r.ApiPath, issue)153 // logrus.Warn(fetchUri)154 body := fmt.Sprintf("{ \"transition\": { \"id\": %s } }", transitionId)155 resp, resperr := r.Client.R().156 SetHeader("Content-Type", "application/json").157 SetBody(body).158 Post(fetchUri)159 if resperr != nil {160 logrus.WithError(resperr).Error("Oops")161 return "", resperr162 }163 return string(resp.Body()[:]), nil164}165func (r *Jira) GetBoards() (string, error) {166 startAt := 0167 var returnValues []BoardValues168 for {169 fetchUri := fmt.Sprintf("%s%s/board?startAt=%d", r.BaseUrl, r.AgilePath, startAt)170 resp, resperr := r.Client.R().171 SetHeader("Content-Type", "application/json").172 Get(fetchUri)173 if resperr != nil {174 logrus.WithError(resperr).Error("Oops")175 return "", resperr176 }177 var boards Boards178 berr := json.Unmarshal([]byte(resp.Body()), &boards)179 if berr != nil {180 fmt.Printf("Error parsing JSON file: %s\n", berr)181 }182 returnValues = append(returnValues, boards.Values...)183 startAt += 50184 if boards.IsLast {185 break186 }187 }188 json, jerr := json.Marshal(returnValues)189 if jerr != nil {190 fmt.Printf("Error parsing JSON file: %s\n", jerr)191 }192 return string(json[:]), nil193}194func (r *Jira) GetActiveSprint(board string) (string, error) {195 // https://alteryx.atlassian.net/rest/agile/1.0/board/388/sprint?state=active196 fetchUri := fmt.Sprintf("%s%s/board/%s/sprint?state=active", r.BaseUrl, r.AgilePath, board)197 resp, resperr := r.Client.R().198 SetHeader("Content-Type", "application/json").199 Get(fetchUri)200 if resperr != nil {201 logrus.WithError(resperr).Error("Oops")202 return "", resperr203 }204 return string(resp.Body()[:]), nil205}206func (r *Jira) GetSprintIssues(board string, sprint int) (string, error) {207 startAt := 0208 var returnValues []interface{}209 for {210 // https://alteryx.atlassian.net/rest/agile/1.0/board/388/sprint/723/issue211 fetchUri := fmt.Sprintf("%s%s/board/%s/sprint/%d/issue?startAt=%d", r.BaseUrl, r.AgilePath, board, sprint, startAt)212 resp, resperr := r.Client.R().213 SetHeader("Content-Type", "application/json").214 Get(fetchUri)215 if resperr != nil {216 logrus.WithError(resperr).Error("Oops")217 return "", resperr218 }219 var sprintIssues SprintIssues220 berr := json.Unmarshal([]byte(resp.Body()), &sprintIssues)221 if berr != nil {222 fmt.Printf("Error parsing JSON file: %s\n", berr)223 }224 returnValues = append(returnValues, sprintIssues.Issues...)225 startAt += 50226 if sprintIssues.Total < sprintIssues.MaxResults {227 break228 }229 if sprintIssues.IsLast {230 break231 }232 }233 jsonData, jerr := json.Marshal(returnValues)234 if jerr != nil {235 fmt.Printf("Error parsing JSON file: %s\n", jerr)236 }237 issueList := fmt.Sprintf("{ \"issues\": %s }", jsonData)238 return issueList, nil239}...

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3}4import (5func main() {6}7import (8func main() {9}10import (11func main() {12}13import (14func main() {15}16import (17func main() {18}19import (20func main() {21}22import (23func main() {24}25import (26func main() {27}28import (29func main() {30}31import (32func main() {

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 defer r.Close()7 io.Copy(os.Stdout, r)8}9import (10func main() {11 if err != nil {12 fmt.Println(err)13 }14 defer r.Close()15 io.Copy(os.Stdout, r)16}17import (18func main() {19 if err != nil {20 fmt.Println(err)21 }22 defer r.Close()23 io.Copy(os.Stdout, r)24}25import (26func main() {27 if err != nil {28 fmt.Println(err)29 }30 defer r.Close()31 io.Copy(os.Stdout, r)32}33import (34func main() {35 if err != nil {36 fmt.Println(err)37 }38 defer r.Close()39 io.Copy(os.Stdout, r)40}41import (42func main() {43 if err != nil {44 fmt.Println(err)45 }46 defer r.Close()47 io.Copy(os.Stdout, r)48}49import (50func main() {51 if err != nil {

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3}4import (5func main() {6}7import (8func FetchURI(uri string) string {9 resp, err := http.Get(uri)10 if err != nil {11 fmt.Println("Error: ", err)12 }13 defer resp.Body.Close()14 buf := make([]byte, 1024)15 for {16 n, err := resp.Body.Read(buf)17 if err != nil {18 }19 result += string(buf[:n])20 }21}22import (23func TestFetchURI(t *testing.T) {24 if FetchURI(uri) == "" {25 t.Error("Expected a non-empty response")26 }27}28--- FAIL: TestFetchURI (0.00s)29--- FAIL: TestFetchURI (0.00s)30--- FAIL: TestFetchURI (0.00s)31--- FAIL: TestFetchURI (0.00s)

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Fetching URI")4}5import (6func main() {7 fmt.Println("Fetching URI")8}9import (10func main() {11 fmt.Println("Fetching URI")12}13import (14func main() {15 fmt.Println("Fetching URI")16}17import (18func main() {19 fmt.Println("Fetching URI")20}21import (22func main() {23 fmt.Println("Fetching URI")24}25import (26func main() {27 fmt.Println("Fetching URI")28}29import (30func main() {31 fmt.Println("Fetching URI")32}33import (34func main() {35 fmt.Println("Fetching URI")36}37import (38func main() {39 fmt.Println("Fetching URI")

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 content.FetchURI(uri)4 fmt.Println("Done")5}6The Go package can be used in any Go program by importing it. The package can be stored in any directory. The

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 content, err := content.FetchURI(uri)4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(html.EscapeString(content))8}9import (10type Content struct {11}12func (c *Content) FetchURI(uri string) (string, error) {13 if uri == "" {14 return "", fmt.Errorf("URI is empty")15 }16 resp, err := http.Get(uri)17 if err != nil {18 }19 defer resp.Body.Close()20 body, err := ioutil.ReadAll(resp.Body)21 if err != nil {22 }23 return string(body), nil24}25import (26func TestFetchURI(t *testing.T) {27 c := Content{}28 if err != nil {29 t.Error(err)30 }31 if content == "" {32 t.Error("Content is empty")33 }34}

Full Screen

Full Screen

FetchURI

Using AI Code Generation

copy

Full Screen

1var content = new Content();2var contentResponse = content.FetchURI(url);3if (contentResponse.HttpStatusCode == 200)4{5 var response = contentResponse.Content;6 var contentType = contentResponse.ContentType;7 var contentLength = contentResponse.ContentLength;8 var lastModified = contentResponse.LastModified;9 var eTag = contentResponse.ETag;10 var charSet = contentResponse.CharSet;11}12var content = new Content();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful