Example #1
0
func main() {
	flag.Parse()

	token := os.Getenv("GITHUB_AUTH_TOKEN")
	if token == "" {
		println("!!! No OAuth token.  Some tests won't run. !!!\n")
		client = github.NewClient(nil)
	} else {
		t := &oauth.Transport{
			Token: &oauth.Token{AccessToken: token},
		}
		client = github.NewClient(t.Client())
		auth = true
	}

	for _, tt := range []struct {
		url string
		typ interface{}
	}{
		//{"rate_limit", &github.RateLimits{}},
		{"users/octocat", &github.User{}},
		{"user", &github.User{}},
		{"users/willnorris/keys", &[]github.Key{}},
		{"orgs/google-test", &github.Organization{}},
		{"repos/google/go-github", &github.Repository{}},
		{"/gists/9257657", &github.Gist{}},
	} {
		err := testType(tt.url, tt.typ)
		if err != nil {
			fmt.Printf("error: %v\n", err)
		}
	}
}
Example #2
0
// Client returns  clients for accessing github.
func (c *Config) Clients() (*Clients, error) {
	orgClient := github.NewClient(
		oauth2.NewClient(
			oauth2.NoContext,
			oauth2.StaticTokenSource(
				&oauth2.Token{
					AccessToken: c.OrganizationKey,
				},
			),
		),
	)
	userClient := github.NewClient(
		oauth2.NewClient(
			oauth2.NoContext,
			oauth2.StaticTokenSource(
				&oauth2.Token{
					AccessToken: c.UserKey,
				},
			),
		),
	)
	return &Clients{
		OrgClient:  orgClient,
		UserClient: userClient,
	}, nil

}
func (grp githubRegistryProvider) createGithubClient(credentialName string) (*http.Client, *github.Client, error) {
	if credentialName == "" {
		return http.DefaultClient, github.NewClient(nil), nil
	}
	c, err := grp.cp.GetCredential(credentialName)

	if err != nil {
		log.Printf("Failed to fetch credential %s: %v", credentialName, err)
		log.Print("Trying to use unauthenticated client")
		return http.DefaultClient, github.NewClient(nil), nil
	}

	if c != nil {
		if c.APIToken != "" {
			ts := oauth2.StaticTokenSource(
				&oauth2.Token{AccessToken: string(c.APIToken)},
			)
			tc := oauth2.NewClient(oauth2.NoContext, ts)
			return tc, github.NewClient(tc), nil
		}
		if c.BasicAuth.Username != "" && c.BasicAuth.Password != "" {
			tp := github.BasicAuthTransport{
				Username: c.BasicAuth.Username,
				Password: c.BasicAuth.Password,
			}
			return tp.Client(), github.NewClient(tp.Client()), nil
		}

	}
	return nil, nil, fmt.Errorf("No suitable credential found for %s", credentialName)

}
Example #4
0
// Before gets called before any action on every execution.
func Before() cli.BeforeFunc {
	return func(c *cli.Context) error {
		logrus.SetOutput(os.Stdout)
		logrus.SetLevel(logrus.DebugLevel)

		if c.BoolT("update") {
			Update()
		}

		if config.Token != "" {
			config.Client = github.NewClient(
				oauth2.NewClient(
					oauth2.NoContext,
					oauth2.StaticTokenSource(
						&oauth2.Token{
							AccessToken: config.Token,
						},
					),
				),
			)
		} else {
			config.Client = github.NewClient(nil)
		}

		return nil
	}
}
// TestAsciiCatRespRecorder uses net/http/httptest ResponseRecorder
// (https://godoc.org/net/http/httptest#ResponseRecorder) to test the AsciiCat
// handler directly.
//
// ResponseRecorder is useful for direct testing of handlers,
// but doesn't provide a complete solution when the router itself handles complex logic.
// See TestGetIssuesTestSrv in get_issues_test.go for an example of testing complex router logic
func TestAsciiCatRespRecorder(t *testing.T) {
	// create a ResponseRecorder, which implements http.ResponseWriter. it will be passed into the handler
	w := httptest.NewRecorder()
	// create a fake request to be passed into the handler
	r, err := http.NewRequest("GET", "/ascii_cat", nil)
	if err != nil {
		t.Fatalf("error constructing test HTTP request [%s]", err)
	}
	// create and execute the handler, passing the ResponseRecorder and fake request
	handler := AsciiCat(github.NewClient(nil))
	handler.ServeHTTP(w, r)

	// now that the request has been 'served' by the handler, check the response that it would
	// have returned
	if w.Code != http.StatusOK {
		t.Fatalf("expected code %d, got %d", http.StatusOK, w.Code)
	}
	bodyStr := string(w.Body.Bytes())
	if len(bodyStr) <= 0 {
		t.Fatalf("expected non-empty response body")
	}
	ghClient := github.NewClient(nil)
	expectedCat, _, err := ghClient.Octocat("Hello, Go In 5 Minutes Viewer!")
	if err != nil {
		t.Fatalf("error getting expected octocat string [%s]", err)
	}
	if bodyStr != expectedCat {
		t.Fatalf("got unexpected octocat string [%s]", bodyStr)
	}
	// ResponseRecorder records more useful data about the response.
	// see http://godoc.org/net/http/httptest#ResponseRecorder for details
}
Example #6
0
func downloadReleaseFromGithub(r repo, artifact string, alias string) {
	client := github.NewClient(nil)

	config, err := loadConfig()
	if err != nil {
		DieWithError(err, "Could not load user config")
	}

	if token, ok := config.Config["token"]; ok {
		log.Debug("Using Github token from config.")
		// if the user has a token stored, use it
		ts := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: token},
		)
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		client = github.NewClient(tc)
	} else {
		log.Debug("No Github token found in config. Add it with `mup config` if you need it")
	}

	// with a provided token, this will also get repos for the authenticated user
	// TODO: support pagination
	releases, resp, err := client.Repositories.ListReleases(r.Owner, r.Repo, nil)
	if resp.StatusCode == 404 {
		Die("Could not find repository %s/%s. Maybe it doesn't exist, or you need to add your token for μpdater to have access.", r.Owner, r.Repo)
	} else if err != nil {
		DieWithError(err, "Error reaching Github")
	}

	updateFromGithubReleases(client, r, releases, "", artifact, alias)
}
Example #7
0
func MakeClient(token string) *github.Client {
	if len(token) > 0 {
		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		return github.NewClient(tc)
	}
	return github.NewClient(nil)
}
Example #8
0
func makeGithubClient(token string) *github.Client {
	if token != "" {
		t := &oauth.Transport{
			Token: &oauth.Token{AccessToken: token},
		}
		return github.NewClient(t.Client())
	}
	return github.NewClient(nil)
}
Example #9
0
func buildGithubClient() *github.Client {
	if token != "" {
		tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
		httpClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
		return github.NewClient(httpClient)
	}

	return github.NewClient(nil)
}
Example #10
0
func newGithubClient() githubClient {
	gt := os.Getenv(gitHubAPITokenEnvVar)
	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: gt},
	}
	github.NewClient(t.Client())
	c := github.NewClient(t.Client())
	return githubClientProd{
		org:  c.Organizations,
		repo: c.Repositories,
	}
}
Example #11
0
func newClient() *github.Client {
	githubToken := os.Getenv("GITHUB_TOKEN")

	if githubToken != "" {
		oauthTransport := &oauth.Transport{
			Token: &oauth.Token{AccessToken: githubToken},
		}
		return github.NewClient(oauthTransport.Client())
	}

	return github.NewClient(nil)
}
Example #12
0
func getGithubClient(db *gorp.DbMap) *github.Client {
	token := getConfig(db).GithubToken
	if token != "" {
		ts := &tokenSource{
			&oauth2.Token{AccessToken: token},
		}
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		return github.NewClient(tc)
	} else {
		return github.NewClient(nil)
	}
}
func GetGithubClient(owner string, repository string) (*github.Client, error) {
	accessToken, getTokenError := loadAccessToken(owner, repository)
	if getTokenError != nil {

		return github.NewClient(nil), getTokenError
	}
	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: accessToken},
	}

	return github.NewClient(t.Client()), nil
}
Example #14
0
func newClient(accessToken string) (client *github.Client) {
	if accessToken == "" {
		client = github.NewClient(nil)
	} else {
		transport := &oauth.Transport{
			Token: &oauth.Token{AccessToken: accessToken},
		}
		client = github.NewClient(transport.Client())
	}

	return
}
Example #15
0
func init() {
	token := os.Getenv("GITHUB_AUTH_TOKEN")
	if token == "" {
		print("!!! No OAuth token.  Some tests won't run. !!!\n\n")
		client = github.NewClient(nil)
	} else {
		tc := oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: token},
		))
		client = github.NewClient(tc)
		auth = true
	}
}
Example #16
0
// CreateClientConnection is a helper function for creating a connection to the
// Github API based on whether or not an auth token is supplied.
func CreateClientConnection() *github.Client {
	var client *github.Client
	config := new(Configuration)
	if config.Github.Token == "empty" {
		client = github.NewClient(nil)
		return client
	} else {
		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: TOKEN})
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		client = github.NewClient(tc)
		return client
	}
}
Example #17
0
func init() {
	token := os.Getenv("GITHUB_AUTH_TOKEN")
	if token == "" {
		print("!!! No OAuth token.  Some tests won't run. !!!\n\n")
		client = github.NewClient(nil)
	} else {
		t := &oauth.Transport{
			Token: &oauth.Token{AccessToken: token},
		}
		client = github.NewClient(t.Client())
		auth = true
	}
}
Example #18
0
func NewIssueAPI() *IssueAPI {
	token, err := queryToken("Github_Token", "vampirewalk")
	if err != nil {
		client := github.NewClient(nil)
		return &IssueAPI{Client: client}
	}

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := github.NewClient(tc)

	return &IssueAPI{Client: client}
}
Example #19
0
func addonZip(ctx *gin.Context, user string, repository string, lastReleaseTag string) {
	release := getReleaseByTag(user, repository, lastReleaseTag)
	// if there a release with an asset that matches a addon zip, use it
	if release != nil {
		client := github.NewClient(nil)
		assets, _, _ := client.Repositories.ListReleaseAssets(user, repository, *release.ID, nil)
		platformStruct := xbmc.GetPlatform()
		platform := platformStruct.OS + "_" + platformStruct.Arch
		var assetAllPlatforms string
		for _, asset := range assets {
			if strings.HasSuffix(*asset.Name, platform+".zip") {
				assetPlatform := *asset.BrowserDownloadURL
				log.Info("Using release asset for " + platform + ": " + assetPlatform)
				ctx.Redirect(302, assetPlatform)
				return
			}
			if addonZipRE.MatchString(*asset.Name) {
				assetAllPlatforms = *asset.BrowserDownloadURL
				log.Info("Found all platforms release asset: " + assetAllPlatforms)
				continue
			}
		}
		if assetAllPlatforms != "" {
			log.Info("Using release asset for all platforms: " + assetAllPlatforms)
			ctx.Redirect(302, assetAllPlatforms)
			return
		}
	}
	ctx.AbortWithError(404, errors.New("Release asset not found."))
}
Example #20
0
// cmdShowLabels prints the labels for a project for easy inclusion
// in the config
func cmdShowLabels(opts *Options, project string) error {
	tc := AuthClient(opts)
	client := github.NewClient(tc)

	owner, repo, err := ownerRepo(project)
	if err != nil {
		return err
	}

	labels, _, err := client.Issues.ListLabels(owner, repo, &github.ListOptions{})
	if err != nil {
		return err
	}

	out := []Label{}
	for _, label := range labels {
		out = append(out, Label{*label.Name, *label.Color})
	}

	d, err := yaml.Marshal(out)
	if err != nil {
		return err
	}
	fmt.Printf("%s", d)
	return nil
}
Example #21
0
// NewPolymerCrawler returns a new PolymerCrawler.
func NewPolymerCrawler(accessToken string) *PolymerCrawler {
	if accessToken == "" {
		log.Println("Github AccessToken is empty.")
		return &PolymerCrawler{
			client: github.NewClient(nil),
		}
	}

	t := &oauth.Transport{
		Token: &oauth.Token{AccessToken: GITHUB_TOKEN},
	}

	return &PolymerCrawler{
		client: github.NewClient(t.Client()),
	}
}
Example #22
0
// Latest returns information on the latest Helm version.
func Latest() (*github.RepositoryRelease, error) {
	if RepoService == nil {
		RepoService = github.NewClient(nil).Repositories
	}
	rel, _, err := RepoService.GetLatestRelease(Owner, Project)
	return rel, err
}
Example #23
0
func init() {
	flag.BoolVar(&isVerbose, "v", false, "")
	flag.BoolVar(&isVerbose, "verbose", false, "")
	flag.Usage = func() {
		fmt.Println(path.Base(os.Args[0]), "- Print DNSPOD table changes")
		fmt.Println()
		fmt.Println("Options:")
		fmt.Println("    -v, --verbose    Show more output")
		fmt.Println()
		fmt.Println("Source: https://github.com/caiguanhao/dnspodd")
	}
	flag.Parse()

	githubClient = github.NewClient(oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: string(GITHUB_TOKEN)},
	)))

	if PROXY_URL != "" {
		proxy, err := url.Parse(PROXY_URL)
		if err == nil {
			http.DefaultTransport = &http.Transport{
				Proxy: func(req *http.Request) (*url.URL, error) {
					if req.URL.Host == "api.github.com" {
						return proxy, nil
					}
					return nil, nil
				},
			}
		}
	}
}
Example #24
0
//RegisterResult registers the supplied result
func (githubClient *GitHubClient) RegisterResult(result Result) error {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: githubClient.Token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := github.NewClient(tc)

	if githubClient.BaseUrl != nil {
		client.BaseURL = githubClient.BaseUrl
	}

	log.Info("Submitting result")
	repositories := client.Repositories
	status, _, err := repositories.CreateStatus(
		githubClient.From,
		githubClient.Repo,
		result.SHA,
		&github.RepoStatus{
			State:       github.String(result.State),
			TargetURL:   github.String(result.Url),
			Description: github.String(result.Message),
			Context:     github.String("continuous-integraion/walter"),
		})
	log.Infof("Submit status: %s", status)
	if err != nil {
		log.Errorf("Failed to register result: %s", err)
	}
	return err
}
Example #25
0
func main() {

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: GITHUB_TOKEN},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	githubClient := github.NewClient(tc)
	release, err := githubClient.Repositories.GetLatestRelease("FRC1360", "Stronghold2016")

	if err != nil {
		panic(err)
	}

	if downloadFromUrl(release.ZipballURL) {

		message := "Code Release Downloaded: " + release.AssetsURL + "\nSaved to Backup Server - Running copy cron job now."
		api := slack.New(SLACK_TOKEN)
		channel, err := api.FindChannelByName(SLACK_CHANNEL)
		if err != nil {
			panic(err)
		}
		err = api.ChatPostMessage(channel.Id, message, nil)
		if err != nil {
			panic(err)
		}
	}

}
// NewGithubRegistry creates a Registry that can be used to talk to github.
func NewGithubPackageRegistry(owner, repository string) *GithubPackageRegistry {
	return &GithubPackageRegistry{
		owner:      owner,
		repository: repository,
		client:     github.NewClient(nil),
	}
}
Example #27
0
func main() {
	ghClient := github.NewClient(nil)
	mux := handlers.NewRouter(ghClient)

	log.Println("serving on port 8080")
	http.ListenAndServe(":8080", mux)
}
Example #28
0
func startCrawler(user string, accessToken string, quit chan struct{}, wg *sync.WaitGroup) {
	authTransport := &oauth2.Transport{
		Source: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken}),
	}
	cacheTransport := &Transport{Transport: authTransport, lastEtag: ""}
	httpClient := &http.Client{Transport: cacheTransport}
	client := github.NewClient(httpClient)

L:
	for {
		select {
		case <-quit:
			// TODO: cleanup
			fmt.Fprintln(os.Stdout, "Clean up")
			wg.Done()
			break L
		default:
			fmt.Fprintln(os.Stdout, "Call API")
			events, resp, err := client.Activity.ListEventsPerformedByUser(user, false, &github.ListOptions{PerPage: 300})
			if err != nil && resp.StatusCode != 304 {
				fmt.Fprintln(os.Stderr, err)
			}
			fmt.Fprintln(os.Stdout, resp.StatusCode)
			fmt.Fprintln(os.Stdout, events)
		}
		time.Sleep(3 * time.Second)
	}
}
Example #29
0
func (gh *Client) Authenticate(username string, password string) error {
	var token []byte
	gh.User = &User{
		Login:    username,
		Password: password,
	}

	// conf := &oauth2.Config{
	// 	Endpoint: githubOauth2.Endpoint,
	// }
	gh.Store.Get(s.ConfigBucket, "gh_token", &token)
	if len(token) == 0 {
		var err error
		token, err = gh.createToken()
		if err != nil {
			return errwrap.Wrapf("[Github] Authentication error: %v", err)
		}
	}

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{
			AccessToken: string(token),
		},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	gh.client = github.NewClient(tc)
	user, _, _ := gh.client.Users.Get("")
	gh.User.Login = *user.Login
	gh.User.issues = map[string][]*github.Issue{}
	gh.User.Password = ""
	gh.Fetch()
	return nil
}
Example #30
0
func getClient(token string) *github.Client {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	return github.NewClient(tc)
}