Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

CLI performance improvements when dealing with large projects that have many files

Dane Schneidera45a82113498
diff --git a/app/cli/cmd/build.go b/app/cli/cmd/build.go
index 59521892..16e5e862 100644
--- a/app/cli/cmd/build.go
+++ b/app/cli/cmd/build.go
@@ -49,9 +49,9 @@ func build(cmd *cobra.Command, args []string) {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
auto := autoConfirm || tellAutoApply || tellAutoContext
- return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts, projectPaths)
},
}, types.BuildFlags{
BuildBg: tellBg,
diff --git a/app/cli/cmd/chat.go b/app/cli/cmd/chat.go
index bb9b0a54..80931561 100644
--- a/app/cli/cmd/chat.go
+++ b/app/cli/cmd/chat.go
@@ -56,9 +56,9 @@ func doChat(cmd *cobra.Command, args []string) {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
auto := autoConfirm || tellAutoApply || tellAutoContext
- return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts, projectPaths)
},
}, prompt, types.TellFlags{
IsChatOnly: true,
diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.go
index d29b2134..b059c22d 100644
--- a/app/cli/cmd/continue.go
+++ b/app/cli/cmd/continue.go
@@ -59,10 +59,10 @@ func doContinue(cmd *cobra.Command, args []string) {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
auto := autoConfirm || tellAutoApply || tellAutoContext
- return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts, projectPaths)
},
}, "", tellFlags)
diff --git a/app/cli/cmd/debug.go b/app/cli/cmd/debug.go
index 823cccd2..69da71be 100644
--- a/app/cli/cmd/debug.go
+++ b/app/cli/cmd/debug.go
@@ -131,8 +131,8 @@ func doDebug(cmd *cobra.Command, args []string) {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(true, true, maybeContexts)
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
+ return lib.CheckOutdatedContextWithOutput(true, true, maybeContexts, projectPaths)
},
}, prompt, tellFlags)
diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.go
index 3fe702c9..d8a92873 100644
--- a/app/cli/cmd/tell.go
+++ b/app/cli/cmd/tell.go
@@ -77,9 +77,9 @@ func doTell(cmd *cobra.Command, args []string) {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
auto := autoConfirm || tellAutoApply || tellAutoContext
- return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(auto, auto, maybeContexts, projectPaths)
},
}, prompt, tellFlags)
diff --git a/app/cli/cmd/update.go b/app/cli/cmd/update.go
index 9fdf4e1c..1e22fbce 100644
--- a/app/cli/cmd/update.go
+++ b/app/cli/cmd/update.go
@@ -2,7 +2,9 @@ package cmd
import (
"fmt"
+ "plandex-cli/api"
"plandex-cli/auth"
+ "plandex-cli/fs"
"plandex-cli/lib"
"plandex-cli/term"
@@ -27,7 +29,21 @@ func update(cmd *cobra.Command, args []string) {
lib.MustResolveProject()
term.StartSpinner("")
- outdated, err := lib.CheckOutdatedContext(nil)
+
+ contexts, apiErr := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)
+
+ if apiErr != nil {
+ term.StopSpinner()
+ term.OutputErrorAndExit("failed to list context: %s", apiErr)
+ }
+
+ paths, err := fs.GetProjectPaths(fs.ProjectRoot)
+
+ if err != nil {
+ term.OutputErrorAndExit("error getting project paths: %v", err)
+ }
+
+ outdated, err := lib.CheckOutdatedContext(contexts, paths)
if err != nil {
term.StopSpinner()
@@ -40,5 +56,9 @@ func update(cmd *cobra.Command, args []string) {
return
}
- lib.UpdateContextWithOutput(nil)
+ lib.UpdateContextWithOutput(lib.UpdateContextParams{
+ Contexts: contexts,
+ OutdatedRes: *outdated,
+ Req: outdated.Req,
+ })
}
diff --git a/app/cli/fs/fs.go b/app/cli/fs/fs.go
index d9d5b254..3080f2c6 100644
--- a/app/cli/fs/fs.go
+++ b/app/cli/fs/fs.go
@@ -1,20 +1,10 @@
package fs
import (
- "context"
- "encoding/json"
- "fmt"
"os"
"os/exec"
"path/filepath"
"plandex-cli/term"
- "plandex-cli/types"
- "strings"
- "sync"
-
- shared "plandex-shared"
-
- ignore "github.com/sabhiram/go-gitignore"
)
var Cwd string
@@ -123,425 +113,6 @@ func IsGitRepo(dir string) bool {
return isGitRepo
}
-func GetProjectPaths(baseDir string) (*types.ProjectPaths, error) {
- if ProjectRoot == "" {
- return nil, fmt.Errorf("no project root found")
- }
-
- return GetPaths(baseDir, ProjectRoot)
-}
-
-func GetPaths(baseDir, currentDir string) (*types.ProjectPaths, error) {
- ignored, err := GetPlandexIgnore(currentDir)
-
- if err != nil {
- return nil, err
- }
-
- allPaths := map[string]bool{}
- activePaths := map[string]bool{}
-
- allDirs := map[string]bool{}
- activeDirs := map[string]bool{}
-
- isGitRepo := IsGitRepo(baseDir)
-
- errCh := make(chan error)
- var mu sync.Mutex
- numRoutines := 0
-
- deletedFiles := map[string]bool{}
-
- if isGitRepo {
-
- // Use git status to find deleted files
- numRoutines++
- go func() {
- cmd := exec.Command("git", "rev-parse", "--show-toplevel")
- output, err := cmd.Output()
- if err != nil {
- errCh <- fmt.Errorf("error getting git root: %s", err)
- return
- }
- repoRoot := strings.TrimSpace(string(output))
-
- cmd = exec.Command("git", "status", "--porcelain")
- cmd.Dir = baseDir
- out, err := cmd.Output()
- if err != nil {
- errCh <- fmt.Errorf("error getting git status: %s", err)
- }
-
- lines := strings.Split(string(out), "\n")
-
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if strings.HasPrefix(line, "D ") {
- path := strings.TrimSpace(line[2:])
- absPath := filepath.Join(repoRoot, path)
- relPath, err := filepath.Rel(currentDir, absPath)
- if err != nil {
- errCh <- fmt.Errorf("error getting relative path: %s", err)
- return
- }
- deletedFiles[relPath] = true
- }
- }
-
- errCh <- nil
- }()
-
- // combine `git ls-files` and `git ls-files --others --exclude-standard`
- // to get all files in the repo
-
- numRoutines++
- go func() {
- // get all tracked files in the repo
- cmd := exec.Command("git", "ls-files")
- cmd.Dir = baseDir
- out, err := cmd.Output()
-
- if err != nil {
- errCh <- fmt.Errorf("error getting files in git repo: %s", err)
- return
- }
-
- files := strings.Split(string(out), "\n")
-
- mu.Lock()
- defer mu.Unlock()
- for _, file := range files {
- absFile := filepath.Join(baseDir, file)
- relFile, err := filepath.Rel(currentDir, absFile)
-
- if err != nil {
- errCh <- fmt.Errorf("error getting relative path: %s", err)
- return
- }
-
- if ignored != nil && ignored.MatchesPath(relFile) {
- continue
- }
-
- activePaths[relFile] = true
-
- parentDir := relFile
- for parentDir != "." && parentDir != "/" && parentDir != "" {
- parentDir = filepath.Dir(parentDir)
- activeDirs[parentDir] = true
- }
- }
-
- errCh <- nil
- }()
-
- // get all untracked non-ignored files in the repo
- numRoutines++
- go func() {
- cmd := exec.Command("git", "ls-files", "--others", "--exclude-standard")
- cmd.Dir = baseDir
- out, err := cmd.Output()
-
- if err != nil {
- errCh <- fmt.Errorf("error getting untracked files in git repo: %s", err)
- return
- }
-
- files := strings.Split(string(out), "\n")
-
- mu.Lock()
- defer mu.Unlock()
- for _, file := range files {
- absFile := filepath.Join(baseDir, file)
- relFile, err := filepath.Rel(currentDir, absFile)
-
- if err != nil {
- errCh <- fmt.Errorf("error getting relative path: %s", err)
- return
- }
-
- if ignored != nil && ignored.MatchesPath(relFile) {
- continue
- }
-
- activePaths[relFile] = true
-
- parentDir := relFile
- for parentDir != "." && parentDir != "/" && parentDir != "" {
- parentDir = filepath.Dir(parentDir)
- activeDirs[parentDir] = true
- }
- }
-
- errCh <- nil
- }()
- }
-
- // get all paths in the directory
- numRoutines++
- go func() {
- err = filepath.Walk(baseDir, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- if info.IsDir() {
- if info.Name() == ".git" {
- return filepath.SkipDir
- }
- if strings.HasPrefix(info.Name(), ".plandex") {
- return filepath.SkipDir
- }
-
- relPath, err := filepath.Rel(currentDir, path)
- if err != nil {
- return err
- }
-
- allDirs[relPath] = true
-
- if ignored != nil && ignored.MatchesPath(relPath) {
- return filepath.SkipDir
- }
- } else {
- relPath, err := filepath.Rel(currentDir, path)
- if err != nil {
- return err
- }
-
- allPaths[relPath] = true
-
- if ignored != nil && ignored.MatchesPath(relPath) {
- return nil
- }
-
- if !isGitRepo {
- mu.Lock()
- defer mu.Unlock()
- activePaths[relPath] = true
-
- parentDir := relPath
- for parentDir != "." && parentDir != "/" && parentDir != "" {
- parentDir = filepath.Dir(parentDir)
- activeDirs[parentDir] = true
- }
- }
- }
-
- return nil
- })
-
- if err != nil {
- errCh <- fmt.Errorf("error walking directory: %s", err)
- return
- }
-
- errCh <- nil
- }()
-
- for i := 0; i < numRoutines; i++ {
- err := <-errCh
- if err != nil {
- return nil, err
- }
- }
-
- for dir := range allDirs {
- allPaths[dir] = true
- }
-
- for dir := range activeDirs {
- activePaths[dir] = true
- }
-
- // remove deleted files from active paths
- for path := range deletedFiles {
- delete(activePaths, path)
- }
-
- ignoredPaths := map[string]string{}
- for path := range allPaths {
- if _, ok := activePaths[path]; !ok {
- if ignored != nil && ignored.MatchesPath(path) {
- ignoredPaths[path] = "plandex"
- } else {
- ignoredPaths[path] = "git"
- }
- }
- }
-
- return &types.ProjectPaths{
- ActivePaths: activePaths,
- AllPaths: allPaths,
- ActiveDirs: activeDirs,
- AllDirs: allDirs,
- PlandexIgnored: ignored,
- IgnoredPaths: ignoredPaths,
- }, nil
-}
-
-func GetPlandexIgnore(dir string) (*ignore.GitIgnore, error) {
- ignorePath := filepath.Join(dir, ".plandexignore")
-
- if _, err := os.Stat(ignorePath); err == nil {
- ignored, err := ignore.CompileIgnoreFile(ignorePath)
-
- if err != nil {
- return nil, fmt.Errorf("error reading .plandexignore file: %s", err)
- }
-
- return ignored, nil
- } else if !os.IsNotExist(err) {
- return nil, fmt.Errorf("error checking for .plandexignore file: %s", err)
- }
-
- return nil, nil
-}
-
-func GetParentProjectIdsWithPaths(currentUserId string) ([][2]string, error) {
- var parentProjectIds [][2]string
- currentDir := filepath.Dir(Cwd)
-
- for currentDir != "/" {
- plandexDir := findPlandex(currentDir)
- projectSettingsPath := filepath.Join(plandexDir, "projects-v2.json")
- if _, err := os.Stat(projectSettingsPath); err == nil {
- bytes, err := os.ReadFile(projectSettingsPath)
- if err != nil {
- return nil, fmt.Errorf("error reading projectId file: %s", err)
- }
-
- var settingsByAccount types.CurrentProjectSettingsByAccount
- err = json.Unmarshal(bytes, &settingsByAccount)
-
- if err != nil {
- term.OutputErrorAndExit("error unmarshalling projects-v2.json: %v", err)
- }
-
- settings := settingsByAccount[currentUserId]
-
- if settings == nil {
- return parentProjectIds, nil
- }
-
- projectId := string(settings.Id)
- parentProjectIds = append(parentProjectIds, [2]string{currentDir, projectId})
- }
- currentDir = filepath.Dir(currentDir)
- }
-
- return parentProjectIds, nil
-}
-
-func GetChildProjectIdsWithPaths(ctx context.Context, currentUserId string) ([][2]string, error) {
- var childProjectIds [][2]string
-
- err := filepath.Walk(Cwd, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- // if permission denied, skip the path
- if os.IsPermission(err) {
- if info.IsDir() {
- return filepath.SkipDir
- } else {
- return nil
- }
- }
-
- return err
- }
-
- if strings.HasPrefix(info.Name(), ".") {
- if info.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
-
- select {
- case <-ctx.Done():
- return fmt.Errorf("context timeout")
- default:
- }
-
- if info.IsDir() && path != Cwd {
- plandexDir := findPlandex(path)
- projectSettingsPath := filepath.Join(plandexDir, "projects-v2.json")
- if _, err := os.Stat(projectSettingsPath); err == nil {
- bytes, err := os.ReadFile(projectSettingsPath)
- if err != nil {
- return fmt.Errorf("error reading projectId file: %s", err)
- }
- var settingsByAccount types.CurrentProjectSettingsByAccount
- err = json.Unmarshal(bytes, &settingsByAccount)
-
- if err != nil {
- term.OutputErrorAndExit("error unmarshalling projects-v2.json: %v", err)
- }
-
- settings := settingsByAccount[currentUserId]
-
- if settings == nil {
- return nil
- }
-
- projectId := string(settings.Id)
- childProjectIds = append(childProjectIds, [2]string{path, projectId})
- }
- }
- return nil
- })
-
- if err != nil {
- if err.Error() == "context timeout" {
- return childProjectIds, nil
- }
-
- return nil, fmt.Errorf("error walking the path %s: %s", Cwd, err)
- }
-
- return childProjectIds, nil
-}
-
-func GetBaseDirForContexts(contexts []*shared.Context) string {
- var paths []string
-
- for _, context := range contexts {
- if context.FilePath != "" {
- paths = append(paths, context.FilePath)
- }
- }
-
- return GetBaseDirForFilePaths(paths)
-}
-
-func GetBaseDirForFilePaths(paths []string) string {
- baseDir := ProjectRoot
- dirsUp := 0
-
- for _, path := range paths {
- currentDir := ProjectRoot
-
- pathSplit := strings.Split(path, string(os.PathSeparator))
-
- n := 0
- for _, p := range pathSplit {
- if p == ".." {
- n++
- currentDir = filepath.Dir(currentDir)
- } else {
- break
- }
- }
-
- if n > dirsUp {
- dirsUp = n
- baseDir = currentDir
- }
- }
-
- return baseDir
-}
-
func FindPlandexDir() {
PlandexDir = findPlandex(Cwd)
}
diff --git a/app/cli/fs/paths.go b/app/cli/fs/paths.go
new file mode 100644
index 00000000..a6fa5747
--- /dev/null
+++ b/app/cli/fs/paths.go
@@ -0,0 +1,442 @@
+package fs
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "plandex-cli/types"
+ "strings"
+ "sync"
+
+ shared "plandex-shared"
+
+ ignore "github.com/sabhiram/go-gitignore"
+)
+
+func GetProjectPaths(baseDir string) (*types.ProjectPaths, error) {
+ if ProjectRoot == "" {
+ return nil, fmt.Errorf("no project root found")
+ }
+
+ return GetPaths(baseDir, ProjectRoot)
+}
+
+func GetPaths(baseDir, currentDir string) (*types.ProjectPaths, error) {
+ ignored, err := GetPlandexIgnore(currentDir)
+
+ if err != nil {
+ return nil, err
+ }
+
+ allPaths := map[string]bool{}
+ activePaths := map[string]bool{}
+
+ allDirs := map[string]bool{}
+ activeDirs := map[string]bool{}
+ gitIgnoredDirs := map[string]bool{}
+
+ isGitRepo := IsGitRepo(baseDir)
+
+ errCh := make(chan error)
+ var mu sync.Mutex
+ numRoutines := 0
+
+ deletedFiles := map[string]bool{}
+
+ if isGitRepo {
+
+ // Use git status to find deleted files
+ numRoutines++
+ go func() {
+ cmd := exec.Command("git", "rev-parse", "--show-toplevel")
+ output, err := cmd.Output()
+ if err != nil {
+ errCh <- fmt.Errorf("error getting git root: %s", err)
+ return
+ }
+ repoRoot := strings.TrimSpace(string(output))
+
+ cmd = exec.Command("git", "status", "--porcelain")
+ cmd.Dir = baseDir
+ out, err := cmd.Output()
+ if err != nil {
+ errCh <- fmt.Errorf("error getting git status: %s", err)
+ }
+
+ lines := strings.Split(string(out), "\n")
+
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "D ") {
+ path := strings.TrimSpace(line[2:])
+ absPath := filepath.Join(repoRoot, path)
+ relPath, err := filepath.Rel(currentDir, absPath)
+ if err != nil {
+ errCh <- fmt.Errorf("error getting relative path: %s", err)
+ return
+ }
+ deletedFiles[relPath] = true
+ }
+ }
+
+ errCh <- nil
+ }()
+
+ // combine `git ls-files` and `git ls-files --others --exclude-standard`
+ // to get all files in the repo
+
+ numRoutines++
+ go func() {
+ // get all tracked files in the repo
+ cmd := exec.Command("git", "ls-files")
+ cmd.Dir = baseDir
+ out, err := cmd.Output()
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting files in git repo: %s", err)
+ return
+ }
+
+ files := strings.Split(string(out), "\n")
+
+ mu.Lock()
+ defer mu.Unlock()
+ for _, file := range files {
+ absFile := filepath.Join(baseDir, file)
+ relFile, err := filepath.Rel(currentDir, absFile)
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting relative path: %s", err)
+ return
+ }
+
+ if ignored != nil && ignored.MatchesPath(relFile) {
+ continue
+ }
+
+ activePaths[relFile] = true
+
+ parentDir := relFile
+ for parentDir != "." && parentDir != "/" && parentDir != "" {
+ parentDir = filepath.Dir(parentDir)
+ activeDirs[parentDir] = true
+ }
+ }
+
+ errCh <- nil
+ }()
+
+ // get all untracked non-ignored files in the repo
+ numRoutines++
+ go func() {
+ cmd := exec.Command("git", "ls-files", "--others", "--exclude-standard")
+ cmd.Dir = baseDir
+ out, err := cmd.Output()
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting untracked files in git repo: %s", err)
+ return
+ }
+
+ files := strings.Split(string(out), "\n")
+
+ mu.Lock()
+ defer mu.Unlock()
+ for _, file := range files {
+ absFile := filepath.Join(baseDir, file)
+ relFile, err := filepath.Rel(currentDir, absFile)
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting relative path: %s", err)
+ return
+ }
+
+ if ignored != nil && ignored.MatchesPath(relFile) {
+ continue
+ }
+
+ activePaths[relFile] = true
+
+ parentDir := relFile
+ for parentDir != "." && parentDir != "/" && parentDir != "" {
+ parentDir = filepath.Dir(parentDir)
+ activeDirs[parentDir] = true
+ }
+ }
+
+ errCh <- nil
+ }()
+
+ // get all ignored paths/dirs in the repo
+ // in some cases when entire directories are ignored, git will just list the directory and not the files within it
+ numRoutines++
+ go func() {
+ cmd := exec.Command("git", "ls-files", "--others", "--ignored", "--exclude-standard")
+ cmd.Dir = baseDir
+ out, err := cmd.Output()
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting untracked files in git repo: %s", err)
+ return
+ }
+
+ paths := strings.Split(string(out), "\n")
+
+ mu.Lock()
+ defer mu.Unlock()
+
+ for _, file := range paths {
+ absFile := filepath.Join(baseDir, file)
+ relFile, err := filepath.Rel(currentDir, absFile)
+
+ if err != nil {
+ errCh <- fmt.Errorf("error getting relative path: %s", err)
+ return
+ }
+
+ // check if git is ignoring the entire directory, meaning it won't list the files within it
+ if strings.HasSuffix(file, "/") {
+ allDirs[relFile] = true
+ allPaths[relFile] = true
+ gitIgnoredDirs[relFile+"/"] = true
+ } else {
+ allPaths[relFile] = true
+ }
+
+ }
+
+ errCh <- nil
+ }()
+
+ } else {
+
+ // get all paths in the directory
+ numRoutines++
+ go func() {
+ err = filepath.Walk(baseDir, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ if info.IsDir() {
+ if info.Name() == ".git" {
+ return filepath.SkipDir
+ }
+ if strings.HasPrefix(info.Name(), ".plandex") {
+ return filepath.SkipDir
+ }
+
+ relPath, err := filepath.Rel(currentDir, path)
+ if err != nil {
+ return err
+ }
+
+ allDirs[relPath] = true
+
+ if ignored != nil && ignored.MatchesPath(relPath) {
+ return filepath.SkipDir
+ }
+ } else {
+ relPath, err := filepath.Rel(currentDir, path)
+ if err != nil {
+ return err
+ }
+
+ allPaths[relPath] = true
+
+ if ignored != nil && ignored.MatchesPath(relPath) {
+ return nil
+ }
+
+ if !isGitRepo {
+ mu.Lock()
+ defer mu.Unlock()
+ activePaths[relPath] = true
+
+ parentDir := relPath
+ for parentDir != "." && parentDir != "/" && parentDir != "" {
+ parentDir = filepath.Dir(parentDir)
+ activeDirs[parentDir] = true
+ }
+ }
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ errCh <- fmt.Errorf("error walking directory: %s", err)
+ return
+ }
+
+ errCh <- nil
+ }()
+ }
+
+ for i := 0; i < numRoutines; i++ {
+ err := <-errCh
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ for dir := range allDirs {
+ allPaths[dir] = true
+ }
+
+ for dir := range activeDirs {
+ activePaths[dir] = true
+ }
+
+ // remove deleted files from active paths
+ for path := range deletedFiles {
+ delete(activePaths, path)
+ }
+
+ ignoredPaths := map[string]string{}
+ for path := range allPaths {
+ if _, ok := activePaths[path]; !ok {
+ if ignored != nil && ignored.MatchesPath(path) {
+ ignoredPaths[path] = "plandex"
+ } else {
+ ignoredPaths[path] = "git"
+ }
+ }
+ }
+
+ return &types.ProjectPaths{
+ ActivePaths: activePaths,
+ AllPaths: allPaths,
+ ActiveDirs: activeDirs,
+ AllDirs: allDirs,
+ PlandexIgnored: ignored,
+ IgnoredPaths: ignoredPaths,
+ GitIgnoredDirs: gitIgnoredDirs,
+ }, nil
+}
+
+func GetPlandexIgnore(dir string) (*ignore.GitIgnore, error) {
+ ignorePath := filepath.Join(dir, ".plandexignore")
+
+ if _, err := os.Stat(ignorePath); err == nil {
+ ignored, err := ignore.CompileIgnoreFile(ignorePath)
+
+ if err != nil {
+ return nil, fmt.Errorf("error reading .plandexignore file: %s", err)
+ }
+
+ return ignored, nil
+ } else if !os.IsNotExist(err) {
+ return nil, fmt.Errorf("error checking for .plandexignore file: %s", err)
+ }
+
+ return nil, nil
+}
+
+func GetBaseDirForContexts(contexts []*shared.Context) string {
+ var paths []string
+
+ for _, context := range contexts {
+ if context.FilePath != "" {
+ paths = append(paths, context.FilePath)
+ }
+ }
+
+ return GetBaseDirForFilePaths(paths)
+}
+
+func GetBaseDirForFilePaths(paths []string) string {
+ baseDir := ProjectRoot
+ dirsUp := 0
+
+ for _, path := range paths {
+ currentDir := ProjectRoot
+
+ pathSplit := strings.Split(path, string(os.PathSeparator))
+
+ n := 0
+ for _, p := range pathSplit {
+ if p == ".." {
+ n++
+ currentDir = filepath.Dir(currentDir)
+ } else {
+ break
+ }
+ }
+
+ if n > dirsUp {
+ dirsUp = n
+ baseDir = currentDir
+ }
+ }
+
+ return baseDir
+}
+
+// isSubpathOf checks if 'child' is within 'parent' (same path or deeper).
+// Both 'parent' and 'child' can be absolute or relative to 'baseDir';
+// we’ll convert them to absolute paths based on 'baseDir' and then compare.
+func IsSubpathOf(parent, child, baseDir string) (bool, error) {
+ // Convert 'parent' -> absolute
+ absParent := parent
+ if !filepath.IsAbs(parent) {
+ absParent = filepath.Join(baseDir, parent)
+ }
+ absParent = filepath.Clean(absParent)
+
+ // Convert 'child' -> absolute
+ absChild := child
+ if !filepath.IsAbs(child) {
+ absChild = filepath.Join(baseDir, child)
+ }
+ absChild = filepath.Clean(absChild)
+
+ // filepath.Rel(absParent, absChild) will be something like:
+ // - ".", "foo", "foo/bar", or ".." references
+ rel, err := filepath.Rel(absParent, absChild)
+ if err != nil {
+ // If there's some I/O error or invalid path, just fail safe
+ return false, fmt.Errorf("error getting relative path: %s", err)
+ }
+
+ // If rel starts with "..", then absChild is outside of absParent
+ // or at a higher level (e.g. absParent/../sibling).
+ if strings.HasPrefix(rel, "..") {
+ return false, nil
+ }
+
+ // If we want "absChild == absParent" to count as inside,
+ // then !HasPrefix(rel, "..") is enough.
+ // This means child == parent or child is deeper within parent.
+ return true, nil
+}
+
+func IsIgnored(paths *types.ProjectPaths, path, baseDir string) (bool, string, error) {
+ if !paths.AllPaths[path] {
+ // if the path isn't in AllPaths, it either:
+ // 1. doesn't exist (in which case we shouldn't be calling this function)
+ // 2. is a subpath of a git ignored dir
+
+ for dir := range paths.GitIgnoredDirs {
+ subpath, err := IsSubpathOf(dir, path, baseDir)
+ if err != nil {
+ return false, "", fmt.Errorf("error checking if %s is a subpath of %s: %s", path, dir, err)
+ }
+ if subpath {
+ return true, "git", nil
+ }
+ }
+ return false, "", fmt.Errorf("path %s is not in the project", path)
+ }
+
+ if paths.ActivePaths[path] {
+ return false, "", nil
+ }
+
+ if paths.PlandexIgnored != nil && paths.PlandexIgnored.MatchesPath(path) {
+ return true, "plandex", nil
+ }
+
+ return true, "git", nil
+}
diff --git a/app/cli/fs/projects.go b/app/cli/fs/projects.go
new file mode 100644
index 00000000..48cb1eed
--- /dev/null
+++ b/app/cli/fs/projects.go
@@ -0,0 +1,116 @@
+package fs
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "plandex-cli/term"
+ "plandex-cli/types"
+ "strings"
+)
+
+func GetParentProjectIdsWithPaths(currentUserId string) ([][2]string, error) {
+ var parentProjectIds [][2]string
+ currentDir := filepath.Dir(Cwd)
+
+ for currentDir != "/" {
+ plandexDir := findPlandex(currentDir)
+ projectSettingsPath := filepath.Join(plandexDir, "projects-v2.json")
+ if _, err := os.Stat(projectSettingsPath); err == nil {
+ bytes, err := os.ReadFile(projectSettingsPath)
+ if err != nil {
+ return nil, fmt.Errorf("error reading projectId file: %s", err)
+ }
+
+ var settingsByAccount types.CurrentProjectSettingsByAccount
+ err = json.Unmarshal(bytes, &settingsByAccount)
+
+ if err != nil {
+ term.OutputErrorAndExit("error unmarshalling projects-v2.json: %v", err)
+ }
+
+ settings := settingsByAccount[currentUserId]
+
+ if settings == nil {
+ return parentProjectIds, nil
+ }
+
+ projectId := string(settings.Id)
+ parentProjectIds = append(parentProjectIds, [2]string{currentDir, projectId})
+ }
+ currentDir = filepath.Dir(currentDir)
+ }
+
+ return parentProjectIds, nil
+}
+
+func GetChildProjectIdsWithPaths(ctx context.Context, currentUserId string) ([][2]string, error) {
+ var childProjectIds [][2]string
+
+ err := filepath.Walk(Cwd, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ // if permission denied, skip the path
+ if os.IsPermission(err) {
+ if info.IsDir() {
+ return filepath.SkipDir
+ } else {
+ return nil
+ }
+ }
+
+ return err
+ }
+
+ if strings.HasPrefix(info.Name(), ".") {
+ if info.IsDir() {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("context timeout")
+ default:
+ }
+
+ if info.IsDir() && path != Cwd {
+ plandexDir := findPlandex(path)
+ projectSettingsPath := filepath.Join(plandexDir, "projects-v2.json")
+ if _, err := os.Stat(projectSettingsPath); err == nil {
+ bytes, err := os.ReadFile(projectSettingsPath)
+ if err != nil {
+ return fmt.Errorf("error reading projectId file: %s", err)
+ }
+ var settingsByAccount types.CurrentProjectSettingsByAccount
+ err = json.Unmarshal(bytes, &settingsByAccount)
+
+ if err != nil {
+ term.OutputErrorAndExit("error unmarshalling projects-v2.json: %v", err)
+ }
+
+ settings := settingsByAccount[currentUserId]
+
+ if settings == nil {
+ return nil
+ }
+
+ projectId := string(settings.Id)
+ childProjectIds = append(childProjectIds, [2]string{path, projectId})
+ }
+ }
+ return nil
+ })
+
+ if err != nil {
+ if err.Error() == "context timeout" {
+ return childProjectIds, nil
+ }
+
+ return nil, fmt.Errorf("error walking the path %s: %s", Cwd, err)
+ }
+
+ return childProjectIds, nil
+}
diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.go
index 7141733f..95e9fd44 100644
--- a/app/cli/lib/apply.go
+++ b/app/cli/lib/apply.go
@@ -103,7 +103,13 @@ func MustApplyPlanAttempt(
}
}
- anyOutdated, didUpdate, err := CheckOutdatedContextWithOutput(true, autoConfirm, nil)
+ paths, err := fs.GetProjectPaths(fs.ProjectRoot)
+
+ if err != nil {
+ term.OutputErrorAndExit("error getting project paths: %v", err)
+ }
+
+ anyOutdated, didUpdate, err := CheckOutdatedContextWithOutput(true, autoConfirm, nil, paths)
if err != nil {
term.OutputErrorAndExit("error checking outdated context: %v", err)
@@ -183,7 +189,7 @@ func MustApplyPlanAttempt(
term.ResumeSpinner()
}
- updatedFiles, toRollback, err = ApplyFiles(toApply, toRemove)
+ updatedFiles, toRollback, err = ApplyFiles(toApply, toRemove, paths)
if err != nil {
onErr("failed to apply files: %s", err)
@@ -539,14 +545,13 @@ func commitApplied(autoCommit bool, commitSummary string, updatedFiles []string,
return nil
}
-func ApplyFiles(toApply map[string]string, toRemove map[string]bool) ([]string, *types.ApplyRollbackPlan, error) {
+func ApplyFiles(toApply map[string]string, toRemove map[string]bool, projectPaths *types.ProjectPaths) ([]string, *types.ApplyRollbackPlan, error) {
var updatedFiles []string
toRevert := map[string]types.ApplyReversion{}
var toRemoveOnRollback []string
- var projectPaths *types.ProjectPaths
var mu sync.Mutex
- totalOps := len(toApply) + len(toRemove) + 1
+ totalOps := len(toApply) + len(toRemove)
errCh := make(chan error, totalOps)
for path, content := range toApply {
@@ -656,15 +661,6 @@ func ApplyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,
}(path, remove)
}
- go func() {
- var err error
- projectPaths, err = fs.GetProjectPaths(fs.ProjectRoot)
- if err != nil {
- errCh <- fmt.Errorf("failed to get project paths: %v", err)
- }
- errCh <- nil
- }()
-
for i := 0; i < totalOps; i++ {
err := <-errCh
if err != nil {
@@ -703,12 +699,12 @@ func Rollback(rollbackPlan *types.ApplyRollbackPlan, msg bool) error {
}
go func() {
var err error
- projectPaths, err := fs.GetProjectPaths(fs.ProjectRoot)
+ updatedProjectPaths, err := fs.GetProjectPaths(fs.ProjectRoot)
if err != nil {
errCh <- fmt.Errorf("failed to get project paths: %v", err)
}
var toRemove []string
- for path := range projectPaths.ActivePaths {
+ for path := range updatedProjectPaths.ActivePaths {
if _, ok := rollbackPlan.PreviousProjectPaths.ActivePaths[path]; !ok {
toRemove = append(toRemove, path)
}
diff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.go
index 062469b4..4fbad955 100644
--- a/app/cli/lib/context_load.go
+++ b/app/cli/lib/context_load.go
@@ -220,8 +220,12 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
var filteredPaths []string
for _, inputFilePath := range inputFilePaths {
if _, ok := paths.ActivePaths[inputFilePath]; !ok {
- if _, ok := paths.IgnoredPaths[inputFilePath]; ok {
- ignoredPaths[inputFilePath] = paths.IgnoredPaths[inputFilePath]
+ ignored, reason, err := fs.IsIgnored(paths, inputFilePath, baseDir)
+ if err != nil {
+ onErr(fmt.Errorf("failed to check if %s is ignored: %v", inputFilePath, err))
+ }
+ if ignored {
+ ignoredPaths[inputFilePath] = reason
}
} else {
filteredPaths = append(filteredPaths, inputFilePath)
@@ -242,7 +246,12 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
numRoutines++
go func(inputFilePath string) {
- flattenedPaths, err := ParseInputPaths([]string{inputFilePath}, params)
+ flattenedPaths, err := ParseInputPaths(ParseInputPathsParams{
+ FileOrDirPaths: []string{inputFilePath},
+ BaseDir: baseDir,
+ ProjectPaths: paths,
+ LoadParams: params,
+ })
if err != nil {
errCh <- fmt.Errorf("failed to parse input paths: %v", err)
return
@@ -254,7 +263,13 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
if _, ok := paths.ActivePaths[path]; ok {
filteredPaths = append(filteredPaths, path)
} else {
- if _, ok := paths.IgnoredPaths[path]; ok {
+ ignored, reason, err := fs.IsIgnored(paths, path, baseDir)
+ if err != nil {
+ errCh <- fmt.Errorf("failed to check if %s is ignored: %v", path, err)
+ return
+ }
+ if ignored {
+ ignoredPaths[path] = reason
ignoredPaths[path] = paths.IgnoredPaths[path]
}
}
@@ -288,7 +303,12 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
}
} else {
- flattenedPaths, err := ParseInputPaths(inputFilePaths, params)
+ flattenedPaths, err := ParseInputPaths(ParseInputPathsParams{
+ FileOrDirPaths: inputFilePaths,
+ BaseDir: baseDir,
+ ProjectPaths: paths,
+ LoadParams: params,
+ })
if err != nil {
onErr(fmt.Errorf("failed to parse input paths: %v", err))
}
@@ -313,8 +333,12 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
if _, ok := paths.ActivePaths[path]; ok {
filteredPaths = append(filteredPaths, path)
} else {
- if _, ok := paths.IgnoredPaths[path]; ok {
- ignoredPaths[path] = paths.IgnoredPaths[path]
+ ignored, reason, err := fs.IsIgnored(paths, path, baseDir)
+ if err != nil {
+ onErr(fmt.Errorf("failed to check if %s is ignored: %v", path, err))
+ }
+ if ignored {
+ ignoredPaths[path] = reason
}
}
}
diff --git a/app/cli/lib/context_paths.go b/app/cli/lib/context_paths.go
index e63b8417..bd56918f 100644
--- a/app/cli/lib/context_paths.go
+++ b/app/cli/lib/context_paths.go
@@ -2,78 +2,63 @@ package lib
import (
"fmt"
- "os"
- "path/filepath"
+ "plandex-cli/fs"
"plandex-cli/types"
- "strings"
- "sync"
)
-func ParseInputPaths(fileOrDirPaths []string, params *types.LoadContextParams) ([]string, error) {
- var wg sync.WaitGroup
- var mu sync.Mutex
- var firstErr error
- resPaths := []string{}
-
- for _, path := range fileOrDirPaths {
- wg.Add(1)
- go func(p string) {
- defer wg.Done()
-
- err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- mu.Lock()
- defer mu.Unlock()
- if firstErr != nil {
- return firstErr // If an error was encountered, stop walking
- }
-
- if info.IsDir() {
- if info.Name() == ".git" || strings.Index(info.Name(), ".plandex") == 0 {
- return filepath.SkipDir
- }
+type ParseInputPathsParams struct {
+ FileOrDirPaths []string
+ BaseDir string
+ ProjectPaths *types.ProjectPaths
+ LoadParams *types.LoadContextParams
+}
- if !(params.Recursive || params.NamesOnly || params.DefsOnly) {
- // log.Println("path", path, "info.Name()", info.Name())
+func ParseInputPaths(params ParseInputPathsParams) ([]string, error) {
+ fileOrDirPaths := params.FileOrDirPaths
+ baseDir := params.BaseDir
+ projectPaths := params.ProjectPaths
+ loadParams := params.LoadParams
- return fmt.Errorf("cannot process directory %s: requires --recursive/-r, --tree, or --map flag", path)
- }
+ resPaths := []string{}
- // calculate directory depth from base
- // depth := strings.Count(path[len(p):], string(filepath.Separator))
- // if params.MaxDepth != -1 && depth > params.MaxDepth {
- // return filepath.SkipDir
- // }
+ for path := range projectPaths.AllPaths {
+ // see if it's a child of any of the fileOrDirPaths
+ found := false
+ for _, p := range fileOrDirPaths {
+ found, err := fs.IsSubpathOf(p, path, baseDir)
+ if err != nil {
+ return nil, fmt.Errorf("error checking if %s is a subpath of %s: %s", path, p, err)
+ }
+ if found {
+ break
+ }
+ }
- if params.NamesOnly {
- // add directory name to results
- resPaths = append(resPaths, path)
- }
- } else {
- // add file path to results
- resPaths = append(resPaths, path)
- }
+ if !found {
+ continue
+ }
- return nil
- })
+ if projectPaths.AllDirs[path] {
+ if !(loadParams.Recursive || loadParams.NamesOnly || loadParams.DefsOnly) {
+ // log.Println("path", path, "info.Name()", info.Name())
- if err != nil {
- mu.Lock()
- if firstErr == nil {
- firstErr = err
- }
- mu.Unlock()
+ return nil, fmt.Errorf("cannot process directory %s: requires --recursive/-r, --tree, or --map flag", path)
}
- }(path)
- }
- wg.Wait()
+ // calculate directory depth from base
+ // depth := strings.Count(path[len(p):], string(filepath.Separator))
+ // if params.MaxDepth != -1 && depth > params.MaxDepth {
+ // return filepath.SkipDir
+ // }
- if firstErr != nil {
- return nil, firstErr
+ if loadParams.NamesOnly {
+ // add directory name to results
+ resPaths = append(resPaths, path)
+ }
+ } else {
+ // add file path to results
+ resPaths = append(resPaths, path)
+ }
}
return resPaths, nil
diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.go
index d7c26966..76a02ea9 100644
--- a/app/cli/lib/context_update.go
+++ b/app/cli/lib/context_update.go
@@ -20,12 +20,12 @@ import (
"github.com/olekukonko/tablewriter"
)
-func CheckOutdatedContextWithOutput(quiet, autoConfirm bool, maybeContexts []*shared.Context) (contextOutdated, updated bool, err error) {
+func CheckOutdatedContextWithOutput(quiet, autoConfirm bool, maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (contextOutdated, updated bool, err error) {
if !quiet {
term.StartSpinner("🔬 Checking context...")
}
- outdatedRes, err := CheckOutdatedContext(maybeContexts)
+ outdatedRes, err := CheckOutdatedContext(maybeContexts, projectPaths)
if err != nil {
term.StopSpinner()
return false, false, fmt.Errorf("failed to check outdated context: %s", err)
@@ -162,7 +162,11 @@ func CheckOutdatedContextWithOutput(quiet, autoConfirm bool, maybeContexts []*sh
}
if confirmed {
- err = UpdateContextWithOutput(maybeContexts)
+ _, err := UpdateContextWithOutput(UpdateContextParams{
+ Contexts: maybeContexts,
+ OutdatedRes: *outdatedRes,
+ Req: map[string]*shared.UpdateContextParams{},
+ })
if err != nil {
return false, false, fmt.Errorf("error updating context: %v", err)
}
@@ -173,35 +177,103 @@ func CheckOutdatedContextWithOutput(quiet, autoConfirm bool, maybeContexts []*sh
}
-func UpdateContextWithOutput(maybeUpdateContexts []*shared.Context) error {
+type UpdateContextParams struct {
+ Contexts []*shared.Context
+ OutdatedRes types.ContextOutdatedResult
+ Req map[string]*shared.UpdateContextParams
+}
+
+type UpdateContextResult struct {
+ HasConflicts bool
+ Msg string
+}
+
+func UpdateContextWithOutput(params UpdateContextParams) (UpdateContextResult, error) {
term.StartSpinner("🔄 Updating context...")
- updateRes, err := UpdateContext(maybeUpdateContexts)
+ updateRes, err := UpdateContext(params)
if err != nil {
- return err
+ return UpdateContextResult{}, err
}
term.StopSpinner()
fmt.Println("✅ " + updateRes.Msg)
- return nil
+ return updateRes, nil
}
-func UpdateContext(maybeContexts []*shared.Context) (*types.ContextOutdatedResult, error) {
- return checkOutdatedAndMaybeUpdateContext(true, maybeContexts)
+func UpdateContext(params UpdateContextParams) (UpdateContextResult, error) {
+ req := params.Req
+
+ var hasConflicts bool
+ var msg string
+
+ contextsById := map[string]*shared.Context{}
+ for _, context := range params.Contexts {
+ contextsById[context.Id] = context
+ }
+
+ deleteIds := map[string]bool{}
+ for _, context := range params.OutdatedRes.RemovedContexts {
+ deleteIds[context.Id] = true
+ }
+
+ filesToLoad := map[string]string{}
+ for id := range req {
+ context := contextsById[id]
+ if context.ContextType == shared.ContextFileType {
+ filesToLoad[context.FilePath] = context.Body
+ }
+ }
+ for id := range deleteIds {
+ context := contextsById[id]
+ if context.ContextType == shared.ContextFileType {
+ filesToLoad[context.FilePath] = ""
+ }
+ }
+
+ var err error
+ hasConflicts, err = checkContextConflicts(filesToLoad)
+ if err != nil {
+ return UpdateContextResult{}, fmt.Errorf("failed to check context conflicts: %v", err)
+ }
+
+ if len(req) > 0 {
+ // log.Println("updating context")
+ res, apiErr := api.Client.UpdateContext(CurrentPlanId, CurrentBranch, req)
+ if apiErr != nil {
+ return UpdateContextResult{}, fmt.Errorf("failed to update context: %v", apiErr)
+ }
+ // log.Println("updated context")
+ // log.Println("res.Msg", res.Msg)
+ msg = res.Msg
+ }
+
+ if len(deleteIds) > 0 {
+ res, apiErr := api.Client.DeleteContext(CurrentPlanId, CurrentBranch, shared.DeleteContextRequest{
+ Ids: deleteIds,
+ })
+ if apiErr != nil {
+ return UpdateContextResult{}, fmt.Errorf("failed to delete contexts: %v", apiErr)
+ }
+ msg += " " + res.Msg
+ }
+
+ return UpdateContextResult{
+ HasConflicts: hasConflicts,
+ Msg: msg,
+ }, nil
}
-func CheckOutdatedContext(maybeContexts []*shared.Context) (*types.ContextOutdatedResult, error) {
- return checkOutdatedAndMaybeUpdateContext(false, maybeContexts)
+func CheckOutdatedContext(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (*types.ContextOutdatedResult, error) {
+ return checkOutdatedAndMaybeUpdateContext(false, maybeContexts, projectPaths)
}
-func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Context) (*types.ContextOutdatedResult, error) {
+func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (*types.ContextOutdatedResult, error) {
var contexts []*shared.Context
- // log.Println("Checking outdated context")
-
if maybeContexts == nil {
var apiErr *shared.ApiError
contexts, apiErr = api.Client.ListContext(CurrentPlanId, CurrentBranch)
@@ -228,24 +300,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
contextsById := map[string]*shared.Context{}
deleteIds := map[string]bool{}
- var paths *types.ProjectPaths
- var hasDirectoryTreeWithIgnoredPaths bool
-
- for _, context := range contexts {
- if context.ContextType == shared.ContextDirectoryTreeType && !context.ForceSkipIgnore {
- hasDirectoryTreeWithIgnoredPaths = true
- break
- }
- }
-
- if hasDirectoryTreeWithIgnoredPaths {
- baseDir := fs.GetBaseDirForContexts(contexts)
- var err error
- paths, err = fs.GetProjectPaths(baseDir)
- if err != nil {
- return nil, fmt.Errorf("failed to get project paths: %v", err)
- }
- }
+ paths := projectPaths
for _, context := range contexts {
contextsById[context.Id] = context
@@ -311,9 +366,16 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
return
}
- flattenedPaths, err := ParseInputPaths([]string{context.FilePath}, &types.LoadContextParams{
- NamesOnly: true,
- ForceSkipIgnore: context.ForceSkipIgnore,
+ baseDir := fs.GetBaseDirForFilePaths([]string{context.FilePath})
+
+ flattenedPaths, err := ParseInputPaths(ParseInputPathsParams{
+ FileOrDirPaths: []string{context.FilePath},
+ BaseDir: baseDir,
+ ProjectPaths: paths,
+ LoadParams: &types.LoadContextParams{
+ NamesOnly: true,
+ ForceSkipIgnore: context.ForceSkipIgnore,
+ },
})
mu.Lock()
@@ -397,13 +459,13 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
// Check if new files were added
baseDir := fs.GetBaseDirForFilePaths([]string{context.FilePath})
- paths, err := fs.GetProjectPaths(baseDir)
- if err != nil {
- errs = append(errs, fmt.Errorf("failed to get project paths: %v", err))
- return
- }
- flattenedPaths, err := ParseInputPaths([]string{context.FilePath}, &types.LoadContextParams{Recursive: true})
+ flattenedPaths, err := ParseInputPaths(ParseInputPathsParams{
+ FileOrDirPaths: []string{context.FilePath},
+ BaseDir: baseDir,
+ ProjectPaths: paths,
+ LoadParams: &types.LoadContextParams{Recursive: true},
+ })
if err != nil {
errs = append(errs, fmt.Errorf("failed to get the directory tree %s: %v", context.FilePath, err))
return
@@ -439,6 +501,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
}
}
// If any files changed, get new map
+
if len(updatedInputs) > 0 || len(removedMapPaths) > 0 {
// log.Println("updatedInputs", len(updatedInputs), "removedMapPaths", len(removedMapPaths))
// log.Println("updatedInputs:")
@@ -554,6 +617,12 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
return nil, fmt.Errorf("total context body size exceeds limit (size %.2f MB, limit %d MB)", float64(totalBodySize)/1024/1024, int(shared.MaxContextBodySize)/1024/1024)
}
+ var removedContexts []*shared.Context
+ for id := range deleteIds {
+ removedContexts = append(removedContexts, contextsById[id])
+ }
+
+ var outdatedRes types.ContextOutdatedResult
var msg string
var hasConflicts bool
@@ -563,46 +632,29 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
Msg: "Context is up to date",
}, nil
} else if doUpdate {
- filesToLoad := map[string]string{}
- for id := range req {
- context := contextsById[id]
- if context.ContextType == shared.ContextFileType {
- filesToLoad[context.FilePath] = context.Body
- }
+ outdatedRes = types.ContextOutdatedResult{
+ UpdatedContexts: updatedContexts,
+ RemovedContexts: removedContexts,
+ TokenDiffsById: tokenDiffsById,
+ NumFiles: numFiles,
+ NumUrls: numUrls,
+ NumTrees: numTrees,
+ NumMaps: numMaps,
+ NumFilesRemoved: numFilesRemoved,
+ NumTreesRemoved: numTreesRemoved,
+ Req: req,
}
- for id := range deleteIds {
- context := contextsById[id]
- if context.ContextType == shared.ContextFileType {
- filesToLoad[context.FilePath] = ""
- }
- }
-
- var err error
- hasConflicts, err = checkContextConflicts(filesToLoad)
+ res, err := UpdateContext(UpdateContextParams{
+ Contexts: contexts,
+ OutdatedRes: outdatedRes,
+ Req: req,
+ })
if err != nil {
- return nil, fmt.Errorf("failed to check context conflicts: %v", err)
- }
-
- if len(req) > 0 {
- // log.Println("updating context")
- res, apiErr := api.Client.UpdateContext(CurrentPlanId, CurrentBranch, req)
- if apiErr != nil {
- return nil, fmt.Errorf("failed to update context: %v", apiErr)
- }
- // log.Println("updated context")
- // log.Println("res.Msg", res.Msg)
- msg = res.Msg
- }
-
- if len(deleteIds) > 0 {
- req, apiErr := api.Client.DeleteContext(CurrentPlanId, CurrentBranch, shared.DeleteContextRequest{
- Ids: deleteIds,
- })
- if apiErr != nil {
- return nil, fmt.Errorf("failed to delete contexts: %v", apiErr)
- }
- msg += " " + req.Msg
+ return nil, fmt.Errorf("failed to update context: %v", err)
}
+ hasConflicts = res.HasConflicts
+ msg = res.Msg
+ outdatedRes.Msg = msg
}
if hasConflicts {
@@ -616,23 +668,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
fmt.Println()
}
- var removedContexts []*shared.Context
- for id := range deleteIds {
- removedContexts = append(removedContexts, contextsById[id])
- }
-
- return &types.ContextOutdatedResult{
- Msg: msg,
- UpdatedContexts: updatedContexts,
- RemovedContexts: removedContexts,
- TokenDiffsById: tokenDiffsById,
- NumFiles: numFiles,
- NumUrls: numUrls,
- NumTrees: numTrees,
- NumMaps: numMaps,
- NumFilesRemoved: numFilesRemoved,
- NumTreesRemoved: numTreesRemoved,
- }, nil
+ return &outdatedRes, nil
}
func tableForContextOutdated(updatedContexts []*shared.Context, tokenDiffsById map[string]int) string {
diff --git a/app/cli/main.go b/app/cli/main.go
index 2a28d82f..c93f5f30 100644
--- a/app/cli/main.go
+++ b/app/cli/main.go
@@ -39,8 +39,8 @@ func init() {
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(true, autoConfirm, maybeContexts)
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
+ return lib.CheckOutdatedContextWithOutput(true, autoConfirm, maybeContexts, projectPaths)
},
}, types.BuildFlags{})
})
diff --git a/app/cli/plan_exec/apply_exec.go b/app/cli/plan_exec/apply_exec.go
index a3cfb046..c42a9c5d 100644
--- a/app/cli/plan_exec/apply_exec.go
+++ b/app/cli/plan_exec/apply_exec.go
@@ -138,8 +138,8 @@ func getOnApplyExecFail(applyFlags types.ApplyFlags, tellFlags types.TellFlags,
CurrentPlanId: lib.CurrentPlanId,
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
- CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(true, true, maybeContexts)
+ CheckOutdatedContext: func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error) {
+ return lib.CheckOutdatedContextWithOutput(true, true, maybeContexts, projectPaths)
},
}, prompt, tellFlags)
diff --git a/app/cli/plan_exec/build.go b/app/cli/plan_exec/build.go
index 598e7b50..222a7d15 100644
--- a/app/cli/plan_exec/build.go
+++ b/app/cli/plan_exec/build.go
@@ -25,7 +25,13 @@ func Build(params ExecParams, flags types.BuildFlags) (bool, error) {
term.OutputErrorAndExit("Error getting context: %v", apiErr)
}
- anyOutdated, didUpdate, err := params.CheckOutdatedContext(contexts)
+ paths, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))
+
+ if err != nil {
+ return false, fmt.Errorf("error getting project paths: %v", err)
+ }
+
+ anyOutdated, didUpdate, err := params.CheckOutdatedContext(contexts, paths)
if err != nil {
term.OutputErrorAndExit("error checking outdated context: %v", err)
@@ -37,12 +43,6 @@ func Build(params ExecParams, flags types.BuildFlags) (bool, error) {
return false, nil
}
- paths, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))
-
- if err != nil {
- return false, fmt.Errorf("error getting project paths: %v", err)
- }
-
var legacyApiKey, openAIBase, openAIOrgId string
if params.ApiKeys["OPENAI_API_KEY"] != "" {
diff --git a/app/cli/plan_exec/params.go b/app/cli/plan_exec/params.go
index 0cee67da..08ab2bbd 100644
--- a/app/cli/plan_exec/params.go
+++ b/app/cli/plan_exec/params.go
@@ -1,10 +1,13 @@
package plan_exec
-import shared "plandex-shared"
+import (
+ "plandex-cli/types"
+ shared "plandex-shared"
+)
type ExecParams struct {
CurrentPlanId string
CurrentBranch string
ApiKeys map[string]string
- CheckOutdatedContext func(maybeContexts []*shared.Context) (bool, bool, error)
+ CheckOutdatedContext func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error)
}
diff --git a/app/cli/plan_exec/tell.go b/app/cli/plan_exec/tell.go
index 6a912b28..658c34dd 100644
--- a/app/cli/plan_exec/tell.go
+++ b/app/cli/plan_exec/tell.go
@@ -55,6 +55,7 @@ func TellPlan(
}
term.StartSpinner("")
+ log.Println("Getting context (ListContext)")
contexts, apiErr := api.Client.ListContext(params.CurrentPlanId, params.CurrentBranch)
if apiErr != nil {
@@ -62,13 +63,29 @@ func TellPlan(
term.OutputErrorAndExit("Error getting context: %v", apiErr)
}
- anyOutdated, didUpdate, err := params.CheckOutdatedContext(contexts)
+ log.Println("Got context (ListContext)")
+
+ log.Println("Getting project paths")
+
+ paths, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))
+
+ if err != nil {
+ outputPromptIfTell()
+ term.OutputErrorAndExit("Error getting project paths: %v", err)
+ }
+
+ log.Println("Got project paths")
+
+ log.Println("Checking outdated context (CheckOutdatedContext)")
+ anyOutdated, didUpdate, err := params.CheckOutdatedContext(contexts, paths)
if err != nil {
outputPromptIfTell()
term.OutputErrorAndExit("Error checking outdated context: %v", err)
}
+ log.Println("Checked outdated context (CheckOutdatedContext)")
+
if anyOutdated && !didUpdate {
term.StopSpinner()
if isUserContinue {
@@ -83,15 +100,6 @@ func TellPlan(
os.Exit(0)
}
- term.StartSpinner("")
- paths, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))
- term.StopSpinner()
-
- if err != nil {
- outputPromptIfTell()
- term.OutputErrorAndExit("Error getting project paths: %v", err)
- }
-
var fn func() bool
fn = func() bool {
diff --git a/app/cli/types/fs.go b/app/cli/types/fs.go
index 7b1b4c2b..22490729 100644
--- a/app/cli/types/fs.go
+++ b/app/cli/types/fs.go
@@ -9,4 +9,5 @@ type ProjectPaths struct {
AllDirs map[string]bool
PlandexIgnored *ignore.GitIgnore
IgnoredPaths map[string]string
+ GitIgnoredDirs map[string]bool
}
diff --git a/app/cli/types/types.go b/app/cli/types/types.go
index 3fadcbca..3bbfc2ed 100644
--- a/app/cli/types/types.go
+++ b/app/cli/types/types.go
@@ -28,6 +28,7 @@ type ContextOutdatedResult struct {
NumMaps int
NumFilesRemoved int
NumTreesRemoved int
+ Req map[string]*shared.UpdateContextParams
}
const (