|
| 1 | +package lockfile |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + |
| 8 | + "go.jetpack.io/devbox/internal/cuecfg" |
| 9 | + "go.jetpack.io/devbox/internal/nix" |
| 10 | +) |
| 11 | + |
| 12 | +// localLockFile is a non-shared lock file that helps track the state of the |
| 13 | +// local devbox environment. It contains hashes that may not be the same across |
| 14 | +// machines (e.g. manifest hash). |
| 15 | +// When we do implement a shared lock file, it may contain some shared fields |
| 16 | +// with this one but not all. |
| 17 | +type localLockFile struct { |
| 18 | + project devboxProject |
| 19 | + ConfigHash string `json:"config_hash"` |
| 20 | + NixProfileManifestHash string `json:"nix_profile_manifest_hash"` |
| 21 | +} |
| 22 | + |
| 23 | +func (l *localLockFile) equals(other *localLockFile) bool { |
| 24 | + return l.ConfigHash == other.ConfigHash && |
| 25 | + l.NixProfileManifestHash == other.NixProfileManifestHash |
| 26 | +} |
| 27 | + |
| 28 | +func (l *localLockFile) IsUpToDate() (bool, error) { |
| 29 | + newLock, err := forProject(l.project) |
| 30 | + if err != nil { |
| 31 | + return false, err |
| 32 | + } |
| 33 | + |
| 34 | + return l.equals(newLock), nil |
| 35 | +} |
| 36 | + |
| 37 | +func (l *localLockFile) Update() error { |
| 38 | + newLock, err := forProject(l.project) |
| 39 | + if err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + *l = *newLock |
| 43 | + |
| 44 | + return cuecfg.WriteFile(localLockFilePath(l.project), l) |
| 45 | +} |
| 46 | + |
| 47 | +type devboxProject interface { |
| 48 | + ConfigHash() (string, error) |
| 49 | + ProjectDir() string |
| 50 | +} |
| 51 | + |
| 52 | +func Local(project devboxProject) (*localLockFile, error) { |
| 53 | + lockFile := &localLockFile{project: project} |
| 54 | + err := cuecfg.ParseFile(localLockFilePath(project), lockFile) |
| 55 | + if errors.Is(err, os.ErrNotExist) { |
| 56 | + return lockFile, nil |
| 57 | + } else if err != nil { |
| 58 | + return nil, err |
| 59 | + } |
| 60 | + return lockFile, nil |
| 61 | +} |
| 62 | + |
| 63 | +func forProject(project devboxProject) (*localLockFile, error) { |
| 64 | + configHash, err := project.ConfigHash() |
| 65 | + if err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + |
| 69 | + nixHash, err := nix.ManifestHash(project.ProjectDir()) |
| 70 | + if err != nil { |
| 71 | + return nil, err |
| 72 | + } |
| 73 | + |
| 74 | + newLock := &localLockFile{ |
| 75 | + project: project, |
| 76 | + ConfigHash: configHash, |
| 77 | + NixProfileManifestHash: nixHash, |
| 78 | + } |
| 79 | + |
| 80 | + return newLock, nil |
| 81 | +} |
| 82 | + |
| 83 | +func localLockFilePath(project devboxProject) string { |
| 84 | + return filepath.Join(project.ProjectDir(), ".devbox", "local.lock") |
| 85 | +} |
0 commit comments