Skip to content

Commit

Permalink
chore: merge changes to master (#80)
Browse files Browse the repository at this point in the history
* Add boilerplate and version command (#50)

* Add basic boilerplate with version command

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add utility to dynamically read version info

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add test

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Autofix issues in 4 files

Resolved issues in the following files via DeepSource Autofix:
1. init.go
2. pkg/cmd/cmd.go
3. pkg/cmd/version/version.go
4. tests/report_workflow_test.go

* Terminate Execute error in caller function

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Update pkg/cmd/cmd.go

Co-authored-by: Vishnu Jayadevan <68588475+vishnu-deepsource@users.noreply.github.com>

* Minor refactoring for CLI auth (#54)

Signed-off-by: Vishnu Jayadevan <vishnu@deepsource.io>

* Fix grammatical error

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
Co-authored-by: Vishnu Jayadevan <68588475+vishnu-deepsource@users.noreply.github.com>
Co-authored-by: Sanket Saurav <sanket@deepsource.io>

* feat: cli authentication (#57)

* cli login implementation

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* minor improvements

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Refactor mutations and return error if login fails

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Remove unnecessary brace

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Remove unnecessary file

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Refactor api directory

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Implement config factory

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* [WIP] Implement token verification

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Use machinebox/graphql and get deviceCode query working

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Use machinebox for fetching jwt

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Remove commented code

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Re-authenticate confirmation prompt

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix reauthentication

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add logout command implementation

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix import error

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add confirmation before logout

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add refresh token query

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Implement auth refresh

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Implement auth status

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Implement repo status command

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Implement repo view command

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add comment

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Merge config generator code

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Move survey prompt functions to cmdutils package

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Integrate analyzer and transformer apis into config generator

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Remove .deepsource.toml file

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Integrate analyzer and transformer apis into config validator

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add queries for issue list

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix resolving owner

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix issue list

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Raise error when the limit is greater than 100

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Push fix

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Last minute fixes

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Change api endpoint

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Remove stale deepsource.toml file (#58)

* Fix retrieval of sentry DSN (#59)

* Remove legacy files and fetch sentry dsn from ldflag

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Declare sentry dsn variable

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Use goreleaser supplied version flag (#60)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add version ldflag to goreleaser config (#61)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Support darwin/arm64 and other arm architecture (#65)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add github action workflow for goreleaser (#63)

* Add github action workflow for goreleaser

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Use workdir to switch to directory containing main package

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Accepts all tags for release creation

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add goreleaser workflow to publish homebrew tap (#67)

* Add goreleaser workflow to publish homebrew tap

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add recipe name

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix the homebrew tap reponame

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Only target arm64 builds for now

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Supply github token for brew publishing

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Use deepsourcebot for pushing taps (#69)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Fix token retrieval (#70)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Some changes to test brew tap (#71)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Supply token to brew workflow

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Use different token for goreleaser

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Restore permissions

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Use same token for homebrew as well as goreleaser

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Use PAT as GITHUB_TOKEN

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

Use different token for homebrew

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* PLT-2365: Increase limit of uploads to 20 MB (#68)

* feat: DeepSource independent SDK package and code refactoring (#66)

* Move the api code to sdk directory

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Use deepsource sdk in config generation and validation workflows

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add global package and modify auth commands w.r.t sdk package

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix the changes in auth w.r.t using sdk

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Modify the repo and issues commands according to the sdk

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Minor fixes

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix setting the tokenExpiry in the config

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Minor fixes in auth related changes

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix setting the tokenExpiry (again)

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix errors while fetching analyzers and transformers list

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix the config validator path extraction

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix issues listing

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Autofix issues in 3 files

Resolved issues in the following files via DeepSource Autofix:
1. command/root.go
2. deepsource/client.go
3. deepsource/repo/queries/repo_status.go

* Implement args validation

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix DeepSource issues

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Rename cmdutils to utils

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Refactor SDK response types and improve usage of global variables

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Refactor issue listing command

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* More fixes related to issue listing and config workflows

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Fix repo status workflow

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* More refactoring in commands

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Autofix issues in 5 files

Resolved issues in the following files via DeepSource Autofix:
1. command/auth/status/status.go
2. command/config/generate/generic_input.go
3. command/repo/status/status.go
4. utils/fetch_remote.go
5. utils/prompt.go

* Rename repo to repository and improve config reading and loading

Signed-off-by: siddhant-deepsource <siddhant@deepsource.io>

* Add sentry to report error

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Delete internal/config package and add comments to SDK code

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* More refactoring of auth subcommands

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* More refactoring of config generate subcommand

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Address codereview for auth package

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Fetch analyzers and transformers data in a single utility

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Refactor remote selection logic and other code review suggested changes

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Fix errors

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Make the host configurable while authentication

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Use the host set by user in SDK client

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Fixes in setting SDK host and fix tokenexpiry timezone setting

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Improve refreshAuth response workflow and minor changes in utils

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Modify the retrieval of config and minor fixes

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* Remove unnecessary use of `fmt.Sprintf` (#73)

* Remove unnecessary use of `fmt.Sprintf`

* chore:fix DeepSource issue

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
Co-authored-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Remove unnecessary calls to fmt.Sprint (#74)

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* Omit comparison with boolean constant (#75)

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* Use plain channel send or receive (#76)

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* test: add unit tests to configvalidator package (#77)

* Add tests to config validator package

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* tests: improve tests and add test names

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: revert changes in unmarshalling toml

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: fix DeepSource issue

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Format code with gofmt (#79)

This commit fixes the style issues introduced in 9964fd1 according to the output
from gofmt.

Details: https://deepsource.io/gh/deepsourcelabs/cli/transform/c5e55d29-af89-4939-92a5-ee7ec1aab303/

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* feat(config-generation): Retrieve compulsory analyzer meta input based on API response (#72)

* Dynamic analyzer meta input based on API response

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Autofix issues in 1 file

Resolved issues in command/config/generate/analyzers_input.go via DeepSource Autofix

* chore: refactor code into separate functions

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: Fix DeepSource issues

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: Rename Field to FieldName

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: Add comments

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* Use gabs to parse analyzer meta JSON

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* refactor: move the data extraction logic to separate function

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: restore analyzer meta required data to nil before checking for next analyzer

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: address code review

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: make changes according to code review

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: create array with length 0 and append data

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>

* feat: support enterprise server (#78)

* chore: configure enterprise api endpoint

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: fix api endpoint

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: address code review

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: improve framing API client URL

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* feat: interactive login flag

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: remove dependency of sdk package on config package

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* refactor: rename ClientProperties as ClientOpts

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* refactor: rename AnaData and TrData

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: use analyzer shortcode for filtering analyzerMeta

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: cleanup analyzer and transformer API data population logic

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: add spaces

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: delete api folder and modify workflow

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: tidy go modules

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: tidy go modules

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: fix and modify legacy test

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: fix error

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* chore: address DeepSource issues

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: handle DSN parsing error

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

* fix: handle DSN parsing error at an earlier step as well

Signed-off-by: Siddhant N Trivedi <siddhant@deepsource.io>

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
Co-authored-by: Vishnu Jayadevan <68588475+vishnu-deepsource@users.noreply.github.com>
Co-authored-by: Sanket Saurav <sanket@deepsource.io>
Co-authored-by: Rahul Jha <68377773+rahul-deepsource@users.noreply.github.com>
  • Loading branch information
5 people authored Nov 2, 2021
1 parent 28e307f commit 59b84f9
Show file tree
Hide file tree
Showing 76 changed files with 4,843 additions and 316 deletions.
8 changes: 8 additions & 0 deletions .deepsource.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,11 @@ enabled = true
[[analyzers]]
name = "secrets"
enabled = true

[[analyzers]]
name = "test-coverage"
enabled = true

[[transformers]]
name = "gofmt"
enabled = true
36 changes: 36 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: goreleaser

on:
push:
tags:
- '*'

permissions:
contents: write

jobs:
release-cli:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: master

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.16

- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
distribution: goreleaser
version: latest
workdir: ./cmd/deepsource
args: release --rm-dist --config ../../goreleaser.yaml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HOMEBREW_TOKEN: ${{ secrets.DS_BOT_PAT }}
DEEPSOURCE_CLI_SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
vendor

# Executable
cli
cmd/deepsource/deepsource

# Goreleaser artifacts
dist

13 changes: 9 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
build:
GOOS=linux GOARCH=amd64 go build -tags static_all -o /tmp/deepsource .
cd cmd/deepsource && GOOS=linux GOARCH=amd64 go build -tags static_all -o /tmp/deepsource .

build_local:
cd cmd/deepsource && GOOS=darwin GOARCH=amd64 go build -tags static_all -o /tmp/deepsource .

test:
CGO_ENABLED=0 go test -cover -coverprofile=coverage.out -v ./tests/... -run TestReportKeyValueWorkflow
CGO_ENABLED=0 go test --cover -coverprofile=coverage.out -v ./tests/... -run TestReportKeyValueFileWorkflow
CGO_ENABLED=0 go test --cover -coverprofile=coverage.out -v ./command/report/tests/... -run TestReportKeyValueWorkflow
CGO_ENABLED=0 go test --cover -coverprofile=coverage.out -v ./command/report/tests/... -run TestReportKeyValueFileWorkflow
echo "\n====TESTING CONFIG VALIDATOR PACKAGE====\n"
cd configvalidator && go test -v . -count=1

test_setup:
mkdir -p ${CODE_PATH}
cd ${CODE_PATH} && ls -A1 | xargs rm -rf
git clone https://github.com/deepsourcelabs/cli ${CODE_PATH}
chmod +x /tmp/deepsource
cp ./tests/dummy/python_coverage.xml /tmp
cp ./command/report/tests/dummy/python_coverage.xml /tmp
43 changes: 43 additions & 0 deletions cmd/deepsource/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"log"
"os"

"github.com/deepsourcelabs/cli/command"
v "github.com/deepsourcelabs/cli/version"
"github.com/getsentry/sentry-go"
"github.com/pterm/pterm"
)

var (
// Version is the build version. This is set using ldflags -X
version = "development"

// Date is the build date. This is set using ldflags -X
Date = "YYYY-MM-DD" // YYYY-MM-DD

// DSN used for sentry
SentryDSN string
)

func main() {

log.SetFlags(log.LstdFlags | log.Lshortfile)

// Init sentry
err := sentry.Init(sentry.ClientOptions{
Dsn: SentryDSN,
})
if err != nil {
log.Println("Could not load sentry.")
}
v.SetBuildInfo(version, Date, "", "")

if err := command.Execute(); err != nil {
// TODO: Handle exit codes here
pterm.Error.Println(err)
sentry.CaptureException(err)
os.Exit(1)
}
}
26 changes: 26 additions & 0 deletions command/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package auth

import (
"github.com/spf13/cobra"

"github.com/deepsourcelabs/cli/command/auth/login"
"github.com/deepsourcelabs/cli/command/auth/logout"
"github.com/deepsourcelabs/cli/command/auth/refresh"
"github.com/deepsourcelabs/cli/command/auth/status"
)

// Options holds the metadata.
type Options struct{}

// NewCmdAuth handles the auth command which has various sub-commands like `login`, `logout`, `refresh` and `status`
func NewCmdAuth() *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Authenticate with DeepSource",
}
cmd.AddCommand(login.NewCmdLogin())
cmd.AddCommand(logout.NewCmdLogout())
cmd.AddCommand(refresh.NewCmdRefresh())
cmd.AddCommand(status.NewCmdStatus())
return cmd
}
116 changes: 116 additions & 0 deletions command/auth/login/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package login

import (
"fmt"

"github.com/deepsourcelabs/cli/config"
"github.com/deepsourcelabs/cli/utils"
"github.com/spf13/cobra"
)

var accountTypes = []string{"DeepSource (deepsource.io)", "DeepSource Enterprise"}

// LoginOptions hold the metadata related to login operation
type LoginOptions struct {
AuthTimedOut bool
TokenExpired bool
User string
HostName string
Interactive bool
}

// NewCmdLogin handles the login functionality for the CLI
func NewCmdLogin() *cobra.Command {

opts := LoginOptions{
AuthTimedOut: false,
TokenExpired: true,
User: "",
HostName: "",
}

cmd := &cobra.Command{
Use: "login",
Short: "Login to DeepSource using Command Line Interface",
Args: utils.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return opts.Run()
},
}

// --host, -h flag
cmd.Flags().StringVar(&opts.HostName, "hostname", "", "Authenticate with a specific DeepSource instance")
cmd.Flags().BoolVarP(&opts.Interactive, "interactive", "i", false, "Interactive login prompt for authenticating with DeepSource")
return cmd
}

// Run executes the auth command and starts the login flow if not already authenticated
func (opts *LoginOptions) Run() (err error) {

// Fetch config
cfg, _ := config.GetConfig()
opts.User = cfg.User
opts.TokenExpired = cfg.IsExpired()

// Login using the interactive mode
if opts.Interactive {
err = opts.handleInteractiveLogin()
if err != nil {
return err
}
}

// Checking if the user passed a hostname. If yes, storing it in the config
// Else using the default hostname (deepsource.io)
if opts.HostName != "" {
cfg.Host = opts.HostName
} else {
cfg.Host = config.DefaultHostName
}

// Before starting the login workflow, check here for two conditions:
// Condition 1 : If the token has expired, display a message about it and re-authenticate user
// Condition 2 : If the token has not expired,does the user want to re-authenticate?

// Checking for condition 1
if !opts.TokenExpired {
// The user is already logged in, confirm re-authentication.
msg := fmt.Sprintf("You're already logged into DeepSource as %s. Do you want to re-authenticate?", opts.User)
response, err := utils.ConfirmFromUser(msg, "")
if err != nil {
return fmt.Errorf("Error in fetching response. Please try again.")
}
// If the response is No, it implies that the user doesn't want to re-authenticate
// In this case, just exit
if !response {
return nil
}
}

// Condition 2
// `startLoginFlow` implements the authentication flow for the CLI
return opts.startLoginFlow(cfg)
}

func (opts *LoginOptions) handleInteractiveLogin() error {
// Prompt messages and help texts
loginPromptMessage := "Which account do you want to login into?"
loginPromptHelpText := "Select the type of account you want to authenticate"
hostPromptMessage := "Please enter the hostname:"
hostPromptHelpText := "The hostname of the DeepSource instance to authenticate with"

// Display prompt to user
loginType, err := utils.SelectFromOptions(loginPromptMessage, loginPromptHelpText, accountTypes)
if err != nil {
return err
}
// Prompt the user for hostname only in the case of on-premise
if loginType == "DeepSource Enterprise" {
opts.HostName, err = utils.GetSingleLineInput(hostPromptMessage, hostPromptHelpText)
if err != nil {
return err
}
}

return nil
}
117 changes: 117 additions & 0 deletions command/auth/login/login_flow.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package login

import (
"context"
"fmt"
"time"

"github.com/cli/browser"
"github.com/deepsourcelabs/cli/config"
"github.com/deepsourcelabs/cli/deepsource"
"github.com/deepsourcelabs/cli/deepsource/auth"
"github.com/fatih/color"
)

// Starts the login flow for the CLI
func (opts *LoginOptions) startLoginFlow(cfg *config.CLIConfig) error {
// Register the device and get a device code through the response
ctx := context.Background()
deviceRegistrationResponse, err := registerDevice(ctx)
if err != nil {
return err
}

// Print the user code and the permission to open browser at verificationURI
c := color.New(color.FgCyan, color.Bold)
c.Printf("Please copy your one-time code: %s\n", deviceRegistrationResponse.UserCode)
c.Printf("Press enter to open deepsource.io in your browser...")
fmt.Scanln()

// Having received the user code, open the browser at verificationURIComplete
err = browser.OpenURL(deviceRegistrationResponse.VerificationURIComplete)
if err != nil {
return err
}

// Fetch the JWT using the device registration resonse
var jwtData *auth.JWT
jwtData, opts.AuthTimedOut, err = fetchJWT(ctx, deviceRegistrationResponse)
if err != nil {
return err
}

// Check if it was a success poll or the Auth timed out
if opts.AuthTimedOut {
return fmt.Errorf("Authentication timed out")
}

// Storing the useful data for future reference and usage
// in a global config object (Cfg)
cfg.User = jwtData.Payload.Email
cfg.Token = jwtData.Token
cfg.RefreshToken = jwtData.Refreshtoken
cfg.RefreshTokenExpiresIn = time.Unix(jwtData.RefreshExpiresIn, 0)
cfg.SetTokenExpiry(jwtData.Payload.Exp)

// Having stored the data in the global Cfg object, write it into the config file present in the local filesystem
err = cfg.WriteFile()
if err != nil {
return fmt.Errorf("Error in writing authentication data to a file. Exiting...")
}
return nil
}

func registerDevice(ctx context.Context) (*auth.Device, error) {
// Fetching DeepSource client in order to interact with SDK
deepsource, err := deepsource.New(deepsource.ClientOpts{
Token: config.Cfg.Token,
HostName: config.Cfg.Host,
})
if err != nil {
return nil, err
}

// Send a mutation to register device and get the device code
res, err := deepsource.RegisterDevice(ctx)
if err != nil {
return nil, err
}
return res, nil
}

func fetchJWT(ctx context.Context, deviceRegistrationData *auth.Device) (*auth.JWT, bool, error) {
var jwtData *auth.JWT
var err error
authTimedOut := true

// Fetching DeepSource client in order to interact with SDK
deepsource, err := deepsource.New(deepsource.ClientOpts{
Token: config.Cfg.Token,
HostName: config.Cfg.Host,
})
if err != nil {
return nil, authTimedOut, err
}

// Keep polling the mutation at a certain interval till the expiry timeperiod
ticker := time.NewTicker(time.Duration(deviceRegistrationData.Interval) * time.Second)
pollStartTime := time.Now()

// Polling for fetching JWT
func() {
for range ticker.C {
jwtData, err = deepsource.Login(ctx, deviceRegistrationData.Code)
if err == nil {
authTimedOut = false
return
}
timeElapsed := time.Since(pollStartTime)
if timeElapsed >= time.Duration(deviceRegistrationData.ExpiresIn)*time.Second {
authTimedOut = true
return
}
}
}()

return jwtData, authTimedOut, nil
}
Loading

0 comments on commit 59b84f9

Please sign in to comment.