Use go-gogs-client as a dependency. Repos.

This commit is contained in:
Mr. Is 2016-07-27 17:15:49 -04:00
parent edb3a9414d
commit 59b874ea7a
27 changed files with 190 additions and 1193 deletions

View File

@ -15,111 +15,95 @@
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gogits/go-gogs-client"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var newRepo bool
var newOrgRepo bool
// Flags.
var repoName string
var repoDescription string
var repoIsPrivate bool
var orgName string
var path string
type repository struct {
Name string `json:"name"`
}
// repoCmd represents the repo command
var repoCmd = &cobra.Command{
var repoRootCmd = &cobra.Command{
Use: "repo",
Short: "Manage gogs repositories",
Long: `Supported operations are .`,
Short: "Manage your repositories.",
Long: "Definitely manage your repositories.",
Run: func(cmd *cobra.Command, args []string) {
// do nothing?
fmt.Println("Args: ", args)
// debug...
client := GetClient()
fmt.Printf("\nClient: %v\n", client)
if newRepo {
// create new repo
if len(args) == 0 { // testes || RotBlauer testes
// a name for the repo is required
fmt.Println("Please provide a name for your new repository.")
return
repos, err := client.ListMyRepos()
if err != nil {
fmt.Println(err)
return
}
}
if !newOrgRepo {
// create repo for user
path = "/user/repos"
repoName = args[0]
} else {
// create repo for organization
if len(args) < 2 {
fmt.Println("Usage: [orgname] [reponame]")
return
}
path = "/org/" + args[0] + "/repos"
repoName = args[1]
}
repo := repository{
Name: repoName,
}
client := &http.Client{}
jsonString, _ := json.Marshal(repo)
req, _ := http.NewRequest("POST", viper.GetString("api_url")+path, bytes.NewBuffer(jsonString))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", ("token " + viper.GetString("token")))
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(body))
}
} else {
// get all repos owned by authenticated user
path = "/user/repos"
client := &http.Client{}
req, err := http.NewRequest("GET", viper.GetString("api_url")+path, nil)
req.Header.Set("Authorization", "token "+viper.GetString("token"))
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(body))
}
for _, repo := range repos {
printRepo(repo)
}
},
}
func init() {
RootCmd.AddCommand(repoCmd)
var repoListCmnd = &cobra.Command{
Use: "list",
Short: "List your repositories.",
Long: "List all your repositories.",
Run: func(cmd *cobra.Command, args []string) {
repos, err := GetClient().ListMyRepos()
if err != nil {
fmt.Println(err)
return
}
for _, repo := range repos {
printRepo(repo)
}
},
}
// repoCmd represents the repo command
var repoCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a repository",
Long: `Create a repository for you or your organization.`,
Run: func(cmd *cobra.Command, args []string) {
createRepoOpts := gogs.CreateRepoOption{
Name: repoName,
Description: repoDescription,
Private: repoIsPrivate,
}
var err error
var repo *gogs.Repository
if orgName == "" {
repo, err = GetClient().CreateRepo(createRepoOpts)
} else {
repo, err = GetClient().CreateOrgRepo(orgName, createRepoOpts)
}
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Repo created! Woohoo!")
printRepo(repo)
},
}
func printRepo(repo *gogs.Repository) {
fmt.Printf("Name: %v\nGit url: %v\n\n", repo.FullName, repo.CloneUrl)
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
@ -129,6 +113,83 @@ func init() {
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// repoCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
repoCmd.Flags().BoolVarP(&newRepo, "new", "n", false, "Create a new repository. A name is required.")
repoCmd.Flags().BoolVarP(&newOrgRepo, "org", "o", false, "Specify an organization you own.")
repoCreateCmd.Flags().StringVarP(&repoName, "name", "n", "", "repo name")
repoCreateCmd.Flags().StringVarP(&repoDescription, "desc", "d", "", "repo description")
repoCreateCmd.Flags().BoolVarP(&repoIsPrivate, "private", "p", false, "repo is private")
repoCreateCmd.Flags().StringVarP(&orgName, "org", "o", "", "organization")
RootCmd.AddCommand(repoRootCmd)
repoRootCmd.AddCommand(repoCreateCmd)
}
// fmt.Println("Args: ", args)
// if createUserRepoFlag {
// // create new repo
// if len(args) == 0 { // testes || RotBlauer testes
// // a name for the repo is required
// fmt.Println("Please provide a name for your new repository.")
// return
// }
// if !createOrganizationRepoFlag {
// // create repo for user
// path = "/user/repos"
// repoName = args[0]
// } else {
// // create repo for organization
// if len(args) < 2 {
// fmt.Println("Usage: [orgname] [reponame]")
// return
// }
// path = "/org/" + args[0] + "/repos"
// repoName = args[1]
// }
// repo := repository{
// Name: repoName,
// }
// client := &http.Client{}
// jsonString, _ := json.Marshal(repo)
// req, _ := http.NewRequest("POST", viper.GetString("api_url")+path, bytes.NewBuffer(jsonString))
// req.Header.Set("Content-Type", "application/json")
// req.Header.Set("Authorization", ("token " + viper.GetString("token")))
// res, err := client.Do(req)
// if err != nil {
// fmt.Println(err)
// }
// defer res.Body.Close()
// body, err := ioutil.ReadAll(res.Body)
// if err != nil {
// fmt.Println(err)
// } else {
// fmt.Println(string(body))
// }
// } else {
// // get all repos owned by authenticated user
// path = "/user/repos"
// client := &http.Client{}
// req, err := http.NewRequest("GET", viper.GetString("api_url")+path, nil)
// req.Header.Set("Authorization", "token "+viper.GetString("token"))
// res, err := client.Do(req)
// if err != nil {
// fmt.Println(err)
// }
// defer res.Body.Close()
// body, err := ioutil.ReadAll(res.Body)
// if err != nil {
// fmt.Println(err)
// } else {
// fmt.Println(string(body))
// }
// }

View File

@ -18,12 +18,15 @@ import (
"fmt"
"os"
gogs "github.com/gogits/go-gogs-client"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var apiURL string
var tokenArg string
var client *gogs.Client
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
@ -39,7 +42,7 @@ $HOME/.gogs-cli.yaml. While you're there you can adjust the default to your liki
Run: func(cmd *cobra.Command, args []string) {
token := viper.GetString("token")
if token != "" {
fmt.Println("Token authentication enabled.")
fmt.Println("Token authentication enabled @ ", token)
} else {
fmt.Println("No token found.")
}
@ -62,15 +65,40 @@ func Execute() {
}
}
func GetClient() *gogs.Client {
fmt.Println("Getting client.")
return client
}
func initClient() {
fmt.Println("initClient")
url := viper.GetString("api_url")
token := viper.GetString("token")
fmt.Printf("api url: %v\n", url)
fmt.Printf("token: %v\n", token)
client = gogs.NewClient(url, token)
}
func init() {
cobra.OnInitialize(initConfig)
cobra.OnInitialize(initConfig, initClient)
// url := viper.GetString("api_url")
// toke := viper.GetString("token")
// fmt.Printf("api url: %v", url)
// fmt.Printf("token: %v", toke)
// client = gogs.NewClient(url, toke)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gogs-cli.yaml)")
RootCmd.PersistentFlags().StringVar(&apiURL, "url", "", "api url should include /api/v1 path (default is try.gogs.io/api/v1)")
// RootCmd.PersistentFlags().StringVar(&apiURL, "url", "", "api url should include /api/v1 path (default is try.gogs.io/api/v1)")
// RootCmd.PersistentFlags().StringVar(&tokenArg, "token", "", "token authorization (if not specified in cfg file)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
@ -85,7 +113,7 @@ func initConfig() {
viper.SetConfigName(".gogs-cli") // name of config file (without extension)
viper.AddConfigPath("$HOME") // adding home directory as first search path
viper.AutomaticEnv() // read in environment variables that match
viper.SetDefault("api_url", "try.gogs.io/api/v1")
// viper.SetDefault("api_url", "try.gogs.io/api/v1")
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
@ -95,8 +123,13 @@ func initConfig() {
}
// if api_url was flagged, set it to that (override cfg)
if apiURL != "" {
viper.Set("api_url", apiURL)
}
// if apiURL != "" {
// viper.Set("api_url", apiURL)
// }
// // if token was flagged, set it to that (override cfg)
// if tokenArg != "" {
// viper.Set("token", tokenArg)
// }
}

View File

@ -1,25 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
.idea

View File

@ -1,22 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Go Git Service
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,8 +0,0 @@
Gogs API client in Go
=====================
This package is still in experiment, see [Wiki](https://github.com/gogits/go-gogs-client/wiki) for documentation.
## License
This project is under the MIT License. See the [LICENSE](https://github.com/gogits/gogs/blob/master/LICENSE) file for the full license text.

View File

@ -1,21 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
)
func (c *Client) AdminCreateOrg(user string, opt CreateOrgOption) (*Organization, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
org := new(Organization)
return org, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/orgs", user),
jsonHeader, bytes.NewReader(body), org)
}

View File

@ -1,21 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
)
func (c *Client) AdminCreateRepo(user string, opt CreateRepoOption) (*Repository, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/repos", user),
jsonHeader, bytes.NewReader(body), repo)
}

View File

@ -1,67 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
)
type CreateUserOption struct {
SourceID int64 `json:"source_id"`
LoginName string `json:"login_name"`
Username string `json:"username" binding:"Required;AlphaDashDot;MaxSize(35)"`
FullName string `json:"full_name" binding:"MaxSize(100)"`
Email string `json:"email" binding:"Required;Email;MaxSize(254)"`
Password string `json:"password" binding:"MaxSize(255)"`
SendNotify bool `json:"send_notify"`
}
func (c *Client) AdminCreateUser(opt CreateUserOption) (*User, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
user := new(User)
return user, c.getParsedResponse("POST", "/admin/users", jsonHeader, bytes.NewReader(body), user)
}
type EditUserOption struct {
SourceID int64 `json:"source_id"`
LoginName string `json:"login_name"`
FullName string `json:"full_name" binding:"MaxSize(100)"`
Email string `json:"email" binding:"Required;Email;MaxSize(254)"`
Password string `json:"password" binding:"MaxSize(255)"`
Website string `json:"website" binding:"MaxSize(50)"`
Location string `json:"location" binding:"MaxSize(50)"`
Active *bool `json:"active"`
Admin *bool `json:"admin"`
AllowGitHook *bool `json:"allow_git_hook"`
AllowImportLocal *bool `json:"allow_import_local"`
}
func (c *Client) AdminEditUser(user string, opt EditUserOption) error {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
_, err = c.getResponse("PATCH", fmt.Sprintf("/admin/users/%s", user), jsonHeader, bytes.NewReader(body))
return err
}
func (c *Client) AdminDeleteUser(user string) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/admin/users/%s", user), nil, nil)
return err
}
func (c *Client) AdminCreateUserPublicKey(user string, opt CreateKeyOption) (*PublicKey, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
key := new(PublicKey)
return key, c.getParsedResponse("POST", fmt.Sprintf("/admin/users/%s/keys", user), jsonHeader, bytes.NewReader(body), key)
}

View File

@ -1,86 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
)
func Version() string {
return "0.9.0"
}
// Client represents a Gogs API client.
type Client struct {
url string
accessToken string
client *http.Client
}
// NewClient initializes and returns a API client.
func NewClient(url, token string) *Client {
return &Client{
url: strings.TrimSuffix(url, "/"),
accessToken: token,
client: &http.Client{},
}
}
// SetHTTPClient replaces default http.Client with user given one.
func (c *Client) SetHTTPClient(client *http.Client) {
c.client = client
}
func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) {
req, err := http.NewRequest(method, c.url+"/api/v1"+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "token "+c.accessToken)
for k, v := range header {
req.Header[k] = v
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case 403:
return nil, errors.New("403 Forbidden")
case 404:
return nil, errors.New("404 Not Found")
}
if resp.StatusCode/100 != 2 {
errMap := make(map[string]interface{})
if err = json.Unmarshal(data, &errMap); err != nil {
return nil, err
}
return nil, errors.New(errMap["message"].(string))
}
return data, nil
}
func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error {
data, err := c.getResponse(method, path, header, body)
if err != nil {
return err
}
return json.Unmarshal(data, obj)
}

View File

@ -1,83 +0,0 @@
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
type PullRequestMeta struct {
HasMerged bool `json:"merged"`
Merged *time.Time `json:"merged_at"`
}
type Issue struct {
ID int64 `json:"id"`
Index int64 `json:"number"`
State string `json:"state"`
Title string `json:"title"`
Body string `json:"body"`
User *User `json:"user"`
Labels []*Label `json:"labels"`
Assignee *User `json:"assignee"`
Milestone *Milestone `json:"milestone"`
Comments int `json:"comments"`
PullRequest *PullRequestMeta `json:"pull_request"`
Created time.Time `json:"created_at"`
Updated time.Time `json:"updated_at"`
}
type ListIssueOption struct {
Page int
}
func (c *Client) ListRepoIssues(owner, repo string, opt ListIssueOption) ([]*Issue, error) {
issues := make([]*Issue, 0, 10)
return issues, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues?page=%d", owner, repo, opt.Page), nil, nil, &issues)
}
func (c *Client) GetIssue(owner, repo string, index int) (*Issue, error) {
issue := new(Issue)
return issue, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index), nil, nil, issue)
}
type CreateIssueOption struct {
Title string `json:"title" binding:"Required"`
Body string `json:"body"`
Assignee string `json:"assignee"`
Milestone int64 `json:"milestone"`
Labels []int64 `json:"labels"`
Closed bool `json:"closed"`
}
func (c *Client) CreateIssue(owner, repo string, opt CreateIssueOption) (*Issue, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
issue := new(Issue)
return issue, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/issues", owner, repo),
jsonHeader, bytes.NewReader(body), issue)
}
type EditIssueOption struct {
Title string `json:"title"`
Body *string `json:"body"`
Assignee *string `json:"assignee"`
Milestone *int64 `json:"milestone"`
}
func (c *Client) EditIssue(owner, repo string, index int, opt EditIssueOption) (*Issue, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
issue := new(Issue)
return issue, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d", owner, repo, index),
jsonHeader, bytes.NewReader(body), issue)
}

View File

@ -1,10 +0,0 @@
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
type Label struct {
Name string `json:"name"`
Color string `json:"color"`
}

View File

@ -1,18 +0,0 @@
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import "time"
type Milestone struct {
ID int64 `json:"id"`
State string `json:"state"`
Title string `json:"title"`
Description string `json:"description"`
OpenIssues int `json:"open_issues"`
ClosedIssues int `json:"closed_issues"`
Closed *time.Time `json:"closed_at"`
Deadline *time.Time `json:"due_on"`
}

View File

@ -1,11 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
type MarkdownOption struct {
Text string
Mode string
Context string
}

View File

@ -1,60 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
)
type Organization struct {
ID int64 `json:"id"`
UserName string `json:"username"`
FullName string `json:"full_name"`
AvatarUrl string `json:"avatar_url"`
Description string `json:"description"`
Website string `json:"website"`
Location string `json:"location"`
}
func (c *Client) ListMyOrgs() ([]*Organization, error) {
orgs := make([]*Organization, 0, 5)
return orgs, c.getParsedResponse("GET", "/user/orgs", nil, nil, &orgs)
}
func (c *Client) ListUserOrgs(user string) ([]*Organization, error) {
orgs := make([]*Organization, 0, 5)
return orgs, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/orgs", user), nil, nil, &orgs)
}
func (c *Client) GetOrg(orgname string) (*Organization, error) {
org := new(Organization)
return org, c.getParsedResponse("GET", fmt.Sprintf("/orgs/%s", orgname), nil, nil, org)
}
type CreateOrgOption struct {
UserName string `json:"username" binding:"Required"`
FullName string `json:"full_name"`
Description string `json:"description"`
Website string `json:"website"`
Location string `json:"location"`
}
type EditOrgOption struct {
FullName string `json:"full_name"`
Description string `json:"description"`
Website string `json:"website"`
Location string `json:"location"`
}
func (c *Client) EditOrg(orgname string, opt EditOrgOption) error {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
_, err = c.getResponse("PATCH", fmt.Sprintf("/orgs/%s", orgname), jsonHeader, bytes.NewReader(body))
return err
}

View File

@ -1,18 +0,0 @@
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
type Team struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Permission string `json:"permission"`
}
type CreateTeamOption struct {
Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(30)"`
Description string `json:"description" binding:"MaxSize(255)"`
Permission string `json:"permission"`
}

View File

@ -1,112 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
// Permission represents a API permission.
type Permission struct {
Admin bool `json:"admin"`
Push bool `json:"push"`
Pull bool `json:"pull"`
}
// Repository represents a API repository.
type Repository struct {
ID int64 `json:"id"`
Owner *User `json:"owner"`
FullName string `json:"full_name"`
Description string `json:"description"`
Private bool `json:"private"`
Fork bool `json:"fork"`
HtmlUrl string `json:"html_url"`
CloneUrl string `json:"clone_url"`
SshUrl string `json:"ssh_url"`
Stars int `json:"stars_count"`
Forks int `json:"forks_count"`
Watchers int `json:"watchers_count"`
OpenIssues int `json:"open_issues_count"`
Created time.Time `json:"created_at"`
Updated time.Time `json:"updated_at"`
Permissions Permission `json:"permissions"`
}
// ListMyRepos lists all repositories for the authenticated user that has access to.
func (c *Client) ListMyRepos() ([]*Repository, error) {
repos := make([]*Repository, 0, 10)
return repos, c.getParsedResponse("GET", "/user/repos", nil, nil, &repos)
}
type CreateRepoOption struct {
Name string `json:"name" binding:"Required;AlphaDashDot;MaxSize(100)"`
Description string `json:"description" binding:"MaxSize(255)"`
Private bool `json:"private"`
AutoInit bool `json:"auto_init"`
Gitignores string `json:"gitignores"`
License string `json:"license"`
Readme string `json:"readme"`
}
// CreateRepo creates a repository for authenticated user.
func (c *Client) CreateRepo(opt CreateRepoOption) (*Repository, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", "/user/repos", jsonHeader, bytes.NewReader(body), repo)
}
// CreateOrgRepo creates an organization repository for authenticated user.
func (c *Client) CreateOrgRepo(org string, opt CreateRepoOption) (*Repository, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", fmt.Sprintf("/org/%s/repos", org), jsonHeader, bytes.NewReader(body), repo)
}
// GetRepo returns information of a repository of given owner.
func (c *Client) GetRepo(owner, reponame string) (*Repository, error) {
repo := new(Repository)
return repo, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s", owner, reponame), nil, nil, repo)
}
// DeleteRepo deletes a repository of user or organization.
func (c *Client) DeleteRepo(owner, repo string) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s", owner, repo), nil, nil)
return err
}
type MigrateRepoOption struct {
CloneAddr string `json:"clone_addr" binding:"Required"`
AuthUsername string `json:"auth_username"`
AuthPassword string `json:"auth_password"`
UID int `json:"uid" binding:"Required"`
RepoName string `json:"repo_name" binding:"Required"`
Mirror bool `json:"mirror"`
Private bool `json:"private"`
Description string `json:"description"`
}
// MigrateRepo migrates a repository from other Git hosting sources for the
// authenticated user.
//
// To migrate a repository for a organization, the authenticated user must be a
// owner of the specified organization.
func (c *Client) MigrateRepo(opt MigrateRepoOption) (*Repository, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
repo := new(Repository)
return repo, c.getParsedResponse("POST", "/repos/migrate", jsonHeader, bytes.NewReader(body), repo)
}

View File

@ -1,25 +0,0 @@
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"fmt"
)
// Branch represents a repository branch.
type Branch struct {
Name string `json:"name"`
Commit *PayloadCommit `json:"commit"`
}
func (c *Client) ListRepoBranches(user, repo string) ([]*Branch, error) {
branches := make([]*Branch, 0, 10)
return branches, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches", user, repo), nil, nil, &branches)
}
func (c *Client) GetRepoBranch(user, repo, branch string) (*Branch, error) {
b := new(Branch)
return b, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/branches/%s", user, repo, branch), nil, nil, &b)
}

View File

@ -1,15 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"fmt"
)
// GetFile downloads a file of repository, ref can be branch/tag/commit.
// e.g.: ref -> master, tree -> macaron.go(no leading slash)
func (c *Client) GetFile(user, repo, ref, tree string) ([]byte, error) {
return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/raw/%s/%s", user, repo, ref, tree), nil, nil)
}

View File

@ -1,213 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
var (
ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook")
)
type Hook struct {
ID int64 `json:"id"`
Type string `json:"type"`
URL string `json:"-"`
Config map[string]string `json:"config"`
Events []string `json:"events"`
Active bool `json:"active"`
Updated time.Time `json:"updated_at"`
Created time.Time `json:"created_at"`
}
func (c *Client) ListRepoHooks(user, repo string) ([]*Hook, error) {
hooks := make([]*Hook, 0, 10)
return hooks, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), nil, nil, &hooks)
}
type CreateHookOption struct {
Type string `json:"type" binding:"Required"`
Config map[string]string `json:"config" binding:"Required"`
Events []string `json:"events"`
Active bool `json:"active"`
}
func (c *Client) CreateRepoHook(user, repo string, opt CreateHookOption) (*Hook, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
h := new(Hook)
return h, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/hooks", user, repo), jsonHeader, bytes.NewReader(body), h)
}
type EditHookOption struct {
Config map[string]string `json:"config"`
Events []string `json:"events"`
Active *bool `json:"active"`
}
func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) error {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
_, err = c.getResponse("PATCH", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), jsonHeader, bytes.NewReader(body))
return err
}
func (c *Client) DeleteRepoHook(user, repo string, id int64) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/hooks/%d", user, repo, id), nil, nil)
return err
}
type Payloader interface {
SetSecret(string)
JSONPayload() ([]byte, error)
}
type PayloadAuthor struct {
Name string `json:"name"`
Email string `json:"email"`
UserName string `json:"username"`
}
type PayloadUser struct {
UserName string `json:"login"`
ID int64 `json:"id"`
AvatarUrl string `json:"avatar_url"`
}
type PayloadCommit struct {
ID string `json:"id"`
Message string `json:"message"`
URL string `json:"url"`
Author *PayloadAuthor `json:"author"`
}
type PayloadRepo struct {
ID int64 `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
SSHURL string `json:"ssh_url"`
CloneURL string `json:"clone_url"`
Description string `json:"description"`
Website string `json:"website"`
Watchers int `json:"watchers"`
Owner *PayloadAuthor `json:"owner"`
Private bool `json:"private"`
DefaultBranch string `json:"default_branch"`
}
var (
_ Payloader = &CreatePayload{}
_ Payloader = &PushPayload{}
)
// _________ __
// \_ ___ \_______ ____ _____ _/ |_ ____
// / \ \/\_ __ \_/ __ \\__ \\ __\/ __ \
// \ \____| | \/\ ___/ / __ \| | \ ___/
// \______ /|__| \___ >____ /__| \___ >
// \/ \/ \/ \/
type CreatePayload struct {
Secret string `json:"secret"`
Ref string `json:"ref"`
RefType string `json:"ref_type"`
Repo *PayloadRepo `json:"repository"`
Sender *PayloadUser `json:"sender"`
}
func (p *CreatePayload) SetSecret(secret string) {
p.Secret = secret
}
func (p *CreatePayload) JSONPayload() ([]byte, error) {
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
return []byte{}, err
}
return data, nil
}
// ParseCreateHook parses create event hook content.
func ParseCreateHook(raw []byte) (*CreatePayload, error) {
hook := new(CreatePayload)
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
// it is possible the JSON was parsed, however,
// was not from Gogs (maybe was from Bitbucket)
// So we'll check to be sure certain key fields
// were populated
switch {
case hook.Repo == nil:
return nil, ErrInvalidReceiveHook
case len(hook.Ref) == 0:
return nil, ErrInvalidReceiveHook
}
return hook, nil
}
// __________ .__
// \______ \__ __ _____| |__
// | ___/ | \/ ___/ | \
// | | | | /\___ \| Y \
// |____| |____//____ >___| /
// \/ \/
// PushPayload represents a payload information of push event.
type PushPayload struct {
Secret string `json:"secret"`
Ref string `json:"ref"`
Before string `json:"before"`
After string `json:"after"`
CompareUrl string `json:"compare_url"`
Commits []*PayloadCommit `json:"commits"`
Repo *PayloadRepo `json:"repository"`
Pusher *PayloadAuthor `json:"pusher"`
Sender *PayloadUser `json:"sender"`
}
func (p *PushPayload) SetSecret(secret string) {
p.Secret = secret
}
func (p *PushPayload) JSONPayload() ([]byte, error) {
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
return []byte{}, err
}
return data, nil
}
// ParsePushHook parses push event hook content.
func ParsePushHook(raw []byte) (*PushPayload, error) {
hook := new(PushPayload)
if err := json.Unmarshal(raw, hook); err != nil {
return nil, err
}
switch {
case hook.Repo == nil:
return nil, ErrInvalidReceiveHook
case len(hook.Ref) == 0:
return nil, ErrInvalidReceiveHook
}
return hook, nil
}
// Branch returns branch name from a payload
func (p *PushPayload) Branch() string {
return strings.Replace(p.Ref, "refs/heads/", "", -1)
}

View File

@ -1,50 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
type DeployKey struct {
ID int64 `json:"id"`
Key string `json:"key"`
URL string `json:"url"`
Title string `json:"title"`
Created time.Time `json:"created_at"`
ReadOnly bool `json:"read_only"`
}
func (c *Client) ListDeployKeys(user, repo string) ([]*DeployKey, error) {
keys := make([]*DeployKey, 0, 10)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys", user, repo), nil, nil, &keys)
}
func (c *Client) GetDeployKey(user, repo string, keyID int64) (*DeployKey, error) {
key := new(DeployKey)
return key, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/keys/%d", user, repo, keyID), nil, nil, &key)
}
type CreateKeyOption struct {
Title string `json:"title" binding:"Required"`
Key string `json:"key" binding:"Required"`
}
func (c *Client) CreateDeployKey(user, repo string, opt CreateKeyOption) (*DeployKey, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
key := new(DeployKey)
return key, c.getParsedResponse("POST", fmt.Sprintf("/repos/%s/%s/keys", user, repo), jsonHeader, bytes.NewReader(body), key)
}
func (c *Client) DeleteDeployKey(owner, repo string, keyID int64) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/keys/%d", owner, repo, keyID), nil, nil)
return err
}

View File

@ -1,24 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"fmt"
)
// User represents a API user.
type User struct {
ID int64 `json:"id"`
UserName string `json:"username"`
FullName string `json:"full_name"`
Email string `json:"email"`
AvatarUrl string `json:"avatar_url"`
}
func (c *Client) GetUserInfo(user string) (*User, error) {
u := new(User)
err := c.getParsedResponse("GET", fmt.Sprintf("/users/%s", user), nil, nil, u)
return u, err
}

View File

@ -1,46 +0,0 @@
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
)
func BasicAuthEncode(user, pass string) string {
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
}
// AccessToken represents a API access token.
type AccessToken struct {
Name string `json:"name"`
Sha1 string `json:"sha1"`
}
func (c *Client) ListAccessTokens(user, pass string) ([]*AccessToken, error) {
tokens := make([]*AccessToken, 0, 10)
return tokens, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/tokens", user),
http.Header{"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}}, nil, &tokens)
}
type CreateAccessTokenOption struct {
Name string `json:"name" binding:"Required"`
}
func (c *Client) CreateAccessToken(user, pass string, opt CreateAccessTokenOption) (*AccessToken, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
t := new(AccessToken)
return t, c.getParsedResponse("POST", fmt.Sprintf("/users/%s/tokens", user),
http.Header{
"content-type": []string{"application/json"},
"Authorization": []string{"Basic " + BasicAuthEncode(user, pass)}},
bytes.NewReader(body), t)
}

View File

@ -1,43 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
)
type Email struct {
Email string `json:"email"`
Verified bool `json:"verified"`
Primary bool `json:"primary"`
}
func (c *Client) ListEmails() ([]*Email, error) {
emails := make([]*Email, 0, 3)
return emails, c.getParsedResponse("GET", "/user/emails", nil, nil, &emails)
}
type CreateEmailOption struct {
Emails []string `json:"emails"`
}
func (c *Client) AddEmail(opt CreateEmailOption) ([]*Email, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
emails := make([]*Email, 0, 3)
return emails, c.getParsedResponse("POST", "/user/emails", jsonHeader, bytes.NewReader(body), emails)
}
func (c *Client) DeleteEmail(opt CreateEmailOption) error {
body, err := json.Marshal(&opt)
if err != nil {
return err
}
_, err = c.getResponse("DELETE", "/user/emails", jsonHeader, bytes.NewReader(body))
return err
}

View File

@ -1,47 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import "fmt"
func (c *Client) ListMyFollowers(page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/followers?page=%d", page), nil, nil, &users)
}
func (c *Client) ListFollowers(user string, page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/followers?page=%d", user, page), nil, nil, &users)
}
func (c *Client) ListMyFollowing(page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/user/following?page=%d", page), nil, nil, &users)
}
func (c *Client) ListFollowing(user string, page int) ([]*User, error) {
users := make([]*User, 0, 10)
return users, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/following?page=%d", user, page), nil, nil, &users)
}
func (c *Client) IsFollowing(target string) bool {
_, err := c.getResponse("GET", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err == nil
}
func (c *Client) IsUserFollowing(user, target string) bool {
_, err := c.getResponse("GET", fmt.Sprintf("/users/%s/following/%s", user, target), nil, nil)
return err == nil
}
func (c *Client) Follow(target string) error {
_, err := c.getResponse("PUT", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err
}
func (c *Client) Unfollow(target string) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/following/%s", target), nil, nil)
return err
}

View File

@ -1,49 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
type PublicKey struct {
ID int64 `json:"id"`
Key string `json:"key"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Created time.Time `json:"created_at,omitempty"`
}
func (c *Client) ListPublicKeys(user string) ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 10)
return keys, c.getParsedResponse("GET", fmt.Sprintf("/users/%s/keys", user), nil, nil, &keys)
}
func (c *Client) ListMyPublicKeys() ([]*PublicKey, error) {
keys := make([]*PublicKey, 0, 10)
return keys, c.getParsedResponse("GET", "/user/keys", nil, nil, &keys)
}
func (c *Client) GetPublicKey(keyID int64) (*PublicKey, error) {
key := new(PublicKey)
return key, c.getParsedResponse("GET", fmt.Sprintf("/user/keys/%d", keyID), nil, nil, &key)
}
func (c *Client) CreatePublicKey(opt CreateKeyOption) (*PublicKey, error) {
body, err := json.Marshal(&opt)
if err != nil {
return nil, err
}
key := new(PublicKey)
return key, c.getParsedResponse("POST", "/user/keys", jsonHeader, bytes.NewReader(body), key)
}
func (c *Client) DeletePublicKey(keyID int64) error {
_, err := c.getResponse("DELETE", fmt.Sprintf("/user/keys/%d", keyID), nil, nil)
return err
}

View File

@ -1,23 +0,0 @@
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gogs
import (
"net/http"
)
var jsonHeader = http.Header{"content-type": []string{"application/json"}}
func Bool(v bool) *bool {
return &v
}
func String(v string) *string {
return &v
}
func Int64(v int64) *int64 {
return &v
}

BIN
gogs

Binary file not shown.