aboutsummaryrefslogtreecommitdiff
path: root/foreach-git
blob: 9ad529f77aeacca2db407720b1eede1d3cd93a39 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#! /usr/bin/env bash

# Run git command in each directory that looks like a git repository. By
# default only top-level directoris are considered but the depth can be
# adjusted with -d.
#
# -x <dir>
#    Exclude <dir>.
#
# -n <num>
#    Directory depth to consider.
#
#

trap "{ exit 1; }" ERR
set -o errtrace # Trap in functions.

function info () { echo "$*" 1>&2; }

exclude=() # Array of excluded directories.
depth=1

while [ $# -gt 0 ]; do
  case $1 in
    -x)
      shift
      exclude+=("${1%/}")
      shift
      ;;
    -n)
      shift
      depth="$1"
      shift
      ;;
    *)
      break
      ;;
  esac
done

# Find all the top-level directories that looks like git repositories.
#
dirs=()
for d in $(find . -mindepth 1 -maxdepth "$depth" -type d -printf '%P\n' | sort); do
  if [ -d "$d/.git" ]; then
    dirs+=("$d")
  fi
done

# Run the command for each of them.
#
for d in "${dirs[@]}"; do
  for e in "${exclude[@]}"; do
    if [[ "$d/" =~ ^"$e/" ]]; then
      d=
      break
    fi
  done

  if [ -n "$d" ]; then
    info "$d/"
    git -C "$d" "${@}"
  fi
done