Skip to content

Commit eba39bb

Browse files
Clean up comments, refactor auth status, add tests
- Remove redundant godoc and inline comments across codebase - Extract auth status into smaller helper methods - Add BackfillUser and default host logic to config manager - Add tests for login edge cases, auth status, and config manager
1 parent 7ed50cf commit eba39bb

46 files changed

Lines changed: 396 additions & 344 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

buildinfo/version.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ type BuildInfo struct {
2323
BuildMode string `json:"build_mode,omitempty"`
2424
}
2525

26-
// SetBuildInfo sets the build info as a package global.
2726
func SetBuildInfo(version, dateStr, buildMode string) {
2827
date, _ := time.Parse("2006-01-02T15:04:05Z", dateStr)
2928

@@ -34,7 +33,6 @@ func SetBuildInfo(version, dateStr, buildMode string) {
3433
}
3534
}
3635

37-
// GetBuildInfo returns the package global `buildInfo`
3836
func GetBuildInfo() *BuildInfo {
3937
return buildInfo
4038
}

cmd/deepsource/main.go

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,9 @@ import (
1616
)
1717

1818
var (
19-
// Version is the build version. This is set using ldflags -X
20-
version = "development"
21-
22-
// Date is the build date. This is set using ldflags -X
23-
Date = "YYYY-MM-DD" // YYYY-MM-DD
24-
25-
// DSN used for sentry
19+
version = "development"
20+
Date = "YYYY-MM-DD"
2621
SentryDSN string
27-
28-
// buildMode is "dev" or "prod" (default). Set via ldflags -X.
2922
buildMode string
3023
)
3124

command/auth/auth.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@ import (
88
"github.com/deepsourcelabs/cli/command/auth/status"
99
)
1010

11-
// Options holds the metadata.
1211
type Options struct{}
1312

14-
// NewCmdAuth handles the auth command which has various sub-commands like `login`, `logout` and `status`
1513
func NewCmdAuth() *cobra.Command {
1614
cmd := &cobra.Command{
1715
Use: "auth",

command/auth/login/login.go

Lines changed: 6 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import (
1717

1818
var accountTypes = []string{"DeepSource (deepsource.com)", "Enterprise Server"}
1919

20-
// LoginOptions hold the metadata related to login operation
2120
type LoginOptions struct {
2221
AuthTimedOut bool
2322
TokenExpired bool
@@ -28,12 +27,10 @@ type LoginOptions struct {
2827
deps *cmddeps.Deps
2928
}
3029

31-
// NewCmdLogin handles the login functionality for the CLI
3230
func NewCmdLogin() *cobra.Command {
3331
return NewCmdLoginWithDeps(nil)
3432
}
3533

36-
// NewCmdLoginWithDeps creates the login command with injectable dependencies.
3734
func NewCmdLoginWithDeps(deps *cmddeps.Deps) *cobra.Command {
3835
doc := heredoc.Docf(`
3936
Log in to DeepSource using the CLI.
@@ -66,7 +63,6 @@ func NewCmdLoginWithDeps(deps *cmddeps.Deps) *cobra.Command {
6663
},
6764
}
6865

69-
// --host flag (--hostname kept as deprecated alias)
7066
cmd.Flags().StringVar(&opts.HostName, "host", "", "Authenticate with a specific DeepSource instance")
7167
cmd.Flags().StringVar(&opts.HostName, "hostname", "", "Authenticate with a specific DeepSource instance")
7268
_ = cmd.Flags().MarkDeprecated("hostname", "use --host instead")
@@ -76,7 +72,6 @@ func NewCmdLoginWithDeps(deps *cmddeps.Deps) *cobra.Command {
7672
return cmd
7773
}
7874

79-
// Run executes the auth command and starts the login flow if not already authenticated
8075
func (opts *LoginOptions) Run() (err error) {
8176
var cfgMgr *config.Manager
8277
if opts.deps != nil && opts.deps.ConfigMgr != nil {
@@ -92,51 +87,33 @@ func (opts *LoginOptions) Run() (err error) {
9287
} else {
9388
svc = authsvc.NewService(cfgMgr)
9489
}
95-
// Fetch config (errors are non-fatal: a zero config just means "not logged in")
9690
cfg, err := svc.LoadConfig()
9791
if err != nil {
98-
cfg = &config.CLIConfig{}
92+
cfg = config.NewDefault()
9993
}
10094
opts.User = cfg.User
10195
opts.TokenExpired = cfg.IsExpired()
10296

103-
// Default host so that verifyTokenWithServer can reach the server
104-
// even when no config file exists yet.
105-
if cfg.Host == "" {
106-
cfg.Host = config.DefaultHostName
107-
}
97+
opts.verifyTokenWithServer(cfg, svc)
10898

109-
// If local says valid, verify against the server
110-
opts.verifyTokenWithServer(cfg, cfgMgr)
111-
112-
// Login using the interactive mode
11399
if opts.Interactive {
114100
err = opts.handleInteractiveLogin()
115101
if err != nil {
116102
return err
117103
}
118104
}
119105

120-
// Checking if the user passed a hostname. If yes, storing it in the config
121-
// Else using the default hostname (deepsource.com)
122106
if opts.HostName != "" {
123107
cfg.Host = opts.HostName
124108
} else {
125109
cfg.Host = config.DefaultHostName
126110
}
127111

128-
// If PAT is passed, start the login flow through PAT (skip interactive prompts)
129112
if opts.PAT != "" {
130113
return opts.startPATLoginFlow(svc, cfg, opts.PAT)
131114
}
132115

133-
// Before starting the login workflow, check here for two conditions:
134-
// Condition 1 : If the token has expired, display a message about it and re-authenticate user
135-
// Condition 2 : If the token has not expired,does the user want to re-authenticate?
136-
137-
// Checking for condition 1
138116
if !opts.TokenExpired {
139-
// The user is already logged in, confirm re-authentication.
140117
var msg string
141118
if opts.User != "" {
142119
msg = fmt.Sprintf("You're already logged into DeepSource as %s. Do you want to re-authenticate?", opts.User)
@@ -147,31 +124,19 @@ func (opts *LoginOptions) Run() (err error) {
147124
if err != nil {
148125
return fmt.Errorf("Error in fetching response. Please try again.")
149126
}
150-
// If the response is No, it implies that the user doesn't want to re-authenticate
151-
// In this case, just exit
152127
if !response {
153128
return nil
154129
}
155130
}
156131

157-
// Condition 2
158-
// `startLoginFlow` implements the authentication flow for the CLI
159132
return opts.startLoginFlow(svc, cfg)
160133
}
161134

162-
func (opts *LoginOptions) verifyTokenWithServer(cfg *config.CLIConfig, cfgMgr *config.Manager) {
163-
if opts.TokenExpired || cfg.Token == "" || cfg.Host == "" {
164-
return
165-
}
166-
client, err := deepsource.New(deepsource.ClientOpts{
167-
Token: cfg.Token,
168-
HostName: cfg.Host,
169-
OnTokenRefreshed: cfgMgr.TokenRefreshCallback(),
170-
})
171-
if err != nil {
135+
func (opts *LoginOptions) verifyTokenWithServer(cfg *config.CLIConfig, svc *authsvc.Service) {
136+
if opts.TokenExpired || cfg.Token == "" {
172137
return
173138
}
174-
viewer, err := client.GetViewer(context.Background())
139+
viewer, err := svc.GetViewer(context.Background(), cfg)
175140
if err != nil {
176141
opts.TokenExpired = true
177142
return
@@ -180,23 +145,20 @@ func (opts *LoginOptions) verifyTokenWithServer(cfg *config.CLIConfig, cfgMgr *c
180145
if cfg.User == "" && viewer.Email != "" {
181146
cfg.User = viewer.Email
182147
opts.User = viewer.Email
183-
_ = cfgMgr.Write(cfg)
148+
_ = svc.SaveConfig(cfg)
184149
}
185150
}
186151

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

194-
// Display prompt to user
195158
loginType, err := prompt.SelectFromOptions(loginPromptMessage, loginPromptHelpText, accountTypes)
196159
if err != nil {
197160
return err
198161
}
199-
// Prompt the user for hostname only in the case of on-premise
200162
if loginType == "Enterprise Server" {
201163
opts.HostName, err = prompt.GetSingleLineInput(hostPromptMessage, hostPromptHelpText)
202164
if err != nil {

command/auth/login/login_flow.go

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,13 @@ import (
1515
"github.com/fatih/color"
1616
)
1717

18-
// Starts the login flow for the CLI
1918
func (opts *LoginOptions) startLoginFlow(svc *authsvc.Service, cfg *config.CLIConfig) error {
20-
// Register the device and get a device code through the response
2119
ctx := context.Background()
2220
deviceRegistrationResponse, err := registerDevice(ctx, svc, cfg)
2321
if err != nil {
2422
return err
2523
}
2624

27-
// Open the browser for authentication
2825
err = browser.OpenURL(deviceRegistrationResponse.VerificationURIComplete)
2926
if err != nil {
3027
c := color.New(color.FgCyan, color.Bold)
@@ -38,7 +35,6 @@ func (opts *LoginOptions) startLoginFlow(svc *authsvc.Service, cfg *config.CLICo
3835
fmt.Println()
3936
fmt.Println("Waiting for authentication")
4037

41-
// Fetch the PAT by polling the server
4238
var tokenData *auth.PAT
4339
tokenData, opts.AuthTimedOut, err = fetchPAT(ctx, deviceRegistrationResponse, svc, cfg)
4440
if err != nil {
@@ -49,7 +45,6 @@ func (opts *LoginOptions) startLoginFlow(svc *authsvc.Service, cfg *config.CLICo
4945
return clierrors.ErrAuthTimeout()
5046
}
5147

52-
// Store auth data in config
5348
cfg.User = tokenData.User.Email
5449
cfg.Token = tokenData.Token
5550
cfg.SetTokenExpiry(tokenData.Expiry)
@@ -76,9 +71,6 @@ func fetchPAT(ctx context.Context, deviceRegistrationData *auth.Device, svc *aut
7671
userName := ""
7772
authTimedOut := true
7873

79-
/* ======================================================================= */
80-
// The username and hostname to add in the description for the PAT request
81-
/* ======================================================================= */
8274
userData, err := user.Current()
8375
if err != nil {
8476
userName = defaultUserName
@@ -92,11 +84,9 @@ func fetchPAT(ctx context.Context, deviceRegistrationData *auth.Device, svc *aut
9284
}
9385
userDescription := fmt.Sprintf("CLI PAT for %s@%s", userName, hostName)
9486

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

99-
// Polling for fetching PAT
10090
func() {
10191
for range ticker.C {
10292
tokenData, err = svc.RequestPAT(ctx, cfg, deviceRegistrationData.Code, userDescription)

command/auth/login/pat_login_flow.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,15 @@ import (
99
"github.com/fatih/color"
1010
)
1111

12-
// Starts the login flow for the CLI (using PAT)
1312
func (opts *LoginOptions) startPATLoginFlow(svc *authsvc.Service, cfg *config.CLIConfig, token string) error {
14-
// set personal access token (PAT)
1513
cfg.Token = token
1614

17-
// Verify the token against the server before saving
1815
viewer, err := svc.GetViewer(context.Background(), cfg)
1916
if err != nil {
2017
return fmt.Errorf("Invalid token: could not authenticate with DeepSource")
2118
}
2219
cfg.User = viewer.Email
2320

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

0 commit comments

Comments
 (0)