Move octokit to a separate project

This commit is contained in:
Jingwen Owen Ou 2013-06-08 16:57:25 -07:00
Родитель 2b29e18e5e
Коммит b9ca73f67b
15 изменённых файлов: 1 добавлений и 465 удалений

Просмотреть файл

@ -1,7 +1,7 @@
package github package github
import ( import (
"github.com/jingweno/gh/octokit" "github.com/jingweno/octokit"
"github.com/jingweno/gh/utils" "github.com/jingweno/gh/utils"
) )

Просмотреть файл

@ -1,49 +0,0 @@
package octokit
type Authorization struct {
Scopes []string `json:"scopes"`
Url string `json:"url"`
App App `json:"app"`
Token string `json:"token"`
Note string `json:"note"`
NoteUrl string `json:"note_url"`
}
type App struct {
Url string `json:"url"`
Name string `json:"name"`
ClientId string `json:"client_id"`
}
type AuthorizationParams struct {
Scopes []string `json:"scopes"`
Note string `json:"note"`
NoteUrl string `json:"note_url"`
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
func (c *Client) Authorizations() ([]Authorization, error) {
body, err := c.get("authorizations", nil)
if err != nil {
return nil, err
}
var auths []Authorization
err = jsonUnmarshal(body, &auths)
if err != nil {
return nil, err
}
return auths, nil
}
func (c *Client) CreatedAuthorization(params AuthorizationParams) (*Authorization, error) {
var auth Authorization
err := c.jsonPost("authorizations", nil, params, &auth)
if err != nil {
return nil, err
}
return &auth, nil
}

Просмотреть файл

@ -1,15 +0,0 @@
package octokit
import (
"github.com/bmizerany/assert"
"os"
"testing"
)
func TestAuthorizations(t *testing.T) {
c := NewClientWithPassword(os.Getenv("GITHUB_USER"), os.Getenv("GITHUB_PASSWORD"))
auths, err := c.Authorizations()
assert.Equal(t, nil, err)
assert.T(t, len(auths) > 0)
}

Просмотреть файл

@ -1,95 +0,0 @@
package octokit
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
)
const (
GitHubApiUrl string = "https://" + GitHubApiHost
GitHubApiHost string = "api.github.com"
)
type Client struct {
httpClient *http.Client
Login string
Password string
Token string
}
func (c *Client) get(path string, extraHeaders map[string]string) ([]byte, error) {
return c.request("GET", path, extraHeaders, nil)
}
func (c *Client) post(path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {
return c.request("POST", path, extraHeaders, content)
}
func (c *Client) jsonGet(path string, extraHeaders map[string]string, v interface{}) error {
body, err := c.get(path, extraHeaders)
if err != nil {
return err
}
return jsonUnmarshal(body, v)
}
func (c *Client) jsonPost(path string, extraHeaders map[string]string, params interface{}, v interface{}) error {
b, err := jsonMarshal(params)
if err != nil {
return err
}
buffer := bytes.NewBuffer(b)
body, err := c.post(path, extraHeaders, buffer)
if err != nil {
return err
}
return jsonUnmarshal(body, v)
}
func (c *Client) request(method, path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {
url := fmt.Sprintf("%s/%s", GitHubApiUrl, path)
request, err := http.NewRequest(method, url, content)
if err != nil {
return nil, err
}
c.setDefaultHeaders(request)
if extraHeaders != nil {
for h, v := range extraHeaders {
request.Header.Set(h, v)
}
}
response, err := c.httpClient.Do(request)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 && response.StatusCode < 600 {
return nil, handleErrors(body)
}
return body, nil
}
func (c *Client) setDefaultHeaders(request *http.Request) {
request.Header.Set("Accept", "application/vnd.github.beta+json")
if c.Token != "" {
request.Header.Set("Authorization", fmt.Sprintf("token %s", c.Token))
}
if c.Login != "" && c.Password != "" {
request.Header.Set("Authorization", fmt.Sprintf("Basic %s", hashAuth(c.Login, c.Password)))
}
}

Просмотреть файл

@ -1,29 +0,0 @@
package octokit
import (
"bytes"
"github.com/bmizerany/assert"
"net/http"
"testing"
)
func TestGet(t *testing.T) {
c := &Client{&http.Client{}, "", "", ""}
body, err := c.get("repos/jingweno/gh/commits", nil)
assert.Equal(t, nil, err)
assert.T(t, len(body) > 0)
}
func TestPost(t *testing.T) {
content := "# title"
c := &Client{&http.Client{}, "", "", ""}
headers := make(map[string]string)
headers["Content-Type"] = "text/plain"
body, err := c.post("markdown/raw", headers, bytes.NewBufferString(content))
assert.Equal(t, nil, err)
expectBody := "<h1>\n<a name=\"title\" class=\"anchor\" href=\"#title\"><span class=\"octicon octicon-link\"></span></a>title</h1>"
assert.Equal(t, expectBody, string(body))
}

Просмотреть файл

@ -1,61 +0,0 @@
package octokit
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
type gitHubError struct {
Resource string `json:"resource"`
Field string `json:"field"`
Value interface{} `json:"value"`
Code string `json:"code"`
Message string `json:"message"`
}
type gitHubErrors struct {
Message string `json:"message"`
Errors []gitHubError `json:"errors"`
}
func handleErrors(body []byte) error {
var githubErrors gitHubErrors
err := json.Unmarshal(body, &githubErrors)
if err != nil {
return err
}
msg := buildErrorMessage(githubErrors)
return errors.New(msg)
}
func buildErrorMessage(githubErrors gitHubErrors) string {
errorMessages := make([]string, 0)
for _, e := range githubErrors.Errors {
var msg string
switch e.Code {
case "custom":
msg = e.Message
case "missing_field":
msg = fmt.Sprintf("Missing field: %s", e.Field)
case "invalid":
msg = fmt.Sprintf("Invalid value for %s: %v", e.Field, e.Value)
case "unauthorized":
msg = fmt.Sprintf("Not allow to change field %s", e.Field)
}
if msg != "" {
errorMessages = append(errorMessages, msg)
}
}
msg := strings.Join(errorMessages, "\n")
if msg == "" {
msg = githubErrors.Message
}
return msg
}

Просмотреть файл

@ -1,13 +0,0 @@
package octokit
import (
"github.com/bmizerany/assert"
"testing"
)
func TestHandleErrors(t *testing.T) {
body := "{\"message\":\"Invalid request media type (expecting 'text/plain')\"}"
err := handleErrors([]byte(body))
assert.Equal(t, "Invalid request media type (expecting 'text/plain')", err.Error())
}

Просмотреть файл

@ -1,17 +0,0 @@
package octokit
import (
"net/http"
)
func NewClientWithToken(token string) *Client {
return &Client{&http.Client{}, "", "", token}
}
func NewClientWithPassword(login, password string) *Client {
return &Client{&http.Client{}, login, password, ""}
}
func NewClient() *Client {
return &Client{&http.Client{}, "", "", ""}
}

Просмотреть файл

@ -1,45 +0,0 @@
package octokit
import (
"fmt"
)
type PullRequestParams struct {
Base string `json:"base"`
Head string `json:"head"`
Title string `json:"title"`
Body string `json:"body"`
}
type PullRequestForIssueParams struct {
Base string `json:"base"`
Head string `json:"head"`
Issue string `json:"issue"`
}
type PullRequest struct {
Url string `json:"url"`
HtmlUrl string `json:"html_url"`
DiffUrl string `json:"diff_url"`
PatchUrl string `json:"patch_url"`
IssueUrl string `json:"issue_url"`
}
func (c *Client) CreatePullRequest(repo Repository, params PullRequestParams) (*PullRequest, error) {
return c.createPullRequest(repo, params)
}
func (c *Client) CreatePullRequestForIssue(repo Repository, params PullRequestForIssueParams) (*PullRequest, error) {
return c.createPullRequest(repo, params)
}
func (c *Client) createPullRequest(repo Repository, params interface{}) (*PullRequest, error) {
path := fmt.Sprintf("repos/%s/pulls", repo)
var pr PullRequest
err := c.jsonPost(path, nil, params, &pr)
if err != nil {
return nil, err
}
return &pr, nil
}

Просмотреть файл

@ -1,14 +0,0 @@
package octokit
import (
"fmt"
)
type Repository struct {
Name string
UserName string
}
func (r Repository) String() string {
return fmt.Sprintf("%s/%s", r.UserName, r.Name)
}

Просмотреть файл

@ -1,36 +0,0 @@
package octokit
import (
"fmt"
"time"
)
type Status struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
State string `json:"state"`
TargetUrl string `json:"target_url"`
Description string `json:"description"`
Id int `json:"id"`
Url string `json:"url"`
Creator StatusCreator `json:"creator"`
}
type StatusCreator struct {
Login string `json:"login"`
Id int `json:"id"`
AvatarUrl string `json:"avatar_url"`
GravatarId string `json:"gravatar_id"`
Url string `json:"url"`
}
func (c *Client) Statuses(repo Repository, sha string) ([]Status, error) {
path := fmt.Sprintf("repos/%s/statuses/%s", repo, sha)
var statuses []Status
err := c.jsonGet(path, nil, &statuses)
if err != nil {
return nil, err
}
return statuses, nil
}

Просмотреть файл

@ -1,16 +0,0 @@
package octokit
import (
"github.com/bmizerany/assert"
"os"
"testing"
)
func TestStatuses(t *testing.T) {
c := NewClientWithToken(os.Getenv("GITHUB_TOKEN"))
repo := Repository{"gh", "jingweno"}
statuses, err := c.Statuses(repo, "99b0f36b24e25a644ed70ace601da857eea4cf72")
assert.Equal(t, nil, err)
assert.T(t, len(statuses) == 0)
}

Просмотреть файл

@ -1,39 +0,0 @@
package octokit
import (
"time"
)
type User struct {
Login string `json:"login"`
Id int `json:"id"`
AvatarUrl string `json:"avatar_url"`
GravatarId string `json:"gravatar_id"`
Url string `json:"url"`
Name string `json:"name"`
Company string `json:"company"`
Blog string `json:"blog"`
Location string `json:"location"`
Email string `json:"email"`
Hireable bool `json:"hireable"`
Bio string `json:"bio"`
PublicRepos int `json:"public_repos"`
PublicGists int `json:"jsonpublic_gists"`
Followers int `json:"followers"`
Following int `json:"following"`
HtmlUrl string `json:"html_url"`
CreatedAt time.Time `json:"created_at"`
Type string `json:"jsontype"`
}
func (c *Client) AuthenticatedUser() (*User, error) {
body, err := c.get("user", nil)
if err != nil {
return nil, err
}
var authUser User
err = jsonUnmarshal(body, &authUser)
return &authUser, err
}

Просмотреть файл

@ -1,15 +0,0 @@
package octokit
import (
"github.com/bmizerany/assert"
"os"
"testing"
)
func TestAuthenticatedUser(t *testing.T) {
c := NewClientWithToken(os.Getenv("GITHUB_TOKEN"))
user, err := c.AuthenticatedUser()
assert.Equal(t, nil, err)
assert.NotEqual(t, "", user.Login)
}

Просмотреть файл

@ -1,20 +0,0 @@
package octokit
import (
"encoding/base64"
"encoding/json"
"fmt"
)
func hashAuth(u, p string) string {
var a = fmt.Sprintf("%s:%s", u, p)
return base64.StdEncoding.EncodeToString([]byte(a))
}
func jsonMarshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func jsonUnmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}