ADAPT-Chase commited on
Commit
15dd6cd
·
verified ·
1 Parent(s): ee8f748

Add files using upload-large-folder tool

Browse files
projects/ui/crush/internal/db/db.go ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+
5
+ package db
6
+
7
+ import (
8
+ "context"
9
+ "database/sql"
10
+ "fmt"
11
+ )
12
+
13
+ type DBTX interface {
14
+ ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
15
+ PrepareContext(context.Context, string) (*sql.Stmt, error)
16
+ QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
17
+ QueryRowContext(context.Context, string, ...interface{}) *sql.Row
18
+ }
19
+
20
+ func New(db DBTX) *Queries {
21
+ return &Queries{db: db}
22
+ }
23
+
24
+ func Prepare(ctx context.Context, db DBTX) (*Queries, error) {
25
+ q := Queries{db: db}
26
+ var err error
27
+ if q.createFileStmt, err = db.PrepareContext(ctx, createFile); err != nil {
28
+ return nil, fmt.Errorf("error preparing query CreateFile: %w", err)
29
+ }
30
+ if q.createMessageStmt, err = db.PrepareContext(ctx, createMessage); err != nil {
31
+ return nil, fmt.Errorf("error preparing query CreateMessage: %w", err)
32
+ }
33
+ if q.createSessionStmt, err = db.PrepareContext(ctx, createSession); err != nil {
34
+ return nil, fmt.Errorf("error preparing query CreateSession: %w", err)
35
+ }
36
+ if q.deleteFileStmt, err = db.PrepareContext(ctx, deleteFile); err != nil {
37
+ return nil, fmt.Errorf("error preparing query DeleteFile: %w", err)
38
+ }
39
+ if q.deleteMessageStmt, err = db.PrepareContext(ctx, deleteMessage); err != nil {
40
+ return nil, fmt.Errorf("error preparing query DeleteMessage: %w", err)
41
+ }
42
+ if q.deleteSessionStmt, err = db.PrepareContext(ctx, deleteSession); err != nil {
43
+ return nil, fmt.Errorf("error preparing query DeleteSession: %w", err)
44
+ }
45
+ if q.deleteSessionFilesStmt, err = db.PrepareContext(ctx, deleteSessionFiles); err != nil {
46
+ return nil, fmt.Errorf("error preparing query DeleteSessionFiles: %w", err)
47
+ }
48
+ if q.deleteSessionMessagesStmt, err = db.PrepareContext(ctx, deleteSessionMessages); err != nil {
49
+ return nil, fmt.Errorf("error preparing query DeleteSessionMessages: %w", err)
50
+ }
51
+ if q.getFileStmt, err = db.PrepareContext(ctx, getFile); err != nil {
52
+ return nil, fmt.Errorf("error preparing query GetFile: %w", err)
53
+ }
54
+ if q.getFileByPathAndSessionStmt, err = db.PrepareContext(ctx, getFileByPathAndSession); err != nil {
55
+ return nil, fmt.Errorf("error preparing query GetFileByPathAndSession: %w", err)
56
+ }
57
+ if q.getMessageStmt, err = db.PrepareContext(ctx, getMessage); err != nil {
58
+ return nil, fmt.Errorf("error preparing query GetMessage: %w", err)
59
+ }
60
+ if q.getSessionByIDStmt, err = db.PrepareContext(ctx, getSessionByID); err != nil {
61
+ return nil, fmt.Errorf("error preparing query GetSessionByID: %w", err)
62
+ }
63
+ if q.listFilesByPathStmt, err = db.PrepareContext(ctx, listFilesByPath); err != nil {
64
+ return nil, fmt.Errorf("error preparing query ListFilesByPath: %w", err)
65
+ }
66
+ if q.listFilesBySessionStmt, err = db.PrepareContext(ctx, listFilesBySession); err != nil {
67
+ return nil, fmt.Errorf("error preparing query ListFilesBySession: %w", err)
68
+ }
69
+ if q.listLatestSessionFilesStmt, err = db.PrepareContext(ctx, listLatestSessionFiles); err != nil {
70
+ return nil, fmt.Errorf("error preparing query ListLatestSessionFiles: %w", err)
71
+ }
72
+ if q.listMessagesBySessionStmt, err = db.PrepareContext(ctx, listMessagesBySession); err != nil {
73
+ return nil, fmt.Errorf("error preparing query ListMessagesBySession: %w", err)
74
+ }
75
+ if q.listNewFilesStmt, err = db.PrepareContext(ctx, listNewFiles); err != nil {
76
+ return nil, fmt.Errorf("error preparing query ListNewFiles: %w", err)
77
+ }
78
+ if q.listSessionsStmt, err = db.PrepareContext(ctx, listSessions); err != nil {
79
+ return nil, fmt.Errorf("error preparing query ListSessions: %w", err)
80
+ }
81
+ if q.updateMessageStmt, err = db.PrepareContext(ctx, updateMessage); err != nil {
82
+ return nil, fmt.Errorf("error preparing query UpdateMessage: %w", err)
83
+ }
84
+ if q.updateSessionStmt, err = db.PrepareContext(ctx, updateSession); err != nil {
85
+ return nil, fmt.Errorf("error preparing query UpdateSession: %w", err)
86
+ }
87
+ return &q, nil
88
+ }
89
+
90
+ func (q *Queries) Close() error {
91
+ var err error
92
+ if q.createFileStmt != nil {
93
+ if cerr := q.createFileStmt.Close(); cerr != nil {
94
+ err = fmt.Errorf("error closing createFileStmt: %w", cerr)
95
+ }
96
+ }
97
+ if q.createMessageStmt != nil {
98
+ if cerr := q.createMessageStmt.Close(); cerr != nil {
99
+ err = fmt.Errorf("error closing createMessageStmt: %w", cerr)
100
+ }
101
+ }
102
+ if q.createSessionStmt != nil {
103
+ if cerr := q.createSessionStmt.Close(); cerr != nil {
104
+ err = fmt.Errorf("error closing createSessionStmt: %w", cerr)
105
+ }
106
+ }
107
+ if q.deleteFileStmt != nil {
108
+ if cerr := q.deleteFileStmt.Close(); cerr != nil {
109
+ err = fmt.Errorf("error closing deleteFileStmt: %w", cerr)
110
+ }
111
+ }
112
+ if q.deleteMessageStmt != nil {
113
+ if cerr := q.deleteMessageStmt.Close(); cerr != nil {
114
+ err = fmt.Errorf("error closing deleteMessageStmt: %w", cerr)
115
+ }
116
+ }
117
+ if q.deleteSessionStmt != nil {
118
+ if cerr := q.deleteSessionStmt.Close(); cerr != nil {
119
+ err = fmt.Errorf("error closing deleteSessionStmt: %w", cerr)
120
+ }
121
+ }
122
+ if q.deleteSessionFilesStmt != nil {
123
+ if cerr := q.deleteSessionFilesStmt.Close(); cerr != nil {
124
+ err = fmt.Errorf("error closing deleteSessionFilesStmt: %w", cerr)
125
+ }
126
+ }
127
+ if q.deleteSessionMessagesStmt != nil {
128
+ if cerr := q.deleteSessionMessagesStmt.Close(); cerr != nil {
129
+ err = fmt.Errorf("error closing deleteSessionMessagesStmt: %w", cerr)
130
+ }
131
+ }
132
+ if q.getFileStmt != nil {
133
+ if cerr := q.getFileStmt.Close(); cerr != nil {
134
+ err = fmt.Errorf("error closing getFileStmt: %w", cerr)
135
+ }
136
+ }
137
+ if q.getFileByPathAndSessionStmt != nil {
138
+ if cerr := q.getFileByPathAndSessionStmt.Close(); cerr != nil {
139
+ err = fmt.Errorf("error closing getFileByPathAndSessionStmt: %w", cerr)
140
+ }
141
+ }
142
+ if q.getMessageStmt != nil {
143
+ if cerr := q.getMessageStmt.Close(); cerr != nil {
144
+ err = fmt.Errorf("error closing getMessageStmt: %w", cerr)
145
+ }
146
+ }
147
+ if q.getSessionByIDStmt != nil {
148
+ if cerr := q.getSessionByIDStmt.Close(); cerr != nil {
149
+ err = fmt.Errorf("error closing getSessionByIDStmt: %w", cerr)
150
+ }
151
+ }
152
+ if q.listFilesByPathStmt != nil {
153
+ if cerr := q.listFilesByPathStmt.Close(); cerr != nil {
154
+ err = fmt.Errorf("error closing listFilesByPathStmt: %w", cerr)
155
+ }
156
+ }
157
+ if q.listFilesBySessionStmt != nil {
158
+ if cerr := q.listFilesBySessionStmt.Close(); cerr != nil {
159
+ err = fmt.Errorf("error closing listFilesBySessionStmt: %w", cerr)
160
+ }
161
+ }
162
+ if q.listLatestSessionFilesStmt != nil {
163
+ if cerr := q.listLatestSessionFilesStmt.Close(); cerr != nil {
164
+ err = fmt.Errorf("error closing listLatestSessionFilesStmt: %w", cerr)
165
+ }
166
+ }
167
+ if q.listMessagesBySessionStmt != nil {
168
+ if cerr := q.listMessagesBySessionStmt.Close(); cerr != nil {
169
+ err = fmt.Errorf("error closing listMessagesBySessionStmt: %w", cerr)
170
+ }
171
+ }
172
+ if q.listNewFilesStmt != nil {
173
+ if cerr := q.listNewFilesStmt.Close(); cerr != nil {
174
+ err = fmt.Errorf("error closing listNewFilesStmt: %w", cerr)
175
+ }
176
+ }
177
+ if q.listSessionsStmt != nil {
178
+ if cerr := q.listSessionsStmt.Close(); cerr != nil {
179
+ err = fmt.Errorf("error closing listSessionsStmt: %w", cerr)
180
+ }
181
+ }
182
+ if q.updateMessageStmt != nil {
183
+ if cerr := q.updateMessageStmt.Close(); cerr != nil {
184
+ err = fmt.Errorf("error closing updateMessageStmt: %w", cerr)
185
+ }
186
+ }
187
+ if q.updateSessionStmt != nil {
188
+ if cerr := q.updateSessionStmt.Close(); cerr != nil {
189
+ err = fmt.Errorf("error closing updateSessionStmt: %w", cerr)
190
+ }
191
+ }
192
+ return err
193
+ }
194
+
195
+ func (q *Queries) exec(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (sql.Result, error) {
196
+ switch {
197
+ case stmt != nil && q.tx != nil:
198
+ return q.tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)
199
+ case stmt != nil:
200
+ return stmt.ExecContext(ctx, args...)
201
+ default:
202
+ return q.db.ExecContext(ctx, query, args...)
203
+ }
204
+ }
205
+
206
+ func (q *Queries) query(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) (*sql.Rows, error) {
207
+ switch {
208
+ case stmt != nil && q.tx != nil:
209
+ return q.tx.StmtContext(ctx, stmt).QueryContext(ctx, args...)
210
+ case stmt != nil:
211
+ return stmt.QueryContext(ctx, args...)
212
+ default:
213
+ return q.db.QueryContext(ctx, query, args...)
214
+ }
215
+ }
216
+
217
+ func (q *Queries) queryRow(ctx context.Context, stmt *sql.Stmt, query string, args ...interface{}) *sql.Row {
218
+ switch {
219
+ case stmt != nil && q.tx != nil:
220
+ return q.tx.StmtContext(ctx, stmt).QueryRowContext(ctx, args...)
221
+ case stmt != nil:
222
+ return stmt.QueryRowContext(ctx, args...)
223
+ default:
224
+ return q.db.QueryRowContext(ctx, query, args...)
225
+ }
226
+ }
227
+
228
+ type Queries struct {
229
+ db DBTX
230
+ tx *sql.Tx
231
+ createFileStmt *sql.Stmt
232
+ createMessageStmt *sql.Stmt
233
+ createSessionStmt *sql.Stmt
234
+ deleteFileStmt *sql.Stmt
235
+ deleteMessageStmt *sql.Stmt
236
+ deleteSessionStmt *sql.Stmt
237
+ deleteSessionFilesStmt *sql.Stmt
238
+ deleteSessionMessagesStmt *sql.Stmt
239
+ getFileStmt *sql.Stmt
240
+ getFileByPathAndSessionStmt *sql.Stmt
241
+ getMessageStmt *sql.Stmt
242
+ getSessionByIDStmt *sql.Stmt
243
+ listFilesByPathStmt *sql.Stmt
244
+ listFilesBySessionStmt *sql.Stmt
245
+ listLatestSessionFilesStmt *sql.Stmt
246
+ listMessagesBySessionStmt *sql.Stmt
247
+ listNewFilesStmt *sql.Stmt
248
+ listSessionsStmt *sql.Stmt
249
+ updateMessageStmt *sql.Stmt
250
+ updateSessionStmt *sql.Stmt
251
+ }
252
+
253
+ func (q *Queries) WithTx(tx *sql.Tx) *Queries {
254
+ return &Queries{
255
+ db: tx,
256
+ tx: tx,
257
+ createFileStmt: q.createFileStmt,
258
+ createMessageStmt: q.createMessageStmt,
259
+ createSessionStmt: q.createSessionStmt,
260
+ deleteFileStmt: q.deleteFileStmt,
261
+ deleteMessageStmt: q.deleteMessageStmt,
262
+ deleteSessionStmt: q.deleteSessionStmt,
263
+ deleteSessionFilesStmt: q.deleteSessionFilesStmt,
264
+ deleteSessionMessagesStmt: q.deleteSessionMessagesStmt,
265
+ getFileStmt: q.getFileStmt,
266
+ getFileByPathAndSessionStmt: q.getFileByPathAndSessionStmt,
267
+ getMessageStmt: q.getMessageStmt,
268
+ getSessionByIDStmt: q.getSessionByIDStmt,
269
+ listFilesByPathStmt: q.listFilesByPathStmt,
270
+ listFilesBySessionStmt: q.listFilesBySessionStmt,
271
+ listLatestSessionFilesStmt: q.listLatestSessionFilesStmt,
272
+ listMessagesBySessionStmt: q.listMessagesBySessionStmt,
273
+ listNewFilesStmt: q.listNewFilesStmt,
274
+ listSessionsStmt: q.listSessionsStmt,
275
+ updateMessageStmt: q.updateMessageStmt,
276
+ updateSessionStmt: q.updateSessionStmt,
277
+ }
278
+ }
projects/ui/crush/internal/db/embed.go ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ package db
2
+
3
+ import "embed"
4
+
5
+ //go:embed migrations/*.sql
6
+ var FS embed.FS
projects/ui/crush/internal/db/files.sql.go ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+ // source: files.sql
5
+
6
+ package db
7
+
8
+ import (
9
+ "context"
10
+ )
11
+
12
+ const createFile = `-- name: CreateFile :one
13
+ INSERT INTO files (
14
+ id,
15
+ session_id,
16
+ path,
17
+ content,
18
+ version,
19
+ created_at,
20
+ updated_at
21
+ ) VALUES (
22
+ ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')
23
+ )
24
+ RETURNING id, session_id, path, content, version, created_at, updated_at
25
+ `
26
+
27
+ type CreateFileParams struct {
28
+ ID string `json:"id"`
29
+ SessionID string `json:"session_id"`
30
+ Path string `json:"path"`
31
+ Content string `json:"content"`
32
+ Version int64 `json:"version"`
33
+ }
34
+
35
+ func (q *Queries) CreateFile(ctx context.Context, arg CreateFileParams) (File, error) {
36
+ row := q.queryRow(ctx, q.createFileStmt, createFile,
37
+ arg.ID,
38
+ arg.SessionID,
39
+ arg.Path,
40
+ arg.Content,
41
+ arg.Version,
42
+ )
43
+ var i File
44
+ err := row.Scan(
45
+ &i.ID,
46
+ &i.SessionID,
47
+ &i.Path,
48
+ &i.Content,
49
+ &i.Version,
50
+ &i.CreatedAt,
51
+ &i.UpdatedAt,
52
+ )
53
+ return i, err
54
+ }
55
+
56
+ const deleteFile = `-- name: DeleteFile :exec
57
+ DELETE FROM files
58
+ WHERE id = ?
59
+ `
60
+
61
+ func (q *Queries) DeleteFile(ctx context.Context, id string) error {
62
+ _, err := q.exec(ctx, q.deleteFileStmt, deleteFile, id)
63
+ return err
64
+ }
65
+
66
+ const deleteSessionFiles = `-- name: DeleteSessionFiles :exec
67
+ DELETE FROM files
68
+ WHERE session_id = ?
69
+ `
70
+
71
+ func (q *Queries) DeleteSessionFiles(ctx context.Context, sessionID string) error {
72
+ _, err := q.exec(ctx, q.deleteSessionFilesStmt, deleteSessionFiles, sessionID)
73
+ return err
74
+ }
75
+
76
+ const getFile = `-- name: GetFile :one
77
+ SELECT id, session_id, path, content, version, created_at, updated_at
78
+ FROM files
79
+ WHERE id = ? LIMIT 1
80
+ `
81
+
82
+ func (q *Queries) GetFile(ctx context.Context, id string) (File, error) {
83
+ row := q.queryRow(ctx, q.getFileStmt, getFile, id)
84
+ var i File
85
+ err := row.Scan(
86
+ &i.ID,
87
+ &i.SessionID,
88
+ &i.Path,
89
+ &i.Content,
90
+ &i.Version,
91
+ &i.CreatedAt,
92
+ &i.UpdatedAt,
93
+ )
94
+ return i, err
95
+ }
96
+
97
+ const getFileByPathAndSession = `-- name: GetFileByPathAndSession :one
98
+ SELECT id, session_id, path, content, version, created_at, updated_at
99
+ FROM files
100
+ WHERE path = ? AND session_id = ?
101
+ ORDER BY version DESC, created_at DESC
102
+ LIMIT 1
103
+ `
104
+
105
+ type GetFileByPathAndSessionParams struct {
106
+ Path string `json:"path"`
107
+ SessionID string `json:"session_id"`
108
+ }
109
+
110
+ func (q *Queries) GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error) {
111
+ row := q.queryRow(ctx, q.getFileByPathAndSessionStmt, getFileByPathAndSession, arg.Path, arg.SessionID)
112
+ var i File
113
+ err := row.Scan(
114
+ &i.ID,
115
+ &i.SessionID,
116
+ &i.Path,
117
+ &i.Content,
118
+ &i.Version,
119
+ &i.CreatedAt,
120
+ &i.UpdatedAt,
121
+ )
122
+ return i, err
123
+ }
124
+
125
+ const listFilesByPath = `-- name: ListFilesByPath :many
126
+ SELECT id, session_id, path, content, version, created_at, updated_at
127
+ FROM files
128
+ WHERE path = ?
129
+ ORDER BY version DESC, created_at DESC
130
+ `
131
+
132
+ func (q *Queries) ListFilesByPath(ctx context.Context, path string) ([]File, error) {
133
+ rows, err := q.query(ctx, q.listFilesByPathStmt, listFilesByPath, path)
134
+ if err != nil {
135
+ return nil, err
136
+ }
137
+ defer rows.Close()
138
+ items := []File{}
139
+ for rows.Next() {
140
+ var i File
141
+ if err := rows.Scan(
142
+ &i.ID,
143
+ &i.SessionID,
144
+ &i.Path,
145
+ &i.Content,
146
+ &i.Version,
147
+ &i.CreatedAt,
148
+ &i.UpdatedAt,
149
+ ); err != nil {
150
+ return nil, err
151
+ }
152
+ items = append(items, i)
153
+ }
154
+ if err := rows.Close(); err != nil {
155
+ return nil, err
156
+ }
157
+ if err := rows.Err(); err != nil {
158
+ return nil, err
159
+ }
160
+ return items, nil
161
+ }
162
+
163
+ const listFilesBySession = `-- name: ListFilesBySession :many
164
+ SELECT id, session_id, path, content, version, created_at, updated_at
165
+ FROM files
166
+ WHERE session_id = ?
167
+ ORDER BY version ASC, created_at ASC
168
+ `
169
+
170
+ func (q *Queries) ListFilesBySession(ctx context.Context, sessionID string) ([]File, error) {
171
+ rows, err := q.query(ctx, q.listFilesBySessionStmt, listFilesBySession, sessionID)
172
+ if err != nil {
173
+ return nil, err
174
+ }
175
+ defer rows.Close()
176
+ items := []File{}
177
+ for rows.Next() {
178
+ var i File
179
+ if err := rows.Scan(
180
+ &i.ID,
181
+ &i.SessionID,
182
+ &i.Path,
183
+ &i.Content,
184
+ &i.Version,
185
+ &i.CreatedAt,
186
+ &i.UpdatedAt,
187
+ ); err != nil {
188
+ return nil, err
189
+ }
190
+ items = append(items, i)
191
+ }
192
+ if err := rows.Close(); err != nil {
193
+ return nil, err
194
+ }
195
+ if err := rows.Err(); err != nil {
196
+ return nil, err
197
+ }
198
+ return items, nil
199
+ }
200
+
201
+ const listLatestSessionFiles = `-- name: ListLatestSessionFiles :many
202
+ SELECT f.id, f.session_id, f.path, f.content, f.version, f.created_at, f.updated_at
203
+ FROM files f
204
+ INNER JOIN (
205
+ SELECT path, MAX(version) as max_version, MAX(created_at) as max_created_at
206
+ FROM files
207
+ GROUP BY path
208
+ ) latest ON f.path = latest.path AND f.version = latest.max_version AND f.created_at = latest.max_created_at
209
+ WHERE f.session_id = ?
210
+ ORDER BY f.path
211
+ `
212
+
213
+ func (q *Queries) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {
214
+ rows, err := q.query(ctx, q.listLatestSessionFilesStmt, listLatestSessionFiles, sessionID)
215
+ if err != nil {
216
+ return nil, err
217
+ }
218
+ defer rows.Close()
219
+ items := []File{}
220
+ for rows.Next() {
221
+ var i File
222
+ if err := rows.Scan(
223
+ &i.ID,
224
+ &i.SessionID,
225
+ &i.Path,
226
+ &i.Content,
227
+ &i.Version,
228
+ &i.CreatedAt,
229
+ &i.UpdatedAt,
230
+ ); err != nil {
231
+ return nil, err
232
+ }
233
+ items = append(items, i)
234
+ }
235
+ if err := rows.Close(); err != nil {
236
+ return nil, err
237
+ }
238
+ if err := rows.Err(); err != nil {
239
+ return nil, err
240
+ }
241
+ return items, nil
242
+ }
243
+
244
+ const listNewFiles = `-- name: ListNewFiles :many
245
+ SELECT id, session_id, path, content, version, created_at, updated_at
246
+ FROM files
247
+ WHERE is_new = 1
248
+ ORDER BY version DESC, created_at DESC
249
+ `
250
+
251
+ func (q *Queries) ListNewFiles(ctx context.Context) ([]File, error) {
252
+ rows, err := q.query(ctx, q.listNewFilesStmt, listNewFiles)
253
+ if err != nil {
254
+ return nil, err
255
+ }
256
+ defer rows.Close()
257
+ items := []File{}
258
+ for rows.Next() {
259
+ var i File
260
+ if err := rows.Scan(
261
+ &i.ID,
262
+ &i.SessionID,
263
+ &i.Path,
264
+ &i.Content,
265
+ &i.Version,
266
+ &i.CreatedAt,
267
+ &i.UpdatedAt,
268
+ ); err != nil {
269
+ return nil, err
270
+ }
271
+ items = append(items, i)
272
+ }
273
+ if err := rows.Close(); err != nil {
274
+ return nil, err
275
+ }
276
+ if err := rows.Err(); err != nil {
277
+ return nil, err
278
+ }
279
+ return items, nil
280
+ }
projects/ui/crush/internal/db/messages.sql.go ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+ // source: messages.sql
5
+
6
+ package db
7
+
8
+ import (
9
+ "context"
10
+ "database/sql"
11
+ )
12
+
13
+ const createMessage = `-- name: CreateMessage :one
14
+ INSERT INTO messages (
15
+ id,
16
+ session_id,
17
+ role,
18
+ parts,
19
+ model,
20
+ provider,
21
+ created_at,
22
+ updated_at
23
+ ) VALUES (
24
+ ?, ?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now')
25
+ )
26
+ RETURNING id, session_id, role, parts, model, created_at, updated_at, finished_at, provider
27
+ `
28
+
29
+ type CreateMessageParams struct {
30
+ ID string `json:"id"`
31
+ SessionID string `json:"session_id"`
32
+ Role string `json:"role"`
33
+ Parts string `json:"parts"`
34
+ Model sql.NullString `json:"model"`
35
+ Provider sql.NullString `json:"provider"`
36
+ }
37
+
38
+ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
39
+ row := q.queryRow(ctx, q.createMessageStmt, createMessage,
40
+ arg.ID,
41
+ arg.SessionID,
42
+ arg.Role,
43
+ arg.Parts,
44
+ arg.Model,
45
+ arg.Provider,
46
+ )
47
+ var i Message
48
+ err := row.Scan(
49
+ &i.ID,
50
+ &i.SessionID,
51
+ &i.Role,
52
+ &i.Parts,
53
+ &i.Model,
54
+ &i.CreatedAt,
55
+ &i.UpdatedAt,
56
+ &i.FinishedAt,
57
+ &i.Provider,
58
+ )
59
+ return i, err
60
+ }
61
+
62
+ const deleteMessage = `-- name: DeleteMessage :exec
63
+ DELETE FROM messages
64
+ WHERE id = ?
65
+ `
66
+
67
+ func (q *Queries) DeleteMessage(ctx context.Context, id string) error {
68
+ _, err := q.exec(ctx, q.deleteMessageStmt, deleteMessage, id)
69
+ return err
70
+ }
71
+
72
+ const deleteSessionMessages = `-- name: DeleteSessionMessages :exec
73
+ DELETE FROM messages
74
+ WHERE session_id = ?
75
+ `
76
+
77
+ func (q *Queries) DeleteSessionMessages(ctx context.Context, sessionID string) error {
78
+ _, err := q.exec(ctx, q.deleteSessionMessagesStmt, deleteSessionMessages, sessionID)
79
+ return err
80
+ }
81
+
82
+ const getMessage = `-- name: GetMessage :one
83
+ SELECT id, session_id, role, parts, model, created_at, updated_at, finished_at, provider
84
+ FROM messages
85
+ WHERE id = ? LIMIT 1
86
+ `
87
+
88
+ func (q *Queries) GetMessage(ctx context.Context, id string) (Message, error) {
89
+ row := q.queryRow(ctx, q.getMessageStmt, getMessage, id)
90
+ var i Message
91
+ err := row.Scan(
92
+ &i.ID,
93
+ &i.SessionID,
94
+ &i.Role,
95
+ &i.Parts,
96
+ &i.Model,
97
+ &i.CreatedAt,
98
+ &i.UpdatedAt,
99
+ &i.FinishedAt,
100
+ &i.Provider,
101
+ )
102
+ return i, err
103
+ }
104
+
105
+ const listMessagesBySession = `-- name: ListMessagesBySession :many
106
+ SELECT id, session_id, role, parts, model, created_at, updated_at, finished_at, provider
107
+ FROM messages
108
+ WHERE session_id = ?
109
+ ORDER BY created_at ASC
110
+ `
111
+
112
+ func (q *Queries) ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error) {
113
+ rows, err := q.query(ctx, q.listMessagesBySessionStmt, listMessagesBySession, sessionID)
114
+ if err != nil {
115
+ return nil, err
116
+ }
117
+ defer rows.Close()
118
+ items := []Message{}
119
+ for rows.Next() {
120
+ var i Message
121
+ if err := rows.Scan(
122
+ &i.ID,
123
+ &i.SessionID,
124
+ &i.Role,
125
+ &i.Parts,
126
+ &i.Model,
127
+ &i.CreatedAt,
128
+ &i.UpdatedAt,
129
+ &i.FinishedAt,
130
+ &i.Provider,
131
+ ); err != nil {
132
+ return nil, err
133
+ }
134
+ items = append(items, i)
135
+ }
136
+ if err := rows.Close(); err != nil {
137
+ return nil, err
138
+ }
139
+ if err := rows.Err(); err != nil {
140
+ return nil, err
141
+ }
142
+ return items, nil
143
+ }
144
+
145
+ const updateMessage = `-- name: UpdateMessage :exec
146
+ UPDATE messages
147
+ SET
148
+ parts = ?,
149
+ finished_at = ?,
150
+ updated_at = strftime('%s', 'now')
151
+ WHERE id = ?
152
+ `
153
+
154
+ type UpdateMessageParams struct {
155
+ Parts string `json:"parts"`
156
+ FinishedAt sql.NullInt64 `json:"finished_at"`
157
+ ID string `json:"id"`
158
+ }
159
+
160
+ func (q *Queries) UpdateMessage(ctx context.Context, arg UpdateMessageParams) error {
161
+ _, err := q.exec(ctx, q.updateMessageStmt, updateMessage, arg.Parts, arg.FinishedAt, arg.ID)
162
+ return err
163
+ }
projects/ui/crush/internal/db/models.go ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+
5
+ package db
6
+
7
+ import (
8
+ "database/sql"
9
+ )
10
+
11
+ type File struct {
12
+ ID string `json:"id"`
13
+ SessionID string `json:"session_id"`
14
+ Path string `json:"path"`
15
+ Content string `json:"content"`
16
+ Version int64 `json:"version"`
17
+ CreatedAt int64 `json:"created_at"`
18
+ UpdatedAt int64 `json:"updated_at"`
19
+ }
20
+
21
+ type Message struct {
22
+ ID string `json:"id"`
23
+ SessionID string `json:"session_id"`
24
+ Role string `json:"role"`
25
+ Parts string `json:"parts"`
26
+ Model sql.NullString `json:"model"`
27
+ CreatedAt int64 `json:"created_at"`
28
+ UpdatedAt int64 `json:"updated_at"`
29
+ FinishedAt sql.NullInt64 `json:"finished_at"`
30
+ Provider sql.NullString `json:"provider"`
31
+ }
32
+
33
+ type Session struct {
34
+ ID string `json:"id"`
35
+ ParentSessionID sql.NullString `json:"parent_session_id"`
36
+ Title string `json:"title"`
37
+ MessageCount int64 `json:"message_count"`
38
+ PromptTokens int64 `json:"prompt_tokens"`
39
+ CompletionTokens int64 `json:"completion_tokens"`
40
+ Cost float64 `json:"cost"`
41
+ UpdatedAt int64 `json:"updated_at"`
42
+ CreatedAt int64 `json:"created_at"`
43
+ SummaryMessageID sql.NullString `json:"summary_message_id"`
44
+ }
projects/ui/crush/internal/db/querier.go ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+
5
+ package db
6
+
7
+ import (
8
+ "context"
9
+ )
10
+
11
+ type Querier interface {
12
+ CreateFile(ctx context.Context, arg CreateFileParams) (File, error)
13
+ CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error)
14
+ CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error)
15
+ DeleteFile(ctx context.Context, id string) error
16
+ DeleteMessage(ctx context.Context, id string) error
17
+ DeleteSession(ctx context.Context, id string) error
18
+ DeleteSessionFiles(ctx context.Context, sessionID string) error
19
+ DeleteSessionMessages(ctx context.Context, sessionID string) error
20
+ GetFile(ctx context.Context, id string) (File, error)
21
+ GetFileByPathAndSession(ctx context.Context, arg GetFileByPathAndSessionParams) (File, error)
22
+ GetMessage(ctx context.Context, id string) (Message, error)
23
+ GetSessionByID(ctx context.Context, id string) (Session, error)
24
+ ListFilesByPath(ctx context.Context, path string) ([]File, error)
25
+ ListFilesBySession(ctx context.Context, sessionID string) ([]File, error)
26
+ ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)
27
+ ListMessagesBySession(ctx context.Context, sessionID string) ([]Message, error)
28
+ ListNewFiles(ctx context.Context) ([]File, error)
29
+ ListSessions(ctx context.Context) ([]Session, error)
30
+ UpdateMessage(ctx context.Context, arg UpdateMessageParams) error
31
+ UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error)
32
+ }
33
+
34
+ var _ Querier = (*Queries)(nil)
projects/ui/crush/internal/db/sessions.sql.go ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by sqlc. DO NOT EDIT.
2
+ // versions:
3
+ // sqlc v1.29.0
4
+ // source: sessions.sql
5
+
6
+ package db
7
+
8
+ import (
9
+ "context"
10
+ "database/sql"
11
+ )
12
+
13
+ const createSession = `-- name: CreateSession :one
14
+ INSERT INTO sessions (
15
+ id,
16
+ parent_session_id,
17
+ title,
18
+ message_count,
19
+ prompt_tokens,
20
+ completion_tokens,
21
+ cost,
22
+ summary_message_id,
23
+ updated_at,
24
+ created_at
25
+ ) VALUES (
26
+ ?,
27
+ ?,
28
+ ?,
29
+ ?,
30
+ ?,
31
+ ?,
32
+ ?,
33
+ null,
34
+ strftime('%s', 'now'),
35
+ strftime('%s', 'now')
36
+ ) RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id
37
+ `
38
+
39
+ type CreateSessionParams struct {
40
+ ID string `json:"id"`
41
+ ParentSessionID sql.NullString `json:"parent_session_id"`
42
+ Title string `json:"title"`
43
+ MessageCount int64 `json:"message_count"`
44
+ PromptTokens int64 `json:"prompt_tokens"`
45
+ CompletionTokens int64 `json:"completion_tokens"`
46
+ Cost float64 `json:"cost"`
47
+ }
48
+
49
+ func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (Session, error) {
50
+ row := q.queryRow(ctx, q.createSessionStmt, createSession,
51
+ arg.ID,
52
+ arg.ParentSessionID,
53
+ arg.Title,
54
+ arg.MessageCount,
55
+ arg.PromptTokens,
56
+ arg.CompletionTokens,
57
+ arg.Cost,
58
+ )
59
+ var i Session
60
+ err := row.Scan(
61
+ &i.ID,
62
+ &i.ParentSessionID,
63
+ &i.Title,
64
+ &i.MessageCount,
65
+ &i.PromptTokens,
66
+ &i.CompletionTokens,
67
+ &i.Cost,
68
+ &i.UpdatedAt,
69
+ &i.CreatedAt,
70
+ &i.SummaryMessageID,
71
+ )
72
+ return i, err
73
+ }
74
+
75
+ const deleteSession = `-- name: DeleteSession :exec
76
+ DELETE FROM sessions
77
+ WHERE id = ?
78
+ `
79
+
80
+ func (q *Queries) DeleteSession(ctx context.Context, id string) error {
81
+ _, err := q.exec(ctx, q.deleteSessionStmt, deleteSession, id)
82
+ return err
83
+ }
84
+
85
+ const getSessionByID = `-- name: GetSessionByID :one
86
+ SELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id
87
+ FROM sessions
88
+ WHERE id = ? LIMIT 1
89
+ `
90
+
91
+ func (q *Queries) GetSessionByID(ctx context.Context, id string) (Session, error) {
92
+ row := q.queryRow(ctx, q.getSessionByIDStmt, getSessionByID, id)
93
+ var i Session
94
+ err := row.Scan(
95
+ &i.ID,
96
+ &i.ParentSessionID,
97
+ &i.Title,
98
+ &i.MessageCount,
99
+ &i.PromptTokens,
100
+ &i.CompletionTokens,
101
+ &i.Cost,
102
+ &i.UpdatedAt,
103
+ &i.CreatedAt,
104
+ &i.SummaryMessageID,
105
+ )
106
+ return i, err
107
+ }
108
+
109
+ const listSessions = `-- name: ListSessions :many
110
+ SELECT id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id
111
+ FROM sessions
112
+ WHERE parent_session_id is NULL
113
+ ORDER BY created_at DESC
114
+ `
115
+
116
+ func (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {
117
+ rows, err := q.query(ctx, q.listSessionsStmt, listSessions)
118
+ if err != nil {
119
+ return nil, err
120
+ }
121
+ defer rows.Close()
122
+ items := []Session{}
123
+ for rows.Next() {
124
+ var i Session
125
+ if err := rows.Scan(
126
+ &i.ID,
127
+ &i.ParentSessionID,
128
+ &i.Title,
129
+ &i.MessageCount,
130
+ &i.PromptTokens,
131
+ &i.CompletionTokens,
132
+ &i.Cost,
133
+ &i.UpdatedAt,
134
+ &i.CreatedAt,
135
+ &i.SummaryMessageID,
136
+ ); err != nil {
137
+ return nil, err
138
+ }
139
+ items = append(items, i)
140
+ }
141
+ if err := rows.Close(); err != nil {
142
+ return nil, err
143
+ }
144
+ if err := rows.Err(); err != nil {
145
+ return nil, err
146
+ }
147
+ return items, nil
148
+ }
149
+
150
+ const updateSession = `-- name: UpdateSession :one
151
+ UPDATE sessions
152
+ SET
153
+ title = ?,
154
+ prompt_tokens = ?,
155
+ completion_tokens = ?,
156
+ summary_message_id = ?,
157
+ cost = ?
158
+ WHERE id = ?
159
+ RETURNING id, parent_session_id, title, message_count, prompt_tokens, completion_tokens, cost, updated_at, created_at, summary_message_id
160
+ `
161
+
162
+ type UpdateSessionParams struct {
163
+ Title string `json:"title"`
164
+ PromptTokens int64 `json:"prompt_tokens"`
165
+ CompletionTokens int64 `json:"completion_tokens"`
166
+ SummaryMessageID sql.NullString `json:"summary_message_id"`
167
+ Cost float64 `json:"cost"`
168
+ ID string `json:"id"`
169
+ }
170
+
171
+ func (q *Queries) UpdateSession(ctx context.Context, arg UpdateSessionParams) (Session, error) {
172
+ row := q.queryRow(ctx, q.updateSessionStmt, updateSession,
173
+ arg.Title,
174
+ arg.PromptTokens,
175
+ arg.CompletionTokens,
176
+ arg.SummaryMessageID,
177
+ arg.Cost,
178
+ arg.ID,
179
+ )
180
+ var i Session
181
+ err := row.Scan(
182
+ &i.ID,
183
+ &i.ParentSessionID,
184
+ &i.Title,
185
+ &i.MessageCount,
186
+ &i.PromptTokens,
187
+ &i.CompletionTokens,
188
+ &i.Cost,
189
+ &i.UpdatedAt,
190
+ &i.CreatedAt,
191
+ &i.SummaryMessageID,
192
+ )
193
+ return i, err
194
+ }
projects/ui/crush/internal/diff/diff.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package diff
2
+
3
+ import (
4
+ "strings"
5
+
6
+ "github.com/aymanbagabas/go-udiff"
7
+ )
8
+
9
+ // GenerateDiff creates a unified diff from two file contents
10
+ func GenerateDiff(beforeContent, afterContent, fileName string) (string, int, int) {
11
+ fileName = strings.TrimPrefix(fileName, "/")
12
+
13
+ var (
14
+ unified = udiff.Unified("a/"+fileName, "b/"+fileName, beforeContent, afterContent)
15
+ additions = 0
16
+ removals = 0
17
+ )
18
+
19
+ lines := strings.SplitSeq(unified, "\n")
20
+ for line := range lines {
21
+ if strings.HasPrefix(line, "+") && !strings.HasPrefix(line, "+++") {
22
+ additions++
23
+ } else if strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "---") {
24
+ removals++
25
+ }
26
+ }
27
+
28
+ return unified, additions, removals
29
+ }
projects/ui/crush/internal/env/env.go ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package env
2
+
3
+ import "os"
4
+
5
+ type Env interface {
6
+ Get(key string) string
7
+ Env() []string
8
+ }
9
+
10
+ type osEnv struct{}
11
+
12
+ // Get implements Env.
13
+ func (o *osEnv) Get(key string) string {
14
+ return os.Getenv(key)
15
+ }
16
+
17
+ func (o *osEnv) Env() []string {
18
+ env := os.Environ()
19
+ if len(env) == 0 {
20
+ return nil
21
+ }
22
+ return env
23
+ }
24
+
25
+ func New() Env {
26
+ return &osEnv{}
27
+ }
28
+
29
+ type mapEnv struct {
30
+ m map[string]string
31
+ }
32
+
33
+ // Get implements Env.
34
+ func (m *mapEnv) Get(key string) string {
35
+ if value, ok := m.m[key]; ok {
36
+ return value
37
+ }
38
+ return ""
39
+ }
40
+
41
+ // Env implements Env.
42
+ func (m *mapEnv) Env() []string {
43
+ if len(m.m) == 0 {
44
+ return nil
45
+ }
46
+ env := make([]string, 0, len(m.m))
47
+ for k, v := range m.m {
48
+ env = append(env, k+"="+v)
49
+ }
50
+ return env
51
+ }
52
+
53
+ func NewFromMap(m map[string]string) Env {
54
+ if m == nil {
55
+ m = make(map[string]string)
56
+ }
57
+ return &mapEnv{m: m}
58
+ }
projects/ui/crush/internal/env/env_test.go ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package env
2
+
3
+ import (
4
+ "strings"
5
+ "testing"
6
+
7
+ "github.com/stretchr/testify/require"
8
+ )
9
+
10
+ func TestOsEnv_Get(t *testing.T) {
11
+ env := New()
12
+
13
+ // Test getting an existing environment variable
14
+ t.Setenv("TEST_VAR", "test_value")
15
+
16
+ value := env.Get("TEST_VAR")
17
+ require.Equal(t, "test_value", value)
18
+
19
+ // Test getting a non-existent environment variable
20
+ value = env.Get("NON_EXISTENT_VAR")
21
+ require.Equal(t, "", value)
22
+ }
23
+
24
+ func TestOsEnv_Env(t *testing.T) {
25
+ env := New()
26
+
27
+ envVars := env.Env()
28
+
29
+ // Environment should not be empty in normal circumstances
30
+ require.NotNil(t, envVars)
31
+ require.Greater(t, len(envVars), 0)
32
+
33
+ // Each environment variable should be in key=value format
34
+ for _, envVar := range envVars {
35
+ require.Contains(t, envVar, "=")
36
+ }
37
+ }
38
+
39
+ func TestNewFromMap(t *testing.T) {
40
+ testMap := map[string]string{
41
+ "KEY1": "value1",
42
+ "KEY2": "value2",
43
+ }
44
+
45
+ env := NewFromMap(testMap)
46
+ require.NotNil(t, env)
47
+ require.IsType(t, &mapEnv{}, env)
48
+ }
49
+
50
+ func TestMapEnv_Get(t *testing.T) {
51
+ testMap := map[string]string{
52
+ "KEY1": "value1",
53
+ "KEY2": "value2",
54
+ }
55
+
56
+ env := NewFromMap(testMap)
57
+
58
+ // Test getting existing keys
59
+ require.Equal(t, "value1", env.Get("KEY1"))
60
+ require.Equal(t, "value2", env.Get("KEY2"))
61
+
62
+ // Test getting non-existent key
63
+ require.Equal(t, "", env.Get("NON_EXISTENT"))
64
+ }
65
+
66
+ func TestMapEnv_Env(t *testing.T) {
67
+ t.Run("with values", func(t *testing.T) {
68
+ testMap := map[string]string{
69
+ "KEY1": "value1",
70
+ "KEY2": "value2",
71
+ }
72
+
73
+ env := NewFromMap(testMap)
74
+ envVars := env.Env()
75
+
76
+ require.Len(t, envVars, 2)
77
+
78
+ // Convert to map for easier testing (order is not guaranteed)
79
+ envMap := make(map[string]string)
80
+ for _, envVar := range envVars {
81
+ parts := strings.SplitN(envVar, "=", 2)
82
+ require.Len(t, parts, 2)
83
+ envMap[parts[0]] = parts[1]
84
+ }
85
+
86
+ require.Equal(t, "value1", envMap["KEY1"])
87
+ require.Equal(t, "value2", envMap["KEY2"])
88
+ })
89
+
90
+ t.Run("empty map", func(t *testing.T) {
91
+ env := NewFromMap(map[string]string{})
92
+ envVars := env.Env()
93
+ require.Nil(t, envVars)
94
+ })
95
+
96
+ t.Run("nil map", func(t *testing.T) {
97
+ env := NewFromMap(nil)
98
+ envVars := env.Env()
99
+ require.Nil(t, envVars)
100
+ })
101
+ }
102
+
103
+ func TestMapEnv_GetEmptyValue(t *testing.T) {
104
+ testMap := map[string]string{
105
+ "EMPTY_KEY": "",
106
+ "NORMAL_KEY": "value",
107
+ }
108
+
109
+ env := NewFromMap(testMap)
110
+
111
+ // Test that empty values are returned correctly
112
+ require.Equal(t, "", env.Get("EMPTY_KEY"))
113
+ require.Equal(t, "value", env.Get("NORMAL_KEY"))
114
+ }
115
+
116
+ func TestMapEnv_EnvFormat(t *testing.T) {
117
+ testMap := map[string]string{
118
+ "KEY_WITH_EQUALS": "value=with=equals",
119
+ "KEY_WITH_SPACES": "value with spaces",
120
+ }
121
+
122
+ env := NewFromMap(testMap)
123
+ envVars := env.Env()
124
+
125
+ require.Len(t, envVars, 2)
126
+
127
+ // Check that the format is correct even with special characters
128
+ found := make(map[string]bool)
129
+ for _, envVar := range envVars {
130
+ if envVar == "KEY_WITH_EQUALS=value=with=equals" {
131
+ found["equals"] = true
132
+ }
133
+ if envVar == "KEY_WITH_SPACES=value with spaces" {
134
+ found["spaces"] = true
135
+ }
136
+ }
137
+
138
+ require.True(t, found["equals"], "Should handle values with equals signs")
139
+ require.True(t, found["spaces"], "Should handle values with spaces")
140
+ }
projects/ui/crush/internal/format/spinner.go ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package format
2
+
3
+ import (
4
+ "context"
5
+ "errors"
6
+ "fmt"
7
+ "os"
8
+
9
+ tea "github.com/charmbracelet/bubbletea/v2"
10
+ "github.com/charmbracelet/crush/internal/tui/components/anim"
11
+ "github.com/charmbracelet/crush/internal/tui/styles"
12
+ "github.com/charmbracelet/x/ansi"
13
+ )
14
+
15
+ // Spinner wraps the bubbles spinner for non-interactive mode
16
+ type Spinner struct {
17
+ done chan struct{}
18
+ prog *tea.Program
19
+ }
20
+
21
+ type model struct {
22
+ cancel context.CancelFunc
23
+ anim *anim.Anim
24
+ }
25
+
26
+ func (m model) Init() tea.Cmd { return m.anim.Init() }
27
+ func (m model) View() string { return m.anim.View() }
28
+
29
+ // Update implements tea.Model.
30
+ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
31
+ switch msg := msg.(type) {
32
+ case tea.KeyPressMsg:
33
+ switch msg.String() {
34
+ case "ctrl+c", "esc":
35
+ m.cancel()
36
+ return m, tea.Quit
37
+ }
38
+ }
39
+ mm, cmd := m.anim.Update(msg)
40
+ m.anim = mm.(*anim.Anim)
41
+ return m, cmd
42
+ }
43
+
44
+ // NewSpinner creates a new spinner with the given message
45
+ func NewSpinner(ctx context.Context, cancel context.CancelFunc, message string) *Spinner {
46
+ t := styles.CurrentTheme()
47
+ model := model{
48
+ anim: anim.New(anim.Settings{
49
+ Size: 10,
50
+ Label: message,
51
+ LabelColor: t.FgBase,
52
+ GradColorA: t.Primary,
53
+ GradColorB: t.Secondary,
54
+ CycleColors: true,
55
+ }),
56
+ cancel: cancel,
57
+ }
58
+
59
+ prog := tea.NewProgram(
60
+ model,
61
+ tea.WithOutput(os.Stderr),
62
+ tea.WithContext(ctx),
63
+ )
64
+
65
+ return &Spinner{
66
+ prog: prog,
67
+ done: make(chan struct{}, 1),
68
+ }
69
+ }
70
+
71
+ // Start begins the spinner animation
72
+ func (s *Spinner) Start() {
73
+ go func() {
74
+ defer close(s.done)
75
+ _, err := s.prog.Run()
76
+ // ensures line is cleared
77
+ fmt.Fprint(os.Stderr, ansi.EraseEntireLine)
78
+ if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, tea.ErrInterrupted) {
79
+ fmt.Fprintf(os.Stderr, "Error running spinner: %v\n", err)
80
+ }
81
+ }()
82
+ }
83
+
84
+ // Stop ends the spinner animation
85
+ func (s *Spinner) Stop() {
86
+ s.prog.Quit()
87
+ <-s.done
88
+ }
projects/ui/crush/internal/fsext/expand.go ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "os"
5
+ "strings"
6
+
7
+ "mvdan.cc/sh/v3/expand"
8
+ "mvdan.cc/sh/v3/syntax"
9
+ )
10
+
11
+ // Expand is a wrapper around [expand.Literal]. It will escape the input
12
+ // string, expand any shell symbols (such as '~') and resolve any environment
13
+ // variables.
14
+ func Expand(s string) (string, error) {
15
+ if s == "" {
16
+ return "", nil
17
+ }
18
+ p := syntax.NewParser()
19
+ word, err := p.Document(strings.NewReader(s))
20
+ if err != nil {
21
+ return "", err
22
+ }
23
+ cfg := &expand.Config{
24
+ Env: expand.FuncEnviron(os.Getenv),
25
+ ReadDir2: os.ReadDir,
26
+ GlobStar: true,
27
+ }
28
+ return expand.Literal(cfg, word)
29
+ }
projects/ui/crush/internal/fsext/fileutil.go ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "fmt"
5
+ "os"
6
+ "path/filepath"
7
+ "sort"
8
+ "strings"
9
+ "time"
10
+
11
+ "github.com/bmatcuk/doublestar/v4"
12
+ "github.com/charlievieth/fastwalk"
13
+ "github.com/charmbracelet/crush/internal/home"
14
+
15
+ ignore "github.com/sabhiram/go-gitignore"
16
+ )
17
+
18
+ type FileInfo struct {
19
+ Path string
20
+ ModTime time.Time
21
+ }
22
+
23
+ func SkipHidden(path string) bool {
24
+ // Check for hidden files (starting with a dot)
25
+ base := filepath.Base(path)
26
+ if base != "." && strings.HasPrefix(base, ".") {
27
+ return true
28
+ }
29
+
30
+ commonIgnoredDirs := map[string]bool{
31
+ ".crush": true,
32
+ "node_modules": true,
33
+ "vendor": true,
34
+ "dist": true,
35
+ "build": true,
36
+ "target": true,
37
+ ".git": true,
38
+ ".idea": true,
39
+ ".vscode": true,
40
+ "__pycache__": true,
41
+ "bin": true,
42
+ "obj": true,
43
+ "out": true,
44
+ "coverage": true,
45
+ "logs": true,
46
+ "generated": true,
47
+ "bower_components": true,
48
+ "jspm_packages": true,
49
+ }
50
+
51
+ parts := strings.SplitSeq(path, string(os.PathSeparator))
52
+ for part := range parts {
53
+ if commonIgnoredDirs[part] {
54
+ return true
55
+ }
56
+ }
57
+ return false
58
+ }
59
+
60
+ // FastGlobWalker provides gitignore-aware file walking with fastwalk
61
+ type FastGlobWalker struct {
62
+ gitignore *ignore.GitIgnore
63
+ crushignore *ignore.GitIgnore
64
+ rootPath string
65
+ }
66
+
67
+ func NewFastGlobWalker(searchPath string) *FastGlobWalker {
68
+ walker := &FastGlobWalker{
69
+ rootPath: searchPath,
70
+ }
71
+
72
+ // Load gitignore if it exists
73
+ gitignorePath := filepath.Join(searchPath, ".gitignore")
74
+ if _, err := os.Stat(gitignorePath); err == nil {
75
+ if gi, err := ignore.CompileIgnoreFile(gitignorePath); err == nil {
76
+ walker.gitignore = gi
77
+ }
78
+ }
79
+
80
+ // Load crushignore if it exists
81
+ crushignorePath := filepath.Join(searchPath, ".crushignore")
82
+ if _, err := os.Stat(crushignorePath); err == nil {
83
+ if ci, err := ignore.CompileIgnoreFile(crushignorePath); err == nil {
84
+ walker.crushignore = ci
85
+ }
86
+ }
87
+
88
+ return walker
89
+ }
90
+
91
+ // ShouldSkip checks if a path should be skipped based on gitignore, crushignore, and hidden file rules
92
+ func (w *FastGlobWalker) ShouldSkip(path string) bool {
93
+ if SkipHidden(path) {
94
+ return true
95
+ }
96
+
97
+ relPath, err := filepath.Rel(w.rootPath, path)
98
+ if err != nil {
99
+ return false
100
+ }
101
+
102
+ if w.gitignore != nil {
103
+ if w.gitignore.MatchesPath(relPath) {
104
+ return true
105
+ }
106
+ }
107
+
108
+ if w.crushignore != nil {
109
+ if w.crushignore.MatchesPath(relPath) {
110
+ return true
111
+ }
112
+ }
113
+
114
+ return false
115
+ }
116
+
117
+ func GlobWithDoubleStar(pattern, searchPath string, limit int) ([]string, bool, error) {
118
+ walker := NewFastGlobWalker(searchPath)
119
+ var matches []FileInfo
120
+ conf := fastwalk.Config{
121
+ Follow: true,
122
+ // Use forward slashes when running a Windows binary under WSL or MSYS
123
+ ToSlash: fastwalk.DefaultToSlash(),
124
+ Sort: fastwalk.SortFilesFirst,
125
+ }
126
+ err := fastwalk.Walk(&conf, searchPath, func(path string, d os.DirEntry, err error) error {
127
+ if err != nil {
128
+ return nil // Skip files we can't access
129
+ }
130
+
131
+ if d.IsDir() {
132
+ if walker.ShouldSkip(path) {
133
+ return filepath.SkipDir
134
+ }
135
+ return nil
136
+ }
137
+
138
+ if walker.ShouldSkip(path) {
139
+ return nil
140
+ }
141
+
142
+ // Check if path matches the pattern
143
+ relPath, err := filepath.Rel(searchPath, path)
144
+ if err != nil {
145
+ relPath = path
146
+ }
147
+
148
+ matched, err := doublestar.Match(pattern, relPath)
149
+ if err != nil || !matched {
150
+ return nil
151
+ }
152
+
153
+ info, err := d.Info()
154
+ if err != nil {
155
+ return nil
156
+ }
157
+
158
+ matches = append(matches, FileInfo{Path: path, ModTime: info.ModTime()})
159
+ if limit > 0 && len(matches) >= limit*2 {
160
+ return filepath.SkipAll
161
+ }
162
+ return nil
163
+ })
164
+ if err != nil {
165
+ return nil, false, fmt.Errorf("fastwalk error: %w", err)
166
+ }
167
+
168
+ sort.Slice(matches, func(i, j int) bool {
169
+ return matches[i].ModTime.After(matches[j].ModTime)
170
+ })
171
+
172
+ truncated := false
173
+ if limit > 0 && len(matches) > limit {
174
+ matches = matches[:limit]
175
+ truncated = true
176
+ }
177
+
178
+ results := make([]string, len(matches))
179
+ for i, m := range matches {
180
+ results[i] = m.Path
181
+ }
182
+ return results, truncated, nil
183
+ }
184
+
185
+ func PrettyPath(path string) string {
186
+ return home.Short(path)
187
+ }
188
+
189
+ func DirTrim(pwd string, lim int) string {
190
+ var (
191
+ out string
192
+ sep = string(filepath.Separator)
193
+ )
194
+ dirs := strings.Split(pwd, sep)
195
+ if lim > len(dirs)-1 || lim <= 0 {
196
+ return pwd
197
+ }
198
+ for i := len(dirs) - 1; i > 0; i-- {
199
+ out = sep + out
200
+ if i == len(dirs)-1 {
201
+ out = dirs[i]
202
+ } else if i >= len(dirs)-lim {
203
+ out = string(dirs[i][0]) + out
204
+ } else {
205
+ out = "..." + out
206
+ break
207
+ }
208
+ }
209
+ out = filepath.Join("~", out)
210
+ return out
211
+ }
212
+
213
+ // PathOrPrefix returns the prefix if the path starts with it, or falls back to
214
+ // the path otherwise.
215
+ func PathOrPrefix(path, prefix string) string {
216
+ if HasPrefix(path, prefix) {
217
+ return prefix
218
+ }
219
+ return path
220
+ }
221
+
222
+ // HasPrefix checks if the given path starts with the specified prefix.
223
+ // Uses filepath.Rel to determine if path is within prefix.
224
+ func HasPrefix(path, prefix string) bool {
225
+ rel, err := filepath.Rel(prefix, path)
226
+ if err != nil {
227
+ return false
228
+ }
229
+ // If path is within prefix, Rel will not return a path starting with ".."
230
+ return !strings.HasPrefix(rel, "..")
231
+ }
232
+
233
+ // ToUnixLineEndings converts Windows line endings (CRLF) to Unix line endings (LF).
234
+ func ToUnixLineEndings(content string) (string, bool) {
235
+ if strings.Contains(content, "\r\n") {
236
+ return strings.ReplaceAll(content, "\r\n", "\n"), true
237
+ }
238
+ return content, false
239
+ }
240
+
241
+ // ToWindowsLineEndings converts Unix line endings (LF) to Windows line endings (CRLF).
242
+ func ToWindowsLineEndings(content string) (string, bool) {
243
+ if !strings.Contains(content, "\r\n") {
244
+ return strings.ReplaceAll(content, "\n", "\r\n"), true
245
+ }
246
+ return content, false
247
+ }
projects/ui/crush/internal/fsext/ignore_test.go ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "os"
5
+ "testing"
6
+
7
+ "github.com/stretchr/testify/require"
8
+ )
9
+
10
+ func TestCrushIgnore(t *testing.T) {
11
+ // Create a temporary directory for testing
12
+ tempDir := t.TempDir()
13
+
14
+ // Change to temp directory
15
+ oldWd, _ := os.Getwd()
16
+ err := os.Chdir(tempDir)
17
+ require.NoError(t, err)
18
+ defer os.Chdir(oldWd)
19
+
20
+ // Create test files
21
+ require.NoError(t, os.WriteFile("test1.txt", []byte("test"), 0o644))
22
+ require.NoError(t, os.WriteFile("test2.log", []byte("test"), 0o644))
23
+ require.NoError(t, os.WriteFile("test3.tmp", []byte("test"), 0o644))
24
+
25
+ // Create a .crushignore file that ignores .log files
26
+ require.NoError(t, os.WriteFile(".crushignore", []byte("*.log\n"), 0o644))
27
+
28
+ dl := NewDirectoryLister(tempDir)
29
+ require.True(t, dl.shouldIgnore("test2.log", nil), ".log files should be ignored")
30
+ require.False(t, dl.shouldIgnore("test1.txt", nil), ".txt files should not be ignored")
31
+ require.True(t, dl.shouldIgnore("test3.tmp", nil), ".tmp files should be ignored by common patterns")
32
+ }
projects/ui/crush/internal/fsext/ls.go ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "log/slog"
5
+ "os"
6
+ "path/filepath"
7
+ "strings"
8
+ "sync"
9
+
10
+ "github.com/charlievieth/fastwalk"
11
+ "github.com/charmbracelet/crush/internal/csync"
12
+ "github.com/charmbracelet/crush/internal/home"
13
+ ignore "github.com/sabhiram/go-gitignore"
14
+ )
15
+
16
+ // commonIgnorePatterns contains commonly ignored files and directories
17
+ var commonIgnorePatterns = sync.OnceValue(func() ignore.IgnoreParser {
18
+ return ignore.CompileIgnoreLines(
19
+ // Version control
20
+ ".git",
21
+ ".svn",
22
+ ".hg",
23
+ ".bzr",
24
+
25
+ // IDE and editor files
26
+ ".vscode",
27
+ ".idea",
28
+ "*.swp",
29
+ "*.swo",
30
+ "*~",
31
+ ".DS_Store",
32
+ "Thumbs.db",
33
+
34
+ // Build artifacts and dependencies
35
+ "node_modules",
36
+ "target",
37
+ "build",
38
+ "dist",
39
+ "out",
40
+ "bin",
41
+ "obj",
42
+ "*.o",
43
+ "*.so",
44
+ "*.dylib",
45
+ "*.dll",
46
+ "*.exe",
47
+
48
+ // Logs and temporary files
49
+ "*.log",
50
+ "*.tmp",
51
+ "*.temp",
52
+ ".cache",
53
+ ".tmp",
54
+
55
+ // Language-specific
56
+ "__pycache__",
57
+ "*.pyc",
58
+ "*.pyo",
59
+ ".pytest_cache",
60
+ "vendor",
61
+ "Cargo.lock",
62
+ "package-lock.json",
63
+ "yarn.lock",
64
+ "pnpm-lock.yaml",
65
+
66
+ // OS generated files
67
+ ".Trash",
68
+ ".Spotlight-V100",
69
+ ".fseventsd",
70
+
71
+ // Crush
72
+ ".crush",
73
+ )
74
+ })
75
+
76
+ var homeIgnore = sync.OnceValue(func() ignore.IgnoreParser {
77
+ home := home.Dir()
78
+ var lines []string
79
+ for _, name := range []string{
80
+ filepath.Join(home, ".gitignore"),
81
+ filepath.Join(home, ".config", "git", "ignore"),
82
+ filepath.Join(home, ".config", "crush", "ignore"),
83
+ } {
84
+ if bts, err := os.ReadFile(name); err == nil {
85
+ lines = append(lines, strings.Split(string(bts), "\n")...)
86
+ }
87
+ }
88
+ return ignore.CompileIgnoreLines(lines...)
89
+ })
90
+
91
+ type directoryLister struct {
92
+ ignores *csync.Map[string, ignore.IgnoreParser]
93
+ rootPath string
94
+ }
95
+
96
+ func NewDirectoryLister(rootPath string) *directoryLister {
97
+ dl := &directoryLister{
98
+ rootPath: rootPath,
99
+ ignores: csync.NewMap[string, ignore.IgnoreParser](),
100
+ }
101
+ dl.getIgnore(rootPath)
102
+ return dl
103
+ }
104
+
105
+ // git checks, in order:
106
+ // - ./.gitignore, ../.gitignore, etc, until repo root
107
+ // ~/.config/git/ignore
108
+ // ~/.gitignore
109
+ //
110
+ // This will do the following:
111
+ // - the given ignorePatterns
112
+ // - [commonIgnorePatterns]
113
+ // - ./.gitignore, ../.gitignore, etc, until dl.rootPath
114
+ // - ./.crushignore, ../.crushignore, etc, until dl.rootPath
115
+ // ~/.config/git/ignore
116
+ // ~/.gitignore
117
+ // ~/.config/crush/ignore
118
+ func (dl *directoryLister) shouldIgnore(path string, ignorePatterns []string) bool {
119
+ if len(ignorePatterns) > 0 {
120
+ base := filepath.Base(path)
121
+ for _, pattern := range ignorePatterns {
122
+ if matched, err := filepath.Match(pattern, base); err == nil && matched {
123
+ return true
124
+ }
125
+ }
126
+ }
127
+
128
+ // Don't apply gitignore rules to the root directory itself
129
+ // In gitignore semantics, patterns don't apply to the repo root
130
+ if path == dl.rootPath {
131
+ return false
132
+ }
133
+
134
+ relPath, err := filepath.Rel(dl.rootPath, path)
135
+ if err != nil {
136
+ relPath = path
137
+ }
138
+
139
+ if commonIgnorePatterns().MatchesPath(relPath) {
140
+ slog.Debug("ignoring common pattern", "path", relPath)
141
+ return true
142
+ }
143
+
144
+ if dl.getIgnore(filepath.Dir(path)).MatchesPath(relPath) {
145
+ slog.Debug("ignoring dir pattern", "path", relPath, "dir", filepath.Dir(path))
146
+ return true
147
+ }
148
+
149
+ if dl.checkParentIgnores(relPath) {
150
+ return true
151
+ }
152
+
153
+ if homeIgnore().MatchesPath(relPath) {
154
+ slog.Debug("ignoring home dir pattern", "path", relPath)
155
+ return true
156
+ }
157
+
158
+ return false
159
+ }
160
+
161
+ func (dl *directoryLister) checkParentIgnores(path string) bool {
162
+ parent := filepath.Dir(filepath.Dir(path))
163
+ for parent != dl.rootPath && parent != "." && path != "." {
164
+ if dl.getIgnore(parent).MatchesPath(path) {
165
+ slog.Debug("ingoring parent dir pattern", "path", path, "dir", parent)
166
+ return true
167
+ }
168
+ parent = filepath.Dir(parent)
169
+ }
170
+ return false
171
+ }
172
+
173
+ func (dl *directoryLister) getIgnore(path string) ignore.IgnoreParser {
174
+ return dl.ignores.GetOrSet(path, func() ignore.IgnoreParser {
175
+ var lines []string
176
+ for _, ign := range []string{".crushignore", ".gitignore"} {
177
+ name := filepath.Join(path, ign)
178
+ if content, err := os.ReadFile(name); err == nil {
179
+ lines = append(lines, strings.Split(string(content), "\n")...)
180
+ }
181
+ }
182
+ if len(lines) == 0 {
183
+ // Return a no-op parser to avoid nil checks
184
+ return ignore.CompileIgnoreLines()
185
+ }
186
+ return ignore.CompileIgnoreLines(lines...)
187
+ })
188
+ }
189
+
190
+ // ListDirectory lists files and directories in the specified path,
191
+ func ListDirectory(initialPath string, ignorePatterns []string, limit int) ([]string, bool, error) {
192
+ var results []string
193
+ truncated := false
194
+ dl := NewDirectoryLister(initialPath)
195
+
196
+ conf := fastwalk.Config{
197
+ Follow: true,
198
+ // Use forward slashes when running a Windows binary under WSL or MSYS
199
+ ToSlash: fastwalk.DefaultToSlash(),
200
+ Sort: fastwalk.SortDirsFirst,
201
+ }
202
+
203
+ err := fastwalk.Walk(&conf, initialPath, func(path string, d os.DirEntry, err error) error {
204
+ if err != nil {
205
+ return nil // Skip files we don't have permission to access
206
+ }
207
+
208
+ if dl.shouldIgnore(path, ignorePatterns) {
209
+ if d.IsDir() {
210
+ return filepath.SkipDir
211
+ }
212
+ return nil
213
+ }
214
+
215
+ if path != initialPath {
216
+ if d.IsDir() {
217
+ path = path + string(filepath.Separator)
218
+ }
219
+ results = append(results, path)
220
+ }
221
+
222
+ if limit > 0 && len(results) >= limit {
223
+ truncated = true
224
+ return filepath.SkipAll
225
+ }
226
+
227
+ return nil
228
+ })
229
+ if err != nil && len(results) == 0 {
230
+ return nil, truncated, err
231
+ }
232
+
233
+ return results, truncated, nil
234
+ }
projects/ui/crush/internal/fsext/ls_test.go ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "os"
5
+ "path/filepath"
6
+ "testing"
7
+
8
+ "github.com/stretchr/testify/assert"
9
+ "github.com/stretchr/testify/require"
10
+ )
11
+
12
+ func chdir(t *testing.T, dir string) {
13
+ original, err := os.Getwd()
14
+ require.NoError(t, err)
15
+
16
+ err = os.Chdir(dir)
17
+ require.NoError(t, err)
18
+
19
+ t.Cleanup(func() {
20
+ err := os.Chdir(original)
21
+ require.NoError(t, err)
22
+ })
23
+ }
24
+
25
+ func TestListDirectory(t *testing.T) {
26
+ tempDir := t.TempDir()
27
+ chdir(t, tempDir)
28
+
29
+ testFiles := map[string]string{
30
+ "regular.txt": "content",
31
+ ".hidden": "hidden content",
32
+ ".gitignore": ".*\n*.log\n",
33
+ "subdir/file.go": "package main",
34
+ "subdir/.another": "more hidden",
35
+ "build.log": "build output",
36
+ }
37
+
38
+ for filePath, content := range testFiles {
39
+ dir := filepath.Dir(filePath)
40
+ if dir != "." {
41
+ require.NoError(t, os.MkdirAll(dir, 0o755))
42
+ }
43
+
44
+ err := os.WriteFile(filePath, []byte(content), 0o644)
45
+ require.NoError(t, err)
46
+ }
47
+
48
+ files, truncated, err := ListDirectory(".", nil, 0)
49
+ require.NoError(t, err)
50
+ assert.False(t, truncated)
51
+ assert.Equal(t, len(files), 4)
52
+
53
+ fileSet := make(map[string]bool)
54
+ for _, file := range files {
55
+ fileSet[filepath.ToSlash(file)] = true
56
+ }
57
+
58
+ assert.True(t, fileSet["./regular.txt"])
59
+ assert.True(t, fileSet["./subdir/"])
60
+ assert.True(t, fileSet["./subdir/file.go"])
61
+ assert.True(t, fileSet["./regular.txt"])
62
+
63
+ assert.False(t, fileSet["./.hidden"])
64
+ assert.False(t, fileSet["./.gitignore"])
65
+ assert.False(t, fileSet["./build.log"])
66
+ }
projects/ui/crush/internal/fsext/owner_others.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //go:build !windows
2
+
3
+ package fsext
4
+
5
+ import (
6
+ "os"
7
+ "syscall"
8
+ )
9
+
10
+ // Owner retrieves the user ID of the owner of the file or directory at the
11
+ // specified path.
12
+ func Owner(path string) (int, error) {
13
+ info, err := os.Stat(path)
14
+ if err != nil {
15
+ return 0, err
16
+ }
17
+ var uid int
18
+ if stat, ok := info.Sys().(*syscall.Stat_t); ok {
19
+ uid = int(stat.Uid)
20
+ } else {
21
+ uid = os.Getuid()
22
+ }
23
+ return uid, nil
24
+ }
projects/ui/crush/internal/fsext/owner_windows.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ //go:build windows
2
+
3
+ package fsext
4
+
5
+ // Owner retrieves the user ID of the owner of the file or directory at the
6
+ // specified path.
7
+ func Owner(path string) (int, error) {
8
+ return -1, nil
9
+ }
projects/ui/crush/internal/fsext/parent.go ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package fsext
2
+
3
+ import (
4
+ "errors"
5
+ "os"
6
+ "path/filepath"
7
+
8
+ "github.com/charmbracelet/crush/internal/home"
9
+ )
10
+
11
+ // SearchParent searches for a target file or directory starting from dir
12
+ // and walking up the directory tree until found or root or home is reached.
13
+ // It also checks the ownership of directories to ensure that the search does
14
+ // not cross ownership boundaries.
15
+ // Returns the full path to the target if found, empty string and false otherwise.
16
+ // The search includes the starting directory itself.
17
+ func SearchParent(dir, target string) (string, bool) {
18
+ absDir, err := filepath.Abs(dir)
19
+ if err != nil {
20
+ return "", false
21
+ }
22
+
23
+ path := filepath.Join(absDir, target)
24
+ if _, err := os.Stat(path); err == nil {
25
+ return path, true
26
+ } else if !errors.Is(err, os.ErrNotExist) {
27
+ return "", false
28
+ }
29
+
30
+ previousParent := absDir
31
+ previousOwner, err := Owner(previousParent)
32
+ if err != nil {
33
+ return "", false
34
+ }
35
+
36
+ for {
37
+ parent := filepath.Dir(previousParent)
38
+ if parent == previousParent || parent == home.Dir() {
39
+ return "", false
40
+ }
41
+
42
+ parentOwner, err := Owner(parent)
43
+ if err != nil {
44
+ return "", false
45
+ }
46
+ if parentOwner != previousOwner {
47
+ return "", false
48
+ }
49
+
50
+ path := filepath.Join(parent, target)
51
+ if _, err := os.Stat(path); err == nil {
52
+ return path, true
53
+ } else if !errors.Is(err, os.ErrNotExist) {
54
+ return "", false
55
+ }
56
+
57
+ previousParent = parent
58
+ previousOwner = parentOwner
59
+ }
60
+ }
projects/ui/crush/internal/history/file.go ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package history
2
+
3
+ import (
4
+ "context"
5
+ "database/sql"
6
+ "fmt"
7
+ "strings"
8
+
9
+ "github.com/charmbracelet/crush/internal/db"
10
+ "github.com/charmbracelet/crush/internal/pubsub"
11
+ "github.com/google/uuid"
12
+ )
13
+
14
+ const (
15
+ InitialVersion = 0
16
+ )
17
+
18
+ type File struct {
19
+ ID string
20
+ SessionID string
21
+ Path string
22
+ Content string
23
+ Version int64
24
+ CreatedAt int64
25
+ UpdatedAt int64
26
+ }
27
+
28
+ type Service interface {
29
+ pubsub.Suscriber[File]
30
+ Create(ctx context.Context, sessionID, path, content string) (File, error)
31
+ CreateVersion(ctx context.Context, sessionID, path, content string) (File, error)
32
+ Get(ctx context.Context, id string) (File, error)
33
+ GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error)
34
+ ListBySession(ctx context.Context, sessionID string) ([]File, error)
35
+ ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error)
36
+ Delete(ctx context.Context, id string) error
37
+ DeleteSessionFiles(ctx context.Context, sessionID string) error
38
+ }
39
+
40
+ type service struct {
41
+ *pubsub.Broker[File]
42
+ db *sql.DB
43
+ q *db.Queries
44
+ }
45
+
46
+ func NewService(q *db.Queries, db *sql.DB) Service {
47
+ return &service{
48
+ Broker: pubsub.NewBroker[File](),
49
+ q: q,
50
+ db: db,
51
+ }
52
+ }
53
+
54
+ func (s *service) Create(ctx context.Context, sessionID, path, content string) (File, error) {
55
+ return s.createWithVersion(ctx, sessionID, path, content, InitialVersion)
56
+ }
57
+
58
+ func (s *service) CreateVersion(ctx context.Context, sessionID, path, content string) (File, error) {
59
+ // Get the latest version for this path
60
+ files, err := s.q.ListFilesByPath(ctx, path)
61
+ if err != nil {
62
+ return File{}, err
63
+ }
64
+
65
+ if len(files) == 0 {
66
+ // No previous versions, create initial
67
+ return s.Create(ctx, sessionID, path, content)
68
+ }
69
+
70
+ // Get the latest version
71
+ latestFile := files[0] // Files are ordered by version DESC, created_at DESC
72
+ nextVersion := latestFile.Version + 1
73
+
74
+ return s.createWithVersion(ctx, sessionID, path, content, nextVersion)
75
+ }
76
+
77
+ func (s *service) createWithVersion(ctx context.Context, sessionID, path, content string, version int64) (File, error) {
78
+ // Maximum number of retries for transaction conflicts
79
+ const maxRetries = 3
80
+ var file File
81
+ var err error
82
+
83
+ // Retry loop for transaction conflicts
84
+ for attempt := range maxRetries {
85
+ // Start a transaction
86
+ tx, txErr := s.db.BeginTx(ctx, nil)
87
+ if txErr != nil {
88
+ return File{}, fmt.Errorf("failed to begin transaction: %w", txErr)
89
+ }
90
+
91
+ // Create a new queries instance with the transaction
92
+ qtx := s.q.WithTx(tx)
93
+
94
+ // Try to create the file within the transaction
95
+ dbFile, txErr := qtx.CreateFile(ctx, db.CreateFileParams{
96
+ ID: uuid.New().String(),
97
+ SessionID: sessionID,
98
+ Path: path,
99
+ Content: content,
100
+ Version: version,
101
+ })
102
+ if txErr != nil {
103
+ // Rollback the transaction
104
+ tx.Rollback()
105
+
106
+ // Check if this is a uniqueness constraint violation
107
+ if strings.Contains(txErr.Error(), "UNIQUE constraint failed") {
108
+ if attempt < maxRetries-1 {
109
+ // If we have retries left, increment version and try again
110
+ version++
111
+ continue
112
+ }
113
+ }
114
+ return File{}, txErr
115
+ }
116
+
117
+ // Commit the transaction
118
+ if txErr = tx.Commit(); txErr != nil {
119
+ return File{}, fmt.Errorf("failed to commit transaction: %w", txErr)
120
+ }
121
+
122
+ file = s.fromDBItem(dbFile)
123
+ s.Publish(pubsub.CreatedEvent, file)
124
+ return file, nil
125
+ }
126
+
127
+ return file, err
128
+ }
129
+
130
+ func (s *service) Get(ctx context.Context, id string) (File, error) {
131
+ dbFile, err := s.q.GetFile(ctx, id)
132
+ if err != nil {
133
+ return File{}, err
134
+ }
135
+ return s.fromDBItem(dbFile), nil
136
+ }
137
+
138
+ func (s *service) GetByPathAndSession(ctx context.Context, path, sessionID string) (File, error) {
139
+ dbFile, err := s.q.GetFileByPathAndSession(ctx, db.GetFileByPathAndSessionParams{
140
+ Path: path,
141
+ SessionID: sessionID,
142
+ })
143
+ if err != nil {
144
+ return File{}, err
145
+ }
146
+ return s.fromDBItem(dbFile), nil
147
+ }
148
+
149
+ func (s *service) ListBySession(ctx context.Context, sessionID string) ([]File, error) {
150
+ dbFiles, err := s.q.ListFilesBySession(ctx, sessionID)
151
+ if err != nil {
152
+ return nil, err
153
+ }
154
+ files := make([]File, len(dbFiles))
155
+ for i, dbFile := range dbFiles {
156
+ files[i] = s.fromDBItem(dbFile)
157
+ }
158
+ return files, nil
159
+ }
160
+
161
+ func (s *service) ListLatestSessionFiles(ctx context.Context, sessionID string) ([]File, error) {
162
+ dbFiles, err := s.q.ListLatestSessionFiles(ctx, sessionID)
163
+ if err != nil {
164
+ return nil, err
165
+ }
166
+ files := make([]File, len(dbFiles))
167
+ for i, dbFile := range dbFiles {
168
+ files[i] = s.fromDBItem(dbFile)
169
+ }
170
+ return files, nil
171
+ }
172
+
173
+ func (s *service) Delete(ctx context.Context, id string) error {
174
+ file, err := s.Get(ctx, id)
175
+ if err != nil {
176
+ return err
177
+ }
178
+ err = s.q.DeleteFile(ctx, id)
179
+ if err != nil {
180
+ return err
181
+ }
182
+ s.Publish(pubsub.DeletedEvent, file)
183
+ return nil
184
+ }
185
+
186
+ func (s *service) DeleteSessionFiles(ctx context.Context, sessionID string) error {
187
+ files, err := s.ListBySession(ctx, sessionID)
188
+ if err != nil {
189
+ return err
190
+ }
191
+ for _, file := range files {
192
+ err = s.Delete(ctx, file.ID)
193
+ if err != nil {
194
+ return err
195
+ }
196
+ }
197
+ return nil
198
+ }
199
+
200
+ func (s *service) fromDBItem(item db.File) File {
201
+ return File{
202
+ ID: item.ID,
203
+ SessionID: item.SessionID,
204
+ Path: item.Path,
205
+ Content: item.Content,
206
+ Version: item.Version,
207
+ CreatedAt: item.CreatedAt,
208
+ UpdatedAt: item.UpdatedAt,
209
+ }
210
+ }