1

I have a repo that has over 300 branches, and I am wanting to store various files on in a Git LFS. To do this I need to add the .gitattributes file to the branches first. However, as I have over 300 branches, manually doing this will be very time consuming.

Is there a way that I can add a prepopulated .gitattributes file to the root of every branch automatically and push them?

L Holden
  • 31
  • 5
  • Is your intention to keep your current history and store some files in LFS *from now on* ? or to also *go over the history of your repo* to move part of the files stored in existing commits to LFS ? – LeGEC Dec 29 '22 at 18:54
  • A script using [git-for-each-ref](https://git-scm.com/docs/git-for-each-ref) and possibly using [git-forward-merge](https://github.com/schuyler1d/git-forward-merge) would probably work. – Adam Dec 29 '22 at 19:00
  • @LeGEC the idea is to eventually migrate the entire repo to an LFS, so I would need to rewrite history. – L Holden Jan 02 '23 at 14:01
  • [this answer to another question](https://stackoverflow.com/a/62580603/86072) is a start, you can also do a `git replace; git filter-branch` trick to insert a commit with the correct `.gitattributes` file at the beginning of your history (for all branches). I will write a more complete answer if I find the time for it. – LeGEC Jan 02 '23 at 14:49

1 Answers1

1

A one-liner which assumes you have a branch named feature/add-gitattributes which makes the necessary changes;

git for-each-ref refs/remotes/origin --format="%(refname:lstrip=3)" | xargs -n 1 sh -c 'git checkout "$1"; git merge feature/add-gitattributes;' --

To break it down...

This part just gets a list of those 300 branch names;

git for-each-ref refs/remotes/origin --format="%(refname:lstrip=3)"

This part takes those names and passes them to a sub-shell;

| xargs -n 1 sh -c

This part is the command to the sub-shell which checks out the target branch and merges your feature branch to add the .gitattributes file.

'git checkout "$1"; git merge feature/add-gitattributes;' --

The trailing -- ensures the branch name is passed as an argument to the sub-shell.

Adam
  • 4,180
  • 2
  • 27
  • 31