# Moving Files from one Git Repository to Another, Preserving History

*2021-10-21*

> Move a directory to another Git repository while preserving its commit history using git filter-branch and merging unrelated histories.

Once upon a time all my [Android apps](https://play.google.com/store/apps/developer?id=VMSoft) and [VMSoft](https://vmsoft-bg.com/) related stuff were part of one big BitBucket git repository along with an issue tracker. This was a good idea when being an Android dev was just a hobby for the weekends and not my primary job.

Enough rambling :) , this blog post is about moving files from one git repository to another and preserving your history.

Our goal is to move a single directory from one big Git repository to it's own repository, we would like to preserve the commits history for that specific directory also.

In this example our big repo will  be called **A** and our new repo that will host it's own subset of files will be called **B**

**First** filter the files from the big repo ( **A**) by leaving only the ones you need:

```sh
git clone < repo A url >
cd < repo A directory >

```

Remove the "origin"

```sh
git remote rm origin
```

and filter **A** by _< directory\_to\_move >_. This action will go trough all the history and files and remove anything that's not in _< directory\_to\_move >_.
More info on the inner workings of git filter-branch [here](https://git-scm.com/docs/git-filter-branch).

```sh
git filter-branch --subdirectory-filter  -- --all
```

filter-branch will leave you with the contents of _< directory\_to\_move >_ in the root of repository **A**. Commit the changes and we can continue with the next step.

```sh
git add .
git commit

```

**Moving to the new repository**

Link **repo A** with **repo B**. The command below will make repository A branch of repository B.

```sh
git remote add repo-A-branch
```

Pull from the branch allowing unrelated histories

```sh
git pull repo-A-branch master --allow-unrelated-histories
```

and finally remove repo-A-branch

```sh
git remote rm repo-A-branch
```

That's it, you now have your files in a new repository while preserving commits history.

