Backport #26346 Follow the CLI refactoring, and add tests. (cherry picked from commit fa431b377d)
fa431b377d