Skip to content
Merged
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
10 changes: 6 additions & 4 deletions cmd/skills/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,15 @@ func visibleSkills(all []libskills.Skill, experimental bool) []libskills.Skill {
return list
}

// provenanceLine says where a stale catalog came from. A bundled copy has no
// fetch time, so the line leaves it out rather than print the zero time.
// provenanceLine says where a stale catalog came from. A bundled copy was never
// refreshed, so its line names no fetch time and claims no failed refresh.
func provenanceLine(catalog *libskills.Catalog) string {
label := filepath.ToSlash(catalog.Label)
if catalog.Label == libskills.BundledLabel {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[nice to have] provenanceLine now selects the wording by catalog.Label, not by catalog.FetchedAt.IsZero(). The Catalog.FetchedAt doc says that a zero time means "unknown" for any source. If a later source returns a stale catalog with a zero FetchedAt and another label, skills list and skills search print fetched 0001-01-01T00:00:00Z. No source does this today, but on main the IsZero() branch and TestProvenanceLineOmitsUnknownFetchTime prevented it. readProvenance in cmd/skills/read.go:140 has the same label check. Keep the bundled wording for BundledLabel, and also keep an IsZero() branch that leaves out the fetch time. Add back a test for a zero time with another label.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Restored an IsZero() branch in both provenanceLine and readProvenance so a non-bundled stale catalog with an unknown fetch time omits the fetch time, and added TestProvenanceLineOmitsUnknownFetchTime.

return fmt.Sprintf("Skills come from %s (release %s). The skills may be out of date.", label, catalog.Version)
}
if catalog.FetchedAt.IsZero() {
return fmt.Sprintf("Skills come from %s (release %s). The source could not be refreshed, so the list may be out of date.",
label, catalog.Version)
return fmt.Sprintf("Skills come from %s (release %s). The source could not be refreshed, so the list may be out of date.", label, catalog.Version)
}
return fmt.Sprintf("Skills come from %s (release %s, fetched %s). The source could not be refreshed, so the list may be out of date.",
label, catalog.Version, catalog.FetchedAt.Format(time.RFC3339))
Expand Down
41 changes: 38 additions & 3 deletions cmd/skills/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import (
"context"
"fmt"
"math/rand/v2"
"os"
"strings"
"testing"
"testing/fstest"
"time"

"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/env"
"github.com/databricks/cli/libs/flags"
libskills "github.com/databricks/cli/libs/skills"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -321,16 +324,48 @@ func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) {
assert.NotContains(t, stdout.String(), "Skills come from")
}

func TestProvenanceLineOmitsUnknownFetchTime(t *testing.T) {
catalog := &libskills.Catalog{Label: "bundled", Version: "1.2.3", Stale: true}
assert.Equal(t, "Skills come from bundled (release 1.2.3). The source could not be refreshed, so the list may be out of date.",
// The bundled copy was never refreshed, so its line must not say a refresh failed.
func TestProvenanceLineForBundledCopyClaimsNoRefresh(t *testing.T) {
catalog := &libskills.Catalog{Label: libskills.BundledLabel, Version: "1.2.3", Stale: true}
assert.Equal(t, "Skills come from bundled copy (release 1.2.3). The skills may be out of date.",
provenanceLine(catalog))
}

// A catalog with an unknown fetch time must not print the zero time.
func TestProvenanceLineOmitsUnknownFetchTime(t *testing.T) {
catalog := &libskills.Catalog{Label: "other", Version: "1.2.3", Stale: true}
assert.NotContains(t, provenanceLine(catalog), "fetched")
assert.NotContains(t, readProvenance(catalog), "fetched")
}

func names(list []libskills.Skill) []string {
var out []string
for _, s := range list {
out = append(out, s.Name)
}
return out
}

// With no skills folder set, `skills list` serves the bundled copy and says so,
// without a fetch time.
func TestListServesBundledCopyWithoutFetchTime(t *testing.T) {
t.Cleanup(libskills.SetBundledFSForTest(os.DirFS("../../libs/skills/testdata/release")))
cmd, stdout, stderr := listTestCmd(t, flags.OutputText)
cmd.SetContext(env.Set(cmd.Context(), "DATABRICKS_SKILLS_DIR", ""))

require.NoError(t, newListCmd().RunE(cmd, nil))

assert.Contains(t, stderr.String(), "Skills come from bundled copy (release 1.2.0). ")
assert.NotContains(t, stderr.String(), "fetched")
assert.NotEmpty(t, stdout.String())
}

// With an empty bundled copy, `skills list` has no source, as before.
func TestListWithoutSourceFails(t *testing.T) {
t.Cleanup(libskills.SetBundledFSForTest(fstest.MapFS{}))
cmd, _, _ := listTestCmd(t, flags.OutputText)
cmd.SetContext(env.Set(cmd.Context(), "DATABRICKS_SKILLS_DIR", ""))

err := newListCmd().RunE(cmd, nil)
assert.ErrorIs(t, err, libskills.ErrNoSource)
}
8 changes: 7 additions & 1 deletion cmd/skills/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,14 @@ func writeReadText(w io.Writer, goos, name string, content []byte, files []strin
}

// readProvenance says where a stale catalog came from. A stale catalog is a
// cached copy the live source could not refresh.
// cached copy the live source could not refresh, or the bundled copy.
func readProvenance(catalog *libskills.Catalog) string {
if catalog.Label == libskills.BundledLabel {
return provenanceLine(catalog)
}
if catalog.FetchedAt.IsZero() {
return fmt.Sprintf("Skills come from %s (release %s). The source could not be refreshed, so the content may be out of date.", catalog.Label, catalog.Version)
}
return fmt.Sprintf("Skills come from %s (release %s, fetched %s). The source could not be refreshed, so the content may be out of date.",
catalog.Label, catalog.Version, catalog.FetchedAt.Format(time.RFC3339))
}
20 changes: 20 additions & 0 deletions cmd/skills/read_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import (
"bytes"
"context"
"errors"
"os"
"testing"
"time"

"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/env"
"github.com/databricks/cli/libs/flags"
libskills "github.com/databricks/cli/libs/skills"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -127,3 +129,21 @@ func TestRunReadNamesReleaseWhenSkillHasNoSkillFile(t *testing.T) {
assert.Contains(t, err.Error(), `skill "broken-skill" has no SKILL.md in this release`)
assert.Empty(t, stdout.String())
}

// With no skills folder set, `skills read` serves the bundled copy and says so,
// without a fetch time.
func TestReadServesBundledCopyWithoutFetchTime(t *testing.T) {
t.Cleanup(libskills.SetBundledFSForTest(os.DirFS("../../libs/skills/testdata/release")))
cmd, stdout, stderr := newReadTestCmd(t)
cmd.SetContext(env.Set(cmd.Context(), "DATABRICKS_SKILLS_DIR", ""))

catalog, err := libskills.LocalCatalog(cmd.Context())
require.NoError(t, err)
require.NotEmpty(t, catalog.Skills)

require.NoError(t, newReadCmd().RunE(cmd, []string{catalog.Skills[0].Name}))

assert.Contains(t, stderr.String(), "Skills come from bundled copy (release 1.2.0). ")
assert.NotContains(t, stderr.String(), "fetched")
assert.NotEmpty(t, stdout.String())
}
41 changes: 32 additions & 9 deletions libs/skills/bundled_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"time"
)

// bundledSnapshot is a skills release compiled into the binary. It is the
// fallback for when the published release cannot be reached and nothing is
// cached. The repo holds only an empty manifest; a later change fills the
// snapshot when release binaries are built.
// bundledSnapshot is a skills release compiled into the binary. Resolve serves
// it today when no skills folder is set; once the live release and the cache
// exist it stays the last fallback. The repo holds only an empty manifest; a
// later change fills the snapshot when release binaries are built.
//
// The all: prefix embeds files whose names start with "." or "_" too. Without
// it the compiler drops them silently, and a skill file such as
Expand All @@ -23,7 +23,8 @@ var bundledSnapshot embed.FS
// BundledLabel says where a catalog from the bundled snapshot came from.
const BundledLabel = "bundled copy"

// bundledFS is the root of the compiled-in snapshot.
// bundledFS is the root of the compiled-in snapshot. Tests replace it through
// SetBundledFSForTest to serve a snapshot that has skills.
var bundledFS = subSnapshot()

func subSnapshot() fs.FS {
Expand All @@ -34,15 +35,25 @@ func subSnapshot() fs.FS {
return sub
}

// SetBundledFSForTest makes the bundled source serve fsys, a release laid out
// like the snapshot folder. It returns a function that restores the compiled-in
// snapshot. It is for tests only, and tests that call it must not run in
// parallel.
func SetBundledFSForTest(fsys fs.FS) (restore func()) {
prev := bundledFS
bundledFS = fsys
return func() { bundledFS = prev }
}

// NewBundledSource returns the source over the snapshot compiled into the
// binary. A snapshot with no skills reports ErrSourceUnreachable, so a
// development build behaves as if it had no bundled copy.
func NewBundledSource() Source {
return newBundledSource(bundledFS)
}

// newBundledSource serves a snapshot rooted at fsys. Tests pass a fixture
// release here, so they do not swap the package variable.
// newBundledSource serves a snapshot rooted at fsys. NewBundledSource passes
// the package variable here; tests replace that through SetBundledFSForTest.
func newBundledSource(fsys fs.FS) Source {
return &bundledSource{src: NewFSSource(fsys, BundledLabel)}
}
Expand All @@ -52,8 +63,8 @@ type bundledSource struct {
}

// Catalog reports the snapshot as a stale copy with no fetch time. The binary
// does not record when the snapshot was built, and the snapshot is only used
// when the release cannot be reached, so it is never current.
// does not record when the snapshot was built, so it is never reported as
// current.
func (s *bundledSource) Catalog(ctx context.Context) (*Catalog, error) {
catalog, err := s.src.Catalog(ctx)
if err != nil {
Expand All @@ -73,3 +84,15 @@ func (s *bundledSource) ReadFile(ctx context.Context, skill, file string) ([]byt
}
return s.src.ReadFile(ctx, skill, file)
}

// FileSize forwards to the snapshot, so list-files reports sizes for it too.
func (s *bundledSource) FileSize(ctx context.Context, skill, file string) (int64, error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[nice to have] No test calls the new bundledSource.FileSize, and no test runs skills list-files on the bundled copy. If the empty-snapshot guard or the size forward breaks, CI does not find it. Add a case to TestBundledSourceFromFixture that calls FileSize on a file of the fixture skill. Also cover the empty snapshot.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added a FileSize case to TestBundledSourceFromFixture and TestBundledSourceFileSizeEmptySnapshot for the empty snapshot guard.

if _, err := s.Catalog(ctx); err != nil {
return 0, err
}
sizer, ok := s.src.(FileSizer)
if !ok {
return 0, fmt.Errorf("%w: %q in skill %q", ErrNoSize, file, skill)
}
return sizer.FileSize(ctx, skill, file)
}
11 changes: 11 additions & 0 deletions libs/skills/bundled_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,20 @@ func TestBundledSourceFromFixture(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "# Guide\n\nRead this for details.\n", lf(string(data)))

size, err := src.(FileSizer).FileSize(t.Context(), "alpha", "references/guide.md")
require.NoError(t, err)
assert.Equal(t, int64(len(data)), size)

_, err = src.ReadFile(t.Context(), "alpha", "missing.md")
assert.ErrorIs(t, err, ErrUnknownFile)

_, err = src.ReadFile(t.Context(), "gamma", "SKILL.md")
assert.ErrorIs(t, err, ErrUnknownSkill)
}

func TestBundledSourceFileSizeEmptySnapshot(t *testing.T) {
t.Parallel()
src := newBundledSource(fstest.MapFS{"manifest.json": {Data: []byte(`{"skills": {}}`)}})
_, err := src.(FileSizer).FileSize(t.Context(), "alpha", "SKILL.md")
assert.ErrorIs(t, err, ErrSourceUnreachable)
}
28 changes: 28 additions & 0 deletions libs/skills/hints_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"
"testing"

"github.com/databricks/cli/internal/testutil"
"github.com/databricks/cli/libs/env"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -63,3 +64,30 @@ func TestWriteGroupHintRunsLeadingHyphenSkillAsPrinted(t *testing.T) {
require.NoError(t, fs.Parse(args))
assert.Equal(t, []string{"-foo"}, fs.Args())
}

// With the preview unset, a non-empty bundled copy must not produce a footer,
// even when hints are forced on.
func TestHintsStayOffWithoutPreviewDespiteBundledCopy(t *testing.T) {
testutil.CleanupEnvironment(t)
t.Cleanup(SetBundledFSForTest(os.DirFS("testdata/release")))
ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")
ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", "1")

assert.Nil(t, GroupSkills(ctx, "jobs"))
var buf bytes.Buffer
WriteGroupHint(ctx, &buf, "jobs")
assert.Empty(t, buf.String())
}

// With the preview and hints on, a non-empty bundled copy produces the footer.
func TestHintsShowForBundledCopyWithPreviewOn(t *testing.T) {
testutil.CleanupEnvironment(t)
t.Cleanup(SetBundledFSForTest(os.DirFS("testdata/release")))
ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")
ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", "1")
ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", "1")

var buf bytes.Buffer
WriteGroupHint(ctx, &buf, "jobs")
assert.Contains(t, buf.String(), "databricks skills read alpha")
}
29 changes: 22 additions & 7 deletions libs/skills/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,34 @@ const dirEnv = "DATABRICKS_SKILLS_DIR"
// ErrNoSource reports that this build has no skills source to read from.
var ErrNoSource = errors.New("no skills source is available in this build")

// Resolve returns the source that serves skills. For now that is the folder in
// DATABRICKS_SKILLS_DIR, when it is set. Otherwise no source is available.
// Resolve returns the source that serves skills. A folder in
// DATABRICKS_SKILLS_DIR wins when it is set. Otherwise the copy bundled into the
// binary serves them. A build whose bundled copy has no skills has no source,
// and Resolve returns ErrNoSource.
//
// The live release and the cache come later. They will sit in front of the
// bundled copy, which stays the last fallback.
func Resolve(ctx context.Context) (Source, error) {
dir := env.Get(ctx, dirEnv)
if dir == "" {
if dir != "" {
return NewFSSource(os.DirFS(dir), filepath.ToSlash(dir)), nil
}

bundled := NewBundledSource()
_, err := bundled.Catalog(ctx)
if errors.Is(err, ErrSourceUnreachable) {
return nil, ErrNoSource
}
return NewFSSource(os.DirFS(dir), filepath.ToSlash(dir)), nil
if err != nil {
return nil, err
}
return bundled, nil
}

// LocalCatalog returns the freshest catalog that needs no network call. For now
// that is the folder in DATABRICKS_SKILLS_DIR. It returns nil when no folder is
// set.
// LocalCatalog returns the freshest catalog that needs no network call: the
// folder in DATABRICKS_SKILLS_DIR when it is set, otherwise the bundled copy.
// It returns nil when no folder is set and the bundled copy has no skills. It
// follows Resolve, so the two agree on which source is read.
func LocalCatalog(ctx context.Context) (*Catalog, error) {
src, err := Resolve(ctx)
if errors.Is(err, ErrNoSource) {
Expand Down
45 changes: 43 additions & 2 deletions libs/skills/resolve_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package skills

import (
"os"
"path/filepath"
"testing"
"testing/fstest"

"github.com/databricks/cli/libs/env"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestResolveWithoutDir(t *testing.T) {
func TestResolveWithoutDirAndEmptyBundledCopy(t *testing.T) {
t.Cleanup(SetBundledFSForTest(fstest.MapFS{}))
src, err := Resolve(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", ""))
assert.ErrorIs(t, err, ErrNoSource)
assert.Nil(t, src)
Expand All @@ -28,7 +31,8 @@ func TestResolveWithDir(t *testing.T) {
assert.Equal(t, "testdata/release", catalog.Label)
}

func TestLocalCatalogWithoutDir(t *testing.T) {
func TestLocalCatalogWithoutDirAndEmptyBundledCopy(t *testing.T) {
t.Cleanup(SetBundledFSForTest(fstest.MapFS{}))
catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", ""))
assert.NoError(t, err)
assert.Nil(t, catalog)
Expand All @@ -47,3 +51,40 @@ func TestLocalCatalogFromAcceptanceFixture(t *testing.T) {
assert.Equal(t, "guide-skill", catalog.Skills[3].Name)
assert.Equal(t, "preview-skill", catalog.Skills[4].Name)
}

func TestResolveWithoutDirServesBundledCopy(t *testing.T) {
t.Cleanup(SetBundledFSForTest(os.DirFS("testdata/release")))
ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")

src, err := Resolve(ctx)
require.NoError(t, err)

catalog, err := src.Catalog(ctx)
require.NoError(t, err)
assert.Equal(t, BundledLabel, catalog.Label)
assert.True(t, catalog.FetchedAt.IsZero())
}

func TestResolveDirWinsOverBundledCopy(t *testing.T) {
t.Cleanup(SetBundledFSForTest(os.DirFS("testdata/release")))
dir := filepath.Join("..", "..", "acceptance", "cmd", "skills", "release")
ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", dir)

src, err := Resolve(ctx)
require.NoError(t, err)

catalog, err := src.Catalog(ctx)
require.NoError(t, err)
assert.NotEqual(t, BundledLabel, catalog.Label)
assert.False(t, catalog.Stale)
}

func TestLocalCatalogWithoutDirReadsBundledCopy(t *testing.T) {
t.Cleanup(SetBundledFSForTest(os.DirFS("testdata/release")))

catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", ""))
require.NoError(t, err)
require.NotNil(t, catalog)
assert.Equal(t, BundledLabel, catalog.Label)
assert.NotEmpty(t, catalog.Skills)
}
Loading
Loading