torsdag den 8. september 2016

Using multiple emails with GIT

Travis CI, for example, uses the email in the git commit for notification.

~/.gitconfig
[organization "git@github.com:myproject1"]
  email = myname@project1.com

[organization "git@github.com:myproject2"]
  email = myname@project2.com

[organization "git@github.com:personal"]
  email = myname@personal.com
.bashrc
alias git=git-org.sh
~/bin/git-org.sh
#!/bin/sh

ORG=$(git-org.php)

if [[ ! -z "$ORG" ]]; then
  ORG_EMAIL=$(/usr/local/bin/git config organization.$ORG.email)
  if [[ ! -z "$ORG_EMAIL" ]]; then
    EMAIL=$(/usr/local/bin/git config user.email)
    if [[ "$EMAIL" != "$ORG_EMAIL" ]]; then
      echo "User mail is: $EMAIL"
      echo "Organization mail should be: $ORG_EMAIL"
      echo "Switching to email: $ORG_EMAIL"
      $(/usr/local/bin/git config user.email $ORG_EMAIL)
    fi
  fi
fi

/usr/local/bin/git "$@"
~/bin/git-org.php
#!/usr/local/bin/php
 /dev/null`;

if (!$remote) {
    exit;
}

$url = null;
$lines = explode("\n", $remote);
foreach ($lines as $line) {
    if (preg_match('/origin\s+(.*?)\s+\(fetch\)$/', $line, $matches)) {
        $url = $matches[1];
      break;
    }
}

if (!$url) {
    exit;
}

$parsed = parse_url($url);

if (!isset($parsed['scheme'])) {
    $pos = strpos($url, ':');
    if ($pos !== false) {
        $url = substr_replace($url, '/', $pos, 1);
        $url = 'git://' . $url;
        $parsed = parse_url($url);
    }
    else {
        exit;
    }
}

$user = $parsed['user'] ?? '';
$host = $parsed['host'] ?? '';
list($org) = explode('/', ltrim($parsed['path'] ?? '', '/'), 2);
print "$user@$host:$org\n";