ktrysmt / go-bitbucket Goto Github PK
View Code? Open in Web Editor NEWBitbucket API library for Golang.
License: Apache License 2.0
Bitbucket API library for Golang.
License: Apache License 2.0
I found the code for reading comments, however, I couldn't find functionality for posting comments.
Is it planned?
Thanks!
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
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.
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?
I'm trying to create a repository witrh this lib but I got errors, theres an example?
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
Hi team,
I'm interested in the Bitbucket API and would like to build an application based on BitBucket.
Just want to ask is this repository the official library maintained by BitBucket development team?
Thanks.
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!
Despite there is bitbucket.NewOAuth() method, it is NOT actually implemented.
Specification can be found here
This is somewhat related to #38.
Having querying/filtering options (in my case specifically for pull requests) would be useful.
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!!!!
Seems like there is nothing for bitbucket project endpoints yet.
A complete CRUD would be nice :)
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?
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!
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
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:
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...
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
After PR #28 log was imported twice causing the build to fail.
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
}
I see there was some pagination support added in #22
Ideally these call sites should allow for pagination to be passed in through the call.
I'll throw something together really quick and get it up for review.
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.
- 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
Hello,
Thanks for go-bitbucket library, this is really helpful for us.
As a feature request, could you add authentication via apikey ?
Hello guys,
I found that Commits.go has not support for the following API endpoint...
I wander if this issue can be addressed.
I can provide a PR for this, but I'd wait for you guys to accept it :)
BTW: This would be my first contribution to open source community
Steps to reproduce
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>
make test
Expected outcome
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
- FAILgo test -v ./tests/client_test.go
- PASSgo test -v ./tests/diff_test.go
- FAILgo test -v ./tests/list_test.go
- PASSgo test -v ./tests/repository_test.go
- PASSgo test -v ./tests/user_test.go
- FAILgo test -v ./tests/workspace_test.go
- FAILSuggested Improvement
Use Github Actions to run tests automatically
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)
if the statusCode == 200, you should treat it as plain text, not json.
otherwise
https://github.com/ktrysmt/go-bitbucket/blob/master/client.go#L110
would return error, and cause the function fail.
(you might have to do some check on the resBodyBytes that it starts with "
or {
)
Would like support to manage branch restrictions
Name | Type | Description |
---|---|---|
state | string | Only return pull requests that are in this state. This parameter can be repeated. |
#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:
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.
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}".
Hey @ktrysmt is that fine if I work on adding a GetDiffStat
func for Diff?
Thanks,
dd
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
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
See: https://github.com/ktrysmt/go-bitbucket/blob/master/client.go#L150
The returned err
is never checked.
Execution continues in error case and error information are lost.
I wish I got api client automatically.
But I still, failed.
go get -u github.com/go-swagger/go-swagger/cmd/swagger
swagger validate https://api.bitbucket.org/swagger.json
wget https://api.bitbucket.org/swagger.json
swagger generate client -f ./swagger.json -A api
$ 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).
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.