tweeeetyのぶろぐ的めも

アウトプットが少なかったダメな自分をアウトプット<br>\(^o^)/

【gulp】サクっと3stepで覚えるgulpとは〜簡単な使い方

はじめに

gulpは長い事つかってますが、
フロントの方が入れてくれた環境を基に使っているのでゼロから学んだ経験は乏しいです。
(自分はサーバサイド)

そこでgulpの基礎をゼロからなるはやで覚えるための自分用メモです

f:id:tweeeety:20180524215025p:plain

アジェンダ

  1. gulpとは
  2. gulp環境つくる
  3. gulp使ってみる

1. gulpとは

公式リポジトリは以下です。
https://github.com/gulpjs/gulp

参考サイトからの抜粋です。

gulpはNode.jsをベースとしたビルドシステムヘルパーです。
gulpの一番の特徴はサイトのトップページで「ストリーミングビルドシステム」と自ら名乗っているように、
ファイルの処理をストリームで行うというところです。
この特徴によって複雑なタスクも細かくカスタマイズして書くことができます。
  現場で使えるgulp入門 第1回 gulpとは何か

2. gulp環境つくる

gulp環境を作るにはシンプルに以下の3つが必要です

  • Node.jsのインストールする
    • nodeコマンドとnpmコマンドを使えるようにする
  • npmでgulpをインストールする
    • gulpコマンド使えるようにする
    • package.json作る
  • タスクを書く
    • gulpfile.js作る

Node.jsのインストールする

公式サイトからダウンロードしてinstallします。
https://nodejs.org/

f:id:tweeeety:20180524215044p:plain

とりあえず動かしてみるにしてもLTSの方を落としてみると良いでしょう。

npmでgulpをインストールする

gulpはglobalとlocalとにインストールします。
また、パッケージ管理のためにpackage.jsonを作成します。

# パッケージディレクトリに移動
$ pwd
/path/to/package dir

# package.jsonを作成
# {} だけ記載
$ vim package.json
---- vi ----
{}
------------

# gulpをグローバルにインストール
$ npm install -g gulp

# gulpをパッケージローカルにインストール
#   このタイミングでpackage.jsonに
#   インストールしたものとversionが書かれる
$ npm install --save-dev gulp

# versionが出れば成功
$ gulp -v
[19:53:54] CLI version 3.9.1
[19:53:54] Local version 3.9.1

$ cat package.json
{
  "devDependencies": {
    "gulp": "^3.9.1"
  }
}

3. gulp使ってみる

gulpタスクの作成

使ってみるといってもまずはgulpタスクを作成する必要があります。
タスクはgulpfile.jsに記載します。

  • gulpfile.js
var gulp = require('gulp');

gulp.task('hello', function() {
  console.log('say Hello!');
});

gulp.task('world', function() {
  console.log('say World!');
});

gulp.task('default', ['hello', 'world']);    

gulpタスクの実行

あとは実行するだけです

# helloタスクを実行してみる
$ gulp hello
[19:58:33] Using gulpfile ~/github/my/for_hatena/gulp-basic-sample/gulpfile.js
[19:58:33] Starting 'hello'...
say Hello!
[19:58:33] Finished 'hello' after 144 μs


# gulpとだけうってdefaultタスクを実行
# default task = hello + worldが呼ばれる
$ gulp
[19:58:48] Using gulpfile ~/github/my/for_hatena/gulp-basic-sample/gulpfile.js
[19:58:48] Starting 'hello'...
say Hello!
[19:58:48] Finished 'hello' after 145 μs
[19:58:48] Starting 'world'...
say World!
[19:58:48] Finished 'world' after 54 μs
[19:58:48] Starting 'default'...
[19:58:48] Finished 'default' after 9.73 μs

いちおうサンプル

作ったサンプルをそのままpushしたので貼っておきます。

おわり

これだけだとまだ何もできないですが、
導入して動かしてみるだけで雰囲気はわかるかと思います\(^o^)/

【git】git mergeでCONFLICTした場合のmerge取り消し - "git merge --abort"

はじめに

gitを使っていればCONFLICTはちょくちょくありますよね。

# 最初は差分がないことを確認
$ git status
On branch [ブランチ1]
nothing to commit, working directory clean

# とあるブランチをmerge
# するとCONFLICT...
$ git merge [ブランチ2]
Auto-merging package.json
CONFLICT (content): Merge conflict in package.json
Automatic merge failed; fix conflicts and then commit the result.

そんな時に通常はCONFLICTを解消しますが、
そうではなく一回なかったことにしたいこともあるわけです。
あるんですよ...

そんな場合の対処法

そこで"git merge --abort"

git merge --abortを使うとマージする前の状態に戻ります。

いちおうCONFLICTしてから取り消す一連を参考程度に。

# 最初は差分がないことを確認
$ git status
On branch [ブランチ1]
nothing to commit, working directory clean

# とあるブランチをmerge
$ git merge [ブランチ2]
Auto-merging package.json
CONFLICT (content): Merge conflict in package.json
Automatic merge failed; fix conflicts and then commit the result.

# statusを見るとCONFLICTしている
$ git status
On branch [ブランチ1]
You have unmerged paths.
  (fix conflicts and run "git commit")

Changes to be committed:

  modified:   README.md

Unmerged paths:
  (use "git add <file>..." to mark resolution)

  both modified:   package.json

# CONFLICTじゃなければ戻せるcheckoutを試しに
# 当然断られる
$ git checkout .
error: path 'package.json' is unmerged

# ここで登場
$ git merge --abort

# 無事になかったことに
$ git status
On branch [ブランチ1]
nothing to commit, working directory clean

おわり

mergeやめたい!って場合がたまーにあるたびに調べてたので自分用備忘録でした\(^o^)/

【Node.js】Node.jsのLTSやCURRENTってなんだ?

はじめに

Node.jsを改めてインストールするときに
LTSとCURRENTがありますが、それぞれなんだっけ?を忘れるので自分用メモです。

公式サイトより

https://github.com/nodejs/Release からの抜粋です

Mandate
 
The Release working group's purpose is:
 
* Management/execution of the release and support process for all releases.
 
Its responsibilities are:
 
* Define the release process.
* Define the content of releases.
* Generate and create releases.
* Test Releases
* Manage the LTS and Current branches including backporting changes to these branches.
* Define the policy for what gets backported to release streams.
 
The Release working group is structured into teams and membership in the working group does not automatically result in membership in these teams. These teams are:
 
* Releasers team
* LTS team
* CITGM team
 
The releasers team is entrusted with the secrets and CI access to be able build and sign releases. Additions to the releasers team must be approved by the TSC following the process outlined in GOVERNANCE.md.
 
The Long Term Support (LTS) team manages the process/content of LTS releases and the required backporting for these releases. Additions to the LTS team needs sign off from the rest of the LTS team.
 
The Canary in the Gold Mine (CITGM) team maintains CITGM as one of the key sanity checks for releases. This team maintains the CITGM repository and works to keep CITGM builds running and passing regularly. This also includes maintaining the CI jobs in collaboration with the Build Working Group.

関係ありそうなところだけ抜粋すると

  • リリースワーキンググループがある
  • リリースにおける管理と実行を行う
  • グループは3つのチーム構成で構成されている
    • Releasers team
    • LTS team
    • CITGM team

これを踏まえて

LTSとCURRENTってなに?

LTSとは

LTSは、Long-term Supportの略で、長期の保守運用が約束されたバージョンです

CURRENTとは

CURRENTは、最新版だけど安定性を約束しないことで機能追加を盛り込んだバージョンです

参考

おわり

ある程度安定したサービスを作る目的ならLTS、
いろいろ試してみたいときはCURRENTですかね\(^o^)/

【GAE】appengine(app-engine-go)をhomebrew経由でinstallするgo1.6.3 (appengine-1.9.48)から、cloud sdk経由でinstallするgo version 1.8.5 (appengine-1.9.68) にupdateするメモ

はじめに

GAE goな環境を使っています。

結構長いことgo1.6.3 (appengine-1.9.48)で困った事はなかったのですが、
goのversionの関係でtestingパッケージのt.Run()が使えなかったりとあったのでupdateしました。

以前は、homebrew経由でinstallおよびアップデートができたのですが、
いまはサポートされておらずcloud sdk経由に変わったとの事です。

その時の自分メモ

f:id:tweeeety:20180503231719p:plain

アジェンダ

  1. 環境確認
  2. google-cloud-sdkをUPDATE
  3. Components(app-engine-go)のインストール

1. 環境確認

あげる前に自分の環境をもろもろ確認しておきます。

gcloud周りの確認
gcloud コマンドまわりを確認
# 場所を確認
# gcloudはhomeに落としたままpathを通していた
# 
# 新しく入れる方は/usr/local/Caskroom配下において/usr/local/bin/gcloudにsymlink予定
/Users/tweeeety/google-cloud-sdk/bin/gcloud

$ ls -la /Users/tweeeety/google-cloud-sdk/bin/gcloud
-rwxr-xr-x  1 tweeeety  tweeeety Users  3089 10 10  2017 /Users/tweeeety/google-cloud-sdk/bin/gcloud

# pathを確認
$ vim ~/.bash_profile
-- vim確認 --
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/tweeeety/google-cloud-sdk/path.bash.inc' ]; then source '/Users/tweeeety/google-cloud-sdk/path.bash.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/tweeeety/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/tweeeety/google-cloud-sdk/completion.bash.inc'; fi
------------

# gcloudのversionを確認
$ gcloud version
Google Cloud SDK 175.0.0
app-engine-python 1.9.61
beta 2017.09.15
bq 2.0.27
core 2017.10.09
gcloud 
gsutil 4.27
Updates are available for some Cloud SDK components.  To install them,
please run:
  $ gcloud components update

Updates are available for some Cloud SDK components.  To install them,
please run:
  $ gcloud components update

# gcoud 情報を確認
$ gcloud info
Google Cloud SDK [175.0.0]

Platform: [Mac OS X, x86_64] ('Darwin', 'tweeeety-MAC', '13.4.0', 'Darwin Kernel Version 13.4.0: Mon Jan 11 18:17:34 PST 2016; root:xnu-2422.115.15~1/RELEASE_X86_64', 'x86_64', 'i386')
Python Version: [2.7.14 (default, Feb  4 2018, 00:19:50)  [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)]]
Python Location: [/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python]
Site Packages: [Disabled]

Installation Root: [/Users/tweeeety/google-cloud-sdk]
Installed Components:
  core: [2017.10.09]
  app-engine-python: [1.9.61]
  gcloud: []
  beta: [2017.09.15]
  gsutil: [4.27]
  bq: [2.0.27]
System PATH: [/usr/local/opt/imagemagick@6/bin:/Users/tweeeety/google-cloud-sdk/bin:/Users/tweeeety/.plenv/shims:/Users/tweeeety/.plenv/bin:/Users/tweeeety/.nodebrew/current/bin:/Users/tweeeety/.mysqlenv/mysqls/5.1.69/bin:/Users/tweeeety/.mysqlenv/bin:/Users/tweeeety/.mysqlenv/shims:/Users/tweeeety/.mysqlenv/mysql-build/bin:/usr/local/sbin:/Users/tweeeety/.mysqlenv/bin:/Users/tweeeety/.mysqlenv/shims:/Users/tweeeety/.mysqlenv/mysql-build/bin:/usr/local/heroku/bin:/Users/tweeeety/.chefdk/gem/ruby/2.1.0/bin:/opt/chefdk/bin:/Users/tweeeety/.rbenv/shims:/Users/tweeeety/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/go/bin:/sbin:/usr/sbin:/Users/tweeeety/local/bin:/usr/local/opt/go/libexec/bin:/Users/tweeeety/.go/bin]
Python PATH: [/Users/tweeeety/google-cloud-sdk/lib/third_party:/Users/tweeeety/google-cloud-sdk/lib:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python27.zip:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old:/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload]
Cloud SDK on PATH: [True]
Kubectl on PATH: [False]

WARNING: There are old versions of the Google Cloud Platform tools on your system PATH.
  /usr/local/Cellar/app-engine-go-64/1.9.48/share/app-engine-go-64/dev_appserver.py
  /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/bq
  /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud
  /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gsutil

Installation Properties: [/Users/tweeeety/google-cloud-sdk/properties]
User Config Directory: [/Users/tweeeety/.config/gcloud]
Active Configuration Name: [sample]
Active Configuration Path: [/Users/tweeeety/.config/gcloud/configurations/config_sample]

Account: [tweeeety@hoge.jp]
Project: [hoge-fuga-gcp]

Current Properties:
  [core]
    project: [hoge-fuga-gcp]
    account: [tweeeety@hoge.jp]
    disable_usage_reporting: [False]
  [compute]
    region: [asia-east1]
    zone: [asia-east1-b]

Logs Directory: [/Users/tweeeety/.config/gcloud/logs]
Last Log File: [/Users/tweeeety/.config/gcloud/logs/2018.04.24/19.25.04.354908.log]

git: [git version 1.9.3 (Apple Git-50)]
ssh: [OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011]
gcloud以外のcommponentsを確認

ついで程度ですが、componensまわりを確認してみます

$ which gsutil
/Users/tweeeety/google-cloud-sdk/bin/gsutil

$ goapp version
go version go1.6.3 (appengine-1.9.48) darwin/amd64

# goappはhomebrewで入れた?か忘れたがCellarに入っていた
# 新しく入れる方は/usr/local/Caskroom配下になる予定
$ which goapp
/usr/local/bin/goapp

$ ls -al /usr/local/bin/goapp
lrwxr-xr-x  1 tweeeety  admin  43  1 11  2017 /usr/local/bin/goapp -> ../Cellar/app-engine-go-64/1.9.48/bin/goapp

2. google-cloud-sdkをUPDATE

まず、以前にgoogle-cloud-sdkbrew caskにて入れていたようなのでその辺の確認から行います。

gcloudの再インストール

# versionを確認
$ brew cask --version
Homebrew-Cask 1.6.1
caskroom/homebrew-cask (git revision 385494; last commit 2018-04-23)

# caskで入れたlistを確認
$ brew cask list
google-cloud-sdk
vagrant

# そのままinstallしてみるが
# re-installしてねと言われる...まぁそうだね
$ brew cask install google-cloud-sdk
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 3 taps (caskroom/cask, homebrew/core, phinze/cask).
==> Updated Formulae
ruby-build ✔     bettercap        cayley           dcd              emscripten       folly            heroku           ice              juju             knot-resolver    meson            r                silk             telegraf         watson
vim ✔            bluepill         cockroach        dscanner         fobis            gollum           hugo             jruby            jvgrep           libsass          pqiv             rocksdb          skaffold         tokei            xonsh

Warning: Cask 'google-cloud-sdk' is already installed.

To re-install google-cloud-sdk, run:

# すなおにreinstall
$ brew cask reinstall google-cloud-sdk
==> Caveats
google-cloud-sdk is installed at /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk. Add your profile:

  for bash users
    source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.bash.inc'
    source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.bash.inc'

  for zsh users
    source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/path.zsh.inc'
    source '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/completion.zsh.inc'

~ 省略 ~ 

==> Your current Cloud SDK version is: 198.0.0
==> Installing components from version: 198.0.0
==> 
==> +----------------------------------------------------------------------------+
==> |                    These components will be installed.                     |
==> +-----------------------------------------------------+------------+---------+
==> |                         Name                        |  Version   |   Size  |
==> +-----------------------------------------------------+------------+---------+
==> | BigQuery Command Line Tool                          |     2.0.32 | < 1 MiB |
==> | BigQuery Command Line Tool (Platform Specific)      |     2.0.26 | < 1 MiB |
==> | Cloud SDK Core Libraries (Platform Specific)        | 2018.03.16 | < 1 MiB |
==> | Cloud Storage Command Line Tool                     |       4.30 | 3.4 MiB |
==> | Cloud Storage Command Line Tool (Platform Specific) |       4.27 | < 1 MiB |
==> | Default set of gcloud commands                      |            |         |
==> | gcloud cli dependencies                             | 2017.10.20 | 1.4 MiB |
==> +-----------------------------------------------------+------------+---------+

~ 省略 ~ 

==> For the latest full release notes, please visit:
==>   https://cloud.google.com/sdk/release_notes
🍺  google-cloud-sdk was successfully installed!

最後にビールの絵とともにgoogle-cloud-sdk was successfully installed!と言われます

gcloudコマンドの初期化(ログイン)

公式を参考に行いました
* Cloud SDK の初期化

公式には以下のように記載されています

通常、Cloud SDK をインストールした後、gcloud init コマンドを実行して初期設定を行います。
後で gcloud init を実行して設定を変更したり、新しい設定を作成したりすることもできます。
 

  • Cloud SDK ツールを承認して、現在のユーザー アカウントの認証情報を使用して Google Cloud Platform にアクセスできるようにします。すでにアクセスが承認されている場合はアカウントを選択できます。
  • Cloud SDK 構成をセットアップし、一連の基本プロパティを設定します。たとえば、上記のステップで設定した有効なアカウント、現在のプロジェクト、Google Compute Engine のデフォルトのリージョンとゾーン(該当する場合)などです。
gcloud init

初回の場合は、gcloud initを打ってセットアップします。
自分は既にセットアップ済みの内容を変えたくなかったのでloginのみにしました。

# そのまま打つだけ
$ gcloud init

# この後いろいろ聞かれるので設定に合わせて答える
gcloud auth login

セットアプップ構成を変えたくなかったので、
ユーザー アカウントを使用して承認だけをおこないました

# ブラウザが起動して認証を行う
$ gcloud auth login

3. Components(app-engine-go)のインストール

goappコマンドが使いたいので
app-engine-goというComponentsをインストールします。

以前にbrewで入れたものとバッティングしてうまくいかなかった編

Componentsのインストール状況を確認

念のためインストール状況を確認します

$ gcloud components list

Your current Cloud SDK version is: 175.0.0
The latest available version is: 198.0.0

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                   Components                                                   │
├──────────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│      Status      │                         Name                         │            ID            │    Size   │
├──────────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Update Available │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Update Available │ Cloud SDK Core Libraries                             │ core                     │   7.6 MiB │
│ Update Available │ Cloud Storage Command Line Tool                      │ gsutil                   │   3.4 MiB │
│ Update Available │ gcloud app Python Extensions                         │ app-engine-python        │   6.1 MiB │
│ Not Installed    │ App Engine Go Extensions                             │ app-engine-go            │ 151.3 MiB │
│ Not Installed    │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.7 MiB │
│ Not Installed    │ Cloud Bigtable Emulator                              │ bigtable                 │   3.8 MiB │
│ Not Installed    │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed    │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  17.9 MiB │
│ Not Installed    │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed    │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  33.4 MiB │
│ Not Installed    │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed    │ Google Container Local Builder                       │ container-builder-local  │   4.3 MiB │
│ Not Installed    │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.5 MiB │
│ Not Installed    │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Not Installed    │ gcloud app Java Extensions                           │ app-engine-java          │ 118.9 MiB │
│ Not Installed    │ gcloud app PHP Extensions                            │ app-engine-php           │  21.9 MiB │
│ Not Installed    │ gcloud app Python Extensions (Extra Libraries)       │ app-engine-python-extras │  28.5 MiB │
│ Not Installed    │ kubectl                                              │ kubectl                  │  12.2 MiB │
│ Installed        │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
└──────────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
To install or remove components at your current SDK version [175.0.0], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [198.0.0], run:
  $ gcloud components update

Update Available のものをUpdateしろよなと言われています。

Componentsのupdates

素直にupdateも行います

$ gcloud components update

Your current Cloud SDK version is: 175.0.0
You will be upgraded to version: 198.0.0

┌─────────────────────────────────────────────────────────────────────┐
│                  These components will be updated.                  │
├──────────────────────────────────────────────┬────────────┬─────────┤
│                     Name                     │  Version   │   Size  │
├──────────────────────────────────────────────┼────────────┼─────────┤
│ BigQuery Command Line Tool                   │     2.0.32 │ < 1 MiB │
│ Cloud SDK Core Libraries                     │ 2018.04.13 │ 7.6 MiB │
│ Cloud SDK Core Libraries (Platform Specific) │ 2018.03.16 │ < 1 MiB │
│ Cloud Storage Command Line Tool              │       4.30 │ 3.4 MiB │
│ gcloud app Python Extensions                 │     1.9.69 │ 6.1 MiB │
│ gcloud cli dependencies                      │ 2018.04.06 │ 1.6 MiB │
│ gcloud cli dependencies                      │ 2017.10.20 │ 1.4 MiB │
└──────────────────────────────────────────────┴────────────┴─────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│                     These components will be installed.                     │
├─────────────────────────────────┬─────────────────────┬─────────────────────┤
│               Name              │       Version       │         Size        │
├─────────────────────────────────┼─────────────────────┼─────────────────────┤
│ gRPC python library             │               1.9.1 │             7.6 MiB │
│ gRPC python library             │                     │                     │
└─────────────────────────────────┴─────────────────────┴─────────────────────┘

A lot has changed since your last upgrade.  For the latest full release notes,
please visit:
  https://cloud.google.com/sdk/release_notes

Do you want to continue (Y/n)?  Y

╔════════════════════════════════════════════════════════════╗
╠═ Creating update staging area                             ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: BigQuery Command Line Tool                 ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: Cloud SDK Core Libraries                   ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: Cloud SDK Core Libraries (Platform Spec... ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: Cloud Storage Command Line Tool            ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: gcloud app Python Extensions               ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: gcloud cli dependencies                    ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Uninstalling: gcloud cli dependencies                    ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: BigQuery Command Line Tool                   ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud SDK Core Libraries                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud SDK Core Libraries (Platform Specific) ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: Cloud Storage Command Line Tool              ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gRPC python library                          ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gRPC python library                          ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gcloud app Python Extensions                 ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gcloud cli dependencies                      ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gcloud cli dependencies                      ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Creating backup and activating new installation          ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.                                                                                                                                                                                                                       

==> Start a new shell for the changes to take effect.


Update done!

To revert your SDK to the previously installed version, you may run:
  $ gcloud components update --version 175.0.0

WARNING:   There are older versions of Google Cloud Platform tools on your system PATH.
  Please remove the following to avoid accidentally invoking these old tools:

/usr/local/Cellar/app-engine-go-64/1.9.48/share/app-engine-go-64/dev_appserver.py
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/bq
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gsutil

と、warningが...
以前、別の方法で入れたヤツがいるぞ と教えてくれてます....

Componentsのupdates後の確認

念のためgcloud components list で確認すると
StatusはInstalledに変わっているのでupdateはされたようです。

$ gcloud components list

Your current Cloud SDK version is: 198.0.0
The latest available version is: 198.0.0

┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                  Components                                                 │
├───────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│     Status    │                         Name                         │            ID            │    Size   │
├───────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Not Installed │ App Engine Go Extensions                             │ app-engine-go            │ 151.3 MiB │
│ Not Installed │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.7 MiB │
│ Not Installed │ Cloud Bigtable Emulator                              │ bigtable                 │   3.8 MiB │
│ Not Installed │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  17.9 MiB │
│ Not Installed │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  33.4 MiB │
│ Not Installed │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed │ Google Container Local Builder                       │ container-builder-local  │   4.3 MiB │
│ Not Installed │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.5 MiB │
│ Not Installed │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Not Installed │ gcloud app Java Extensions                           │ app-engine-java          │ 118.9 MiB │
│ Not Installed │ gcloud app PHP Extensions                            │ app-engine-php           │  21.9 MiB │
│ Not Installed │ gcloud app Python Extensions (Extra Libraries)       │ app-engine-python-extras │  28.5 MiB │
│ Not Installed │ kubectl                                              │ kubectl                  │  12.2 MiB │
│ Installed     │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Installed     │ Cloud SDK Core Libraries                             │ core                     │   7.6 MiB │
│ Installed     │ Cloud Storage Command Line Tool                      │ gsutil                   │   3.4 MiB │
│ Installed     │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
│ Installed     │ gcloud app Python Extensions                         │ app-engine-python        │   6.1 MiB │
└───────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
To install or remove components at your current SDK version [198.0.0], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [198.0.0], run:
  $ gcloud components update
app-engine-goを入れたい
app-engine-goが以前のものとバッティング
# 念のため確認
# brewで入れたやつがいるけど...
$ goapp version
go version go1.6.3 (appengine-1.9.48) darwin/amd64

# gcloudコマンドでインストール
$ gcloud components install app-engine-go


Your current Cloud SDK version is: 198.0.0
Installing components from version: 198.0.0

┌────────────────────────────────────────────────┐
│      These components will be installed.       │
├──────────────────────────┬─────────┬───────────┤
│           Name           │ Version │    Size   │
├──────────────────────────┼─────────┼───────────┤
│ App Engine Go Extensions │         │           │
│ App Engine Go Extensions │  1.9.64 │ 151.3 MiB │
└──────────────────────────┴─────────┴───────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

Do you want to continue (Y/n)?  Y

╔════════════════════════════════════════════════════════════╗
╠═ Creating update staging area                             ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: App Engine Go Extensions                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: App Engine Go Extensions                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Creating backup and activating new installation          ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.                                                                                                                                                                                                                       

Update done!

WARNING:   There are older versions of Google Cloud Platform tools on your system PATH.
  Please remove the following to avoid accidentally invoking these old tools:

/usr/local/Cellar/app-engine-go-64/1.9.48/share/app-engine-go-64/dev_appserver.py
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/bq
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gsutil

# ↑この変にolderなやつがいるぞと教えてくれる
# さらにはremoveしろと...

# 当然goappも以前のまま
$ goapp version
go version go1.6.3 (appengine-1.9.48) darwin/amd64
brewで入れた方を消す

最初から消せば良かったのですが、ここでようやく消します。

# brewで入れか確認
$ brew list | grep app-engine
app-engine-go-64

# appengine系のコマンドも、きっとbrew経由のままだろうな、を確認
$ ls -al /usr/local/bin/appcfg.py
lrwxr-xr-x  1 tweeeety  admin  47  1 11  2017 /usr/local/bin/appcfg.py -> ../Cellar/app-engine-go-64/1.9.48/bin/appcfg.py

# 一応unlinkだけしてみる
$ brew unlink app-engine-go-64
Unlinking /usr/local/Cellar/app-engine-go-64/1.9.48... 7 symlinks removed

# リンクは外れた
$ goapp version
-bash: /usr/local/bin/goapp: No such file or directory

# 思い切ってremove
$ brew remove app-engine-go-64
Uninstalling /usr/local/Cellar/app-engine-go-64/1.9.48... (9,842 files, 247.8MB)
app-engine-go-64 1.9.38 1 is still installed.
Remove all versions with `brew uninstall --force app-engine-go-64`.

# ↑でRemove allしてよね、と言われてるが再度確認
# やっぱりまだいる
$ brew list | grep app-engine-
app-engine-go-64

# 再度消す
$ brew remove app-engine-go-64
Uninstalling /usr/local/Cellar/app-engine-go-64/1.9.38... (6,634 files, 225.0MB)

# gcloudコマンドもhomeに置いたままなので、この辺も消す
$ which gcloud
/Users/tweeeety/google-cloud-sdk/bin/gcloud

# 消す(いったん移動...)
$ mv ~/google-cloud-sdk .google-cloud-sdk

# 再度確認すると、Caskroomの方に切り替わってくれた模様
$ which gcloud 
/usr/local/bin/gcloud

$ ls -al /usr/local/bin/gcloud
lrwxr-xr-x  1 tweeeety  admin  71  4 24 22:10 /usr/local/bin/gcloud -> /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud

# 以前入れた方のpathをコメントアウト
$ vim ~/.bash_profile
-- vi編集 --
# The next line updates PATH for the Google Cloud SDK.
#if [ -f '/Users/tweeeety/google-cloud-sdk/path.bash.inc' ]; then source '/Users/tweeeety/google-cloud-sdk/path.bash.inc'; fi

# The next line enables shell command completion for gcloud.
#if [ -f '/Users/tweeeety/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/tweeeety/google-cloud-sdk/completion.bash.inc'; fi
------------

再度、app-engine-goをインストールでうまくいった編

$ gcloud components install app-engine-go


Your current Cloud SDK version is: 198.0.0
Installing components from version: 198.0.0

┌────────────────────────────────────────────────────┐
│        These components will be installed.         │
├──────────────────────────────┬─────────┬───────────┤
│             Name             │ Version │    Size   │
├──────────────────────────────┼─────────┼───────────┤
│ App Engine Go Extensions     │         │           │
│ App Engine Go Extensions     │  1.9.64 │ 151.3 MiB │
│ gRPC python library          │   1.9.1 │   7.6 MiB │
│ gRPC python library          │         │           │
│ gcloud app Python Extensions │  1.9.69 │   6.1 MiB │
└──────────────────────────────┴─────────┴───────────┘

For the latest full release notes, please visit:
  https://cloud.google.com/sdk/release_notes

Do you want to continue (Y/n)?  Y

╔════════════════════════════════════════════════════════════╗
╠═ Creating update staging area                             ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: App Engine Go Extensions                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: App Engine Go Extensions                     ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gRPC python library                          ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gRPC python library                          ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Installing: gcloud app Python Extensions                 ═╣
╠════════════════════════════════════════════════════════════╣
╠═ Creating backup and activating new installation          ═╣
╚════════════════════════════════════════════════════════════╝

Performing post processing steps...done.                                                                                                                                                                                                                       

Update done!

# パスを通して反映
vim ~/.bash_profile
-- vim追記 --
export PATH=$PATH:/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine
-------------

$ source ~/.bash_profile

# そのままだと実行権限がついてないので実行権限をつける
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp

# 無事、versionが上がりました!
$ goapp version
go version 1.8.5 (appengine-1.9.68) darwin/amd64

さらに

実行権限をつけましたが、以下も必要に応じてつけると良いです

$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/appcfg.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/dev_appserver.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/backends_conversion.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/bulkload_client.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/bulkloader.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/download_appstats.py
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/endpointscfg.py

補足

以下もご参考ください

おわり

cloud sdk便利!enjoy!\(^o^)/

【Mac】Homebrewとは? - からのFormula、keg、Cellar、Tapってなに?

はじめに

Macな環境はHomebrew使いますよね。

自分も長い事使っていますが、
FormulakegCellarTapあたりについて理解がぼやぁ〜としているなーと思ったので理解整理のための自分メモです。

タイトルとは裏腹にHomebrewそのものの説明は少なめです、すみませんすみません...

f:id:tweeeety:20180503231014p:plain

もくじ

  1. Homebrewとは
  2. Homebrew terminology
  3. Homebrewでのパッケージやアプリのインストール方法
    • brew install
    • brew cask install

1. Homebrewとは

Homebrewそのものの説明ではないと言ったものの
前提としてHomebrewについても触れておきます。

Homebrewとは?

wikiからの引用です

Homebrew(ホームブルー)は、macOSオペレーティングシステム上でソフトウェアの導入を単純化するパッケージ管理システムのひとつである。
MacPortsFinkと同様の目的と機能を備えている。LinuxDebianのAPTに似た使用感で急速に利用が広がっている。  
Homebrew (パッケージ管理システム))

Homebrewのinstall

これも簡単に触れる程度に

$ ruby -e "$(curl -fsS http://gist.github.com/raw/323731/install_homebrew.rb)"

home-brewとは?

home-brewを和訳すると自家醸造飲料(ビール、酒)のことらしいです。

参考サイトの例えが非常にわかりやすかったので引用させていただくと

手順(調理法formula)通りにパッケージを ビルド(醸造brew)して保存(/usr/local/cellerに格納)して、 使う(/usr/loca/binにリンク)ってことです。  
HomeBrewの仕組みについてまとめておく

という感じです。

homebrewのパッケージ管理

一部参考サイトを引用させて頂きますが、主に以下の2種類があります

  1. バイナリを取得するもの
    • ビルド済みのものを配布
  2. ソースコードを取得してビルドするもの

homebrewとは何者か。仕組みについて調べてみた

2. Homebrew terminology

ここからが本題です。

terminologyとは用語の事です。
用語とはFomulaとかCellarとかのことですね。

公式サイトにもHomebrew terminologyとして載っています。
f:id:tweeeety:20180503231110p:plain

公式サイトから引用しつつ、
自分なりに説明とたとえを記載してみました。

Homebrew - Formula Cookbook

公式:Term 公式:Description 補足 ビール作りでいうと
Formula The package definition パッケージの説明書や手順書 調理法
Keg The installation prefix of a Formula Formula のインストール先パス タル、熟成用
opt prefix A symlink to the active version of a Keg version違いのkegに対するactiveへのsymlink 使用中のタルの目印
Cellar All Kegs are installed here keg群のインストール先のパス 地下貯蔵室
Tap A Git repository of Formula and/or commands 公式以外のFormulaやコマンドがおいてあるgitリポジトリ 手順書の集まりとするとCookpad的な..!?
Bottle Pre-built Keg used instead of building from source ソースからビルドするタイプのbuildされていないkeg kegができあがったものとすると、こちらは自宅用手作りキッド的な感じ
Cask An extension of homebrew to install macOS native apps macOSのnativeアプリのパッケージ置き場 自家醸造ビールの酒樽置き場
Brew Bundle An extension of homebrew to describe dependencies アプリなどを一括でインストールするやーつ 1ずつの手順書があるとすると、全部まとめたオードブル手順書みたいな感じ

書いてて無理矢理すぎだろ...
と自分でも思いましたが説明下手にはご愛嬌を...w

3. Homebrewでのパッケージやアプリのインストール方法

Homebrewでのパッケージやアプリのインストール方法2つに触れておきます

  • brew公式のもののインストール
  • brew公式以外のもののインストール

brew公式のもののインストール

コマンド例
# パッケージをさがす
$ brew search <パッケージ名>

# インストール
$ brew install <パッケージ名>
参考

brew公式以外のもののインストール

bew tapとは

brew tapは Homebrewに実装されてるコマンドで、
GitHubのレポジトリにある パッケージをそのままインストールするコマンドです。
 
Homebrewの拡張:brewdler, tap, cask

コマンド例
# brew tapコマンドでcaskのリポジトリ登録
$ brew tap caskroom/cask

# お目当てのものをインストール
$ brew cask install google-chrome
参考
補足

以下のように、以前はbrew tap caskroom/caskも必要だったようですが今は必要なくなっています。

$ brew tap caskroom/cask

# caskをインストール?
$ brew install brew-cask

$ brew cask install google-chrome

その他: ①や②をまとめた手順を書いておいてのインストール

一連の操作を記述したbrewfileを作り
brew bundleコマンドでまとめてインストールすることも可能です。

# Homebrew/bundleをインストール
$ brew tap Homebrew/bundle

# Brewfileを作成する
# dumpに頼らず自身で作るのもあり
$ brew bundle dump

# インストール
$ brew bundle
参考

おわり

自分のたとえがイケてないのが気にかかりますが、
整理してまとめるとすっきりしますね! enjoy!\(^o^)/

【GAE】Google Cloud SDKとgcloudとコンポーネント(components)とgoappをおさらい

はじめに

GAE goな環境を利用しています。
最初に環境構築して以来、google-cloud-sdk 周りにはあまり触れていませんでした。

とある事がきっかけで、

  • google-cloud-sdkgcloudgoappってそれぞれなにするやつ?
  • gcloudコンポーネントgoappってどういう関係?

という所を自分の中で整理できていないなーと思ったので、整理をかねた自分用メモです

アジェンダ

  1. Google Cloud SDKとは
  2. gcloudとは
  3. コンポーネント(components)とは
  4. goappコマンドとは

補足

だいたいの説明は公式サイトから引用させて頂いてます。
引用させて頂いたページはrefします。

1. Google Cloud SDKとは

Google Cloud SDKは、
Google Cloud Platformにホスティングされているリソースと
アプリケーションの管理に使用できる一連のツールです。
gcloud、gsutil、bqなどのコマンドライン ツールもその一部です。
 
gcloud コマンドライン ツールは Cloud SDKと一緒にダウンロードされます。
gcloud の詳しい説明はgcloudの概要にあります。
 
Google Cloud SDK ドキュメント

インストール後のディレクトリはgoogle-cloud-sdkという名前になっています。

Cloud SDK のインストール

このブログでは、それぞれが何なのかの説明にとどめます。

cloud SDK のインストール は以下をご参考ください。
* cloud SDK のインストール

2. gcloudとは

gcloudとは

gcloudは Google Cloud Platformへの
主要なコマンドライン インターフェースを提供するツールです。
 
このツールを使用すると、
コマンドラインから、またはスクリプトその他の自動化により、多くの一般的なプラットフォーム タスクを実行することができます。
 
gcloud の概要

gcloudとSDK

gcloudは Google Cloud SDKの一部です。
gcloud を使用するには、その前にシステムにSDKをダウンロードしてインストールし、初期化する必要があります。
 
デフォルトでは、リリースレベルが一般提供とプレビューのgcloudコマンドのみがインストールされます。
その他の機能は、SDKコンポーネントのalphaとbetaに含まれています。
 
これらのコンポーネントを使用すると、
Google Cloud BigtableGoogle Cloud Dataflow など、一般提供リリースレベルより前の Cloud Platform 機能を gcloud で使用できるようになります。
 
gcloud の概要

3. コンポーネント(components)とは

コンポーネントとは

コンポーネントとは SDKの一部で、個別にインストールできます。
コマンドライン ツール(gcloud、bq、gsutil)、
リリースレベルがアルファ版またはベータ版の gcloud コマンド、
SDK のツールによって使用される依存関係を含むパッケージなどがあります。
 
最も一般的なコンポーネントはデフォルトでインストールされます。
 
SDK コンポーネントの管理 > コンポーネントとは

デフォルトのコンポーネント

以下は、SDKをインストールすると
デフォルトでインストールされるコンポーネントです。

ID 名前 説明
gcloud Default gcloud Commands Google Cloud Platform を操作するためのツール。
このコンポーネントと一緒にインストールされるのは、リリースレベルが一般提供かプレビューのコマンドだけです。
その他のリリースレベルのコマンドを使用するには、gcloud alpha コマンドや gcloud beta コマンド コンポーネントを別途インストールする必要があります。
bq BigQuery Command-Line Tool Google BigQuery 内のデータを操作するためのツール。
gsutil Cloud Storage Command-Line Tool Google Cloud Storage に関連するタスクを実行するためのツール。
core Cloud SDK Core Libraries SDK ツールが内部で使用するライブラリ。

コンポーネントはIDという単位で管理されています。

componentsコマンド

componentsは、gcloudコマンドのサブコマンドのように指定して使います

componentsコマンドのhelp

以下のコマンドでhelpを見ることができます。

$ gcoud components --help

実際に叩いてみた例です

$ gcloud components --help

NAME
    gcloud components - list, install, update, or remove Google Cloud SDK
        components

SYNOPSIS
    gcloud components GROUP | COMMAND [GCLOUD_WIDE_FLAG ...]

DESCRIPTION
    The gcloud components command group lets you control which tools are
    installed in the Cloud SDK. It can be used to install, update and remove
    components of the Cloud SDK, ensuring a lean, up-to-date installation.

    gcloud components regularly checks whether updates are available for the
    tools you already have installed, and gives you the opportunity to upgrade
    to the latest version.

    Certain components have dependencies. gcloud components will install any
    dependencies, and during removal, any dependant components will be
    uninstalled automatically.

GCLOUD WIDE FLAGS
    These flags are available to all commands: --account, --configuration,
    --flatten, --format, --help, --log-http, --project, --quiet, --trace-token,
    --user-output-enabled, --verbosity. Run $ gcloud help for details.

GROUPS
    GROUP is one of the following:

     repositories
        Manage additional component repositories for Trusted Tester programs.

COMMANDS
    COMMAND is one of the following:

     install
        Install one or more Cloud SDK components.

     list
        List the status of all Cloud SDK components.

     reinstall
        Reinstall the Cloud SDK with the same components you have now.

     remove
        Remove one or more installed components.

     restore
        Restore the Cloud SDK installation to its previous state.

     update
        Update all of your installed components to the latest version.

EXAMPLES
    To see all available components:

        $ gcloud components list

    To install a component you don't have:

        $ gcloud components install COMPONENT

    To remove a component you no longer need:

        $ gcloud components remove COMPONENT

    To update all components you have to their latest version:

        $ gcloud components update

    To update all installed components to version 1.2.3:

        $ gcloud components update --version 1.2.3
components list

以下のコマンドで、提供されているcomponentsの一覧とインストール状況を見る事ができます。

$ gcoud components --help

実際に叩いてみた例です。

$ gcloud components list

Your current Cloud SDK version is: 198.0.0
The latest available version is: 200.0.0

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                   Components                                                   │
├──────────────────┬──────────────────────────────────────────────────────┬──────────────────────────┬───────────┤
│      Status      │                         Name                         │            ID            │    Size   │
├──────────────────┼──────────────────────────────────────────────────────┼──────────────────────────┼───────────┤
│ Update Available │ BigQuery Command Line Tool                           │ bq                       │   < 1 MiB │
│ Update Available │ Cloud SDK Core Libraries                             │ core                     │   7.9 MiB │
│ Update Available │ Cloud Storage Command Line Tool                      │ gsutil                   │   3.5 MiB │
│ Not Installed    │ Cloud Bigtable Command Line Tool                     │ cbt                      │   4.6 MiB │
│ Not Installed    │ Cloud Bigtable Emulator                              │ bigtable                 │   3.8 MiB │
│ Not Installed    │ Cloud Datalab Command Line Tool                      │ datalab                  │   < 1 MiB │
│ Not Installed    │ Cloud Datastore Emulator                             │ cloud-datastore-emulator │  17.9 MiB │
│ Not Installed    │ Cloud Datastore Emulator (Legacy)                    │ gcd-emulator             │  38.1 MiB │
│ Not Installed    │ Cloud Pub/Sub Emulator                               │ pubsub-emulator          │  33.4 MiB │
│ Not Installed    │ Emulator Reverse Proxy                               │ emulator-reverse-proxy   │  14.5 MiB │
│ Not Installed    │ Google Container Local Builder                       │ container-builder-local  │   4.3 MiB │
│ Not Installed    │ Google Container Registry's Docker credential helper │ docker-credential-gcr    │   2.5 MiB │
│ Not Installed    │ gcloud app Java Extensions                           │ app-engine-java          │ 118.9 MiB │
│ Not Installed    │ gcloud app PHP Extensions                            │ app-engine-php           │  21.9 MiB │
│ Not Installed    │ gcloud app Python Extensions (Extra Libraries)       │ app-engine-python-extras │  28.5 MiB │
│ Not Installed    │ kubectl                                              │ kubectl                  │  12.2 MiB │
│ Installed        │ App Engine Go Extensions                             │ app-engine-go            │ 151.3 MiB │
│ Installed        │ gcloud Alpha Commands                                │ alpha                    │   < 1 MiB │
│ Installed        │ gcloud Beta Commands                                 │ beta                     │   < 1 MiB │
│ Installed        │ gcloud app Python Extensions                         │ app-engine-python        │   6.1 MiB │
└──────────────────┴──────────────────────────────────────────────────────┴──────────────────────────┴───────────┘
To install or remove components at your current SDK version [198.0.0], run:
  $ gcloud components install COMPONENT_ID
  $ gcloud components remove COMPONENT_ID

To update your SDK installation to the latest version [200.0.0], run:
  $ gcloud components update

アルファ版コンポーネントとベータ版コンポーネント

コンポーネントにはα版とβ版があり、
それぞれ以下のようにインストールすることで利用可能になります。

$ gcloud components install alpha
$ gcloud components install beta

詳しく知りたい場合は、公式サイトが参考になります

4. goappコマンドとは

これまでなんとなく使っていたものの
goappコマンド が何かというのは自分的に結構曖昧なままでした。

goappコマンドについては別途軽く調べてみたのでこちらもご参考ください。
* 【GAE】goappコマンドについて簡単にまとめてみた

goappコマンドとは

goappコマンドの説明です。

Google Cloud SDKの一部である
gcloudでインストールするコンポーネントの1つに含まれるコマンド

どのコンポーネント

goappコマンドは、
前述したcomponentsコマンドでインストールすることで利用可能です。

先ほどのcomponents listでいうところのapp-engine-goです

$ gcloud components list
~ 省略 ~ 

│ Installed        │ App Engine Go Extensions                             │ app-engine-go            │ 151.3 MiB │

~ 省略 ~ 

goappコマンドの使い方例

以下のように利用することで、
ローカルでGAEアプリの起動ができます。

$ goapp serve app.yaml

おわり

これで誰かに聞かれても
Google Cloud SDKとgcloudとコンポーネント(components)とgoappについて説明ができそうです
\(^o^)/

【GAE】goappコマンドについて簡単にまとめてみた

はじめに

GAE goな環境で開発しているときに、

$ goapp serve app.yaml

という感じで使うわけですが、そもそもgoappってなんぞやという事を軽くまとめてみました。

アジェンダ

  1. goappコマンドの簡単な紹介
  2. goappコマンドとは
  3. goappコマンドのinstall
  4. goapp serveコマンドの挙動

1. goappコマンドの簡単な紹介

goappコマンドは、GAE goな環境で開発する際に使うコマンドです。

例えば、以下はローカルでGAEアプリを起動する際の例です

$ goapp serve app.yaml
INFO     2018-05-02 14:45:49,257 devappserver2.py:120] Skipping SDK update check.
INFO     2018-05-02 14:45:49,353 api_server.py:274] Starting API server at: http://localhost:51983
INFO     2018-05-02 14:45:49,360 dispatcher.py:270] Starting module "Hoge" running at: http://localhost:8080
INFO     2018-05-02 14:45:49,365 admin_server.py:152] Starting admin server at: http://localhost:8000
WARNING  2018-05-02 14:45:49,367 devappserver2.py:215] No default module found. Ignoring.
/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/mtime_file_watcher.py:182: UserWarning: There are too many files in your application for changes in all of them to be monitored. You may have to restart the development server to see some changes to your files.
  'There are too many files in your application for '

2. goappコマンドとは

goappコマンドとは、自分なりの言葉で表現すると

Google Cloud SDKの一部である
gcloudでインストールするコンポーネントの1つに含まれるコマンド

です。(文章がわかりずらくてすみません)

gcloud/SDK/コンポーネントあたりについては別に書いてみたのでご参考ください。

【GAE】Google Cloud SDKとgcloudとコンポーネント(components)とgoappをおさらい

以降で、goappについて掘り下げます

GAEとgo

GAE goな環境で開発すると記載しましたが、
GAEはgoを内包しています。

ためしにversionを見てみます。
PCにインストールしたgoとversionが違う事がわかります

# goappのversionと
# 内包されているgoのversionを確認
$ goapp version
go version 1.8.5 (appengine-1.9.68) darwin/amd64

# PCのgoのversionを確認
$ go version
go version go1.6.2 darwin/amd64

goappのコマンド

helpを見てみるとgoそのもののhelpと似ています

goapp help
$ goapp help
Go is a tool for managing Go source code.

Usage:

  goapp command [arguments]

The commands are:

  serve       starts a local development App Engine server
  deploy      deploys your application to App Engine
  build       compile packages and dependencies
  clean       remove object files
  doc         show documentation for package or symbol
  env         print Go environment information
  bug         start a bug report
  fix         run go tool fix on packages
  fmt         run gofmt on package sources
  generate    generate Go files by processing source
  get         download and install packages and dependencies
  install     compile and install packages and dependencies
  list        list packages
  run         compile and run Go program
  test        test packages
  tool        run specified go tool
  version     print Go version
  vet         run go tool vet on packages

Use "goapp help [command]" for more information about a command.

Additional help topics:

  c           calling between Go and C
  buildmode   description of build modes
  filetype    file types
  gopath      GOPATH environment variable
  environment environment variables
  importpath  import path syntax
  packages    description of package lists
  testflag    description of testing flags
  testfunc    description of testing functions

Use "goapp help [topic]" for more information about that topic.
go help
$ go help
Go is a tool for managing Go source code.

Usage:

  go command [arguments]

The commands are:

  build       compile packages and dependencies
  clean       remove object files
  doc         show documentation for package or symbol
  env         print Go environment information
  fix         run go tool fix on packages
  fmt         run gofmt on package sources
  generate    generate Go files by processing source
  get         download and install packages and dependencies
  install     compile and install packages and dependencies
  list        list packages
  run         compile and run Go program
  test        test packages
  tool        run specified go tool
  version     print Go version
  vet         run go tool vet on packages

Use "go help [command]" for more information about a command.

Additional help topics:

  c           calling between Go and C
  buildmode   description of build modes
  filetype    file types
  gopath      GOPATH environment variable
  environment environment variables
  importpath  import path syntax
  packages    description of package lists
  testflag    description of testing flags
  testfunc    description of testing functions

Use "go help [topic]" for more information about that topic.

goのラッパー的な要素に+αして
GAE goな環境で開発する際に便利な
servdeploybugなどを加えたといった感じです。

3. goappコマンドのinstall

goappコマンドは直接インストールするわけではありません。

2. goappコマンドとは に記載しましたが、
gcloudコンポーネント群のうち、app-engine-goというコンポーネントに含まれるコマンドです。

ここではgoappについてのみ記載します。
gcloudについては公式がわかりやすいです
gcloud の概要

# インストールされる場所を確認
$ gcloud info | grep Installation
Installation Root: [/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk]
Installation Properties: [/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/properties]

# gcloud経由でapp-engine-goをインストールする
$ gcloud components install app-engine-go

# 確認すると
# /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine
# というパスに入っている
$ ls -l /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/*goapp*
-rwxr-xr-x+ 1 tweeeety  tweeeety  5109  5  2 22:08 /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp

# パスを追加
$ export PATH=$PATH:/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine

# 実行権限がないので追加
$ chmod +x /usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp

# 使えるようになる
$ goapp version
go version 1.8.5 (appengine-1.9.68) darwin/amd64

app-engine-goでインストールされるもの

/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine 配下には
すでにいくつかのリソースが配置されてますが、
gcloud components install app-engine-go によって以下が追加されます。

-rw-r--r--+  1 tweeeety  tweeeety     5949  3 17 16:55 LICENSE.golang
-rw-r--r--+  1 tweeeety  tweeeety    17738  3 17 16:59 RELEASE_NOTES.golang
-rw-r--r--+  1 tweeeety  tweeeety      248  3 17 16:55 VERSION.golang
-rwxr-xr-x+  1 tweeeety  tweeeety  3679424  3 17 17:00 go-app-stager
-rw-r--r--+  1 tweeeety  tweeeety     4798  3 17 16:59 goapp
-rw-r--r--+  1 tweeeety  tweeeety     4798  3 17 16:59 godoc
-rw-r--r--+  1 tweeeety  tweeeety     4798  3 17 16:59 gofmt
drwxr-xr-x+  2 tweeeety  tweeeety       68  3 17 17:01 gopath
drwxr-xr-x+ 14 tweeeety  tweeeety      476  5  2 21:30 goroot-1.6
drwxr-xr-x+ 14 tweeeety  tweeeety      476  5  2 21:30 goroot-1.8
drwxr-xr-x+ 14 tweeeety  tweeeety      476  5  2 21:30 goroot-1.9

まぁ、go関連で納得という感じですね

4. goapp serveコマンドの挙動

goappというかgoapp serveの挙動です。

help

まずはhelpを見てみます。

$ goapp serve --help

usage: serve [serve flags] [application_dir | package | yaml_files...]

Serve launches your application on a local development App Engine server.

The argument to this command should be your application's root directory or a
single package which contains an app.yaml file. If you are using the Modules
feature, then you should pass multiple YAML files to serve, rather than a
directory, to specify which modules to serve. If no arguments are provided,
serve looks in your current directory for an app.yaml file.

The -host flag controls the host name to which application modules should bind
(default localhost).

The -port flag controls the lowest port to which application modules should
bind (default 8080).

The -use_mtime_file_watcher flag causes the development server to use mtime
polling for detecting source code changes, as opposed to inotify watches.

The -admin_port flag controls the port to which the admin server should bind
(default 8000).

The -clear_datastore flag clears the local datastore on startup.

The -debug flag builds the binary with debug information so that gdb or delve
can be used (default false).

This command wraps the dev_appserver.py command provided as part of the
App Engine SDK. For help using that command directly, run:
  ./dev_appserver.py --help

最後に書いてありますが、dev_appserver.py のラッパーであることがわかります。
また、オプションでportなどが指定できます。

goapp コマンドの中身

中身はpythonで書かれています。
100行ちょいなので読めるレベルです。

#!/usr/bin/env python2.7                                                                                                                                                                                                                                     
#
# Copyright 2011 Google Inc. All rights reserved.
# Use of this source code is governed by the Apache 2.0
# license that can be found in the LICENSE file.

"""Convenience wrapper for starting a Go tool in the App Engine SDK."""
from __future__ import print_function

import argparse
import os
import sys 

SDK_BASE = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))


def FixGooglePath():
  """Adds the python libraries vendored with the SDK to sys.path.

  This allows us to run gotool.py directly and import the dependencies under the
  google/ directory.
  """
  # pylint: disable=g-import-not-at-top
  import wrapper_util
  # pylint: enable=g-import-not-at-top
  sys.path = wrapper_util.Paths(SDK_BASE).v1_extra_paths + sys.path
  if 'google' in sys.modules:
    google_path = os.path.join(os.path.dirname(__file__), 'google')
    google_module = sys.modules['google']
    google_module.__path__.append(google_path)
    if not hasattr(google_module, '__file__') or not google_module.__file__:
      google_module.__file__ = os.path.join(google_path, '__init__.py')


FixGooglePath()


# pylint: disable=g-import-not-at-top
from google.appengine.api import appinfo_includes
from google.appengine.tools.devappserver2.go import goroots
# pylint: enable=g-import-not-at-top


def GetArgsAndArgv():
  """Parses command-line arguments and strips out flags the control this file.

  Returns:
    Tuple of (flags, rem) where "flags" is a map of key,value flags pairs
    and "rem" is a list that strips the used flags and acts as a new
    replacement for sys.argv.
  """
  parser = argparse.ArgumentParser(add_help=False)
  parser.add_argument(
      '--dev_appserver', default=os.path.join(SDK_BASE, 'dev_appserver.py'))
  parser.add_argument(
      '--print-command', dest='print_command', default=False,
      action='store_true')
  namespace, rest = parser.parse_known_args()
  flags = vars(namespace)
  rem = [sys.argv[0]]
  rem.extend(rest)
  return flags, rem


def GetAppYamlPaths(gopath, app_path):
  """Generate possible paths to app.yaml.

  Args:
    gopath: String path to gopath directory.
    app_path: String path to the app.

  Yields:
    Possible paths for app.yaml from app_path up to the gopath root.
  """
  gopath = os.path.abspath(gopath)
  app_path = os.path.abspath(app_path)
  # If we were given an app.yaml, return only it
  if app_path.endswith('.yaml'):
    yield app_path
    raise StopIteration()
  # Always include the app_path, even if not on gopath
  yield os.path.join(app_path, 'app.yaml')
  # But only walk up if we're still on the gopath
  while app_path.startswith(gopath) and app_path != gopath:
    app_path = os.path.abspath(os.path.join(app_path, '..'))
    yield os.path.join(app_path, 'app.yaml')


def _ParseAppYaml(file_name):
  with open(file_name, 'r') as f:
    return appinfo_includes.Parse(f)


def GetGoRoot(gopath, argv):
  """Find the goroot.

  Args:
    gopath: String path to gopath directory.
    argv: A list of strings that looks like sys.argv. The last element of this
      list is checked to see if it's a valid path and, if so, is included in the
      search.

  Returns:
    The path to the correct goroot for the project.
  """
  # First, look for an app.yaml starting in the pwd
  paths = [os.path.realpath(os.path.curdir)]
  # Check if the last cli arg was a path, and look there as well
  if len(argv) > 2:
    app_path = argv[-1]
    if not app_path.startswith('-'):
      app_path = app_path.rstrip('...')
      paths += [os.path.realpath(app_path)]
  for path in paths:
    for app_yaml_path in GetAppYamlPaths(gopath, path):
      if os.path.exists(app_yaml_path):
        app_yaml = _ParseAppYaml(app_yaml_path) 
        if hasattr(app_yaml, 'api_version'):
          return os.path.join(SDK_BASE, goroots.GOROOTS[app_yaml.api_version])

  # Default to the goroot for go1
  return os.path.join(SDK_BASE, goroots.GOROOTS['go1'])


if __name__ == '__main__':
  vals, new_argv = GetArgsAndArgv()
  tool = os.path.basename(__file__)

  # Set a GOPATH if one is not set.
  if not os.environ.get('GOPATH'):
    os.environ['GOPATH'] = os.path.join(SDK_BASE, 'gopath')
  os.environ['APPENGINE_DEV_APPSERVER'] = vals['dev_appserver']

  # Find the correct goroot for the app and make sure we're running the given
  # tool from there.
  goroot = GetGoRoot(os.environ['GOPATH'], sys.argv)
  os.environ['GOROOT'] = goroot
  tool = os.path.join(goroot, 'bin', tool)

  # Remove env variables that may be incompatible with the SDK.
  for e in ('GOARCH', 'GOBIN', 'GOOS'):
    os.environ.pop(e, None)

  # Replace the path to this file with the path to the underlying tool
  new_argv[0] = tool
  if vals['print_command']:
    print(' '.join(new_argv))
  else:
    os.execve(tool, new_argv, os.environ)               

if __name__ == '__main__':がメインです。

tool, new_argv, os.environらを組み立てて
最後のos.execveで実行しています。

os.execveは、現在のプロセスを置き換える形で新たなプログラムを実行します。
os.execve(path, args, env)

os.execveの前に登場する各変数をdumpしてみるとこんな値が入ってます

tool

/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goroot-1.8/bin/goapp

vals

{'dev_appserver': '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/dev_appserver.py','print_command': False}

new_argv
['/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp',
 'serve',
 'app.yaml']
os.environ
{
 'DIRENV_DIR': '-/Users/tweeeety/gitrepos/Hoge',
 'GOPATH': '/Users/tweeeety/gitrepos/Hoge',
 'PERL_CPANM_OPT': '--mirror http://cpan.metacpan.org',
 'APPENGINE_DEV_APPSERVER': '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/dev_appserver.py',
 'GOROOT': '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goroot-1.8',
 'DIRENV_DIFF': 'hogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehoge',
 'TERM_PROGRAM_VERSION': '326',
 'SHELL': '/bin/bash',
 'LOGNAME': 'tweeeety',
 'USER': 'tweeeety',
 'HOME': '/Users/tweeeety',
 'PATH': '/usr/local/opt/imagemagick@6/bin:/Users/tweeeety/.plenv/shims:/Users/tweeeety/.plenv/bin:/Users/tweeeety/.nodebrew/current/bin:/Users/tweeeety/.mysqlenv/mysqls/5.1.69/bin:/Users/tweeeety/.mysqlenv/bin:/Users/tweeeety/.mysqlenv/shims:/Users/tweeeety/.mysqlenv/mysql-build/bin:/usr/local/sbin:/Users/tweeeety/.mysqlenv/bin:/Users/tweeeety/.mysqlenv/shims:/Users/tweeeety/.mysqlenv/mysql-build/bin:/usr/local/heroku/bin:/Users/tweeeety/.chefdk/gem/ruby/2.1.0/bin:/opt/chefdk/bin:/Users/tweeeety/.rbenv/shims:/Users/tweeeety/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/go/bin:/sbin:/usr/sbin:/Users/tweeeety/local/bin:/usr/local/opt/go/libexec/bin:/Users/tweeeety/.go/bin:/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine',
 'PS1': '[\\[\\033[40;1;32m\\]\\w \\[\\033[40;2;37m\\]\\t\\[\\033[0m\\]]$ ',
 'TERM_PROGRAM': 'Apple_Terminal',
 'LANG': 'ja_JP.UTF-8',
 'TERM': 'xterm-256color',
 'Apple_PubSub_Socket_Render': '/tmp/launch-95EcNN/Render',
 'SHLVL': '1',
 'TEST_MYSQL_SOCK': '/tmp/mysql.sock',
 'SECURITYSESSIONID': 'hoge',
 'RBENV_SHELL': 'bash',
 'EDITOR': 'vim',
 'TERM_SESSION_ID': 'hogehogehogehoge',
 'SSH_AUTH_SOCK': '/tmp/launch-Z5iV4t/Listeners',
 'MODULE': 'Hoge',
 'TEST_LOCAL_MYSQL_SOCK': '/tmp/mysql.sock',
 '_': '/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/goapp',
 'TMPDIR': '/var/folders/5x/2wrjp7td5bj9cprs4c4cwxswqmbl26/T/',
 'PERL5LIB': '/Users/tweeeety/testApp/Sample/lib/:',
 'PLENV_SHELL': 'bash',
 'OLDPWD': '/Users/tweeeety/gitrepos/Fuga',
 '__CF_USER_TEXT_ENCODING': '0x2F45CC46:1:14',
 'PWD': '/Users/tweeeety/gitrepos/Hoge',
 'DIRENV_WATCHES': 'hogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehogehoge',
 '__CHECKFIX1436934': '1'
}

おわり

なんとなくわかった気になりました\(^o^)/