After sending a git repository remotely to GitHub and sharing it, for some reason - for example, there’s a typo in the readme.md file and you just made a small change, or you’ve committed some edit history you don’t want to be seen - you might want to push the repository in its current state to GitHub remote as the “first commit”.
I’ll introduce a method that can be used in such cases.
We’ll use the “orphan” option of “git checkout”. With the “orphan” option, you virtually create a branch as if git has been initialized, with no past commits, and by committing with “git commit” on that virtual branch, that commit is registered as the first commit on that branch. In short, it’s a branch for creating a branch that makes the first commit while ignoring past commits.
git checkout --orphan tmp02
When you checkout with the orphan option, the branch is not displayed in “branch” immediately after executing the command. This is by design.
$ git branch
main
tmp
However, the current actual branch is “tmp02”. Run “git log” to confirm that there are no past commits, resulting in a no-commits error.
$ git log
fatal: your current branch 'tmp02' does not have any commits yet
If you check status with “git status”, it’s the same. If there were already past commits, the displayed files would be “change”, but here they’re “new file”.
$ git status
On branch tmp02
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: main.user.js
new file: readme.md
Let’s commit.
git add .
git commit -m .
After committing, check the branch again with “git branch”. Only now does “tmp02” appear in the branch.
$ git branch
main
tmp
* tmp02
Now, the following is the process of initializing the local git repository. The following command “-D” deletes the “main” branch. Be careful because past commits will be lost.
git branch -D main
After the commits are deleted, copy and move the tmp02 branch to the main branch.
git checkout -b main
Push to the GitHub remote repository with “git push”. Be careful because this will overwrite and delete commits in the remote destination.
git push -f origin main:main
If you push without the “-f” —force option, you’ll get an error. This is because the progress of the remote repository and local repository differ (the remote has past commits but the local has only 1 commit). The —force option overwrites and pushes this.
$ git push -u origin main
Username for 'https://github.com': yuis-ice
Password for 'https://[email protected]':
To https://github.com/yuis-ice/alc-plus.js.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/yuis-ice/alc-plus.js.git'
hint: Updates were rejected because the tip of your current branch is behind
Alternatively, you can do it well without changing the branch to main by changing the local branch specification in “git push”.
git push -f origin tmp02:main