That procedure is partially, but not entirely, correct for your use case. Consider this approach:
# ... in the local directory
git init
You mention that your local has files that shouldnt' be in the repo - and presumably aren't in the repo yet. So create a .gitignore
file that lists those files. Then
git add .
git commit
Now you have a local commit with your current worktree state.
A <--(master)
Then
git remote add origin URL/OF/REMOTE/REPO
(Note that URL/OF/REMOTE/REPO could be PATH/TO/REPO, if REPO is on the local filesystem; but even then I generally use a file://
URL.)
git fetch
Now you have access to the repo's history. Maybe it looks like
x -- x -- x -- O <--(origin/master)
A <--(master)
Next step is to merge the changes from the remote.
git merge --allow-unrelated-histories origin/master
For files only on your local copy... well, you put them in .gitignore
so they should remain untracked.
For files only on the repo copy, they'll be added to the merge result.
For files identical in both locations, the merge will auto-resolve.
For anything else, you'll get a standard merge conflict.
Once you've resolved the conflicts, you should have a working tree state like what you want. Just so we have a clear picture, let's look at what happens if you complete the merge.
git add .
git commit
Now you have
x -- x -- x -- O <--(origin/master)
\
A -- M <--(master)
You could push that, so that master
shows updates to match your local state (excluding the files you .gitignore
d). That will also make commit A
part of the origin history, which you might not want. So another option from here would be
git reset --soft origin/master
Your local change will still be in the index and worktree, but the commit graph will now look like
x -- x -- x -- O <--(origin/master)(master)
A -- M
So now you can re-commit. A
and M
will eventually drop from your local repo due to gc
, and will never be made part of the remote history; but by re-committing you do add the changes to the remote, to sync it with your local directory (other than the ignored files).