<commit_before>package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

var (
	tokenFile   = flag.String("token_file", "", "File containing Auth Token.")
	owner       = flag.String("owner", "istio", "Github Owner or org.")
	repo        = flag.String("repo", "", "Github repo within the org.")
	base        = flag.String("base", "stable", "The base branch used for PR.")
	head        = flag.String("head", "master", "The head branch used for PR.")
	fastForward = flag.Bool("fast_forward", false, "Creates a PR updating Base to Head.")
	verify      = flag.Bool("verify", false, "Verifies PR on Base and push them if success.")
	GH          = newGhConst()
)

type ghConst struct {
	success string
	failure string
	pending string
	closed  string
	all     string
	commit  string
}

// Simple Github Helper
type helper struct {
	Owner  string
	Repo   string
	Base   string
	Head   string
	Client *github.Client
}

// Get token from tokenFile is set, otherwise is anonymous.
func getToken() (*http.Client, error) {
	if *tokenFile == "" {
		return nil, nil
	}
	b, err := ioutil.ReadFile(*tokenFile)
	if err != nil {
		return nil, err
	}
	token := strings.TrimSpace(string(b[:]))
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: string(token[:])})
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	return tc, nil
}

// Creates a new ghConst
func newGhConst() *ghConst {
	return &ghConst{
		success: "success",
		failure: "failure",
		pending: "pending",
		closed: "closed",
		all: "all",
		commit: "commit",
	}
}

// Creates a new Github Helper from provided
func newHelper() (*helper, error) {
	if tc, err := getToken(); err == nil {
		if *repo == "" {
			return nil, errors.New("repo flag must be set!")
		}
		client := github.NewClient(tc)
		return &helper{
			Owner:  *owner,
			Repo:   *repo,
			Base:   *base,
			Head:   *head,
			Client: client,
		}, nil
	} else {
		return nil, err
	}
}

// Creates a pull request from Base branch
func (h helper) createPullRequestToBase(commit *string) error {
	if commit == nil {
		return errors.New("commit cannot be nil.")
	}
	title := fmt.Sprintf(
		"Fast Forward %s to %s", h.Base, *commit)
	body := "Do not use the UI to merge this PR."
	req := github.NewPullRequest{
		Head:  &h.Head,
		Base:  &h.Base,
		Title: &title,
		Body: &body,
	}
	log.Printf("Creating a PR with Title: \"%s\"", title)
	if pr, _, err := h.Client.PullRequests.Create(h.Owner, h.Repo, &req); err == nil {
		log.Printf("Created new PR at %s", *pr.HTMLURL)
	} else {
		return err
	}
	return nil
}

// Gets the last commit from Head branch.
func (h helper) getLastCommitFromHead() (*string, error) {
	comp, _, err := h.Client.Repositories.CompareCommits(h.Owner, h.Repo, h.Head, h.Base)
	if err == nil {
		if *comp.BehindBy > 0 {
			commit := comp.BaseCommit.SHA
			log.Printf(
				"%s is %d commits ahead from %s, and HEAD commit is %s",
				h.Head, *comp.BehindBy, h.Base, *commit)
			return commit, nil
		}
	}
	return nil, err
}

// Fast forward Base branch to the last commit of Head branch.
func (h helper) fastForwardBase() error {
	commit, err := h.getLastCommitFromHead()
	if err != nil {
		return err
	}
	if commit != nil {
		options := github.PullRequestListOptions{
			Head:  h.Head,
			Base:  h.Base,
			State: GH.all,
		}

		prs, _, err := h.Client.PullRequests.List(h.Owner, h.Repo, &options)
		if err == nil {
			for _, pr := range prs {
				if strings.Contains(*pr.Title, *commit) {
					log.Printf("A PR already exist for %s", *commit)
					return nil
				}
			}
		}
		return h.createPullRequestToBase(commit)
	}
	log.Printf("Branches %s and %s as in sync.", h.Base, h.Head)
	return nil
}

// Close an existing PR
func (h helper) closePullRequest(pr *github.PullRequest) error {
	log.Printf("Closing PR %d", *pr.ID)
	*pr.State = GH.closed
	_, _, err := h.Client.PullRequests.Edit(h.Owner, h.Repo, *pr.ID, pr)
	return err
}

// Create an annotated stable tag from the given commit.<commit_msg>Updates wording for Automated PR to stable (#41)<commit_after>package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"

	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

var (
	tokenFile   = flag.String("token_file", "", "File containing Auth Token.")
	owner       = flag.String("owner", "istio", "Github Owner or org.")
	repo        = flag.String("repo", "", "Github repo within the org.")
	base        = flag.String("base", "stable", "The base branch used for PR.")
	head        = flag.String("head", "master", "The head branch used for PR.")
	fastForward = flag.Bool("fast_forward", false, "Creates a PR updating Base to Head.")
	verify      = flag.Bool("verify", false, "Verifies PR on Base and push them if success.")
	GH          = newGhConst()
)

type ghConst struct {
	success string
	failure string
	pending string
	closed  string
	all     string
	commit  string
}

// Simple Github Helper
type helper struct {
	Owner  string
	Repo   string
	Base   string
	Head   string
	Client *github.Client
}

// Get token from tokenFile is set, otherwise is anonymous.
func getToken() (*http.Client, error) {
	if *tokenFile == "" {
		return nil, nil
	}
	b, err := ioutil.ReadFile(*tokenFile)
	if err != nil {
		return nil, err
	}
	token := strings.TrimSpace(string(b[:]))
	ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: string(token[:])})
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	return tc, nil
}

// Creates a new ghConst
func newGhConst() *ghConst {
	return &ghConst{
		success: "success",
		failure: "failure",
		pending: "pending",
		closed: "closed",
		all: "all",
		commit: "commit",
	}
}

// Creates a new Github Helper from provided
func newHelper() (*helper, error) {
	if tc, err := getToken(); err == nil {
		if *repo == "" {
			return nil, errors.New("repo flag must be set!")
		}
		client := github.NewClient(tc)
		return &helper{
			Owner:  *owner,
			Repo:   *repo,
			Base:   *base,
			Head:   *head,
			Client: client,
		}, nil
	} else {
		return nil, err
	}
}

// Creates a pull request from Base branch
func (h helper) createPullRequestToBase(commit *string) error {
	if commit == nil {
		return errors.New("commit cannot be nil.")
	}
	title := fmt.Sprintf(
		"DO NOT MERGE! Fast Forward %s to %s.", h.Base, *commit)
	body := "This PR will be merged automatically once checks are successful."
	req := github.NewPullRequest{
		Head:  &h.Head,
		Base:  &h.Base,
		Title: &title,
		Body: &body,
	}
	log.Printf("Creating a PR with Title: \"%s\"", title)
	if pr, _, err := h.Client.PullRequests.Create(h.Owner, h.Repo, &req); err == nil {
		log.Printf("Created new PR at %s", *pr.HTMLURL)
	} else {
		return err
	}
	return nil
}

// Gets the last commit from Head branch.
func (h helper) getLastCommitFromHead() (*string, error) {
	comp, _, err := h.Client.Repositories.CompareCommits(h.Owner, h.Repo, h.Head, h.Base)
	if err == nil {
		if *comp.BehindBy > 0 {
			commit := comp.BaseCommit.SHA
			log.Printf(
				"%s is %d commits ahead from %s, and HEAD commit is %s",
				h.Head, *comp.BehindBy, h.Base, *commit)
			return commit, nil
		}
	}
	return nil, err
}

// Fast forward Base branch to the last commit of Head branch.
func (h helper) fastForwardBase() error {
	commit, err := h.getLastCommitFromHead()
	if err != nil {
		return err
	}
	if commit != nil {
		options := github.PullRequestListOptions{
			Head:  h.Head,
			Base:  h.Base,
			State: GH.all,
		}

		prs, _, err := h.Client.PullRequests.List(h.Owner, h.Repo, &options)
		if err == nil {
			for _, pr := range prs {
				if strings.Contains(*pr.Title, *commit) {
					log.Printf("A PR already exist for %s", *commit)
					return nil
				}
			}
		}
		return h.createPullRequestToBase(commit)
	}
	log.Printf("Branches %s and %s are in sync.", h.Base, h.Head)
	return nil
}

// Close an existing PR
func (h helper) closePullRequest(pr *github.PullRequest) error {
	log.Printf("Closing PR %d", *pr.ID)
	*pr.State = GH.closed
	_, _, err := h.Client.PullRequests.Edit(h.Owner, h.Repo, *pr.ID, pr)
	return err
}

// Create an annotated stable tag from the given commit.
{'fraction_non_alphanumeric': 0.1453001968503937, 'fraction_numerical': 0.0017224409448818897, 'mean_word_length': 3.262716308337703, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1035481', 'n_tokens_mistral': 3081, 'n_tokens_neox': 2895, 'n_words': 892}