20200107のMacに関する記事は6件です。

WindowsプログラマーがMacを使いこなすまでにやるべきこと(基本操作編)

はじめに

WindowsユーザーがMacを使いやすくするために変更した設定や操作方法などをメモしていきます。
まずはキーボードやウィンドウなどの基本操作に慣れていきたいと思います。
同じような人の悩みを解決できれば幸いです。

環境

  • Windows 10
  • Mac 10.15.2 Catalina

キーボードの設定

ショートカットキーを押しやすくする設定

使い慣れたCtrlの位置をCommandに変えたい!
1. アップルメニュー → 「システム環境設定」 をクリック
2. 「キーボード」 → 「修飾キー」 をクリック
3. 以下の図のように割り当てを変更する
CapsLockキーをCommandに割り当て、CommandキーをCapsLockに設定を変更する
スクリーンショット

日本語入力中に英字を入力する設定

日本語入力中にShiftを押しながらアルファベットの半角英字を入力したい!
1. アップルメニュー → 「システム環境設定」 をクリック
2. 「入力ソース」 をクリック
3. 「Windows風のキー操作」をチェックON
この設定をすることで「Shiftキーの動作」が「英字モードに入る」に固定される。
他にどんな操作がWindows風になるのかは不明。
#などの記号はShift+#でも半角にならない…

ファンクションキーの特殊機能とFnを入れ替える設定

デスクトップ表示するための Fn+F11 のファンクションキーを省略したい!
1. アップルメニュー → 「システム環境設定」 をクリック
2. 「キーボード」 をクリック
3. 「F1、F2などのキーを標準のファンクションキーとして使用」をチェックON

キーボードショートカットの対応表

やりたいこと Windows Mac
開いているウィンドウ一覧表示 Windows+Tab F3(※1) or トラックパッド操作
デスクトップ表示 Windows+D Fn+F11(※1) or トラックパッド操作
画面スクリーンショット(キャプチャー) PrintScreen Command+Shift+4 → 矩形選択 → デスクトップに画像が自動保存

※1:Fnキー入れ替え設定している場合は逆になります
(例)F3 なら Fn+F3の同時押し、Fn+F11 なら F11のみ

ウィンドウ操作の対応表

やりたいこと Windows Mac
2つのウィンドウを並べて表示 ウィンドウを画面端にD&D 緑色のボタンを長押しして左か右にD&D
スクリーンショット

おわりに

操作に悩んだら随時追加していきます。
おすすめがあったらぜひ教えてください。

外部リンク

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

CapistranoをMacOS X MojaveのRoRにインストールする

Capistrano

前提条件

  • Capistrano 3.11.2
  • slackistrano >= 4.0.1
  • P

    セットアップ

  • Capistranoのインストール

Terminal
$ bundle exec cap install STAGES=staging,production
bundler: command not found: cap
Install missing gem executables with `bundle install`

あら。まあそりゃそうです笑

command not found: capとなった場合

  • この場合、capistranoのGEMがインストールされていない為、GEMインストールを行う

  • Gemfileを開き、編集

Terminal
# Gemfileの編集
$ vi Gemfile
group :staging, :production do
  # Use Capistrano for deployment
  gem 'capistrano',                 '3.11.2'
  gem 'capistrano-rails',           '1.4.0'
  gem 'capistrano-rbenv',           '2.1.4 '
  gem 'capistrano-passenger',       '0.2.0'
  # 今回はSlack通知も行うため、便宜上載せています
  gem 'slackistrano', '>=4.0.1'
end
  • bundle install
Terminal
$ bundle _1.17.2_ install --path vendor/bundle
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mingw32, x86-mswin32, x64-mingw32, java. To add those platforms to the bundle, run `bundle lock --add-platform x86-mingw32 x86-mswin32 x64-mingw32 java`.
・・・
Fetching capistrano 3.11.2
Installing capistrano 3.11.2
Fetching capistrano-bundler 1.6.0
Installing capistrano-bundler 1.6.0
Fetching capistrano-passenger 0.2.0
Installing capistrano-passenger 0.2.0
Fetching capistrano-rails 1.4.0
Installing capistrano-rails 1.4.0
Fetching capistrano-rbenv 2.1.4
Installing capistrano-rbenv 2.1.4
・・・
Fetching slackistrano 4.0.1
Installing slackistrano 4.0.1
・・・
Bundle complete! 38 Gemfile dependencies, 148 gems now installed.
Bundled gems are installed into `./vendor/bundle`
Post-install message from capistrano-passenger:
==== Release notes for capistrano-passenger ====
passenger once had only one way to restart: `touch tmp/restart.txt`
Beginning with passenger v4.0.33, a new way was introduced: `passenger-config restart-app`

The new way to restart was not initially practical for everyone,
since for versions of passenger prior to v5.0.10,
it required your deployment user to have sudo access for some server configurations.

capistrano-passenger gives you the flexibility to choose your restart approach, or to rely on reasonable defaults.

If you want to restart using `touch tmp/restart.txt`, add this to your config/deploy.rb:

    set :passenger_restart_with_touch, true

If you want to restart using `passenger-config restart-app`, add this to your config/deploy.rb:

    set :passenger_restart_with_touch, false # Note that `nil` is NOT the same as `false` here

If you don't set `:passenger_restart_with_touch`, capistrano-passenger will check what version of passenger you are running
and use `passenger-config restart-app` if it is available in that version.

If you are running passenger in standalone mode, it is possible for you to put passenger in your
Gemfile and rely on capistrano-bundler to install it with the rest of your bundle.
If you are installing passenger during your deployment AND you want to restart using `passenger-config restart-app`,
you need to set `:passenger_in_gemfile` to `true` in your `config/deploy.rb`.
================================================
  • CapistranoとCapifyアプリケーションをインストールする
Terminal
$ bundle exec cap install STAGES=staging,production
mkdir -p config/deploy
create config/deploy.rb
create config/deploy/staging.rb
create config/deploy/production.rb
mkdir -p lib/capistrano/tasks
create Capfile
Capified

階層構造は以下となる

Tree-map
[rails app root]
├─ Capfile
├─ config
│ ├─ deploy
│ │ ├─production.rb
│ │ └─staging.rb
│ └─deploy.rb
└─ lib
  └─capistrano
    └─tasks
  └─tasks

capistranoをインストールしたので、capistrano/setup と capistrano/deploy の準備は一旦はこれでできました

capistrano/deploy タスク

  • デプロイを自動化する、capistranoのタスクです

Deployタスクの一覧

実行順 タスク名 意味
1 deploy Deploy実行
2 deploy:starting Deploy実行開始、サーバー待機中
2.1 deploy:check -
2.1.1 #{scm}:check -
2.1.2 deploy:check:directories -
2.1.3 deploy:check:linked_dirs -
2.1.4 deploy:check:make_linked_dirs -
2.1.5 deploy:check:linked_files -
2.2 deploy:set_previous_revision -
3 deploy:started Deploy開始中
4 deploy:updating Deploy実行中
4.1 #{scm}:create_release -
4.2 deploy:symlink:shared -
4.2.1 deploy:symlink:linked_files -
4.2.2 deploy:symlink:linked_dirs -
5 deploy:updated 更新完了
6 deploy:publishing デプロイ処理中
6.1 deploy:symlink:release -
7 deploy:published デプロイ処理終了
8 deploy:finishing デプロイ終了中、サーバークリーンアップ中
8.1 deploy:cleanup -
9 deploy:finished 処理終了
9.1 deploy:log_revision -
実行順 タスク名 意味
1 deploy:rollback 前回リリースバージョンにロールバック
2 deploy:starting Deploy実行開始、サーバー待機中
3 deploy:started Deploy開始中
4 deploy:reverting 前回リリースバージョンにrevert完了
5 deploy:reverted 前回リリースバージョンにrevert
6 deploy:publishing デプロイ処理中
7 deploy:published デプロイ処理終了
8 deploy:finishing_rollback ロールバック完了
9 deploy:finished 処理終了
実行順 タスク名 意味
1 install Capistranoインストール
(凡例:cap install STAGES=staging,production)

プラグインによるフローの追加

capistrano/rails/assets

  • Assetsのプリコンパイルを行う
インストール
Capfile
require capistrano/rails/assets
実行順 タスク名 意味
5 deploy:updated 更新完了
5.1 deploy:compile_assets 追加される
5.1.1 deploy:assets:precompile 追加される
5.1.2 deploy:assets:backup_manifest 追加される
5.2 deploy:normalize_assets 追加される

capistrano/rails/migrations

  • DBMigrationを行う
インストール
Capfile
require "capistrano/rails/migrations"
実行順 タスク名 意味
5 deploy:updated 更新完了
5.1 deploy:migrate 追加される

capistrano/npm

  • npm installを行う
インストール
Capfile
require "capistrano/rails/migrations"
実行順 タスク名 意味
4 deploy:updating Deploy実行中
4.1 #{scm}:create_release -
4.2 deploy:symlink:shared -
4.2.1 deploy:symlink:linked_files -
4.2.2 deploy:symlink:linked_dirs -
5 npm:install 追加される

前提条件

  • ssh-agentを使用

セットアップ手順

  • Capfile を編集する
Capfile
# Load DSL and set up stages
require "capistrano/setup"

# Include default deployment tasks
require "capistrano/deploy"

# Load the SCM plugin appropriate to your project:
#
# require "capistrano/scm/hg"
# install_plugin Capistrano::SCM::Hg
# or
# require "capistrano/scm/svn"
# install_plugin Capistrano::SCM::Svn
# or
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
# require "capistrano/rvm"
# require "capistrano/rbenv"
# require "capistrano/chruby"
# require "capistrano/bundler"
# require "capistrano/rails/assets"
# require "capistrano/rails/migrations"
# require "capistrano/passenger"
# if you used rbenv
require "capistrano/rbenv"

require 'capistrano/rails'

require 'capistrano/bundler'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
  • deploy.rb を編集する
config/deploy.rb
# config valid for current version and patch releases of Capistrano
lock "~> 3.11.2"

set :application, "%app name%"
set :repo_url, "git@github.com:****/*****.git"

# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp

# Default deploy_to directory is /var/www/my_app_name
# set :deploy_to, "/var/www/my_app_name"
set :deploy_to, "/var/www/#{fetch(:application)}"

# Default value for :format is :airbrussh.
# set :format, :airbrussh

# You can configure the Airbrussh format using :format_options.
# These are the defaults.
# set :format_options, command_output: true, log_file: "log/capistrano.log", color: :auto, truncate: :auto

# Default value for :pty is false
# set :pty, true
set :pty, true      # sudoを使用する場合はtrue

# Default value for :linked_files is []
# append :linked_files, "config/database.yml"

# Default value for linked_dirs is []
# append :linked_dirs, "log", "tmp/pids", "tmp/cache", "tmp/sockets", "public/system"

# Default value for default_env is {}
# capistrano用bundleするのに必要
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
set :default_env, { path: "/usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH" }

# Default value for local_user is ENV['USER']
# set :local_user, -> { `git config user.name`.chomp }

# Default value for keep_releases is 5
# set :keep_releases, 5
set :keep_releases, 5

# Uncomment the following to require manually verifying the host key before first deploy.
# set :ssh_options, verify_host_key: :secure


# Configure ur Slack's Incoming Webhook
# if you want to be disable deployment notifications to a specific stage by setting the :slackistrano configuration variable to false instead of actual settings.
# When you desable slackistrano, comment out the description below.
set :slackistrano, false
# set :slackistrano, {
#  klass:   Slackistrano::CustomMessaging,
#  channel: '#bot-#{fetch(:application)}_deploy',
#  webhook: 'https://hooks.slack.com/services/*/*/*'
#}

# Configure ssh agent
set :ssh_options, {
  keys: %w(~/.ssh/id_rsa),
  forward_agent: true,
  auth_methods: %w(publickey)
}

# Configure 
# デプロイ開始通知タイミングの変更
# デフォルトだと、gitのチェック等のstarting処理後に通知が行くが、それよりタイミングを早めたいため
# 'deploy:starting'の前にすることで、rollbackなのか通常デプロイなのかタスク自体で判別できなくなるため、`deploying`にセットされた値のboolean値でどちらなのか判断している。
# 参考:https://github.com/capistrano/capistrano/blob/v3.11.2/lib/capistrano/tasks/framework.rake#L57
before 'deploy:starting', 'slack:deploy:updating'

# デプロイ失敗時にエラーを変数に保存しておくための処理
# https://github.com/capistrano/capistrano/blob/v3.11.2/lib/capistrano/dsl/task_enhancements.rb#L51
# ここの処理に一行追加しているだけ
module Capistrano
  module TaskEnhancements
    def exit_deploy_because_of_exception(ex)
      warn t(:deploy_failed, ex: ex.message)
      set :deploy_failed_exception, ex # 追加した1行
      invoke "deploy:failed"
      exit(false)
    end
  end
end
  1. 各環境のデプロイ用ファイルの編集
config/deploy/stating.rb
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:

# server "example.com", user: "deploy", roles: %w{app db web}, my_property: :my_value
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", roles: %w{db}



# role-based syntax
# ==================

# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.

# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db,  %w{deploy@example.com}



# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.



# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
#  set :ssh_options, {
#    keys: %w(/home/rlisowski/.ssh/id_rsa),
#    forward_agent: false,
#    auth_methods: %w(password)
#  }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server "example.com",
#   user: "user_name",
#   roles: %w{web app},
#   ssh_options: {
#     user: "user_name", # overrides user setting above
#     keys: %w(/home/user_name/.ssh/id_rsa),
#     forward_agent: false,
#     auth_methods: %w(publickey password)
#     # password: "please use keys"
#   }

set :stage, :staging
set :branch, ENV['GIT_BRANCH'] || `git rev-parse --abbrev-ref HEAD`.strip
set :rails_env, "staging"

# for *****
server "%hostname%", user: `whoami`.strip, roles: %w{web app}
config/deploy/production.rb
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:

# server "example.com", user: "deploy", roles: %w{app db web}, my_property: :my_value
# server "example.com", user: "deploy", roles: %w{app web}, other_property: :other_value
# server "db.example.com", user: "deploy", roles: %w{db}



# role-based syntax
# ==================

# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.

# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db,  %w{deploy@example.com}



# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.



# Custom SSH Options
# ==================
# You may pass any option but keep in mind that net/ssh understands a
# limited set of options, consult the Net::SSH documentation.
# http://net-ssh.github.io/net-ssh/classes/Net/SSH.html#method-c-start
#
# Global options
# --------------
#  set :ssh_options, {
#    keys: %w(/home/rlisowski/.ssh/id_rsa),
#    forward_agent: false,
#    auth_methods: %w(password)
#  }
#
# The server-based syntax can be used to override options:
# ------------------------------------
# server "example.com",
#   user: "user_name",
#   roles: %w{web app},
#   ssh_options: {
#     user: "user_name", # overrides user setting above
#     keys: %w(/home/user_name/.ssh/id_rsa),
#     forward_agent: false,
#     auth_methods: %w(publickey password)
#     # password: "please use keys"
#   }

set :stage, :production
set :branch, "master"
set :rails_env, "production"
  • Slackistranoの設定
lib/slackistrano/custom_messaging.rb
if defined?(Slackistrano::Messaging)
   module Slackistrano
     class CustomMessaging < Messaging::Base

      # Suppress starting message.
      def payload_for_updating

        attachments = []
        # 通常デプロイなのかロールバックなのか場合分け
        title = fetch(:deploying, false) ? 'Deploy start' : 'Rollback start'
        color = fetch(:deploying, false) ? 'good' : '#439FE0'

        # メイン
        attachments << base_attachments(title: title, color: color, fallback: super[:text])

        # gitの差分が取れた場合は差分を、取れなかった場合はgitの直近のlogを表示する
        diff_commits_str = `cap #{fetch(:rails_env)} deploy:pending`
        unless diff_commits_str.delete("\n").length.zero?
          diff_commits = convert_diff_commits(diff_commits_str.split("\n\ncommit "))
          attachments << {
            color:  color,
            title:  "git 差分",
            fields: diff_commits.map{|commit|
              {
                value: commit
              }
            }
          }
        else
          # git log
          attachments << {
            color:  color,
            title:  "git log",
            fields: git_last_commits_fields
          }
        end

        return {attachments: attachments}
      end

      # デプロイ完了
      def payload_for_updated
        attachments = []
        attachments << base_attachments(title: 'Deploy accomplished', color: '#439FE0', fallback: super[:text])

        return {attachments: attachments}
      end

      # ロールバック開始
      def payload_for_reverting
        # ロールバックの開始はデプロイ開始側のタスクで場合分けしている
      end

      # ロールバック完了
      def payload_for_reverted
        attachments = []
        attachments << base_attachments(title: 'Rollback accomplished', color: '#439FE0', fallback: super[:text])

        return {attachments: attachments}
      end

      # デプロイ失敗
      def payload_for_failed
        attachments = []
        attachments << base_attachments(title: 'Deploy failed', color: 'danger', fallback: super[:text])

        # エラー内容を取得
        exception = fetch(:deploy_failed_exception)
        error_message = exception.inspect + "\n" + exception.backtrace.join("\n")

        # エラー内容
        attachments << {
          color: 'danger',
          title: "エラー内容",
          fields: [{
            value: error_message
          }]
        }

        return {attachments: attachments}
      end

      private
        def git_last_commits_fields
          git_last_commit_messages = `git log -5 --date=iso --pretty=format:'%H_|_%an_|_%s_|_%cd' HEAD`.force_encoding('UTF-8').split("\n").map do |message|
            data = message.split('_|_')
            commit_name, pr_number = data[2].scan(/^[\s]*(.*)\s\(\#([^\)]+)\)$/)[0]
            commit_name = data[2] if commit_name.nil?
            {
              hash:        data[0],
              user_name:   data[1],
              commit_name: commit_name,
              pr_number:   pr_number,
              commit_date: data[3]
            }
          end
          git_last_commit_messages.map do |message|
            if message[:pr_number].nil?
              {
                value: "*#{message[:commit_name]}*>\nAuthor: #{message[:user_name]}\nDate:   #{message[:commit_date]}"
              }
            else
              # git@github.com:%organization%/%repo name%.git to github.com/%organization%/%repo name%
              {
                value: "*#{message[:commit_name]}* (<https://#{fetch(:repo_url).split("git@").second.split("/").first.sub(/:/, "/")}/#{fetch(:application)}/pull/|##{message[:pr_number]}>)\nAuthor: #{message[:user_name]}\nDate:   #{message[:commit_date]}"
              }
            end
          end
        end

        def base_attachments(title:, color:, fallback: nil)
          {
            color: color,
            title: "#{application} #{title}",
            fields: [
              {
                title: 'Environment',
                value: stage,
                short: true
              },
              {
                title: 'Branch',
                value: branch,
                short: true
              },
              {
                title: 'Deployer',
                value: deployer,
                short: true
              },
              {
                title: 'Time',
                value: elapsed_time,
                short: true
              }
            ],
            fallback: fallback
          }
        end

        def convert_diff_commits(diff_commits)
          diff_commits.map do |diff_commit|
            lines = diff_commit.split("\n")

            # commit_hash = lines[0]
            author      = lines[1].match(/^Author:\s([^\s]+)/)[1] rescue nil
            date        = Time.parse(lines[2].match(/^Date:\s*(.+)/)[1]) rescue nil
            commit_name, pr_number = lines[4].scan(/^[\s]*(.*)\s\(\#([^\)]+)\)$/)[0] rescue []
            commit_name = lines[4] if commit_name.nil?

            messages = []
            if pr_number.blank?
              messages << "*#{commit_name}*"
            else
              # git@github.com:%organization%/%repo name%.git to github.com/%organization%/%repo name%
              messages << "*#{commit_name}* (<https://#{fetch(:repo_url).split("git@").second.split("/").first.sub(/:/, "/")}/#{fetch(:application)}/pull/#{pr_number}|##{pr_number}>)"
            end
            messages << "Author: <@#{author}>"
            messages << "Date: #{date}"

            messages.join("\n")
          end
        end

        def deployer
          `who -m | awk '{print $1}'`
        end
    end
  end
end

変更の構成は以下の通り

Terminal
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

  modified:   Gemfile
  modified:   Gemfile.lock
  modified:   config/environments/development.rb
  modified:   config/environments/production.rb

Untracked files:
  (use "git add <file>..." to include in what will be committed)

  Capfile
  config/deploy.rb
  config/deploy/
  lib/slackistrano/

ADD

Terminal
$ git add Gemfile*
$ git add config/environments
$ git add Capfile
$ git add config/deploy*
$ git add lib/slackistrano
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

  new file:   Capfile
  modified:   Gemfile
  modified:   Gemfile.lock
  new file:   config/deploy.rb
  new file:   config/deploy/production.rb
  new file:   config/deploy/staging.rb
  modified:   config/environments/development.rb
  modified:   config/environments/production.rb
  new file:   lib/slackistrano/custom_messaging.rb

コミット&push

Terminal
$ git commit -m "capistranoたたき台"
[master 26dbe1b] capistranoたたき台
 9 files changed, 567 insertions(+), 3 deletions(-)
 create mode 100644 Capfile
 create mode 100644 config/deploy.rb
 create mode 100644 config/deploy/production.rb
 create mode 100644 config/deploy/staging.rb
 create mode 100644 lib/slackistrano/custom_messaging.rb

$ git push --set-upstream origin master
Enumerating objects: 23, done.
Counting objects: 100% (23/23), done.
Delta compression using up to 8 threads
Compressing objects: 100% (15/15), done.
Writing objects: 100% (16/16), 9.37 KiB | 3.12 MiB/s, done.
Total 16 (delta 6), reused 0 (delta 0)
remote: Resolving deltas: 100% (6/6), completed with 5 local objects.
To https://github.com/%organization%/%repos name%.git
   578d396..26dbe1b  master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Slackistrano

  • Capistranoの自動デプロイをChatOpsに組み込みたいので、Incoming Webhookに連携します

セットアップ手順

  • config/deploy.rb を編集する
config/deploy.rb
# Configure ur Slack's Incoming Webhook
# if you want to be disable deployment notifications to a specific stage by setting the :slackistrano configuration variable to false instead of actual settings.
# When you desable slackistrano, comment out the description below.
set :slackistrano, false # falseの場合はslackistranoによるIncoming Webhookは発生しない
# set :slackistrano, { # こちらは発生する設定、上記かこちらのいずれかを記載する
#  klass:   Slackistrano::CustomMessaging,
#  channel: '#bot-#{fetch(:application)}_deploy',
#  webhook: 'https://hooks.slack.com/services/*/*/*'
#}
  • Capfile を編集する
Capfile
# Require the slackistrano need the deploy.rb
require 'slackistrano/capistrano'

NameError: uninitialized constant Slackistrano::CustomMessaging が発生した場合

  • この場合、 Capfile にrequireでGemがロードされていないのが原因の為、Capfileを編集する

  • Capfileを開き、編集(上記セットアップ手順を忘れていることが考えられる)

デバッグ実行

  • 設定が一通り終わったら、次はデバッグ実行でチェックしてみます

  • --dry-run オプションで実行せずにデプロイをシミュレーションします

  • trace オプションでデプロイ実行中の例外スロー(スタックトレース?)をします

Terminal
$ bundle exec cap staging deploy --dry-run --trace
** Invoke staging (first_time)
** Execute staging
** Invoke load:defaults (first_time)
** Execute load:defaults
[Deprecation Notice] `set :scm, :git` is deprecated.
To ensure your project is compatible with future versions of Capistrano,
remove the :scm setting and instead add these lines to your Capfile after
`require "capistrano/deploy"`:
    require "capistrano/scm/git"
    install_plugin Capistrano::SCM::Git
** Invoke rbenv:validate (first_time)
** Execute rbenv:validate
** Invoke rbenv:map_bins (first_time)
** Execute rbenv:map_bins
** Invoke bundler:map_bins (first_time)
** Execute bundler:map_bins
** Invoke deploy:set_rails_env (first_time)
** Execute deploy:set_rails_env
** Invoke deploy:set_linked_dirs (first_time)
** Execute deploy:set_linked_dirs
** Invoke deploy:set_rails_env 
** Invoke deploy (first_time)
** Invoke deploy:git_confirm (first_time)
** Execute deploy:git_confirm
00:00 deploy:git_confirm
      [git:confirm] Skip git confirm
      [git:confirm] Skip git confirm
** Execute deploy
** Invoke deploy:starting (first_time)
** Invoke slack:deploy:starting (first_time)
** Execute slack:deploy:starting
** Invoke slack:deploy:updating (first_time)
** Execute slack:deploy:updating
** Invoke deploy:upload (first_time)
** Execute deploy:upload
00:00 deploy:upload
      01 mkdir -p /var/www/capistrano_sample_app_v1/shared/config
      02 config/database.yml /var/www/capistrano_sample_app_v1/shared/config/database.yml
** Execute deploy:starting
** Invoke deploy:check (first_time)
** Invoke git:check (first_time)
** Invoke git:wrapper (first_time)
** Execute git:wrapper
00:00 git:wrapper
      01 mkdir -p /tmp
      02 #<StringIO:0x00000000025f9838> /tmp/git-ssh-capistrano_sample_app_v1-staging-webmaster-patche.sh
      03 chmod 700 /tmp/git-ssh-capistrano_sample_app_v1-staging-webmaster-patche.sh
      04 #<StringIO:0x0000000002617720> /tmp/git-ssh-capistrano_sample_app_v1-staging-webmaster-patche.sh
** Execute git:check
00:00 git:check
      01 git ls-remote git@github.com:webmaster-patche/capistrano_sample_app_v1.git HEAD
** Execute deploy:check
** Invoke deploy:check:directories (first_time)
** Execute deploy:check:directories
00:00 deploy:check:directories
      01 mkdir -p /var/www/capistrano_sample_app_v1/shared /var/www/capistrano_sample_app_v1/releases
** Invoke deploy:check:linked_dirs (first_time)
** Execute deploy:check:linked_dirs
00:00 deploy:check:linked_dirs
      01 mkdir -p /var/www/capistrano_sample_app_v1/shared/bin /var/www/capistrano_sample_app_v1/shared/log /var/www/capistrano_sample_app_v1/shared/tmp/backup /var/www/capistrano_sample_app_v1/shared/tmp/pids /var/www/capistrano_sample_app_v1/shared/tmp/cache /var/www/capistrano_sample_app_v1/shared/t…
** Invoke deploy:check:make_linked_dirs (first_time)
** Execute deploy:check:make_linked_dirs
00:00 deploy:check:make_linked_dirs
      01 mkdir -p /var/www/capistrano_sample_app_v1/shared/config
** Invoke deploy:check:linked_files (first_time)
** Execute deploy:check:linked_files
** Invoke deploy:set_previous_revision (first_time)
** Execute deploy:set_previous_revision
** Invoke deploy:started (first_time)
** Execute deploy:started
** Invoke deploy:updating (first_time)
** Invoke deploy:new_release_path (first_time)
** Execute deploy:new_release_path
** Invoke git:create_release (first_time)
** Invoke git:update (first_time)
** Invoke git:clone (first_time)
** Invoke git:wrapper 
** Execute git:clone
00:00 git:clone
      The repository mirror is at /var/www/capistrano_sample_app_v1/repo
      The repository mirror is at /var/www/capistrano_sample_app_v1/repo
** Execute git:update
00:00 git:update
      01 git remote set-url origin git@github.com:webmaster-patche/capistrano_sample_app_v1.git
      02 git remote update --prune
** Execute git:create_release
00:00 git:create_release
      01 mkdir -p /var/www/capistrano_sample_app_v1/releases/20200108015441
      02 git archive master | /usr/bin/env tar -x -f - -C /var/www/capistrano_sample_app_v1/releases/20200108015441
** Invoke slack:deploy:updating 
** Execute deploy:updating
** Invoke deploy:set_current_revision (first_time)
** Invoke git:set_current_revision (first_time)
** Execute git:set_current_revision
** Execute deploy:set_current_revision
00:00 deploy:set_current_revision
      01 echo "" > REVISION
** Invoke deploy:symlink:shared (first_time)
** Execute deploy:symlink:shared
** Invoke deploy:symlink:linked_files (first_time)
** Execute deploy:symlink:linked_files
00:00 deploy:symlink:linked_files
      01 mkdir -p /var/www/capistrano_sample_app_v1/releases/20200108015441/config
** Invoke deploy:symlink:linked_dirs (first_time)
** Execute deploy:symlink:linked_dirs
00:00 deploy:symlink:linked_dirs
      01 mkdir -p /var/www/capistrano_sample_app_v1/releases/20200108015441 /var/www/capistrano_sample_app_v1/releases/20200108015441/tmp /var/www/capistrano_sample_app_v1/releases/20200108015441/vendor /var/www/capistrano_sample_app_v1/releases/20200108015441/public
** Invoke deploy:updated (first_time)
** Invoke bundler:install (first_time)
** Execute bundler:install
00:00 bundler:install
      The Gemfile's dependencies are satisfied, skipping installation
      The Gemfile's dependencies are satisfied, skipping installation
** Execute deploy:updated
** Invoke deploy:compile_assets (first_time)
** Invoke deploy:set_rails_env 
** Execute deploy:compile_assets
** Invoke deploy:assets:precompile (first_time)
** Execute deploy:assets:precompile
** Invoke deploy:assets:backup_manifest (first_time)
** Execute deploy:assets:backup_manifest
** Invoke deploy:cleanup_assets (first_time)
** Invoke deploy:set_rails_env 
** Execute deploy:cleanup_assets
** Invoke deploy:normalize_assets (first_time)
** Invoke deploy:set_rails_env 
** Execute deploy:normalize_assets
** Invoke deploy:migrate (first_time)
** Invoke deploy:set_rails_env 
** Execute deploy:migrate
** Invoke deploy:publishing (first_time)
** Execute deploy:publishing
** Invoke deploy:symlink:release (first_time)
** Execute deploy:symlink:release
00:00 deploy:symlink:release
      01 ln -s /var/www/capistrano_sample_app_v1/releases/20200108015441 /var/www/capistrano_sample_app_v1/releases/current
      02 mv /var/www/capistrano_sample_app_v1/releases/current /var/www/capistrano_sample_app_v1
** Invoke deploy:published (first_time)
** Execute deploy:published
** Invoke deploy:finishing (first_time)
** Execute deploy:finishing
** Invoke deploy:cleanup (first_time)
** Execute deploy:cleanup
** Invoke slack:deploy:updated (first_time)
** Execute slack:deploy:updated
** Invoke deploy:finished (first_time)
** Execute deploy:finished
** Invoke deploy:log_revision (first_time)
** Execute deploy:log_revision
00:00 deploy:log_revision
      01 echo "Branch master (at ) deployed as release 20200108015441 by webmaster-patche" >> /var/www/capistrano_sample_app_v1/revisions.log
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Linuxサーバからリモートリポジトリにpush & リモートリポジトリからローカルPCにclone

目標
  • linuxサーバ上で運用されているrailsアプリのソースコードをGitlab.comのリモートリポジトリにプッシュする。
  • リモートリポジトリからローカルPCのローカルリポジトリにクローンする。
環境
  • linux(GCE, Debian)
  • Gitlab.com
  • Mac(OSX 10.15.2)
準備:git install (linuxサーバ、ローカルPCにGitをインストール)

下記サイトなどを参考にしてください。
https://git-scm.com/book/ja/v2/%E4%BD%BF%E3%81%84%E5%A7%8B%E3%82%81%E3%82%8B-Git%E3%81%AE%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB

1. linuxの操作
git config(USER_NAMEとEMAILは環境による)
ターミナル
git config --list
git config --global user.name "USER_NAME"
git config --global user.email "EMAIL"
ファイル権限(USERNAMEとUSERGROUPは環境による)

権限を間違えるとgit push時に権限エラーになります。

ターミナル
sudo chown -R USERNAME:USERGROUP ./
sudo find ./ -type d -exec chmod 755 {} +
sudo find ./ -type f -exec chmod 644 {} +
SSH鍵(gitlab_rsaは好きな名前をつける)
  • 秘密鍵は~/.ssh/に置いてください。
  • .pubの内容をGitlab.comのユーザーのssh鍵に貼り付けてください。
ターミナル
ssh-keygen -t rsa -f gitlab_rsa

mv ./gitlab_rsa ~/.ssh/
mv ./gitlab_rsa.pub ~/.ssh/
cat gitlab_rsa.pub 
=>.pubの内容をGitlab.comに貼り付け

eval $(ssh-agent -s)

ssh-add ~/.ssh/gitlab_rsa

ssh -T git@gitlab.com
git init ~ git pushまで(:repoは環境による)

gitコマンドの詳細の説明は省略します。
サーバのローカルリポジトリを初期化+初期コミットして、リモートリポジトリにプッシュしています。

ターミナル
git init

vi .gitignore 
=>rails用のテンプレートから持ってくるとラク

git add .

git commit .

git remote add origin git@gitlab.com:repo

git push origin master
2. ローカルPC操作
プロジェクト用ディレクトリ作成(好きな名前のディレクトリを作成する)
ターミナル
mkdir Gitlab
SSH鍵(gitlab_rsa_userは好きな名前をつける)
  • 秘密鍵は~/.ssh/に置いてください。
  • .pubの内容をGitlab.comのユーザーのssh鍵に貼り付けてください。
ターミナル
ssh-keygen -t rsa -f gitlab_rsa_user

mv gitlab_rsa_user ~/.ssh/

mv gitlab_rsa_user.pub  ~/.ssh/

cat gitlab_rsa_user.pub
=>Gitlabに貼り付け

eval $(ssh-agent -s)

ssh-add ~/.ssh/gitlab_rsa_user

ssh -T git@gitlab.com
git config(USERNAMEとEMAILは環境による)

リモートリポジトリからローカルPCのローカルリポジトリにクローンしています。

ターミナル
git config --global user.name "USERNAME"
git config --global user.email EMAIL
git clone(/repo.gitは環境による)
ターミナル
git clone https://gitlab.com/repo.git
bundle ~ rails sまで

ローカルPCにクローンしてきたディレクトリでbundleとrails sが実行可能か確認する。
サーバ環境と同じrubyバージョン、railsバージョンで実行すると環境依存のエラーを回避できる。
rbenvを使用するとプロジェクトディレクトリ毎にrubyバージョンを指定できるのでラク。
windowsでrbenvを使用する場合は、wslを有効化してubuntuターミナル上で作業する。
参考:
https://qiita.com/chimame/items/8130aa2c07a152a865b1

エラーが出たらエラーメッセージを読んで不足するファイルをサーバから直接持ってくる。
(.gitignoreで指定したファイルはgit管理から外れるため。)

ターミナル
bundle

rails s
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Git(Sourcetree)とGitHubを連携する

Git(Sourcetree)とGitHubを触り始めてあと数ヶ月で一年になるのですが、あまりに理解できておらずどハマり(して作成していたSwift file たちを全消去)したので、これを機に少しは理解してみようと体当たりで挑んだ忘備録です。

目的は、ローカルで既に開発が進んでいる状態のところにGitHub(新規)と連携すること。
そしてターミナルを使わず、できるかぎりSourcetreeでそれを実行すること、です。

GitもGitHubも初期の場合

  1. 管理したいディレクトリをSourcetreeに入れる/GitHubのリポジトリ(READMEも)を作成しておく ※README は後からでも作成可能
  2. Sourcetreeで「設定」→「リモート」→GitHubの名前(ここではgithubとする), SSH(HTTP) を入力し、連携
  3. (管理したいディレクトリが空の状態でない場合は) Sourcetreeにコミットがある状態かつmasterブランチ (以下 master)も出ていない状態と思われるが、その状態から「プル」を押しブランチの更新を押す(出てくるまでに数回押さないといけない場合もあり)と、masterが読み込まれ表示される。(ここでInitial commitができる)
  4. コミットがある場合はmasterGitHubのmaster (以下 github/master) ブランチがあることを確認してコミットし、プッシュする
  5. GitHubの「code」タブページを更新し、Sourcetreeでコミット&プッシュした内容が反映されているか確認する
  6. Sourcetree内でmastergithub/masterが横並び状態になっていると思うので、その状態でmasterからdevelopブランチ(以下 develop)を切る
  7. (変更等せず)developをプッシュしてgithubの「code」タブページの「branch」を確認すると、developができていると思うので出来ていたらdevelopをデフォルト設定にしたい場合はここでする。 ※変更してmasterと同じでなくなった場合は考えて調整する
  8. 最終的に、develop, mastergithub/develop, github/master が一列に横並びになればOK

Gitで既に開発を進めていて新たにGitHub(新規)と連携させる場合

※結果だけ知りたい場合は下の方から読んでください※

developmasterが横並びでない状態の場合

【developとmasterを先に横並びにして連携する】

developmasterを同じ状態にしてgithubと連携。
連携反映のためブランチを適当に切り替えていると、github/masterが出てきた。
が、繋がっていない。
スクリーンショット 2020-01-07 10.45.03.png (119.5 kB)

mastergithub/masterをマージさせて解決させようと思ったが
スクリーンショット 2020-01-07 10.45.27.png (170.3 kB)

と言われて出来なかったのでターミナルで行うことに。git statusで状況確認。
スクリーンショット 2020-01-07 10.47.23.png (23.8 kB)

xcode は全くいじっていないのだが、リモート設定でgithubを連携させた際にこの変更がでた(UserInterfaceState.xcuserstate は何かアクションがあると変更されてしまうらしい。UserInterfaceState.xcuserstate.gitignoreに後ほど書き足すことにする。)(2つ前の画像のコミットされていない変更はこれのことである)。

コミットしないと変更できないのかなと思い(あとで気がついたがスタッシュするか、ファイル破棄してもよかった)、git addを実行。
しかし更に怒られ、言われるがままgit add .を実行。git statusで確認。問題なさそうだったのでgit merge --allow-unrelated-histories github/masterを実行。

すると、「先ほど、git add .で実行して変更したのでできません✋」のような内容のメッセージが出たので一旦ターミナルを終了し、developはどうなるか試してみた。developをプッシュすると、それはgitにもgithubにも認知され、develop, masterと線が繋がった状態で表示された。
気を取り直してもう一度ターミナルを開きgit merge --allow-unrelated-histories github/masterを試みてみると、viモードが開き、繋げられた。
スクリーンショット 2020-01-07 11.17.55.png (18.3 kB)

Sourcetreeで見てみるとこのような形に。。。mastergithub/masterに統合されてしまったようである。
スクリーンショット 2020-01-07 11.17.19.png (161.9 kB)

develop はまだXcodeが入ったディレクトリを保有していたので、それならプッシュしてマージしちゃえば万事解決!と勇んでgithubに行った結果、、
スクリーンショット 2020-01-07 11.39.23.png (98.2 kB)

だがしかし、先ほどの失敗でわかったことがある。
git merge --allow-unrelated-histories XXX は「今のブランチにXXXをマージする」っぽい!←
ということで、branch: master, XXX: develop にしてターミナルでgit merge --allow-unrelated-histories XXXを実行。
スクリーンショット 2020-01-07 11.42.31.png (233.8 kB)

なんとか繋がった!!?
githubを見に行くと、master(github/master)にちゃんとXcode が入ったディレクトリがありました!成功!!

ということで、最初developmasterは同じ状態: 横並びであったので、全てのブランチを同じ状態にするために masterdevelopをマージしたりプッシュしたりポチポチ(mastergithub/masterをマージ→developmasterをマージ→developをプッシュ) して同状態にする。

スクリーンショット 2020-01-07 11.44.13.png (215.4 kB)

(ここはきっとgit rebaseとか使うともっと一瞬で綺麗になるんだろうなとも思いつつ..)
長かった.... Orz |||||

git merge --allow-unrelated-histories XXX このコマンドは「現ブランチとXXXをXXXで完全に置き換える」もので、コンフリクトの解消とは少し違うのだなと再認識。”関係ない履歴”と言われているところから気付けよ?

ということは、リモートを繋げる際にどうしてもmasterdevelopを同状態にしたくない場合は新たにブランチを作成して、まずそこで繋げてからdevelopなり他のブランチなりをマージするようにすれば安全に連携できるのでは??
ということで↓

【developとmasterを横並びにしない状態で連携する】

masterdevelopを同状態にせずにgithubと連携する方法を探ってみた。
developと同状態のブランチ(以下 toConnectBranch)を連携用に作っておく。
githubとのリモート設定を行うととりあえず線が切れているので、まずtoConnectBranchを用いてgiuhub/mastergit merge --allow-unrelated-histories XXX (XXX: github/master) で実行して繋げる。
ブランチの状態を確認するためSourcetreeで既存ブランチを切り替えているとmaster以外のブランチに切り替えられない事態に(エラーの内容のスクショは取り忘れ)。
またUserInterfaceState.xcuserstateに変更がかかったのでとりあえずmasterにコミット。
スクリーンショット 2020-01-07 13.23.51.png (200.2 kB)

上の画像の状態になったののとSourcetree上ではブランチの切り替えが出来なかったが何故かターミナル上ではブランチの切り替えができたので(Sourcetreeがバグってたのか?? ) git rebaseを使う時がついに来たなと思いターミナルでgit rebase -i YYYを実行。
スクリーンショット 2020-01-07 14.19.07.png (9.0 kB)

これは成功したのでgit rebaseを行う前に一旦Sourcetreeで確認してみると、他のブランチに切り替えられるようになっていたのでmastertoConnectBranchをSourcetree上でマージ。
スクリーンショット 2020-01-07 14.05.40.png (263.2 kB)

うまく行ったようなので、ここで初めてdevelopをプッシュ。github/developができる。

※そしてプルリクも出来上がる(github/mastermaster, developより下にいるため) ので、developをプッシュする前にmasterをプッシュした方が手間も省け、見やすくもなりそう。
スクリーンショット 2020-01-07 14.28.05.png (247.6 kB)

結局masterdevelopは横並びになったのでdevelopからではなくmasterからブランチ切っておくのが正解か??

【developとmasterを横並びにしない part2】

先ほどのは結局developmasterが同状態になってしまったので、今回はmasterからtoConnectBranchを作成して行ってみる。
toConnectBranchgithub/masterをマージした結果。
スクリーンショット 2020-01-07 15.07.50.png (164.3 kB)

mastertoConnectBranchは同状態であったのでmastertoConnectBranchをマージする。
成功したのでUserInterfaceState.xcuserstate の変更をコミットしてプッシュ。
スクリーンショット 2020-01-07 15.14.17.png (178.2 kB)

元々developmasterより上にいたのでdevelopmasterをマージ。
UserInterfaceState.xcuserstate がコンフリクトを起こしたので相手(master)側で解決。
スクリーンショット 2020-01-07 15.17.38.png (189.8 kB)

developをプッシュ。
スクリーンショット 2020-01-07 15.18.43.png (201.9 kB)

Xcodeもgithubのリポジトリ内もちゃんとなってました!!
github上でデフォルトブランチをdevelop(github/develop)に変更するのも大丈夫でした!
長かった!!!?

結論

ローカル(Git)で作業していてそれに新規のリモートリポジトリ(GitHub)を連携させる場合は、

  • Sourcetree内で完結はできない(ターミナル使う)
  • git merge --allow-unrelated-histories XXXを使う
  • 連携用のブランチを作って実行したほうが綺麗に見える
  • UserInterfaceState.xcuserstateはファイル破棄しても問題なさそう(.gitignoreファイルに書けばいちいち出てこない)

の4点が重点かつ新規ローカルと新規リモートリポジトリを連携する際と異なる点と思われました!

知識も経験もまだまだとても浅いので、もっといいやり方あるよ!とか解釈おかしいよ!といった点があれば是非教えてください?‍♂️


環境
macOS: Catalina ver 10.15.2
Xcode: ver 11.3 (11C29) *SwiftUI 使用
Sourcetree: ver 3.2.1 (225)

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

embulkを使ってcsvからBigqueryへloadする

環境

  • macOS Catalina

インストール

  • Java
$ brew cask install homebrew/cask-versions/adoptopenjdk8
  • embulk
$ brew install embulk
  • Bigqueryプラグイン
embulk gem install embulk-output-bigquery

config.ymlの作成

Bigqueryへloadするファイルをdata.csvとして用意する。

data.csv
id,name,price,start_date
103001,ほげほげ,890,2019-07-20
103001,ふがふが,1100婦人公論,2019-09-06

seed.ymlを作成する。

seed.yml
in:
  type: file
  path_prefix: "data.csv"
out:
  type: stdout

config.ymlを作成する。

$  embulk guess seed.yml -o config.yml

config.ymlをBigquery用に修正する。

config.yml
in:
  type: file
  path_prefix: data.csv
  parser:
    charset: UTF-8
    newline: LF
    type: csv
    delimiter: ','
    quote: '"'
    escape: '"'
    trim_if_not_quoted: false
    skip_header_lines: 1
    allow_extra_columns: false
    allow_optional_columns: false
    columns:
    - {name: id, type: long}
    - {name: name, type: string}
    - {name: price, type: long}
    - {name: start_date, type: timestamp, format: '%Y-%m-%d'}
out:
  type: bigquery  # Bigquery
  auto_create_table: true  # テーブルが存在しなかったら作成する
  mode: append  # データは追加
  auth_method: application_default # 認証方式
  project: gcp-tutorial  # GCPプロジェクトID
  dataset: test_dataset  # データセット名
  table: books  # テーブル名

詳しいオプションは
https://github.com/embulk/embulk-output-bigquery
を参照する。

実行

$ embulk run config.yml

データがloadされたかGCPコンソールで確認する。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

embulkを使ってcsvをBigqueryへloadする

環境

  • macOS Catalina

インストール

  • Java
$ brew cask install homebrew/cask-versions/adoptopenjdk8
  • embulk
$ brew install embulk
  • Bigqueryプラグイン
embulk gem install embulk-output-bigquery

config.ymlの作成

Bigqueryへloadするファイルをdata.csvとして用意する。

data.csv
id,name,price,start_date
103001,ほげほげ,890,2019-07-20
103001,ふがふが,1100婦人公論,2019-09-06

seed.ymlを作成する。

seed.yml
in:
  type: file
  path_prefix: "data.csv"
out:
  type: stdout

config.ymlを作成する。

$  embulk guess seed.yml -o config.yml

config.ymlをBigquery用に修正する。

config.yml
in:
  type: file
  path_prefix: data.csv
  parser:
    charset: UTF-8
    newline: LF
    type: csv
    delimiter: ','
    quote: '"'
    escape: '"'
    trim_if_not_quoted: false
    skip_header_lines: 1
    allow_extra_columns: false
    allow_optional_columns: false
    columns:
    - {name: id, type: long}
    - {name: name, type: string}
    - {name: price, type: long}
    - {name: start_date, type: timestamp, format: '%Y-%m-%d'}
out:
  type: bigquery  # Bigquery
  auto_create_table: true  # テーブルが存在しなかったら作成する
  mode: append  # データは追加
  auth_method: application_default # 認証方式
  project: gcp-tutorial  # GCPプロジェクトID
  dataset: test_dataset  # データセット名
  table: books  # テーブル名

詳しいオプションは
https://github.com/embulk/embulk-output-bigquery
を参照する。

実行

$ embulk run config.yml

データがloadされたかGCPコンソールで確認する。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む