sandalone sandalone - 3 months ago 11
Git Question

Push changes on many files into separate branches

Our junior worked on 5-6 tasks and did not create a branch for each task before starting to work on it, but just started making changes remaining on the

Master
. Now, we have dozens of files changed (modified, deleted and new files) and even dozen that are still not in the Git. Good thing he did not make any commit or push to the remote.

Is there a way that I can now make things right by creating multiple branches (such as
feature-1
,
feature-2
,...) and push the right files into them? So I would push 10 files to
feature-1
, 25 to
feature-2
and so on.

I tried to create a new branch from the current state, but (expectedly) the branch I've just created includes all changed files.

Another thing. We keep Git on the remote repo which has not been synced with the local repo (junior never committed or pushed to this remote). I tried creating a branch on the remote as it will not include the local changes, BUT when I try to checkout to it, Git complaints that it cannot checkout as it would overwrite changes made in a few files.

What shall I do now?

Could stash help here? I have never worked with it nor I have ever stashed files when switching to another repo. I always work in a clean way - first commit, then checkout another repo.

Answer

Using git stash would be one solution here.

First, stash all the work from your junior:

git stash

Step two:

Next, create a new branch which will contain one set of files. But first, pull the latest changes from the master branch:

git checkout master
git pull origin master
git checkout -b feature1

Now apply the stash:

git stash apply

This will bring back all the changed files, including those which you don't want to be in the feature1 branch. Add all the files you do want via:

git add <path/to/file1>
git add <path/to/file2>
# etc.

Now make a commit on feature1 and push it to the repository:

git commit -m 'Junior commit with first set of files'
git push origin feature1

Now, the first set of file changes are safely in a remote branch of their own. But the working directory should still contain the other changed files. Once again, stash them away via:

git stash

Now you can return to Step two above, create a new branch, and continue this set of steps until you have committed all file changes to their own respective branches.

When there is nothing left to stash, then you have finished handling all of your junior's work.