Skip to content

Commit

Permalink
Remove the deadcode (#283)(#282)
Browse files Browse the repository at this point in the history
Check the repository initialization when the program starts
Currently, the repository initialization is checked deeper in the
program. Instead, this change checks that when we open the database.


Closes #282
  • Loading branch information
draftcode authored May 16, 2024
1 parent 58284cf commit fa0bb12
Show file tree
Hide file tree
Showing 22 changed files with 56 additions and 312 deletions.
6 changes: 1 addition & 5 deletions cmd/av/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os"

"emperror.dev/errors"
"github.com/aviator-co/av/internal/actions"
"github.com/aviator-co/av/internal/gh"
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/utils/cleanup"
Expand Down Expand Up @@ -38,10 +37,7 @@ var fetchCmd = &cobra.Command{
tx.Abort()
})

info, ok := tx.Repository()
if !ok {
return actions.ErrRepoNotInitialized
}
info := tx.Repository()
branches := tx.AllBranches()

client, err := getGitHubClient()
Expand Down
34 changes: 26 additions & 8 deletions cmd/av/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"github.com/aviator-co/av/internal/meta"
"github.com/aviator-co/av/internal/meta/jsonfiledb"
"github.com/aviator-co/av/internal/meta/refmeta"
"github.com/sirupsen/logrus"
)

var cachedRepo *git.Repo
Expand Down Expand Up @@ -50,18 +49,37 @@ func getRepo() (*git.Repo, error) {
return cachedRepo, nil
}

var ErrRepoNotInitialized = errors.Sentinel(
"this repository is not initialized; please run `av init`",
)

func getDB(repo *git.Repo) (meta.DB, error) {
dbPath := filepath.Join(repo.AvDir(), "av.db")
existingStat, _ := os.Stat(dbPath)
db, err := jsonfiledb.OpenPath(dbPath)
db, exists, err := getOrCreateDB(repo)
if err != nil {
return nil, err
}
if existingStat == nil {
logrus.Debug("Initializing new av database")
if !exists {
return nil, ErrRepoNotInitialized
}
return db, nil
}

func getOrCreateDB(repo *git.Repo) (meta.DB, bool, error) {
dbPath := filepath.Join(repo.AvDir(), "av.db")
oldDBPathPath := filepath.Join(repo.AvDir(), "repo-metadata.json")
dbPathStat, _ := os.Stat(dbPath)
oldDBPathStat, _ := os.Stat(oldDBPathPath)

if dbPathStat == nil && oldDBPathStat != nil {
// Migrate old db to new db
db, exists, err := jsonfiledb.OpenPath(dbPath)
if err != nil {
return nil, false, err
}
if err := refmeta.Import(repo, db); err != nil {
return nil, errors.WrapIff(err, "failed to import ref metadata into av database")
return nil, false, errors.WrapIff(err, "failed to import ref metadata into av database")
}
return db, exists, nil
}
return db, nil
return jsonfiledb.OpenPath(dbPath)
}
2 changes: 1 addition & 1 deletion cmd/av/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var initCmd = &cobra.Command{
return err
}

db, err := getDB(repo)
db, _, err := getOrCreateDB(repo)
if err != nil {
return err
}
Expand Down
6 changes: 1 addition & 5 deletions cmd/av/pr_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/aviator-co/av/internal/utils/colors"
"github.com/sirupsen/logrus"

"github.com/aviator-co/av/internal/actions"
"github.com/aviator-co/av/internal/avgql"
"github.com/shurcooL/graphql"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -51,10 +50,7 @@ var prQueueCmd = &cobra.Command{
}

prNumber := branch.PullRequest.Number
repository, exists := tx.Repository()
if !exists {
return actions.ErrRepoNotInitialized
}
repository := tx.Repository()

var variables = map[string]interface{}{
"repoOwner": graphql.String(repository.Owner),
Expand Down
7 changes: 1 addition & 6 deletions cmd/av/pr_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"fmt"
"os"

"github.com/aviator-co/av/internal/actions"
"github.com/aviator-co/av/internal/avgql"
"github.com/aviator-co/av/internal/utils/colors"
"github.com/aviator-co/av/internal/utils/timeutils"
Expand Down Expand Up @@ -225,11 +224,7 @@ func getQueryVariables() (map[string]interface{}, error) {
}

prNumber := branch.PullRequest.Number
repository, exists := tx.Repository()
if !exists {
return nil, actions.ErrRepoNotInitialized
}

repository := tx.Repository()
var variables = map[string]interface{}{
"repoOwner": graphql.String(repository.Owner),
"repoName": graphql.String(repository.Name),
Expand Down
6 changes: 0 additions & 6 deletions internal/actions/errors.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
package actions

import "emperror.dev/errors"

var ErrRepoNotInitialized = errors.Sentinel(
"this repository is not initialized; please run `av init`",
)

// errExitSilently is an error type that indicates that program should exit
// without printing any additional information with the given exit code.
// This is meant for cases where the running commands wants to manage its own
Expand Down
15 changes: 3 additions & 12 deletions internal/actions/pr.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,7 @@ func CreatePullRequest(
logrus.Panicf("internal invariant error: CreatePullRequest called with empty branch name")
}

repoMeta, ok := tx.Repository()
if !ok {
return nil, ErrRepoNotInitialized
}
repoMeta := tx.Repository()
branchMeta, _ := tx.Branch(opts.BranchName)

var existingPR *gh.PullRequest
Expand Down Expand Up @@ -558,10 +555,7 @@ func UpdatePullRequestState(
tx meta.WriteTx,
branchName string,
) (*UpdatePullRequestResult, error) {
repoMeta, ok := tx.Repository()
if !ok {
return nil, ErrRepoNotInitialized
}
repoMeta := tx.Repository()
branch, _ := tx.Branch(branchName)

_, _ = fmt.Fprint(os.Stderr,
Expand Down Expand Up @@ -898,10 +892,7 @@ func UpdatePullRequestWithStack(
branchMeta, _ := tx.Branch(branchName)
logrus.WithField("branch", branchName).WithField("pr", branchMeta.PullRequest.ID).Debug("Updating pull requests with stack")

repoMeta, ok := tx.Repository()
if !ok {
return ErrRepoNotInitialized
}
repoMeta := tx.Repository()

stackToWrite, err := stackutils.BuildStackTreeForPullRequest(tx, branchName)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/actions/pr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ This information is embedded by the av CLI when creating PRs to track the status

type fakeReadTx map[string]meta.Branch

func (tx fakeReadTx) Repository() (meta.Repository, bool) {
return meta.Repository{}, false
func (tx fakeReadTx) Repository() meta.Repository {
return meta.Repository{}
}

func (tx fakeReadTx) Branch(name string) (meta.Branch, bool) {
Expand Down
15 changes: 0 additions & 15 deletions internal/actions/reorder.go

This file was deleted.

86 changes: 1 addition & 85 deletions internal/gh/client.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
package gh

import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"time"

"github.com/aviator-co/av/internal/config"

"emperror.dev/errors"
"github.com/aviator-co/av/internal/config"
"github.com/aviator-co/av/internal/utils/logutils"
"github.com/shurcooL/githubv4"
"github.com/sirupsen/logrus"
Expand All @@ -22,8 +18,6 @@ type Client struct {
gh *githubv4.Client
}

const githubCloudApiBaseUrl = "https://api.github.com"

// NewClient creates a new GitHub client.
// It takes configuration from the global config.Av.GitHub variable.
func NewClient(token string) (*Client, error) {
Expand Down Expand Up @@ -87,81 +81,3 @@ func (c *Client) mutate(
}()
return c.gh.Mutate(ctx, mutation, input, variables)
}

// restPost executes a POST request to the endpoint (e.g., /repos/:owner/:repo/pulls).
// It unmarshals the response into the given result type (unless it's nil).
func (c *Client) restPost(
ctx context.Context,
endpoint string,
body interface{},
result interface{},
) error {
if endpoint[0] != '/' {
logrus.WithField("endpoint", endpoint).Panicf("malformed REST endpoint")
}

startTime := time.Now()

// GitHub cloud and GHES have different API URLs.
// For cloud, it's `https://api.github.com/repos/...`.
// For GHES, it's `https://github.mycompany.com/api/v3/repos/...`.
var url string
if config.Av.GitHub.BaseURL == "" {
url = githubCloudApiBaseUrl + endpoint
} else {
url = config.Av.GitHub.BaseURL + "/api/v3" + endpoint
}

log := logrus.WithFields(logrus.Fields{
"url": url,
"body": logutils.Format("%#+v", body),
})
bodyJson, err := json.Marshal(body)
if err != nil {
return errors.Wrap(err, "failed to marshal request body to JSON")
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(bodyJson))
if err != nil {
return errors.Wrap(err, "failed to create request")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/vnd.github.v3+json")

log.Debug("executing GitHub API request...")
res, err := c.httpClient.Do(req)
log.Debugf("header: %#+v", req.Header)
if err != nil {
return errors.Wrap(err, "failed to make API request")
}
defer res.Body.Close()

resBody, err := io.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read response body")
}
log.WithField("elapsed", time.Since(startTime)).Debug("GitHub API request completed")

if res.StatusCode != http.StatusOK {
log.WithFields(logrus.Fields{
"status": res.StatusCode,
"body": string(resBody),
}).Debug("GitHub API request failed")
return errors.Errorf("GitHub API request for %s failed: %s", endpoint, res.Status)
}

// Don't try to unmarshal into nil, it will return an error.
// NOTE: Go is weird with nil ("nil" can be typed or untyped) and this will
// only capture an untyped nil (i.e., where the result parameter is given as
// a nil literal), but that should be fine.
if result == nil {
return nil
}

if err := json.Unmarshal(resBody, result); err != nil {
return errors.Wrap(err, "failed to unmarshal response body")
}
return nil
}
32 changes: 0 additions & 32 deletions internal/gh/pullrequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gh

import (
"context"
"fmt"
"strings"

"emperror.dev/errors"
Expand Down Expand Up @@ -214,37 +213,6 @@ func (c *Client) MarkPullRequestReadyForReview(
return &mutation.MarkPullRequestReadyForReview.PullRequest, nil
}

type AddIssueLabelInput struct {
// The owner of the GitHub repository.
Owner string
// The name of the GitHub repository.
Repo string
// The number of the issue or pull request to add a label to.
Number int64
// The names of the labels to add to the issue. This will implicitly create
// a label on the repository if the label doesn't already exist (this is the
// main reason we use the REST API for this call).
LabelNames []string
}

// AddIssueLabels adds labels to an issue (or pull request, since in GitHub
// a pull request is a superset of an issue).
func (c *Client) AddIssueLabels(ctx context.Context, input AddIssueLabelInput) error {
// Working with labels is still kind of a pain in the GitHub GraphQL API
// (you have to add labels by node id, not label name, and there's no way to
// create labels from the GraphQL API), so we just use v3/REST here.
req := struct {
Labels []string `json:"labels"`
}{
Labels: input.LabelNames,
}
endpoint := fmt.Sprintf("/repos/%s/%s/issues/%d", input.Owner, input.Repo, input.Number)
if err := c.restPost(ctx, endpoint, req, nil); err != nil {
return errors.Wrap(err, "failed to add labels")
}
return nil
}

type RepoPullRequestOpts struct {
Owner string
Repo string
Expand Down
16 changes: 0 additions & 16 deletions internal/git/err.go

This file was deleted.

7 changes: 5 additions & 2 deletions internal/git/gittest/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ func NewTempRepo(t *testing.T) *GitTestRepo {
// This repository obviously doesn't exist so tests still need to be careful
// not to invoke operations that would communicate with GitHub (e.g.,
// by using the `--no-fetch` and `--no-push` flags).
db := repo.OpenDB(t)
db, _, err := jsonfiledb.OpenPath(filepath.Join(repo.GitDir, "av", "av.db"))
if err != nil {
require.NoError(t, err, "failed to open database")
}
tx := db.WriteTx()
tx.SetRepository(meta.Repository{
ID: "R_nonexistent_",
Expand Down Expand Up @@ -129,7 +132,7 @@ func (r *GitTestRepo) Git(t *testing.T, args ...string) string {
}

func (r *GitTestRepo) OpenDB(t *testing.T) *jsonfiledb.DB {
db, err := jsonfiledb.OpenPath(filepath.Join(r.GitDir, "av", "av.db"))
db, _, err := jsonfiledb.OpenPath(filepath.Join(r.GitDir, "av", "av.db"))
require.NoError(t, err, "failed to open database")
return db
}
Expand Down
2 changes: 1 addition & 1 deletion internal/meta/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type DB interface {
// It presents a consistent view of the underlying database.
type ReadTx interface {
// Repository returns the repository information.
Repository() (Repository, bool)
Repository() Repository
// Branch returns the branch with the given name. If no such branch exists,
// the second return value is false.
Branch(name string) (Branch, bool)
Expand Down
Loading

0 comments on commit fa0bb12

Please sign in to comment.