From c7a92bccc60ba64ccc2e1d60db1d7ca5487422b3 Mon Sep 17 00:00:00 2001 From: Stephen Estrada Date: Tue, 28 May 2024 18:14:31 -0400 Subject: [PATCH] Optimize repo removal logic using in-place swap and truncate method - Use a single loop to locate the repository by name. - Swap the target repository with the last element in the slice. - Truncate the slice to remove the last element. - Avoid creating a new slice for efficiency. - Gracefully handle the case where the repository is not found. --- cmd/remove.go | 26 +++++++++++--------------- pkg/util/repo_helpers.go | 2 +- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/cmd/remove.go b/cmd/remove.go index b313716..7d2d29a 100644 --- a/cmd/remove.go +++ b/cmd/remove.go @@ -53,7 +53,7 @@ func (cmd *RemoveCommand) Run(c *cli.Context) error { return util.NewWarning("please specify the repository name to remove") } } - util.VerboseLog("removing repository %s", repoName) + util.VerboseLog("attempting to remove %s from gee.toml", repoName) // Load the configuration geeCtx, err := cmd.LoadConfiguration() @@ -61,33 +61,29 @@ func (cmd *RemoveCommand) Run(c *cli.Context) error { return err } - repoPath := "" - for _, repo := range geeCtx.Repos { + var index *int + for i, repo := range geeCtx.Repos { if repo.Name == repoName { - repoPath = repo.Path + index = &i break } } - if repoPath == "" { - return util.NewWarning(fmt.Sprintf("repository %s not found in the configuration", repoName)) + if index == nil { + return util.NewWarning(fmt.Sprintf("%s not found in gee.toml", repoName)) } - // update configuration - newRepos := []types.Repo{} - for _, repo := range geeCtx.Repos { - if repo.Name != repoName { - newRepos = append(newRepos, repo) - } - } + repoLength := len(geeCtx.Repos) + // update repos list in configuration + geeCtx.Repos[repoLength-1], geeCtx.Repos[*index] = geeCtx.Repos[*index], geeCtx.Repos[repoLength-1] + geeCtx.Repos = geeCtx.Repos[:repoLength-1] - geeCtx.Repos = newRepos configHelper := util.NewConfigHelper() err = configHelper.SaveConfig(geeCtx.ConfigFilePath, geeCtx) if err != nil { return util.NewWarning(err.Error()) } - return util.NewInfo(fmt.Sprintf("repository %s successfully remove", repoName)) + return util.NewInfo(fmt.Sprintf("successfully removed %s from gee.toml", repoName)) } func (cmd *RemoveCommand) GetWorkingDirectory() (string, error) { diff --git a/pkg/util/repo_helpers.go b/pkg/util/repo_helpers.go index f5203ed..0272c1b 100644 --- a/pkg/util/repo_helpers.go +++ b/pkg/util/repo_helpers.go @@ -133,7 +133,7 @@ func (r *RepoUtils) WriteRepoToConfig(ctx *types.GeeContext, cwd string) error { if err != nil { return err } - return NewInfo(fmt.Sprintf("Successfully added repo in %s", cwd)) + return NewInfo(fmt.Sprintf("successfully added %s", name)) } // RepoExists checks if the repository already exists in the provided list