Git Product home page Git Product logo

go-bitbucket's People

Contributors

adamconnelly avatar analogj avatar cgroschupp avatar chmouel avatar craftamap avatar datadavd avatar dependabot[bot] avatar ebh avatar egorovv avatar giladhseek avatar ilius avatar josemiguelmelo avatar ktrysmt avatar makkrnic avatar mfb2 avatar nhorman avatar oogali avatar pjarmalavicius avatar pstuifzand avatar sffortytwo avatar sl4mmy avatar soult avatar soupdiver avatar srgrn avatar toneill818 avatar xx-parks-xx avatar yahavi avatar yongseonlee avatar zachsmith1 avatar zahiar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-bitbucket's Issues

Posting PR comments

I found the code for reading comments, however, I couldn't find functionality for posting comments.
Is it planned?

Thanks!

Panic for Create BranchRestrictions.

Don't have time to log a PR at the moment, but figured I'd log it just in case I can't get to it:

Running a create on branch restrictions, where the user or group is empty causes the server to respond with a bad request "users malformed". It's because it's expecting a list, not a key-value hash. However, when I add an empty user it panics. I was able to get around this by applying the diff below, and leaving users and groups blank (which defaults to "everyone", which is what I wanted). I didn't have time to check if it still fired off a panic with this change though.

diff --git a/branchrestrictions.go b/branchrestrictions.go
index 6c696a1..31e6865 100644
--- a/branchrestrictions.go
+++ b/branchrestrictions.go
@@ -40,8 +40,8 @@ func (b *BranchRestrictions) Delete(bo *BranchRestrictionsOptions) interface{} {
 func (b *BranchRestrictions) buildBranchRestrictionsBody(bo *BranchRestrictionsOptions) string {

        body := map[string]interface{}{}
-       body["groups"] = map[string]string{}
-       body["users"] = map[string]string{}
+       body["groups"] = []map[string]string{}
+       body["users"] = []map[string]string{}

        if bo.Pattern != "" {
                body["pattern"] = bo.Pattern

BranchRestrictions Create and Get should not return BranchRestrictions

hey @ktrysmt I took a further look at #144 and it seems like the BranchRestrictions Create and Get methods need a little work as well. I got rid of the unneeded interface type assertion for the Create tests (since it no longer returns an interface testing a type is redundant given compilation checks types for us) but still had issues with nil pointer deference in the tests which is probably due to the fact that the decode function is returning the same BranchRestrictions type but not specifying the *client.

From my review it appears that a BranchRestrictions Response type needs to be created and the decode function should return that instead.

Is that OK if I work on fixing/adding this stuff?????? The branch/PR for this Issue will close both issues related to branch restrictions.

Thanks in advance.

Thread Safety of `apiBaseURL`

Thanks for your work on this library. I'm currently examining it and saw that apiBaseURL is a global variable. When I get this right, it's not possible to use this library with different Base URLs concurrently?

How to refer API documents

bitbucket server (1.0) api reference

bitbucket cloud (2.0) rest api reference

Create a repository

I'm trying to create a repository witrh this lib but I got errors, theres an example?

c.apiBaseURL.GetApiHostnameURL undefined

Hi

Last commit breaks the build
5bccfc3

$ make test                                   
go test -v ./tests
# github.com/ktrysmt/go-bitbucket
./client.go:164:41: c.apiBaseURL.GetApiHostnameURL undefined (type *url.URL has no field or method GetApiHostnameURL)
FAIL	github.com/ktrysmt/go-bitbucket/tests [build failed]
FAIL
Makefile:18 : la recette pour la cible « test » a échouée
make: *** [test] Erreur 2

ListTags in repository.go throws SIGSEGV panic

Hello!

First of all, thank you very much for your work!

I would like to note that I am a golang noob, and hopefully it is just me not understanding something :-)

I am trying to list all the repository tags for a given repo. Here's the code snippet I wrote for that:

func BitBucketImportRepositories() {
    c := bitbucket.NewBasicAuth(os.Getenv("BITBUCKET_USERNAME"), os.Getenv("BITBUCKET_PASSWORD"))

    opt := &bitbucket.RepositoriesOptions{
        Owner: config.Module.Import.Bitbucket.Organization,
    }

    repos, err := c.Repositories.ListForAccount(opt)

    if err != nil {
        log.Fatalf("Failed to fetch repositories from BitBucket! %+v", err)
    }

    for i := 0; i < len(repos.Items); i++ {
        if re.MatcherString(repos.Items[i].Slug, 0).Matches() {

            tagOpt := &bitbucket.RepositoryTagOptions{
                Owner: "myorgname",
                RepoSlug: repos.Items[i].Slug,
                Query: "",
                Sort: "",
                PageNum: 1,
                Pagelen: 100000,
                MaxDepth: 1,
            }

            log.Println(repos.Items[i].ListTags(tagOpt))
            break
        }
    }
}

Execution fails with the following error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x50 pc=0x43e2081]

goroutine 1 [running]:
github.com/ktrysmt/go-bitbucket.(*Client).requestUrl(0x0, 0x46e56c0, 0x20, 0xc0005075d8, 0x3, 0x3, 0x404174a, 0xc000041000)
    /Users/username/go/pkg/mod/github.com/ktrysmt/[email protected]/client.go:347 +0x81
github.com/ktrysmt/go-bitbucket.(*Repository).ListTags(0xc0006e3560, 0xc000507840, 0xc0000244b0, 0x24, 0x0)
    /Users/username/go/pkg/mod/github.com/ktrysmt/[email protected]/repository.go:266 +0x225
main.BitBucketImportRepositories()
    /Users/username/path/cmd_import_bb.go:54 +0x397
main.main.func4(0xc00012e580)
    /Users/username/path/main.go:76 +0x25
github.com/urfave/cli.HandleAction(0x45f18c0, 0x46fd008, 0xc00012e580, 0xc00012e580, 0x0)
    /Users/username/go/pkg/mod/github.com/urfave/[email protected]/app.go:528 +0x58
github.com/urfave/cli.Command.Run(0x46d5860, 0x8, 0x0, 0x0, 0xc000244ce0, 0x1, 0x1, 0x46eee4a, 0x31, 0x0, ...)
    /Users/username/go/pkg/mod/github.com/urfave/[email protected]/command.go:174 +0x58e
github.com/urfave/cli.(*App).Run(0xc0001561c0, 0xc00000e0a0, 0x2, 0x2, 0x0, 0x0)
    /Users/username/go/pkg/mod/github.com/urfave/[email protected]/app.go:279 +0x7e8
main.main()
    /Users/username/path/main.go:82 +0x395
exit status 2

I am running go version go1.15 darwin/amd64

Is there anything I am doing wrong here? I'd appreciate any hints and directions.

Thank you!

Invalid type assertion issues for Branch Restrict Tests

When trying to test the repo received this error (two times) failing the test build
invalid type assertion: res.(map[string]<inter>) (non-interface type *bitbucket.BranchRestrictions on left

It appears to be caused by changing the return type of BranchRestrictions.Create() method; completed during this PR merge. It was interface{} before whereas now its *BranchRestrictions so the type assertion during the BranchRestrictionsTests causes the test build to fail.

Specifically, now the issue is caused by this line and this line

I can try and fix this after I complete my DiffStat PR if thats fine. Is that cool if I take this bug-fix over?

Also, can I ignore this type assertion issue when testing and submitting my DiffStat PR ?

Thanks again!!!!

Project management

Seems like there is nothing for bitbucket project endpoints yet.

A complete CRUD would be nice :)

Support BitBucket Server

I can see that the API_BASE_URI is a constant. Would you accept a PR to make that a parameter, so that BitBucket Server can become supported?

buildPullRequestBody panics when attempting to build reviewers map

Hello,
Ran into a bug when attempting to update a pull request's reviewers.

Description

The buildPullRequestBody function has a panic while attempting to build a map for the reviewers for the body of the payload. This error occurs due to the way type assertion is used on line 96 of pull requests.go.

Currently the code for building the reviewers map is as follows:

	if n := len(po.Reviewers); n > 0 {
		for i, user := range po.Reviewers {
			body["reviewers"].([]map[string]string)[i] = map[string]string{"username": user}
		}
	}

Resolution

I managed to resolve the panic by not using type assertion, here is my fix:

	var reviewers []map[string]string
	if n := len(po.Reviewers); n > 0 {
		for _, user := range po.Reviewers {
			reviewer := map[string]string{"username": user}
			reviewers = append(reviewers, reviewer)
		}
		body["reviewers"] = reviewers
	}

Please let me know your thoughts on this proposed change or if you'd like me to create a PR for this.

Cheers!

400 Bad Request when setting branch permissions using groups

When setting branch permissions restrict_merges am passing map[string]string{"admin": "administrator", "dev": "developer"} as the BranchRestrictionsOptions.Groups value . It throws an error 400 Bad Request and sets the permission group to Everybody

Support pagination

The bitbucket API provides paginated output but this repo doesn't handle it. Consequently, result sets are limited to the first page only and for large responses the result set is incomplete.

In particular, the parser will need to handle the following values in the bitbucket's JSON response:

  • next
  • page
  • pagelen
  • previous

Support BitBucket Server api v1.0

I discovered that BitBucket Server does not support the v2.0 API that bitbucket.org does.

One could add this via 1-suffixed functions, for example on PullRequests:

func (p *PullRequests) Gets1(po *PullRequestsOptions) interface{} {
	url := GetApiBaseUrl() + "/projects/" + po.Owner + "/repos/" + po.Repo_slug + "/pull-requests/"
	return p.c.execute("GET", url, "")
}

Or one could make a new struct, like PullRequests1 and inject that into the client, so client.Repositories.PullRequests1.Blah(...) would be the calling code.

Or I think it would be possible to parameterise which API version being used (probably when creating the client), and then use that to key into a map of url-generation funcs.

Would you be open to PRs that add v1 APIs? If so, by which means of the above, or another?

Alternatively, I'd love to find out I'm wrong about BB Server only exposing v1.0...

Create Branch & Push

Hello,

Is there a way to create a new branch using this library¿? and after make some changes, make a push ¿?

I already check and it is possible to commit but can't find how to do what I have been mentioned before.

Regards

Make test codes enough

  • bitbucket
  • branchrestrictions
  • repository
  • user
  • client
  • commits
  • diff
  • error
  • pullrequests
  • repositories
  • repository
  • teams
  • user
  • users
  • webhooks

Question about repositories.ListForAccount()

Hello @ktrysmt ,

A question about repositories.ListForAccount() method.
Is it normal that this method is returning an interface{} ?
Note : I would expect to have a []string with repo names.

Maybe it is because this method is not finalized ? Any other reasons ?

In order to get the list of repo names, I did the following ugly code (just for testing). But maybe there is another smart way or magic method to get this ?

	res2, err2 := c.Repositories.ListForTeam(opt2)
	if err2 != nil {
		panic(err2)
	}

	repos := show_repo(res2)
	fmt.Printf("%#v\n", repos) // Just to debug content
func show_repo(data interface{}) []string {
	var output []string // New slice

	repos := data.(map[string]interface{})["values"].([]interface{})

	// Loop on slice
	for i := 0; i < len(repos); i++ {
		output = append(output, repos[i].(map[string]interface{})["name"].(string))
	}
	return output
}

LICENSE

I did a fork of this project and I was wondering which license are you using, I used swagger to generated all data structures from Bitbucket swagger definition and the generated code is under the Apache License 2.0 so hopefully your license is compatible with it.

I'm thinking on licensing my changes to LGPL v3.

swagger generate failed.

- paths./repositories/{username}/{repo_slug}/properties/{app_key}/{property_name}.get.responses in body is required
- paths./repositories/{username}/{repo_slug}/properties/{app_key}/{property_name}.put.responses in body is required
- paths./repositories/{username}/{repo_slug}/properties/{app_key}/{property_name}.delete.responses in body is required

Add auth via apikey

Hello,

Thanks for go-bitbucket library, this is really helpful for us.
As a feature request, could you add authentication via apikey ?

Error when running tests

Steps to reproduce

  1. Cloned repo to my local machine
  2. Set the values for and run:
export BITBUCKET_TEST_USERNAME=<your_username>
export BITBUCKET_TEST_PASSWORD=<your_password>
export BITBUCKET_TEST_OWNER=<your_repo_owner>
export BITBUCKET_TEST_REPOSLUG=<your_repo_name>
  1. Run make test

Expected outcome

  • All tests passed

Actual outcome

go test -v ./tests
=== RUN   TestCreateBranchRestrictionsKindPush
--- FAIL: TestCreateBranchRestrictionsKindPush (1.19s)
panic: interface conversion: interface {} is nil, not map[string]interface {} [recovered]
        panic: interface conversion: interface {} is nil, not map[string]interface {}

goroutine 19 [running]:
testing.tRunner.func1.1(0x1311e40, 0xc00009dad0)
        /usr/local/Cellar/go/1.15.5/libexec/src/testing/testing.go:1072 +0x30d
testing.tRunner.func1(0xc000082900)
        /usr/local/Cellar/go/1.15.5/libexec/src/testing/testing.go:1075 +0x41a
panic(0x1311e40, 0xc00009dad0)
        /usr/local/Cellar/go/1.15.5/libexec/src/runtime/panic.go:969 +0x1b9
github.com/ktrysmt/go-bitbucket/tests.TestCreateBranchRestrictionsKindPush(0xc000082900)
        /Users/alexdess/ebh-services/go-bitbucket/tests/branchrestrictions_test.go:48 +0x325
testing.tRunner(0xc000082900, 0x137e428)
        /usr/local/Cellar/go/1.15.5/libexec/src/testing/testing.go:1123 +0xef
created by testing.(*T).Run
        /usr/local/Cellar/go/1.15.5/libexec/src/testing/testing.go:1168 +0x2b3
FAIL    github.com/ktrysmt/go-bitbucket/tests   1.517s
FAIL
make: *** [test] Error 1

Further investigation

I run the tests individually:

  • go test -v ./tests/branchrestrictions_test.go - FAIL
  • go test -v ./tests/client_test.go - PASS
  • go test -v ./tests/diff_test.go - FAIL
  • go test -v ./tests/list_test.go - PASS
  • go test -v ./tests/repository_test.go - PASS
  • go test -v ./tests/user_test.go - FAIL
  • go test -v ./tests/workspace_test.go - FAIL

Suggested Improvement

Use Github Actions to run tests automatically

ListTags function in repository.go is throwing error

Looks to be an identical bug to #92

interface conversion: interface {} is *http.http2gzipReader, not []uint8
/usr/local/go/src/runtime/iface.go:260 (0x40bbc1)
        panicdottypeE: panic(&TypeAssertionError{iface, have, want, ""})
/home/vagrant/go/pkg/mod/github.com/ktrysmt/[email protected]/repository.go:581 (0xd42d9f)
        decodeRepositoryTags: err := json.Unmarshal(tagResponse.([]byte), &tagResponseMap)
/home/vagrant/go/pkg/mod/github.com/ktrysmt/[email protected]/repository.go:272 (0xd3f217)
        (*Repository).ListTags: return decodeRepositoryTags(response)

You might want to revert PR (#58)

#58 was rebased against my fork's master branch so it picked up a ton of potentially breaking changes rather than just having @mjpitz changes:
Screen Shot 2019-05-31 at 18 13 01

I suggest your revert (#58) from your repository and ask @mjpitz (if she still wants) to cherry pick her commits from (#58) to a new PR that's based from 1f1c5e7.

json.Unmarshal() throws error while GetDiff() between 2 commits of 2 branches

While I call GetDiff() to get diff of 2 branches, I fed it with a &DiffOptions{Owner:"myOwner", RepoSlug:"myRepo", Spec: "364bb0..7cfdc3"}
, 364bb0 is the last commitId of branch1 and 7cfdc3 is the last commitId of branch2. [Refer to the usage of {spec} in atlassian doc [https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/diff/%7Bspec%7D]]

Error occurred while parse response body into interface{} in client.go
var result interface{} err = json.Unmarshal(resBodyBytes, &result)
err: invalid character 'd' looking for beginning of value

Not sure if here needs an enhancement, because the return is a []uint8 type of a plain string not with a JSON struct like "{a:x, y:b}".

Error when calling Repository.ListFiles

Hello,

I'm trying to list files in my BitBucket repository but I get an error.

My module setup is:

go 1.16

require github.com/ktrysmt/go-bitbucket v0.9.9 // indirect

The test code is as follows:

(just change the "my" variables for your user, pass, owner, repo, etc.)

package lib

import (
	"fmt"
	"testing"
	"github.com/ktrysmt/go-bitbucket"
)

func Test(t *testing.T) {
	c := bitbucket.NewBasicAuth("myuser", "mypass")

	fmt.Println("List repos...")
	optr := &bitbucket.RepositoriesOptions{
		Owner: "myowner",
		Role:  "",
	}

	repos, err1 := c.Repositories.ListForAccount(optr)
	if err1 != nil {
		fmt.Println("Error listing repos:", err1)
		panic(err1)
	}
	fmt.Println("List number of repos:", repos.Size)

	for _, repo := range repos.Items {
		fmt.Println("List repo with name:", repo.Name)
	}

	repong6 := repos.Items[4] // a public repo to test

	fmt.Println("List files in repo:", repong6.Name, "...")
	optrf := &bitbucket.RepositoryFilesOptions{
		Owner:    "myowner",
		RepoSlug: "myslug",
		Ref:      "myref",
		Path:     "mypath",
	}

	files, err2 := repong6.ListFiles(optrf)
	if err2 != nil {
		fmt.Println("Error listing files:", err2)
		panic(err2)
	}
	fmt.Println("List number of files:", len(files))

	for _, file := range files {
		fmt.Println("List file with name:", file.Path)
	}
}

The error happens in the line:

files, err2 := repong6.ListFiles(optrf)

--- FAIL: Test (0.74s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
        panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x58 pc=0x60ccca]

goroutine 6 [running]:
testing.tRunner.func1.2(0x648a00, 0x88cb70)
        C:/Program Files/Go/src/testing/testing.go:1144 +0x345
testing.tRunner.func1(0xc00002d080)
        C:/Program Files/Go/src/testing/testing.go:1147 +0x4b6
panic(0x648a00, 0x88cb70)
        C:/Program Files/Go/src/runtime/panic.go:965 +0x1c7
github.com/ktrysmt/go-bitbucket.(*Client).requestUrl(0x0, 0xc0002bc420, 0x5f, 0x0, 0x0, 0x0, 0x5f, 0xc00014a180)
        C:/Users/dani/go/pkg/mod/github.com/ktrysmt/[email protected]/client.go:376 +0x8a
github.com/ktrysmt/go-bitbucket.(*Repository).ListFiles(0xc00004fd00, 0xc00004fc60, 0xc00004fc30, 0x3, 0x3, 0x29, 0x0)
        C:/Users/dani/go/pkg/mod/github.com/ktrysmt/[email protected]/repository.go:220 +0x17f
github.com/twopelu/hulk/lib.Test(0xc00002d080)
        D:/DANI/go/hulk/lib/lib_test.go:40 +0x4e6
testing.tRunner(0xc00002d080, 0x6b5f50)
        C:/Program Files/Go/src/testing/testing.go:1194 +0xef
created by testing.(*T).Run
        C:/Program Files/Go/src/testing/testing.go:1239 +0x2b3
exit status 2
FAIL    github.com/twopelu/hulk/lib     0.860s

I have checked that the options and the url are ok, and also that it works when called from the browser:

https://github.com/ktrysmt/go-bitbucket/blob/v0.9.9/repository.go#L220

https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/src

Example URL: https://api.bitbucket.org/2.0/repositories/myuser/myslug/src/myref/mypath

But when I call it from code it returns "invalid memory address or nil pointer dereference", any help please?

Many thanks,

Dani

Try generate api client from bitbucket api by swagger ...

I wish I got api client automatically.
But I still, failed.

Install swagger

go get -u github.com/go-swagger/go-swagger/cmd/swagger

Try it

swagger validate https://api.bitbucket.org/swagger.json
wget https://api.bitbucket.org/swagger.json
swagger generate client -f ./swagger.json -A api

Log

$ swagger validate https://api.bitbucket.org/swagger.json
The swagger spec at "https://api.bitbucket.org/swagger.json" is invalid against swagger specification 2.0. see errors :
- definition "pipeline_selector" contains duplicate properties: [pipeline_selector.type]
- duplicate parameter name "files" for "query" in operation ""
- path param "{schedule_uuid}" has no parameter definition
- path param "pull_request_id" is not present in path "/repositories/{username}/{repo_slug}/pullrequests/activity"

Oops,

$ wget https://api.bitbucket.org/swagger.json
$ swagger generate client -f ./swagger.json -A api
The swagger spec at "./swagger.json" is invalid against swagger specification 2.0. see errors :
- definition "pipeline_selector" contains duplicate properties: [pipeline_selector.type]
- path param "pull_request_id" is not present in path "/repositories/{username}/{repo_slug}/pullrequests/activity"
- path param "{schedule_uuid}" has no parameter definition
- duplicate parameter name "files" for "query" in operation ""

Also generate client was failed.

Seems that have to fix some errors, but the json content is so huge(473kb).

Result must be addressable (a pointer)

If this is a noob mistake I apologize, I've asked around on slack/IRC and can't seem to figure out what I'm doing wrong here... Other people seemed stumped too.

I copied your test case for repos and get the following error..

package main

import (
	"github.com/ktrysmt/go-bitbucket"
)

func main() {

	client := bitbucket.NewBasicAuth("me", "pass")
	ro := &bitbucket.RepositoryOptions{
		Owner:     "owner",
		Repo_slug: "repo",
	}
	res, err := client.Repositories.Repository.Get(ro)
	if err == nil {
		print(res)
		print("no error!")
	}
	panic(err)
}
[2] % go run test.go                                                                                                                                                                                   /tmp
panic: result must be addressable (a pointer)

goroutine 1 [running]:
main.main()
	/tmp/test.go:19 +0x14c
exit status 2

I'm on go 1.10.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.