Repository navigation
feat(daemon): send the git repository so projects group by repository #356
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5f7fc0f
feat(daemon): send the git repository so projects group by repository
claude 81850e6
fix(daemon): bound and dedupe git lookups, keep migration to this mac…
claude f116c76
fix(daemon): finish the project migration only when every folder was …
claude e29ee39
fix(model): bound repository lookups and let users turn them off
claude 8e4e5d8
fix(daemon): drop the repository from spans when it isn't to be sent
claude e5828fd
fix(model): escape repository names and read git's messages in English
claude a58c002
fix(model): stop a migration run only for hung stats
claude c08b32a
fix(model): merge a local aiCodeOtel block field by field
claude 118fc32
fix(daemon): don't give a record in another folder the resource's rep…
claude 6a3c55f
fix(daemon): keep the repository for records in a subfolder of the clone
claude 9c8e29e
fix(model): let a lookup outlive the caller that started it
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
| "os" | ||
| "strconv" | ||
| "time" | ||
|
|
||
| "github.com/gookit/color" | ||
| "github.com/malamtime/cli/model" | ||
| "github.com/olekukonko/tablewriter" | ||
| "github.com/urfave/cli/v2" | ||
| "go.opentelemetry.io/otel/attribute" | ||
| "go.opentelemetry.io/otel/trace" | ||
| ) | ||
|
|
||
| // AICodeProjectsCommand is `shelltime cc projects` and `shelltime codex projects`: the projects | ||
| // of both agents are grouped together, so either runs the same migration. | ||
| var AICodeProjectsCommand = &cli.Command{ | ||
| Name: "projects", | ||
| Usage: "Group this machine's coding agent projects by git repository instead of folder", | ||
|
AnnatarHe marked this conversation as resolved.
Resolved
|
||
| Description: "Sessions recorded before ShellTime named their git repository are grouped into projects by\n" + | ||
| "machine and folder, so a renamed or moved clone shows up as another project. This finds the\n" + | ||
| "repository of each such folder that still exists on this machine and moves its sessions into\n" + | ||
| "that repository's project. The daemon does this once on its own; run it again any time.", | ||
| Flags: []cli.Flag{ | ||
| &cli.BoolFlag{ | ||
| Name: "dry-run", | ||
| Usage: "show which folders would move without changing anything", | ||
| }, | ||
| }, | ||
| Action: commandAICodeProjects, | ||
| } | ||
|
|
||
| // aiCodeProjectsHosts names this machine for the migration; tests replace it. | ||
| var aiCodeProjectsHosts = func() []string { | ||
| return model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) | ||
| } | ||
|
|
||
| func commandAICodeProjects(c *cli.Context) error { | ||
| ctx, span := commandTracer.Start(c.Context, "aicode.projects", trace.WithSpanKind(trace.SpanKindClient)) | ||
| defer span.End() | ||
| SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER)) | ||
|
|
||
| cfg, err := configService.ReadConfigFile(ctx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if cfg.Token == "" { | ||
|
AnnatarHe marked this conversation as resolved.
Resolved
|
||
| return errors.New("no ShellTime token configured, run `shelltime init` first") | ||
| } | ||
| if skippedInAICloudOnly(cfg, "Projects not grouped") { | ||
| return nil | ||
| } | ||
| if !cfg.SendsRepository() { | ||
| color.Yellow.Println("Projects not grouped: aiCodeOtel.sendRepository is off, so no repository is sent.") | ||
| return nil | ||
| } | ||
| endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} | ||
| hosts := aiCodeProjectsHosts() | ||
| if len(hosts) == 0 { | ||
| return errors.New("this machine's host name is one many machines share (like localhost), so its projects can't be told apart from theirs") | ||
| } | ||
| dryRun := c.Bool("dry-run") | ||
|
|
||
| color.Yellow.Println("Looking for projects grouped by folder...") | ||
| result, err := model.MigrateProjectRepositories(ctx, endpoint, hosts, model.NewGitRepositoryResolver(time.Hour), dryRun) | ||
| span.SetAttributes(attribute.Int("checked", result.Checked), attribute.Int("linked", len(result.Linked))) | ||
| if err != nil { | ||
| var statusErr *model.HTTPStatusError | ||
| if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound { | ||
| return errors.New("the ShellTime server can't group projects by repository yet, please try again after it is updated") | ||
| } | ||
| return fmt.Errorf("project migration failed: %w", err) | ||
| } | ||
|
|
||
| if result.Checked == 0 { | ||
| color.Green.Println("Every project of this machine is already grouped by repository.") | ||
| return nil | ||
| } | ||
| if len(result.Linked) > 0 { | ||
| w := tablewriter.NewWriter(os.Stdout) | ||
| w.Header([]string{"FOLDER", "REPOSITORY"}) | ||
| for _, p := range result.Linked { | ||
| w.Append([]string{p.Pwd, p.Repository}) | ||
| } | ||
| w.Render() | ||
| } | ||
|
|
||
| fmt.Printf("%d folder projects found: %d in a git repository, %d no longer here, %d not in a repository with a remote.\n", | ||
| result.Checked, len(result.Linked), result.Missing, result.NotRepositories) | ||
| if result.Unchecked > 0 { | ||
| color.Yellow.Printf("git didn't answer for %d folders; run it again to check them.\n", result.Unchecked) | ||
| } | ||
| if result.Truncated { | ||
| color.Yellow.Println("This machine has more folder projects than one run goes through; run it again to check the rest.") | ||
| } | ||
| switch { | ||
| case dryRun: | ||
| color.Green.Println("Dry run: nothing was changed.") | ||
| case len(result.Linked) > 0: | ||
| color.Green.Printf("Moved %s sessions into their repositories' projects.\n", strconv.Itoa(result.Sessions)) | ||
| } | ||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| package commands | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "os/exec" | ||
| "testing" | ||
|
|
||
| "github.com/malamtime/cli/model" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/mock" | ||
| "github.com/stretchr/testify/require" | ||
| "github.com/urfave/cli/v2" | ||
| ) | ||
|
|
||
| func runProjects(t *testing.T, group string, token, endpoint string, args ...string) error { | ||
| t.Helper() | ||
| setupCCTest(t) | ||
| original := configService | ||
| mc := model.NewMockConfigService(t) | ||
| mc.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{Token: token, APIEndpoint: endpoint}, nil).Maybe() | ||
| configService = mc | ||
| t.Cleanup(func() { configService = original }) | ||
|
|
||
| // The machine's own host name may be a generic one (a CI runner's), which names nothing. | ||
| originalHosts := aiCodeProjectsHosts | ||
| aiCodeProjectsHosts = func() []string { return []string{"mbp"} } | ||
| t.Cleanup(func() { aiCodeProjectsHosts = originalHosts }) | ||
|
|
||
| app := &cli.App{Name: "t", Commands: []*cli.Command{{Name: group, Subcommands: []*cli.Command{AICodeProjectsCommand}}}} | ||
| return app.Run(append([]string{"t", group, "projects"}, args...)) | ||
| } | ||
|
|
||
| func TestAICodeProjectsMovesClones(t *testing.T) { | ||
|
AnnatarHe marked this conversation as resolved.
Resolved
|
||
| if _, err := exec.LookPath("git"); err != nil { | ||
| t.Skip("git is not installed") | ||
| } | ||
| dir := t.TempDir() | ||
| for _, args := range [][]string{{"init", "-q"}, {"remote", "add", "origin", "https://github.com/acme/web.git"}} { | ||
| out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput() | ||
| require.NoError(t, err, string(out)) | ||
| } | ||
|
|
||
| var moves int | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| switch r.URL.Path { | ||
| case "/api/v1/cc/projects/unresolved": | ||
| _ = json.NewEncoder(w).Encode(map[string]any{"projects": []map[string]any{{"host": "mbp", "pwd": dir, "sessions": 2}}}) | ||
| case "/api/v1/cc/projects/repositories": | ||
| moves++ | ||
| _ = json.NewEncoder(w).Encode(map[string]int{"updated": 2}) | ||
| } | ||
| })) | ||
| t.Cleanup(server.Close) | ||
|
|
||
| require.NoError(t, runProjects(t, "codex", "tok", server.URL, "--dry-run")) | ||
| assert.Zero(t, moves) | ||
| require.NoError(t, runProjects(t, "cc", "tok", server.URL)) | ||
| assert.Equal(t, 1, moves) | ||
| } | ||
|
|
||
| func TestAICodeProjectsSkippedInAICloudOnly(t *testing.T) { | ||
| t.Setenv("CLAUDE_CODE_REMOTE", "true") | ||
| var requests int | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| requests++ | ||
| })) | ||
| t.Cleanup(server.Close) | ||
|
|
||
| require.NoError(t, runProjects(t, "cc", "tok", server.URL)) | ||
| assert.Zero(t, requests, "a cloud VM sends no host name or folders") | ||
| } | ||
|
|
||
| func TestAICodeProjectsErrors(t *testing.T) { | ||
| assert.ErrorContains(t, runProjects(t, "cc", "", "http://127.0.0.1:0"), "no ShellTime token") | ||
|
|
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusNotFound) | ||
| })) | ||
| t.Cleanup(server.Close) | ||
| assert.ErrorContains(t, runProjects(t, "cc", "tok", server.URL), "can't group projects by repository yet") | ||
|
AnnatarHe marked this conversation as resolved.
Resolved
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.