| 1 | package tool |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | ) |
| 7 | |
| 8 | // FileWriteIntent is local evidence about an actual prepared write. Unknown |
| 9 | // versions are retained as raw JSON by the session and never verified. |
| 10 | type FileWriteIntent struct { |
| 11 | Version int `json:"version"` |
| 12 | Path string `json:"path"` |
| 13 | Host string `json:"host"` |
| 14 | TransportID string `json:"transport_id,omitempty"` |
| 15 | Route string `json:"route"` |
| 16 | ResolvedPath string `json:"resolved_path"` |
| 17 | Before string `json:"before"` |
| 18 | After string `json:"after"` |
| 19 | Encoding string `json:"encoding"` |
| 20 | Existed bool `json:"existed"` |
| 21 | } |
| 22 | |
| 23 | type WriteVerification string |
| 24 | |
| 25 | const ( |
| 26 | WriteSatisfied WriteVerification = "satisfied" |
| 27 | WriteUnchanged WriteVerification = "unchanged" |
| 28 | WriteConflict WriteVerification = "conflict" |
| 29 | WriteUnknown WriteVerification = "unknown" |
| 30 | ) |
| 31 | |
| 32 | type WriteVerifier interface { |
| 33 | VerifyWrite(context.Context, FileWriteIntent) WriteVerification |
| 34 | } |
| 35 | type writeIntentHookKey struct{} |
| 36 | type WriteIntentHook func(FileWriteIntent) error |
| 37 | |
| 38 | func WithWriteIntentHook(ctx context.Context, hook WriteIntentHook) context.Context { |
| 39 | return context.WithValue(ctx, writeIntentHookKey{}, hook) |
| 40 | } |
| 41 | func RecordWriteIntent(ctx context.Context, intent FileWriteIntent) error { |
| 42 | if hook, ok := ctx.Value(writeIntentHookKey{}).(WriteIntentHook); ok { |
| 43 | return hook(intent) |
| 44 | } |
| 45 | return nil |
| 46 | } |
| 47 | func DecodeWriteIntent(raw json.RawMessage) (FileWriteIntent, bool) { |
| 48 | var intent FileWriteIntent |
| 49 | err := json.Unmarshal(raw, &intent) |
| 50 | return intent, err == nil && intent.Version == 1 && intent.Path != "" && intent.Host != "" && intent.After != "" |
| 51 | } |
| 52 | |
| 53 | func HasWriteIntentHook(ctx context.Context) bool { |
| 54 | _, ok := ctx.Value(writeIntentHookKey{}).(WriteIntentHook) |
| 55 | return ok |
| 56 | } |
| 57 |