Create persists a new instruction and writes its managed file.
(ctx context.Context, name, desc, content string)
| 259 | |
| 260 | // Create persists a new instruction and writes its managed file. |
| 261 | func (s *Store) Create(ctx context.Context, name, desc, content string) (Instruction, error) { |
| 262 | if err := validateName(name); err != nil { |
| 263 | return Instruction{}, err |
| 264 | } |
| 265 | if err := s.Init(ctx); err != nil { |
| 266 | return Instruction{}, err |
| 267 | } |
| 268 | db, err := s.open() |
| 269 | if err != nil { |
| 270 | return Instruction{}, err |
| 271 | } |
| 272 | defer db.Close() |
| 273 | |
| 274 | exists, err := nameExists(ctx, db, name, 0) |
| 275 | if err != nil { |
| 276 | return Instruction{}, fmt.Errorf("instructions: check name: %w", err) |
| 277 | } |
| 278 | if exists { |
| 279 | return Instruction{}, fmt.Errorf("%w: %q", ErrDuplicateName, name) |
| 280 | } |
| 281 | |
| 282 | if err := writeManagedFile(name, content); err != nil { |
| 283 | return Instruction{}, err |
| 284 | } |
| 285 | |
| 286 | now := time.Now().UTC().Format(rfc) |
| 287 | res, err := db.ExecContext(ctx, `INSERT INTO instructions(name, description, content, created_at, updated_at) VALUES(?, ?, ?, ?, ?)`, name, desc, content, now, now) |
| 288 | if err != nil { |
| 289 | if strings.Contains(err.Error(), "UNIQUE") { |
| 290 | return Instruction{}, fmt.Errorf("%w: %q", ErrDuplicateName, name) |
| 291 | } |
| 292 | return Instruction{}, fmt.Errorf("instructions: insert: %w", err) |
| 293 | } |
| 294 | id, _ := res.LastInsertId() |
| 295 | return s.Get(ctx, id) |
| 296 | } |
| 297 | |
| 298 | // Update changes an instruction's name/description/content, keeps the managed |
| 299 | // file in sync, and re-targets symlink installs when the safe-name changes. |