Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
61 changes: 61 additions & 0 deletions internal/librarian/rust/crate_exists.go
Original file line number Diff line number Diff line change
@@ -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))
Comment thread
coryan marked this conversation as resolved.
Resolved
if !hasCargoEntry && hasDirectory {
return false, fmt.Errorf("inconsistent repository state, crate missing in Cargo.toml, but the directory exists: %s", output)
Comment thread
coryan marked this conversation as resolved.
Resolved
}
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
}
126 changes: 126 additions & 0 deletions internal/librarian/rust/crate_exists_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// 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) {
Comment thread
coryan marked this conversation as resolved.
Resolved
const testDir = "src/generated/test/service/v1"
for _, test := range []struct {
name string
cargoText string
makeDir string
wantErr bool
wantResult bool
}{
{
name: "exists",
cargoText: fmt.Sprintf(` "%s",`, testDir),
makeDir: testDir,
wantErr: false,
wantResult: true,
},
{
name: "not exists",
cargoText: ` "src/generated/test/service/v2",`,
makeDir: "src/generated/test/service/v2",
wantErr: false,
wantResult: false,
},
{
name: "only directory",
cargoText: ` "bad-bad-bad",`,
makeDir: testDir,
wantErr: true,
wantResult: false,
},
{
name: "only entry",
cargoText: fmt.Sprintf(` "%s",`, testDir),
makeDir: "src/generated",
wantErr: true,
wantResult: false,
},
{
name: "entry is substring",
cargoText: ` "src/generated/test/service/v1/weird/but/should/test",`,
makeDir: testDir,
wantErr: true,
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 test.wantErr && err == nil {
t.Fatalf("crateExists() succeed when an error was expected: %v", got)
}
if !test.wantErr && err != nil {
t.Fatalf("crateExists() failed unexpectedly: %v", err)
}
if test.wantResult != got {
t.Errorf("crateExists() mismatch, want=%v, got=%v", test.wantResult, 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)
Comment thread
coryan marked this conversation as resolved.
Resolved
}
}

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)
}
}
11 changes: 3 additions & 8 deletions internal/librarian/rust/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ package rust

import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"

Expand Down Expand Up @@ -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 {
Expand Down
31 changes: 15 additions & 16 deletions internal/librarian/rust/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package rust
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
Expand Down Expand Up @@ -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
Expand All @@ -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) })

Expand Down
Loading