diff --git a/internal/librarian/rust/crate_exists.go b/internal/librarian/rust/crate_exists.go new file mode 100644 index 00000000000..7b6849e8241 --- /dev/null +++ b/internal/librarian/rust/crate_exists.go @@ -0,0 +1,61 @@ +// Copyright 2026 Google LLC +// +// 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 +// +// https://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 rust + +import ( + "bytes" + "errors" + "fmt" + "io/fs" + "os" +) + +// crateExists determines if a crate (the Rust mapping for "library") exists. +// +// Once a crate is generated the following things are true: +// - The output directory exists +// - The output directory is listed in the top-level Cargo.toml file +// +// If none of those things are true, it is safe to assume the crate is a new +// crate and to execute the commands to add the crate to the repository. If +// both are true, then we can skip the commands to add the crate. +// +// If one of them is true, but not the other, then there is an error in the +// repository configuration that requires human intervention. +func crateExists(output string) (bool, error) { + hasDirectory := true + if _, err := os.Stat(output); err != nil { + hasDirectory = false + if !errors.Is(err, fs.ErrNotExist) { + return false, fmt.Errorf("cannot access output directory %q: %w", output, err) + } + } + // The librarian commands are always executed at the top-level directory of + // the monorepo. + contents, err := os.ReadFile("Cargo.toml") + if err != nil { + return false, err + } + // The production version of `Cargo.toml` is always formatted with `taplo + // fmt`. That guarantees the entries will follow this strict format. + hasCargoEntry := bytes.Contains(contents, fmt.Appendf(nil, "\n \"%s\",\n", output)) + if !hasCargoEntry && hasDirectory { + return false, fmt.Errorf("inconsistent repository state, crate missing in Cargo.toml, but the directory exists: %s", output) + } + if hasCargoEntry && !hasDirectory { + return false, fmt.Errorf("inconsistent repository state, crate listed in Cargo.toml, but the directory is missing: %s", output) + } + return hasDirectory && hasCargoEntry, nil +} diff --git a/internal/librarian/rust/crate_exists_test.go b/internal/librarian/rust/crate_exists_test.go new file mode 100644 index 00000000000..236a2caca8b --- /dev/null +++ b/internal/librarian/rust/crate_exists_test.go @@ -0,0 +1,139 @@ +// Copyright 2026 Google LLC +// +// 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 +// +// https://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 rust + +import ( + "fmt" + "os" + "testing" +) + +const formatTestCargoToml = ` +[workspace] +resolver = "3" + +members = [ + "src/auth", +%s +] +` + +func TestCrateExists(t *testing.T) { + const testDir = "src/generated/test/service/v1" + for _, test := range []struct { + name string + cargoText string + makeDir string + wantResult bool + }{ + { + name: "exists", + cargoText: fmt.Sprintf(` "%s",`, testDir), + makeDir: testDir, + wantResult: true, + }, + { + name: "not exists", + cargoText: ` "src/generated/test/service/v2",`, + makeDir: "src/generated/test/service/v2", + wantResult: false, + }, + } { + t.Run(test.name, func(t *testing.T) { + d := t.TempDir() + t.Chdir(d) + if err := os.MkdirAll(test.makeDir, 0775); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("Cargo.toml", fmt.Appendf(nil, formatTestCargoToml, test.cargoText), 0644); err != nil { + t.Fatal(err) + } + got, err := crateExists(testDir) + if err != nil { + t.Fatal(err) + } + if test.wantResult != got { + t.Errorf("crateExists() mismatch, want=%v, got=%v", test.wantResult, got) + } + }) + } +} + +func TestCrateExists_Errors(t *testing.T) { + const testDir = "src/generated/test/service/v1" + for _, test := range []struct { + name string + cargoText string + makeDir string + }{ + { + name: "only directory", + cargoText: ` "bad-bad-bad",`, + makeDir: testDir, + }, + { + name: "only entry", + cargoText: fmt.Sprintf(` "%s",`, testDir), + makeDir: "src/generated", + }, + { + name: "entry is substring", + cargoText: ` "src/generated/test/service/v1/weird/but/should/test",`, + makeDir: testDir, + }, + } { + t.Run(test.name, func(t *testing.T) { + d := t.TempDir() + t.Chdir(d) + if err := os.MkdirAll(test.makeDir, 0775); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("Cargo.toml", fmt.Appendf(nil, formatTestCargoToml, test.cargoText), 0644); err != nil { + t.Fatal(err) + } + got, err := crateExists(testDir) + if err == nil { + t.Fatalf("crateExists() succeed when an error was expected: %v", got) + } + }) + } +} + +func TestCrateExistsDirectoryError(t *testing.T) { + d := t.TempDir() + t.Chdir(d) + // Create part of the path, but make it unreadable. + if err := os.MkdirAll("src", 0000); err != nil { + t.Fatal(err) + } + if err := os.WriteFile("Cargo.toml", []byte("# test only"), 0644); err != nil { + t.Fatal(err) + } + if got, err := crateExists("src/generated/unreachable"); err == nil { + t.Errorf("expected an error from crateExists(), got=%v", got) + } +} + +func TestCrateExistsCargoTomlError(t *testing.T) { + d := t.TempDir() + t.Chdir(d) + // Create part of the path, but make it unreadable. + if err := os.MkdirAll("src/generated/test", 0755); err != nil { + t.Fatal(err) + } + if got, err := crateExists("src/generated/test"); err == nil { + t.Errorf("expected an error from crateExists(), got=%v", got) + } +} diff --git a/internal/librarian/rust/generate.go b/internal/librarian/rust/generate.go index fbb53b5347c..aad1ce2d135 100644 --- a/internal/librarian/rust/generate.go +++ b/internal/librarian/rust/generate.go @@ -16,10 +16,8 @@ package rust import ( "context" - "errors" "fmt" "io/fs" - "os" "path/filepath" "strings" @@ -73,12 +71,9 @@ func Generate(ctx context.Context, cfg *config.Config, library *config.Library, if err != nil { return err } - exists := true - if _, err := os.Stat(library.Output); err != nil { - if !errors.Is(err, fs.ErrNotExist) { - return fmt.Errorf("cannot access output directory %q: %w", library.Output, err) - } - exists = false + exists, err := crateExists(library.Output) + if err != nil { + return err } if !exists { if err := create(ctx, library.Output); err != nil { diff --git a/internal/librarian/rust/generate_test.go b/internal/librarian/rust/generate_test.go index faba30c5ca6..3cab138c9c6 100644 --- a/internal/librarian/rust/generate_test.go +++ b/internal/librarian/rust/generate_test.go @@ -17,6 +17,7 @@ package rust import ( "context" "errors" + "fmt" "io/fs" "os" "path/filepath" @@ -418,15 +419,6 @@ func TestGenerateLibrary(t *testing.T) { if err != nil { t.Fatal(err) } - workspaceDir, err := filepath.Abs("testdata") - if err != nil { - t.Fatal(err) - } - - t.Cleanup(func() { - os.RemoveAll(filepath.Join(workspaceDir, "target")) - os.Remove(filepath.Join(workspaceDir, "Cargo.lock")) - }) // Mock validate to speed up the test. oldValidate := validate @@ -447,19 +439,26 @@ func TestGenerateLibrary(t *testing.T) { }, } { t.Run(test.name, func(t *testing.T) { - // Change to testdata directory so cargo fmt can find Cargo.toml - t.Chdir(workspaceDir) + // Do all the work in a temporary directory, to keep the source + // directory unchanged. + temp := t.TempDir() + t.Chdir(temp) libName := "google-cloud-secretmanager-v1" - outDir := filepath.Join(workspaceDir, libName) - - if err := os.RemoveAll(outDir); err != nil { - t.Fatal(err) - } + outDir := "src/generated/cloud/secretmanager/v1" if test.preExists { if err := os.MkdirAll(outDir, 0755); err != nil { t.Fatal(err) } + contents := fmt.Appendf(nil, formatTestCargoToml, fmt.Sprintf(` "%s",`, outDir)) + if err := os.WriteFile("Cargo.toml", contents, 0644); err != nil { + t.Fatal(err) + } + } else { + contents := fmt.Appendf(nil, formatTestCargoToml, "") + if err := os.WriteFile("Cargo.toml", contents, 0644); err != nil { + t.Fatal(err) + } } t.Cleanup(func() { os.RemoveAll(outDir) })