mirror of
https://github.com/runkids/skillshare.git
synced 2026-11-19 02:17:09 +00:00
Keep machine-specific project changes out of shared configuration while preserving shared registrations and making their origin visible. Handle missing replicated roots and preserve startup maintenance for mutating commands.
58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package projects
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gofrs/flock"
|
|
"skillshare/internal/config"
|
|
"skillshare/internal/utils"
|
|
)
|
|
|
|
// LockConfig serializes project mutations across CLI and dashboard processes.
|
|
// Callers reload after acquisition and hold the lock through detach and save.
|
|
// Other config writers do not participate. Reads and previews must not call it.
|
|
// The lock lives in the state dir, like the MCP and hooks locks, so it never
|
|
// lands in a config folder that skillshare push commits.
|
|
func LockConfig(ctx context.Context, path string) (func(), error) {
|
|
dest, err := utils.ConfigWritePath(path, false)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
file, err := lockPath(dest)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("project config lock %s: %w", dest, err)
|
|
}
|
|
lock := flock.New(file)
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
ok, err := lock.TryLockContext(ctx, 50*time.Millisecond)
|
|
if err != nil || !ok {
|
|
_ = lock.Close()
|
|
if err == nil {
|
|
err = ctx.Err()
|
|
}
|
|
return nil, fmt.Errorf("project config lock %s: %w", dest, err)
|
|
}
|
|
var once sync.Once
|
|
return func() { once.Do(func() { _ = lock.Close() }) }, nil
|
|
}
|
|
|
|
// lockPath keys the lock by the resolved config file, so links to one config
|
|
// share a lock and separate configs do not.
|
|
func lockPath(dest string) (string, error) {
|
|
dir := filepath.Join(config.ProjectStateDir(), "projects")
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
id, err := config.ProjectConfigIdentity(dest)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.Join(dir, id+".lock"), nil
|
|
}
|