LoginSignup
18
18

More than 5 years have passed since last update.

Github から Gitlab へリポジトリをミラーする

Posted at

概要

Github から Gitlab へのミラーリングをする方法です。

Gitlab などから Github などへのミラーリングはよく行われていると思いますが、Github のバックアップを取るというのはあまり行われていないようです。

確かに、リポジトリのミラーを取るなら正リポジトリを自前サーバにするのが普通のような気もします。
その方法だとミラーリングについては、./git/hooks/正リポジトリ配下にスクリプトを書けば良いので楽勝ですね!たぶん!

手順

  1. Gitlab にリポジトリ(プロジェクト)を作成する
  2. Gitlab のリポジトリを Github のミラーにする
  3. リポジトリをミラーするシェルスクリプトを準備する
  4. Github の Webhook を Hubot で受けシェルスクリプトを叩く

Gitlab にリポジトリを建てる

まずは Gitlab にリポジトリを作ります。
こちらは Gitlab の画面からプロジェクトの作成を行えばよいです。

Gitlab のリポジトリを Github のミラーにする

次に、作成したリポジトリを Github のミラーリポジトリにします。
まずは、リポジトリができた場所に移動してみます。

$ ssh gitlab.necojackarc.com
$ sudo su - root
$ cd /var/opt/gitlab/git-data/repositories/necojackarc/
$ ls
repo1.git/  repo1.wiki.git/

リポジトリはここ bare リポジトリとして配置されています。
この中にある config に origin の設定を書いてあげても良いのですが、面倒くさいのでまずは元のリポジトリを消し去ります。

$ rm -rf repo1.git/

次に、一般ユーザ(後ほどシェルスクリプトから SSH するユーザ)に戻り、好きな場所で以下のコマンドを叩きます。
これは後ほどシェルスクリプトから SSH した際、sudoなしで実行できるリポジトリを作成するための作業です。

私はホームディレクトリ以下にrepositories/:groupディレクトリを作り、その下で行いました。

$ git clone --mirror https://necojackarc:password@github.com/necojackarc/repo1.git

次に、リポジトリが本来あるべき場所に対して、シンボリックリンクを貼ります。

$ sudo ln -s ~/necojackarc/repo1.git /var/opt/gitlab/git-data/repositories/necojackarc/repo1.git

これでミラーのリポジトリができました。
Gitlab から確認すれば、無事ミラーできていることがわかります。

補足

Gitlab と Hubot が別サーバで動作しており、SSH ログインを前提としています。

リポジトリをミラーするシェルスクリプトを準備する

サクッと書きます。

#!/bin/sh
ssh necojackarc@gitlab.necojackarc.com "cd ~/repositories/necojackarc/repo1.git/; git fetch origin"

ログインして移動して fetch するだけです!余裕!
こいつを Hubot のリポジトリのscripts/shellscriptsにでも叩き込んでおきましょう。

Github の Webhook を Hubot で受けシェルスクリプトを叩く

サクッと Hubot のスクリプトを CoffeeScirpt で書きます。

module.exports = (robot) ->
  # Mirror Github
  mirror_github = ->
    @exec = require('child_process').exec
    command = "sh ./shellscripts/mirror_github.sh"
    @exec command, (error, stdout, stderr) ->
      console.log error if error?
      console.log stdout if stdout?
      console.log stderr if stderr?

  # Listen to "POST /github"
  robot.router.post "/github", (req, res) ->
    event_name = req.headers["x-github-event"]
    payload = req.body

    console.log event_name
    switch event_name
      when "push" then mirror_github
      when "create" then mirror_github
      when "delete" t

Hubot からのシェルスクリプト起動は以下の記事を参考にしました。

SlackからHubot経由で 、サーバのシェルを実行してみよう!

ありがとうございます。

まとめ

Hubot で Webhook を受けて、スクリプトを叩くだけです!

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18