diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 9d3c7102f4b..3f6956cafdf 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -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 { + 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)) diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index ae0c4d906e1..fde7b10a8b2 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -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" @@ -321,12 +324,20 @@ 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 { @@ -334,3 +345,27 @@ func names(list []libskills.Skill) []string { } 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) +} diff --git a/cmd/skills/read.go b/cmd/skills/read.go index ed4c253430c..73339d2dd0d 100644 --- a/cmd/skills/read.go +++ b/cmd/skills/read.go @@ -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)) } diff --git a/cmd/skills/read_test.go b/cmd/skills/read_test.go index 5af1faa587b..35036b94709 100644 --- a/cmd/skills/read_test.go +++ b/cmd/skills/read_test.go @@ -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" @@ -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()) +} diff --git a/libs/skills/bundled_source.go b/libs/skills/bundled_source.go index a7288789226..2e3d1eb2a78 100644 --- a/libs/skills/bundled_source.go +++ b/libs/skills/bundled_source.go @@ -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 @@ -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 { @@ -34,6 +35,16 @@ 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. @@ -41,8 +52,8 @@ 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)} } @@ -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 { @@ -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) { + 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) +} diff --git a/libs/skills/bundled_source_test.go b/libs/skills/bundled_source_test.go index 8bf9584811c..8ea81a38bd0 100644 --- a/libs/skills/bundled_source_test.go +++ b/libs/skills/bundled_source_test.go @@ -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) +} diff --git a/libs/skills/hints_test.go b/libs/skills/hints_test.go index ceec374e22f..dab4e2d86d4 100644 --- a/libs/skills/hints_test.go +++ b/libs/skills/hints_test.go @@ -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" @@ -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") +} diff --git a/libs/skills/resolve.go b/libs/skills/resolve.go index a8d8886ca1d..7720a01eb57 100644 --- a/libs/skills/resolve.go +++ b/libs/skills/resolve.go @@ -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) { diff --git a/libs/skills/resolve_test.go b/libs/skills/resolve_test.go index 25857b1b73b..f70d6a878be 100644 --- a/libs/skills/resolve_test.go +++ b/libs/skills/resolve_test.go @@ -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) @@ -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) @@ -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) +} diff --git a/libs/skills/skills.go b/libs/skills/skills.go index 5fb3f1fb191..f0cd938c335 100644 --- a/libs/skills/skills.go +++ b/libs/skills/skills.go @@ -72,8 +72,8 @@ type Catalog struct { // Stale reports that the catalog is not the current release. The source // served a cached copy it could not refresh, or it is the bundled copy, - // which is only served when the release cannot be reached. Sources that - // always read the release themselves leave it false. + // which may be older than the release. Sources that always read the + // release themselves leave it false. Stale bool // Rules is text shown above the catalog, empty when the release has none.