Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/dbc/completions/dbc.bash
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ _dbc_sync_completions() {
esac

if [[ "$cur" == -* ]]; then
COMPREPLY=($(compgen -W "-h --level -l --path -p --no-verify --json --json-stream-progress" -- "$cur"))
COMPREPLY=($(compgen -W "-h --level -l --path -p --no-verify --locked --json --json-stream-progress" -- "$cur"))
return 0
fi

Expand Down
1 change: 1 addition & 0 deletions cmd/dbc/completions/dbc.fish
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l help -d 'Help'
complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l level -s l -d 'Installation level' -xa 'user system'
complete -c dbc -n '__fish_dbc_using_subcommand sync' -l path -s p -r -F -a '*.toml' -d 'Driver list to sync'
complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l no-verify -d 'Do not verify the driver after installation'
complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l locked -d 'Install what the lock file records without updating it'
complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l json -d 'Print output as JSON instead of plaintext'
complete -f -c dbc -n '__fish_dbc_using_subcommand sync' -l json-stream-progress -d 'Stream progress events as JSON lines (implies --json)'

Expand Down
1 change: 1 addition & 0 deletions cmd/dbc/completions/dbc.zsh
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ function _dbc_sync_completions {
'(-p)--path[driver list to add to]: :_files -g \*.toml' \
'(--path)-p[driver list to add to]: :_files -g \*.toml' \
'--no-verify[do not verify the driver after installation]' \
'--locked[install what the lock file records without updating it]' \
'--json[Print output as JSON instead of plaintext]' \
'--json-stream-progress[Stream progress events as JSON lines (implies --json)]'
}
Expand Down
39 changes: 34 additions & 5 deletions cmd/dbc/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type SyncCmd struct {
Path string `arg:"-p" placeholder:"FILE" default:"./dbc.toml" help:"Driver list to sync from"`
Level config.ConfigLevel `arg:"-l" help:"Config level to install to (user, system)"`
NoVerify bool `arg:"--no-verify" help:"Allow installation of drivers without a signature file"`
Locked bool `arg:"--locked" help:"Install exactly what the lock file records, without updating it; fail if it does not match the driver list"`
Json bool `arg:"--json" help:"Print output as JSON instead of plaintext"`
JsonStreamProgress bool `arg:"--json-stream-progress" help:"Stream progress events as JSON lines (implies --json)"`
}
Expand All @@ -58,6 +59,7 @@ func (c SyncCmd) newModel(base baseModel) syncModel {
Path: c.Path,
cfg: getConfig(c.Level),
NoVerify: c.NoVerify,
Locked: c.Locked,
jsonOutput: c.Json || c.JsonStreamProgress,
jsonStreamProgress: c.JsonStreamProgress,
ctx: ctx,
Expand Down Expand Up @@ -120,7 +122,10 @@ type syncModel struct {
// path to driver list
Path string
NoVerify bool
cfg config.Config
// Locked installs from the lock file without fetching an index or
// writing the lock file; see driverListResolution.locked.
Locked bool
cfg config.Config

jsonOutput bool
jsonStreamProgress bool
Expand Down Expand Up @@ -307,6 +312,7 @@ func (s syncModel) prepareWithWarnings() (items []syncItem, warnings []string, e
ctx: s.ctx,
projectLock: s.projectLock,
base: s.baseModel,
locked: s.Locked,
}.resolve(s.fetch)
}

Expand Down Expand Up @@ -340,6 +346,11 @@ type driverListResolution struct {
// hostOptional plans drivers whose locked version has no build for this
// platform; see syncPlanner.hostOptional.
hostOptional bool
// locked plans every driver from its lock entry and never writes the
// lock file or fetches an index. The lock file must exist and match the
// driver list; otherwise resolve fails before fetch runs. dbc sync
// --locked sets it.
locked bool
}

// resolve plans every driver, runs fetch for each planned driver and writes
Expand Down Expand Up @@ -381,12 +392,22 @@ func (r driverListResolution) resolve(fetch func(*plannedDriver) (syncItem, erro
if err != nil {
return nil, warnings, err
}
if err := validateDriverSources(list); err != nil {
return nil, warnings, err
// lockMismatches reports invalid sources together with the other
// differences, so --locked does not stop at the first one.
if !r.locked {
if err := validateDriverSources(list); err != nil {
return nil, warnings, err
}
}
existing, err := readLockFile(lockPath)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
switch {
case r.locked && errors.Is(err, fs.ErrNotExist):
return nil, warnings, errLockedNoLockFile
case err != nil && !errors.Is(err, fs.ErrNotExist):
return nil, warnings, err
case r.locked && existing.Version != lockFileVersionV2:
return nil, warnings, fmt.Errorf("dbc sync --locked needs a version %d lock file, but %s is version %d; run `dbc lock` to update it",
lockFileVersionV2, lockPath, existing.Version)
}
if err := applyProjectRegistries(list); err != nil {
var urls []*url.URL
Expand All @@ -406,7 +427,12 @@ func (r driverListResolution) resolve(fetch func(*plannedDriver) (syncItem, erro
allowSourceChange: r.allowSourceChange,
hostOptional: r.hostOptional,
}
planned, warnings, err := planner.plan(list, existing)
var planned []plannedDriver
if r.locked {
planned, err = planLocked(&planner, list, existing.V2)
} else {
planned, warnings, err = planner.plan(list, existing)
}
if warning := projectRegistryWarning(list); warning != "" {
warnings = append([]string{warning}, warnings...)
}
Expand All @@ -432,6 +458,9 @@ func (r driverListResolution) resolve(fetch func(*plannedDriver) (syncItem, erro
if err := r.ctx.Err(); err != nil {
return items, warnings, err
}
if r.locked {
return items, warnings, nil
}
if err := writeLockFileV2(lockPath, lockFileV2{Version: lockFileVersionV2, Platforms: planner.platforms, Drivers: entries}); err != nil {
return items, warnings, err
}
Expand Down
240 changes: 240 additions & 0 deletions cmd/dbc/sync_locked.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
// Copyright 2026 Columnar Technologies Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"errors"
"fmt"
"maps"
"slices"
"strings"

"github.com/Masterminds/semver/v3"
"github.com/columnar-tech/dbc/internal/resolution"
)

// lockMismatches returns every way in which a version 2 lock file does not
// match the driver list, one message per difference, ordered by driver name.
// It reads nothing but the two files: no registry configuration and no
// index. An empty result means that dbc lock would keep every entry as it
// is. The error is about invalid input, such as invalid platforms in the
// driver list; lock must be valid, as readLockFile returns it.
func lockMismatches(list DriversList, lock lockFileV2) ([]string, error) {
declared, err := list.targetPlatforms()
if err != nil {
return nil, err
}
var mismatches []string
if !sameTargets(declared, lock.Platforms) {
mismatches = append(mismatches, platformsMismatch(declared, lock.Platforms))
}

locked := make(map[string]lockedDriver, len(lock.Drivers))
for _, d := range lock.Drivers {
locked[d.Name] = d
}
names := slices.Collect(maps.Keys(list.Drivers))
for name := range locked {
if _, ok := list.Drivers[name]; !ok {
names = append(names, name)
}
}
slices.Sort(names)

for _, name := range names {
spec, listed := list.Drivers[name]
d, isLocked := locked[name]
switch {
case !isLocked:
mismatches = append(mismatches, fmt.Sprintf("driver %s is in the driver list but not in the lock file", name))
continue
case !listed:
mismatches = append(mismatches, fmt.Sprintf("driver %s is in the lock file but not in the driver list", name))
continue
}
spec = spec.withPrerelease()
if spec.Source != nil {
// Unlike validateDriverSources, an invalid source is one more
// difference to report, not the end of the check.
target, err := spec.Source.target(list.Registries)
switch {
case err != nil:
mismatches = append(mismatches, fmt.Sprintf("driver %s: %v", name, err))
case target.identity != d.Source.URL:
mismatches = append(mismatches, fmt.Sprintf("driver %s: the driver list takes it from %s, but the lock file has it from %s",
name, target.identity, d.Source.URL))
}
}
v, err := semver.NewVersion(d.Version)
if err != nil {
return nil, fmt.Errorf("driver %s: invalid locked version: %w", name, err)
}
if !lockSatisfies(spec, v) {
mismatches = append(mismatches, versionMismatch(name, spec, v))
}
}
return mismatches, nil
}

// sameTargets reports whether two sets of canonical targets are equal. A
// lock file need not list its platforms in order.
func sameTargets(a, b []resolution.Target) bool {
if len(a) != len(b) {
return false
}
a, b = slices.Clone(a), slices.Clone(b)
sortTargets(a)
sortTargets(b)
return slices.Equal(a, b)
}

func platformsMismatch(declared, locked []resolution.Target) string {
describe := func(targets []resolution.Target) string {
if len(targets) == 0 {
return "no platforms"
}
targets = slices.Clone(targets)
sortTargets(targets)
return "platforms " + platformList(targets)
}
return fmt.Sprintf("the driver list declares %s, but the lock file was created for %s", describe(declared), describe(locked))
}

func versionMismatch(name string, spec driverSpec, v *semver.Version) string {
if spec.Version != nil {
return fmt.Sprintf("driver %s: version %s in the lock file does not satisfy %s", name, v, spec.Version)
}
return fmt.Sprintf("driver %s: version %s in the lock file is a pre-release, which the driver list does not allow", name, v)
}

// lockedSyncError reports why dbc sync --locked cannot install from a lock
// file. Mismatches between the lock file and the driver list are fixed by
// dbc lock; trust problems, such as a key that the lock file pins but the
// configuration does not trust, by checking that configuration first.
type lockedSyncError struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since CI is the main use case: jsonErrorCode maps this to the generic fallback, so a --json consumer can't tell a stale lockfile from a network or registry failure without parsing the message. Maybe add a dedicated code (e.g. lock_mismatch / lock_untrusted), or expose mismatches/trust as structured fields in the error envelope?

mismatches []string
trust []string
}

func (e *lockedSyncError) Error() string {
var b strings.Builder
if len(e.mismatches) > 0 {
b.WriteString("the lock file does not match the driver list, so dbc sync --locked cannot install from it:\n")
writeItems(&b, e.mismatches)
b.WriteString("run `dbc lock` to update the lock file, or `dbc sync` without --locked")
}
if len(e.trust) > 0 {
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString("the configuration does not accept the lock file:\n")
writeItems(&b, e.trust)
b.WriteString("check the registries and signing keys in the configuration; updating the lock file would change what it pins")
}
return b.String()
}

func writeItems(b *strings.Builder, items []string) {
for _, item := range items {
fmt.Fprintf(b, " - %s\n", item)
}
}

// errLockedNoLockFile is returned by dbc sync --locked without a lock file.
var errLockedNoLockFile = errors.New("dbc sync --locked needs a lock file; run `dbc lock` to create it")

// planLocked plans every driver of the driver list from its lock entry, for
// dbc sync --locked. It never fetches an index and never changes an entry.
// Every problem that lockMismatches and checkLockedReplay find is reported
// at once, and nothing is planned unless there is none.
func planLocked(p *syncPlanner, list DriversList, lock lockFileV2) ([]plannedDriver, error) {
mismatches, err := lockMismatches(list, lock)
if err != nil {
return nil, err
}
replays, problems, err := p.checkLockedReplay(list, lock)
if err != nil {
return nil, err
}
problems.mismatches = append(mismatches, problems.mismatches...)
if len(problems.mismatches) > 0 || len(problems.trust) > 0 {
return nil, &problems
}
planned := make([]plannedDriver, len(replays))
for i, r := range replays {
planned[i] = r.planned()
}
return planned, nil
}

// checkLockedReplay replays the lock entry of every driver of the driver
// list with replayLock and collects all of their problems, instead of
// stopping at the first one or completing an entry from an index as the
// normal plan does: the platform must be declared and every entry must have
// an artifact for it, a configured registry and the signer that the
// registry selects. It returns the replays only when it found no problem.
// Entries of drivers that the driver list does not have are left to
// lockMismatches.
//
// lock must be valid, as readLockFile returns it; an invalid locked version
// is an error, not a problem.
func (p *syncPlanner) checkLockedReplay(list DriversList, lock lockFileV2) ([]lockReplay, lockedSyncError, error) {
var problems lockedSyncError
platforms, err := list.targetPlatforms()
if err != nil {
return nil, problems, err
}
p.platforms = platforms
// An undeclared platform is one problem of the project; no driver is
// reported for lacking an artifact for it.
hostDeclared := platforms == nil || p.hostDeclared()
if !hostDeclared {
problems.mismatches = append(problems.mismatches, undeclaredHostError(p.target, platforms).Error())
}

var replays []lockReplay
drivers := slices.Clone(lock.Drivers)
slices.SortFunc(drivers, func(a, b lockedDriver) int { return strings.Compare(a.Name, b.Name) })
for _, d := range drivers {
if _, ok := list.Drivers[d.Name]; !ok {
continue
}
v, err := semver.NewVersion(d.Version)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this branch (and the one in lockMismatches) can't trigger for a lockfile returned by readLockFile, because validate() already requires a canonical semver. Fine to keep for consistency with plan().

if err != nil {
return nil, problems, fmt.Errorf("driver %s: invalid locked version: %w", d.Name, err)
}
r, err := p.replayLock(d.Name, d, v)
if err != nil {
return nil, problems, err
}
if r.trustErr != nil {
problems.trust = append(problems.trust, r.trustErr.Error())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: a signer mismatch from trustedSigner already ends with signerChangeHint ("remove the lock file and run dbc lock…"), and the closing line of lockedSyncError then says to check the configuration because updating the lock file would change what it pins. Both make sense, but they show up one after the other. Maybe word the closing line as "if the key change is intended, …", or leave out the hint for items shown here?

}
switch {
case !hostDeclared:
case r.host == nil:
problems.mismatches = append(problems.mismatches, fmt.Sprintf("driver %s %s has no artifact for this platform (%s) in the lock file",
d.Name, d.Version, p.target))
case r.artifactErr != nil:
problems.mismatches = append(problems.mismatches, r.artifactErr.Error())
default:
replays = append(replays, r)
}
}
if len(problems.mismatches) > 0 || len(problems.trust) > 0 {
return nil, problems, nil
}
return replays, problems, nil
}
Loading
Loading