Git Tips - Reset local files to a remote branch | Git in-use

Posted by Phong To on Sun, Mar 19, 2023

TL;DR:

1git checkout <remote>/<branch_name> -- <file_path_1> <file_path_2> ...

For example:

1git checkout origin/develop -- src/components/Banner.tsx
2git checkout upstream/master -- src/components/Header.tsx src/utils/utils.ts

The Scenarios

Several most common use cases for this command:

  • You raised a pull request and reviewer said that several specific files should not be there.
  • You made a mistake that committed several files into a commit on your local development environment.
  • You realized something wrong, or you wanted to re-code a specific file that already committed or pushed.
  • You wanted to exclude several files from your commit or pull request.

Those are the case you might need to use the command to bring your files to the status at another stable branch (usually master, release or develop)

The command

1git checkout <remote>/<branch_name> -- <file_path_1> <file_path_2> ...
  • git checkout: brings the branch/files to a specific destination status
  • <remote>/<branch_name>: refers to the HEAD of the destination branch that we wanted to reset to
  • --: indicates that you’re about to provide a set of path(s) or file(s)
  • <file_path_1> <file_path_2>: list of file paths that you wanted to perform the reset

Examples:

1git checkout origin/develop -- src/components/Banner.tsx
2git checkout upstream/master -- src/components/Header.tsx src/utils/utils.ts

All Done

Now you get the files reset to a specific state on another stable branch.

Remember it’s a destructive action, you can not get your previous state once you execute this command.

Be sure that you know exactly what you’re about to do, or doing the backup to keep everything safe.

Thanks for reading!



comments powered by Disqus