ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: scripts/update_dep.sh (Shell)

Code before:
  # step and let `go get -u` handle it directly.
  if [ -n "${ver}" ]; then
    run go mod edit -require "${mod}@${ver}" || true
  fi

  # Check if the module is a dependency.
  if go list -m all | grep -q -E "^\s*${mod}\s"; then
    log_info "  Updating in ${subdir}..."
    if [ -z "${ver}" ]; then
      run go get -u "${mod}"
    else
      run go get "${mod}@${ver}"
    fi
  fi
}

print_current_dep_version
if is_fully_indirect; then
  read -p "Module ${mod} is a purely indirect dependency. Are you sure you want to update it? [y/N] " -r confirm
  [[ "$confirm" == [Yy] ]] || exit # Default is No
fi

log_info "Updating '${mod}' to ${ver:-latest} across all modules..."
run_for_modules update_module

make fix verify-dep

print_current_dep_version


Review comment (suggestion):
`make fix` take a long time. I don't think we need to run all fixes (e.g. fix-lint) when we just bump dependencies.
```suggestion
make fix-mod-tidy fix-bom update-go-workspace verify-dep
```

Code after:
  # step and let `go get -u` handle it directly.
  if [ -n "${ver}" ]; then
    run go mod edit -require "${mod}@${ver}" || true
  fi

  # Check if the module is a dependency.
  if go list -m all | grep -q -E "^\s*${mod}\s"; then
    log_info "  Updating in ${subdir}..."
    if [ -z "${ver}" ]; then
      run go get -u "${mod}"
    else
      run go get "${mod}@${ver}"
    fi
  fi
}

print_current_dep_version
if is_fully_indirect; then
  read -p "Module ${mod} is a purely indirect dependency. Are you sure you want to update it? [y/N] " -r confirm
  [[ "$confirm" == [Yy] ]] || exit # Default is No
fi

log_info "Updating '${mod}' to ${ver:-latest} across all modules..."
run_for_modules update_module

make fix-mod-tidy fix-bom update-go-workspace verify-dep

print_current_dep_version
Repository: etcd-io/etcd
File: server/auth/store_test.go (Go)

Code before:
		t.Fatal(err)
	}
	as := NewAuthStore(zaptest.NewLogger(t), newBackendMock(), tp, bcrypt.MinCost)
	err = enableAuthAndCreateRoot(as)
	if err != nil {
		t.Fatal(err)
	}

	// adds a new role
	_, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test"})
	if err != nil {
		t.Fatal(err)
	}

	ua := &pb.AuthUserAddRequest{Name: "foo", HashedPassword: encodePassword("bar"), Options: &authpb.UserAddOptions{NoPassword: false}}
	_, err = as.UserAdd(ua) // add a non-existing user
	if err != nil {
		t.Fatal(err)
	}

	// The UserAdd function cannot generate old etcd version user data (user's option is nil)
	// add special users through the underlying interface
	asImpl, ok := as.(*authStore)
	if !ok {
		t.Fatal(errors.New("addUserWithNoOption: needs an AuthStore implementation"))
	}
	addUserWithNoOption(asImpl)

	tearDown := func(_ *testing.T) {
		as.Close()
	}
	return asImpl, tearDown
}

func addUserWithNoOption(as *authStore) {
	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()
	tx.UnsafePutUser(&authpb.User{
		Name:     []byte("foo-no-user-options"),
		Password: []byte("bar"),
	})
	as.commitRevision(tx)
	as.refreshRangePermCache(tx)
}

func enableAuthAndCreateRoot(as AuthStore) error {
	_, err := as.UserAdd(&pb.AuthUserAddRequest{Name: "root", HashedPassword: encodePassword("root"), Options: &authpb.UserAddOptions{NoPassword: false}})
	if err != nil {
		return err
	}

Review comment (security):
```suggestion
	require.True(t, ok, "addUserWithNoOption: needs an AuthStore implementation")
```

Code after:
	err = enableAuthAndCreateRoot(as)
	if err != nil {
		t.Fatal(err)
	}

	// adds a new role
	_, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test"})
	if err != nil {
		t.Fatal(err)
	}

	ua := &pb.AuthUserAddRequest{Name: "foo", HashedPassword: encodePassword("bar"), Options: &authpb.UserAddOptions{NoPassword: false}}
	_, err = as.UserAdd(ua) // add a non-existing user
	if err != nil {
		t.Fatal(err)
	}

	// The UserAdd function cannot generate old etcd version user data (user's option is nil)
	// add special users through the underlying interface
	asImpl, ok := as.(*authStore)
	require.Truef(t, ok, "addUserWithNoOption: needs an AuthStore implementation")
	addUserWithNoOption(asImpl)

	tearDown := func(_ *testing.T) {
		as.Close()
	}
	return asImpl, tearDown
}

func addUserWithNoOption(as *authStore) {
	tx := as.be.BatchTx()
	tx.Lock()
	defer tx.Unlock()
	tx.UnsafePutUser(&authpb.User{
		Name:     []byte("foo-no-user-options"),
		Password: []byte("bar"),
	})
	as.commitRevision(tx)
	as.refreshRangePermCache(tx)
}

func enableAuthAndCreateRoot(as AuthStore) error {
	_, err := as.UserAdd(&pb.AuthUserAddRequest{Name: "root", HashedPassword: encodePassword("root"), Options: &authpb.UserAddOptions{NoPassword: false}})
	if err != nil {
		return err
	}

	_, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: "root"})
	if err != nil {
		return err
	}
Repository: etcd-io/etcd
File: server/storage/mvcc/watchable_store_test.go (Go)

Code before:
				for j := 0; j < tc.eventsPerRevision; j++ {
					txn.Put(v, v, lease.NoLease)
				}
				txn.End()
			}

			w := s.NewWatchStream()
			defer w.Close()

			w.Watch(0, v, nil, 1)
			var revisionBatches [][]int64
			eventCount := 0
			for eventCount < tc.revisions*tc.eventsPerRevision {
				var revisions []int64
				for _, e := range (<-w.Chan()).Events {
					revisions = append(revisions, e.Kv.ModRevision)
					eventCount++
				}
				revisionBatches = append(revisionBatches, revisions)
			}
			assert.Equal(t, tc.expectRevisionBatches, revisionBatches)

			sImpl, ok := s.(*watchableStore)
			if !ok {
				t.Fatal(errors.New("TestWatchBatchUnsynced: needs a WatchableKV implementation"))
			}

			sImpl.store.revMu.Lock()
			defer sImpl.store.revMu.Unlock()
			assert.Equal(t, 1, sImpl.synced.size())
			assert.Equal(t, 0, sImpl.unsynced.size())
		})
	}
}

func TestNewMapwatcherToEventMap(t *testing.T) {
	k0, k1, k2 := []byte("foo0"), []byte("foo1"), []byte("foo2")
	v0, v1, v2 := []byte("bar0"), []byte("bar1"), []byte("bar2")

	ws := []*watcher{{key: k0}, {key: k1}, {key: k2}}

	evs := []mvccpb.Event{
		{
			Type: mvccpb.PUT,
			Kv:   &mvccpb.KeyValue{Key: k0, Value: v0},
		},
		{
			Type: mvccpb.PUT,
			Kv:   &mvccpb.KeyValue{Key: k1, Value: v1},
		},
		{

Review comment (performance):
```suggestion
			require.True(t, ok, "TestWatchBatchUnsynced: needs a WatchableKV implementation")
```

Code after:
				txn.End()
			}

			w := s.NewWatchStream()
			defer w.Close()

			w.Watch(0, v, nil, 1)
			var revisionBatches [][]int64
			eventCount := 0
			for eventCount < tc.revisions*tc.eventsPerRevision {
				var revisions []int64
				for _, e := range (<-w.Chan()).Events {
					revisions = append(revisions, e.Kv.ModRevision)
					eventCount++
				}
				revisionBatches = append(revisionBatches, revisions)
			}
			assert.Equal(t, tc.expectRevisionBatches, revisionBatches)

			sImpl, ok := s.(*watchableStore)
			require.Truef(t, ok, "TestWatchBatchUnsynced: needs a WatchableKV implementation")

			sImpl.store.revMu.Lock()
			defer sImpl.store.revMu.Unlock()
			assert.Equal(t, 1, sImpl.synced.size())
			assert.Equal(t, 0, sImpl.unsynced.size())
		})
	}
}

func TestNewMapwatcherToEventMap(t *testing.T) {
	k0, k1, k2 := []byte("foo0"), []byte("foo1"), []byte("foo2")
	v0, v1, v2 := []byte("bar0"), []byte("bar1"), []byte("bar2")

	ws := []*watcher{{key: k0}, {key: k1}, {key: k2}}

	evs := []mvccpb.Event{
		{
			Type: mvccpb.PUT,
			Kv:   &mvccpb.KeyValue{Key: k0, Value: v0},
		},
		{
			Type: mvccpb.PUT,
			Kv:   &mvccpb.KeyValue{Key: k1, Value: v1},
		},
		{
			Type: mvccpb.PUT,
			Kv:   &mvccpb.KeyValue{Key: k2, Value: v2},
		},
	}
Repository: etcd-io/etcd
File: server/storage/backend/backend.go (Go)

Code before:
	bcfg.Path = path
	for _, opt := range opts {
		opt(&bcfg)
	}

	return newBackend(bcfg)
}

func newBackend(bcfg BackendConfig) *backend {
	bopts := &bolt.Options{}
	if boltOpenOptions != nil {
		*bopts = *boltOpenOptions
	}
	bopts.InitialMmapSize = bcfg.mmapSize()
	bopts.FreelistType = bcfg.BackendFreelistType
	bopts.NoSync = bcfg.UnsafeNoFsync
	bopts.NoGrowSync = bcfg.UnsafeNoFsync
	bopts.Mlock = bcfg.Mlock
	bopts.Logger = newBoltLoggerZap(bcfg)

	db, err := bolt.Open(bcfg.Path, 0o600, bopts)
	if err != nil {
		bcfg.Logger.Panic("failed to open database", zap.String("path", bcfg.Path), zap.Error(err))
	}

	if bcfg.Logger == nil {
		bcfg.Logger = zap.NewNop()
	}

	// In future, may want to make buffering optional for low-concurrency systems
	// or dynamically swap between buffered/non-buffered depending on workload.
	b := &backend{
		bopts: bopts,
		db:    db,

		batchInterval: bcfg.BatchInterval,
		batchLimit:    bcfg.BatchLimit,
		mlock:         bcfg.Mlock,

		readTx: &readTx{
			baseReadTx: baseReadTx{
				buf: txReadBuffer{
					txBuffer:   txBuffer{make(map[BucketID]*bucketBuffer)},
					bufVersion: 0,
				},
				buckets: make(map[BucketID]*bolt.Bucket),
				txWg:    new(sync.WaitGroup),
				txMu:    new(sync.RWMutex),
			},
		},
		txReadBufferCache: txReadBufferCache{

Review comment (suggestion):
I don't think it works. Both the `newBoltLoggerZap` call and Line 200 `panic` already use `bcfg.Logger`.
That assignment should be placed at the beginning of the `newBackend`

Code after:
	bcfg.Path = path
	for _, opt := range opts {
		opt(&bcfg)
	}

	return newBackend(bcfg)
}

func newBackend(bcfg BackendConfig) *backend {
	bopts := &bolt.Options{}
	if boltOpenOptions != nil {
		*bopts = *boltOpenOptions
	}

	if bcfg.Logger == nil {
		bcfg.Logger = zap.NewNop()
	}

	bopts.InitialMmapSize = bcfg.mmapSize()
	bopts.FreelistType = bcfg.BackendFreelistType
	bopts.NoSync = bcfg.UnsafeNoFsync
	bopts.NoGrowSync = bcfg.UnsafeNoFsync
	bopts.Mlock = bcfg.Mlock
	bopts.Logger = newBoltLoggerZap(bcfg)

	db, err := bolt.Open(bcfg.Path, 0o600, bopts)
	if err != nil {
		bcfg.Logger.Panic("failed to open database", zap.String("path", bcfg.Path), zap.Error(err))
	}

	// In future, may want to make buffering optional for low-concurrency systems
	// or dynamically swap between buffered/non-buffered depending on workload.
	b := &backend{
		bopts: bopts,
		db:    db,

		batchInterval: bcfg.BatchInterval,
		batchLimit:    bcfg.BatchLimit,
		mlock:         bcfg.Mlock,

		readTx: &readTx{
			baseReadTx: baseReadTx{
				buf: txReadBuffer{
					txBuffer:   txBuffer{make(map[BucketID]*bucketBuffer)},
					bufVersion: 0,
				},
				buckets: make(map[BucketID]*bolt.Bucket),
				txWg:    new(sync.WaitGroup),
				txMu:    new(sync.RWMutex),
			},
		},
Repository: etcd-io/etcd
File: server/etcdserver/server_test.go (Go)

Code before:
	cl.SetBackend(schema.NewMembershipBackend(lg, be))

	testdir := t.TempDir()

	snapdir := filepath.Join(testdir, "member", "snap")
	if err := os.MkdirAll(snapdir, 0o755); err != nil {
		t.Fatalf("couldn't make snap dir (%v)", err)
	}

	rs := raft.NewMemoryStorage()
	p := mockstorage.NewStorageRecorderStream(testdir)
	tr, snapDoneC := newSnapTransporter(lg, snapdir)
	r := newRaftNode(raftNodeConfig{
		lg:          lg,
		isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
		Node:        n,
		transport:   tr,
		storage:     p,
		raftStorage: rs,
	})
	ci := cindex.NewConsistentIndex(be)
	cfg := config.ServerConfig{
		Logger:                 lg,
		DataDir:                testdir,
		SnapshotCatchUpEntries: DefaultSnapshotCatchUpEntries,
		ServerFeatureGate:      features.NewDefaultServerFeatureGate("TxnModeWriteWithSharedBuffer", nil),
	}

	s := &EtcdServer{
		lgMu:         new(sync.RWMutex),
		lg:           lg,
		Cfg:          cfg,
		r:            *r,
		v2store:      st,
		snapshotter:  snap.New(lg, snapdir),
		cluster:      cl,
		SyncTicker:   &time.Ticker{},
		consistIndex: ci,
		beHooks:      serverstorage.NewBackendHooks(lg, ci),
	}

	s.kv = mvcc.New(lg, be, &lease.FakeLessor{}, mvcc.StoreConfig{})
	s.be = be

	s.start()
	defer s.Stop()

	n.readyc <- raft.Ready{Messages: []raftpb.Message{{Type: raftpb.MsgSnap}}}
	go func() {
		// get the snapshot sent by the transport
		snapMsg := <-snapDoneC

Review comment (suggestion):
```suggestion
		ServerFeatureGate:      features.NewDefaultServerFeatureGate("test", lg),
```

Code after:
	cl.SetBackend(schema.NewMembershipBackend(lg, be))

	testdir := t.TempDir()

	snapdir := filepath.Join(testdir, "member", "snap")
	if err := os.MkdirAll(snapdir, 0o755); err != nil {
		t.Fatalf("couldn't make snap dir (%v)", err)
	}

	rs := raft.NewMemoryStorage()
	p := mockstorage.NewStorageRecorderStream(testdir)
	tr, snapDoneC := newSnapTransporter(lg, snapdir)
	r := newRaftNode(raftNodeConfig{
		lg:          lg,
		isIDRemoved: func(id uint64) bool { return cl.IsIDRemoved(types.ID(id)) },
		Node:        n,
		transport:   tr,
		storage:     p,
		raftStorage: rs,
	})
	ci := cindex.NewConsistentIndex(be)
	cfg := config.ServerConfig{
		Logger:                 lg,
		DataDir:                testdir,
		SnapshotCatchUpEntries: DefaultSnapshotCatchUpEntries,
		ServerFeatureGate:      features.NewDefaultServerFeatureGate("test", lg),
	}

	s := &EtcdServer{
		lgMu:         new(sync.RWMutex),
		lg:           lg,
		Cfg:          cfg,
		r:            *r,
		v2store:      st,
		snapshotter:  snap.New(lg, snapdir),
		cluster:      cl,
		SyncTicker:   &time.Ticker{},
		consistIndex: ci,
		beHooks:      serverstorage.NewBackendHooks(lg, ci),
	}

	s.kv = mvcc.New(lg, be, &lease.FakeLessor{}, mvcc.StoreConfig{})
	s.be = be

	s.start()
	defer s.Stop()

	n.readyc <- raft.Ready{Messages: []raftpb.Message{{Type: raftpb.MsgSnap}}}
	go func() {
		// get the snapshot sent by the transport
		snapMsg := <-snapDoneC
Repository: etcd-io/etcd
File: etcdutl/etcdutl/check_command.go (Go)

Code before:
	argCheckV2StoreDataDir string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	err := checkV2StoreDataDir(argCheckV2StoreDataDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
}

func checkV2StoreDataDir(dataDir string) error {
	var (
		storeClusterPrefix = "/0"
		storeKeysPrefix    = "/1"

		lg = GetLogger()

		walDir  = filepath.Join(dataDir, "member", "wal")
		snapDir = filepath.Join(dataDir, "member", "snap")
	)

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
		return err
	}
	if snapshot == nil {
		return nil

Review comment (suggestion):
We can reuse the existing definitions,
https://github.com/etcd-io/etcd/blob/762e93874f23213c3b3d918ba82ce2803bee3d46/server/etcdserver/server.go#L83-L84

Code after:
var (
	argCheckV2StoreDataDir string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	err := checkV2StoreDataDir(argCheckV2StoreDataDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
	fmt.Println("No custom content found in v2store.")
}

func checkV2StoreDataDir(dataDir string) error {
	var (
		lg = GetLogger()

		walDir  = filepath.Join(dataDir, "member", "wal")
		snapDir = filepath.Join(dataDir, "member", "snap")
	)

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
		return err
	}
	if snapshot == nil {
		return nil
	}
Repository: etcd-io/etcd
File: etcdutl/etcdutl/check_command.go (Go)

Code before:

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
		return err
	}
	if snapshot == nil {
		return nil
	}

	st := v2store.New(storeClusterPrefix, storeKeysPrefix)

	if err := st.Recovery(snapshot.Data); err != nil {
		return fmt.Errorf("failed to recover v2store from snapshot: %w", err)
	}
	return assertNoV2StoreContent(st)
}

func assertNoV2StoreContent(st v2store.Store) error {
	metaOnly, err := membership.IsMetaStoreOnly(st)
	if err != nil {
		return err
	}
	if metaOnly {
		return nil
	}
	return fmt.Errorf("detected custom content in v2store")
}


Review comment (suggestion):
Ideally we should replay the WAL records following the v2 snapshot, but it's a little hard for an offline tool to do that. Also in practice, it's almost impossible that the v2snapshot don't custom content but the WAl records following the v2snapshot have custom content. So it's OK. 

Code after:
	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
		return err
	}
	if snapshot == nil {
		return nil
	}

	st := v2store.New(etcdserver.StoreClusterPrefix, etcdserver.StoreKeysPrefix)

	if err := st.Recovery(snapshot.Data); err != nil {
		return fmt.Errorf("failed to recover v2store from snapshot: %w", err)
	}
	return assertNoV2StoreContent(st)
}

func assertNoV2StoreContent(st v2store.Store) error {
	metaOnly, err := membership.IsMetaStoreOnly(st)
	if err != nil {
		return err
	}
	if metaOnly {
		return nil
	}
	return fmt.Errorf("detected custom content in v2store")
}
Repository: etcd-io/etcd
File: etcdutl/etcdutl/check_command.go (Go)

Code before:
	}
	cmd.AddCommand(NewCheckV2StoreCommand())
	return cmd
}

var (
	argCheckV2StoreDataDir string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	err := checkV2StoreDataDir(argCheckV2StoreDataDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
}

func checkV2StoreDataDir(dataDir string) error {
	var (
		lg = GetLogger()

		walDir  = filepath.Join(dataDir, "member", "wal")
		snapDir = filepath.Join(dataDir, "member", "snap")
	)

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
		return err

Review comment (suggestion):
```suggestion
	}
	fmt.Println("No custom content found in v2store.")
```

Code after:
	}
	cmd.AddCommand(NewCheckV2StoreCommand())
	return cmd
}

var (
	argCheckV2StoreDataDir string
)

// NewCheckV2StoreCommand returns the cobra command for "check v2store".
func NewCheckV2StoreCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "v2store",
		Short: "Check custom content in v2store",
		Run:   checkV2StoreRunFunc,
	}
	cmd.Flags().StringVar(&argCheckV2StoreDataDir, "data-dir", "", "Required. A data directory not in use by etcd.")
	cmd.MarkFlagRequired("data-dir")
	return cmd
}

func checkV2StoreRunFunc(_ *cobra.Command, _ []string) {
	err := checkV2StoreDataDir(argCheckV2StoreDataDir)
	if err != nil {
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
	fmt.Println("No custom content found in v2store.")
}

func checkV2StoreDataDir(dataDir string) error {
	var (
		lg = GetLogger()

		walDir  = filepath.Join(dataDir, "member", "wal")
		snapDir = filepath.Join(dataDir, "member", "snap")
	)

	walSnaps, err := wal.ValidSnapshotEntries(lg, walDir)
	if err != nil {
		if errors.Is(err, wal.ErrFileNotFound) {
			return nil
		}
		return err
	}

	ss := snap.New(lg, snapDir)
	snapshot, err := ss.LoadNewestAvailable(walSnaps)
	if err != nil {
		if errors.Is(err, snap.ErrNoSnapshot) {
			return nil
		}
Repository: etcd-io/etcd
File: tests/e2e/v2store_deprecation_test.go (Go)

Code before:
			cfg.ClusterSize = 3
			cfg.SnapshotCount = 5
			cfg.EnableV2 = true

			// create a cluster with 3 members
			epc, err := e2e.NewEtcdProcessCluster(t, &cfg)
			assert.NoError(t, err)

			cCtx.epc = epc
			dataDirPath = epc.Procs[0].Config().DataDirPath

			defer func() {
				assert.NoError(t, epc.Stop())
			}()

			// create key-values with v3 api
			for i := 0; i < 10; i++ {
				assert.NoError(t, ctlV3Put(cCtx, fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i), ""))
			}
		}()

		proc, err := e2e.SpawnCmd([]string{e2e.BinDir + "/etcdutl", "check", "v2store", "--data-dir=" + dataDirPath}, nil)
		assert.NoError(t, err)

		proc.Wait()
		assert.NotContains(t, proc.Lines(), "detected custom content in v2store")
	})
}

func assertVerifyCheckCustomContentOffline(t *testing.T, dataDirPath string) {
	t.Logf("Checking custom content in v2store - %s", dataDirPath)

	proc, err := e2e.SpawnCmd([]string{e2e.BinDir + "/etcdutl", "check", "v2store", "--data-dir=" + dataDirPath}, nil)
	assert.NoError(t, err)

	_, err = proc.Expect("detected custom content in v2store")
	assert.NoError(t, err)
}


Review comment (suggestion):
```suggestion
		assert.Contains(t, proc.Lines(), "No custom content found in v2store")
```

Code after:
			cfg.ClusterSize = 3
			cfg.SnapshotCount = 5
			cfg.EnableV2 = true

			// create a cluster with 3 members
			epc, err := e2e.NewEtcdProcessCluster(t, &cfg)
			assert.NoError(t, err)

			cCtx.epc = epc
			dataDirPath = epc.Procs[0].Config().DataDirPath

			defer func() {
				assert.NoError(t, epc.Stop())
			}()

			// create key-values with v3 api
			for i := 0; i < 10; i++ {
				assert.NoError(t, ctlV3Put(cCtx, fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i), ""))
			}
		}()

		proc, err := e2e.SpawnCmd([]string{e2e.BinDir + "/etcdutl", "check", "v2store", "--data-dir=" + dataDirPath}, nil)
		assert.NoError(t, err)

		_, err = proc.Expect("No custom content found in v2store")
		assert.NoError(t, err)
	})
}

func assertVerifyCheckCustomContentOffline(t *testing.T, dataDirPath string) {
	t.Logf("Checking custom content in v2store - %s", dataDirPath)

	proc, err := e2e.SpawnCmd([]string{e2e.BinDir + "/etcdutl", "check", "v2store", "--data-dir=" + dataDirPath}, nil)
	assert.NoError(t, err)

	_, err = proc.Expect("detected custom content in v2store")
	assert.NoError(t, err)
}