LoginSignup
3
0

More than 1 year has passed since last update.

githubへのリポジトリ作成をコマンドでやって、いい感じに管理したい

Last updated at Posted at 2022-12-01

本記事は ディップ with 全部俺 Advent Calendar 2022 2日目の記事になります。

昨日に引き続きまたzshrc系の記事になります。

何をしたいか

検証などで新しいgitリポジトリを作りつつgithubにもあげてーというのが面倒だったので一回でリポジトリ作成と管理まで出来るコマンドを作ってみたというものです。

私は基本的にローカルのソース管理?をghqに任せてしまっているので、git リポジトリの作成などもこれに習った感じにしたい。
だけどいちいちghqの管理用のディレクトリでmkdirしたりしてというは面倒。
どこでコマンドを打ってもちゃんと管理された状態になって欲しい。
という気持ちで作成しました。

前提条件

  • gitコマンドがインストールされている
  • ghqコマンドがインストールされている
  • hubコマンドがインストールされている

 

ソースコード

npj() {
  local help_msg=$(cat <<-EOL
NAME:
  npj - Create Git repository and Manage remote repository with ghq

USAGE:
  npj RepositoryName [options]

RepositoryName:
  Specify the repository name to be created.
  This args is required.

OPTIONS:
  -u    Change the owner of the repository to be created. (default: git global user name )
EOL
)

  local -A opthash
  local user=`git config --global --get user.name`
  zparseopts -D -A opthash -- -help -h u:


  if [[ -n "${opthash[(i)--help]}" ]]; then
    # --helpが指定された場合
    echo $help_msg
    return
  fi

  if [[ -n "${opthash[(i)-h]}" ]]; then
    # -hが指定された場合
    echo $help_msg
    return
  fi

  if [[ -n "${opthash[(i)-u]}" ]]; then
    # -uが指定された場合
    user=${opthash[-u]}
  fi

  if [ -z "$user" ]; then
    echo "you need to set user.name or options -u."
    echo "git config --global user.name YOUR_GITHUB_USER_NAME"
    return 1
  fi

  local root=`ghq root`
  local name=$1

  if [ -z "$name" ]; then
    echo "The project name is required."
    return 1
  fi

  local user_name="$user/$name"
  local repo="$root/github.com/$user_name"
  if [ -e "$repo" ]; then
    echo "This project existed, so I moved it to a directory."
    cd $repo
    return 1
  fi

  local TMPDIR=/tmp/ghq_new
  local TMPREPODIR="$TMPDIR/$name"

  mkdir -p $TMPREPODIR
  cd $TMPREPODIR

  hub init
  hub create
  echo "# $name" >> readme.md
  git add readme.md
  git commit -m "First Commit"
  git push origin main

  local ghqrepo="git@github.com:$user_name.git"

  ghq get $ghqrepo

  cd $repo
  rm -rf $TMPREPODIR
}

何をやっているか?

npj という名前でzshrcに関数登録を行います。
引数としてProject Nameを取ります(これがRepository名になります)

オプションとして -u オプションを付けており、これはorganizationに自分のアカウント以外にRepositoryを作りたい場合(organizationなどを想定)に利用する感じにしています。

やっていることはそれほど難しくなく、/tmp/ghq_new/[Project Name] というディレクトリを作成し、そこで hub init 及び hub create を行いgithubにRepositoryを作成します。
次にreadmeを作成し、first commitとします。

このあと、ghq getで作成したRepositoryをghq管理のディレクトリにcloneし、そのディレクトリに移動します。
最後に初期作成したディレクトリを削除する。
という流れです。

最後に

どこでnpjを行ってもいい感じに管理ディレクトリにRepositoryが作られる&すでにgithubにRepositoryがあり、git管理されている状態となるので、サクッと検証したいなぁ。。。みたいなときに重宝しています。

3
0
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
3
0