Skip to content

Commit

Permalink
Optimize repo removal logic using in-place swap and truncate method
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
stcrestrada committed May 28, 2024
1 parent f02b01f commit c7a92bc
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
26 changes: 11 additions & 15 deletions cmd/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,41 +53,37 @@ 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()
if err != nil {
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) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/util/repo_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c7a92bc

Please sign in to comment.