iEFdev

Code, Computers & Random Junk

A Function for Git Archive

Here’s a function to export your repos into a compressed archive. It’s not a script… just a function, so it can go inside the .bash_git file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Function to create archives
# Usage: gitArchive [zip|bz|xz|gz] (xz = default)
function gitArchive ()
{
  # Only use inside a repo.
  [ ! -d '.git' ] && echo -e "\e[1;31m :: \e[m\"`pwd`\" is not a git repository." && return 1;

  local _ext=$1;
  _branch=$(git symbolic-ref --short HEAD 2> /dev/null);
  _repo=$(basename `git rev-parse --show-toplevel`);
  [[ $_branch == 'master' ]] && _append='' || _append="-$_branch";
  [[ -z $_ext ]] && _ext='xz';
  [[ $_ext == 'zip' ]] && _ext='zip' || _ext="$_ext";

  # File name, examples:
  # master:       fooProject_2015-01-01
  # branchname:   fooProject_2015-01-01-branchname
  _output="${_repo}_$(date '+%F')$_append";

  case $_ext in
      # zip
      zip)
          git archive --format=zip -9 -o ../${_output}.$_ext --prefix=${_output}/ $_branch;
          ;;

      # tar.bz
      bz)
          git archive --prefix=${_output}/ $_branch | bzip2 > ../${_output}.tar.$_ext;
          ;;

      # tar.gz & tar.xz (default = xz)
      # To use xz, add to config: git config --global tar.tar.xz.command "xz -c"
      xz|gz|*)
          git archive --format=tar.$_ext -o ../${_output}.tar.$_ext --prefix=${_output}/ $_branch;
          ;;
  esac
}

Usage

Inside the repository /path/to/repos/fooProject:

$ gitArchive

Will create /path/to/repos/fooProject_2015-01-01.tar.xz (same as gitArchive xz).

Switching to another branch, like devel, the output will be: /path/to/repos/fooProject_2015-01-01-devel.tar.xz

Same thing goes with:

$ gitArchive zip
$ gitArchive bz
$ gitArchive gz
$ gitArchive xz     # default

[note] With xzgit archive --help says:

git config tar.tar.xz.command "xz -c"
    Configure a "tar.xz" format for making LZMA-compressed tarfiles.
    You can use it specifying --format=tar.xz, or by creating an output file like -o foo.tar.xz.

I’ve added that, but to my global config file.

git config --global tar.tar.xz.command "xz -c"

.bash_git

Here are my 2 .bash_git files. They are slighlty different due to xclip vs pbcopy.


Happy hacking… octocat

Comments