コピペコードで快適生活

明日使えるソースを自分のために

WindowsでAndroid開発環境を整える

仕事でAndroidアプリを扱うことになったけど、開発環境構築で色々とハマった。同じことを繰り返さないように設定メモを残しておく。

インストール

JDK

ここからダウンロードしてインストールする。
http://www.oracle.com/technetwork/jp/java/javase/downloads/index.html

AndrodiStudio

ここからダウンロードしてインストールする。
https://developer.android.com/studio/index.html

JDKの参照設定

AndroidStudioがJDKを参照できるように設定する。

環境変数

JAVA_HOME に jdkのインストールディレクトリを設定。
 (例: C:\Program Files\Java\jdk1.8.0_112)

・PATH に jdkインストールディレクトリ直下のbin を設定。
 (例: C:\Program Files\Java\jdk1.8.0_112\bin)

AndroidStudioのJDK Location

File -> Project Structureを開いて SDK LocationのJDK location に JDKのインストールディレクトリを設定。

Gitの設定

AndroidStudioは内部でgitコマンドを打つっぽい。コマンドプロンプトでgitコマンドが使えるように設定する。Cygwinっ子の僕はこんな感じで。
http://kinosuke.hatenablog.jp/entry/2016/12/02/151109

開発チュートリアル

Googleから初心者向けのチュートリアルが公開されている。ありがたい。
https://developer.android.com/training/basics/firstapp/index.html

AARファイルの作り方&取り込み方

Googleにドキュメントがある。ありがたい。
https://developer.android.com/studio/projects/android-library.html

なお、AARファイルを取り込むときに modules:aarファイル名 とすると、modulesディレクトリの下にモジュールが保存されるみたい。

実機テスト

こちらをご参考に。
https://blog.codecamp.jp/android_test

コマンドプロンプトでCygwinのシェルを使う

DLLコピー

C:\app\cygwin\bin\cygwin1.dll

C:\Windows\System32

配下にコピーする。

環境変数設定

システム環境変数のPATHに下記を追加。

C:\app\cygwin\bin
C:\app\cygwin\usr\bin
C:\app\cygwin\usr\local\bin

最後に

再度ログインする。これで使える。

CygwinはC:\app\以下にインストールされている前提。
※参照:http://news.mynavi.jp/articles/2013/11/25/zerokaracygwin/

Gruntの基本をおさえておく

仕事でGrunt使う機会があったので、きちんと基本を押さえておくことにしました。

Gruntってなに?

WEBフロント開発で使うJavaScriptCSSの変換ツール
目的は、JSやCSSを書きやすい形で実装して、ブラウザで実行できる形に変換する環境を提供すること。
主にやることは下記。

  • CoffeScript/TypeScriptのJS変換
  • SCSS/LESSのCSS変換
  • JavaScript/CSSの圧縮(minify)

環境構築

例えばこんな感じで。nodejsが必要なのでnvmでインストール、gruntコマンドを使うためにgrunt-cliをインストールしています。

cd ~
curl -o- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
export NVM_DIR="/home/vagrant/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
nvm install 6.9.1
nvm alias default 6.9.1
npm update -g npm
npm install -g grunt-cli

プロジェクトつくる

my-projectというディレクトリにpackage.jsonを作成します。
package.jsonはこのプロジェクトで使用したいプラグインを記述するファイルです。

mkdir my-project
cd my-project/
npm init

Gruntをインストール

npm install grunt -save-dev
npm install grunt-contrib -save-dev
npm install grunt-contrib-concat -save-dev
npm install grunt-contrib-cssmin -save-dev
npm install grunt-contrib-uglify -save-dev
npm install grunt-contrib-watch -save-dev
npm install grunt-contrib-connect -save-dev

Gruntがインストールされます。-save-devオプションでpackage.jsonにも追記されます。
ついでにpluginもインストールしています。
※warning出まくるけど無視(していいのかわからんけど)。

Gruntfile.jsの作成

Grunt実行時の処理を記述するGruntfile.jsを作成します。
たとえばこんな感じ。

module.exports = function(grunt) {
  //Gruntの設定
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    // ファイル結合だけ
    concat: {
      js: {
        src: ['src/js/*.js'],
        dest: 'build/application.js'
      },
      css: {
        src: ['src/css/*.css'],
        dest: 'build/application.css'
      }
    },

    // CSSの結合+圧縮
    cssmin: {
      minify: {
        src: ['src/css/*.css'],
        dest: 'build/application.min.css'
      }
    },

    // JSの結合+圧縮
    uglify: {
      build: {
        src: ['src/js/*.js'],
        dest: 'build/application.min.js'
      }
    },

    // ファイル変更を感知して自動的にタスク実行する設定
    // いちいちgruntコマンド叩かなくてよくなる
    watch: {
      css: {
        files: ['src/css/*.css'],
        tasks: ['concat:css', 'cssmin']
      },
      js: {
        files: ['src/js/*.js'],
        tasks: ['concat:js', 'uglify']
      }
    },

    // 簡易サーバ
    // grunt connect で起動する
    connect: {
      local: {
        options: {
          port: 9998,
          livereload: true,
          keepalive: true,
        }
      }
    },
  });

  // プラグインを読み込む
  // usage: http://gruntjs.com/plugins
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-connect');

  // grunt 実行されるタスク
  grunt.registerTask('default', ['concat', 'cssmin', 'uglify']);

  // grunt dev で実行されるタスク
  grunt.registerTask('dev', ['concat', 'cssmin', 'uglify', 'watch']);
};

Grunt実行

あとは変換対象の src/js/*.js, src/css/*.css を配置してgrunt実行。

grunt         # => これでCSS/JSの変換処理
grunt dev     # => ファイル変更があったときに自動的に変換処理
grunt connect # => 簡易サーバ立ち上がる

ディレクトリの容量を表示する - duコマンド

書式

du [オプション] [ディレクトリ名|ファイル名]

主なオプション

-a # ディレクトリ内の各ファイルに対しても使用量を表示する
-b # 結果をバイト単位で表示する
-k # 結果をキロバイト単位で表示する(デフォルト)
-s # 合計サイズのみを表示する
-h # 人間に分かりやすい表記で出力する

容量を圧迫しているディレクトリ・ファイルを調査する

まずはおおよその見当をつけて調査。下記では、カレントディレクトリが対象。

$ du -sh *
16K Maildir
396K script
24M SRC
32K tartest

WordPressのサイトURLを変更する一撃SQL

WordPressのDBにはサイトURLの情報があちこちに散りばめられて登録されています。
なので、ローカルで作ったサイトを本番に反映するとき、サイトのドメインを変えるときなど、サイトのURLを変えて動作させたいときはやっかいです。DBの中のURL情報をまとめて書き換える必要があります。
ここに記すは、WordPressのURL情報を書き換える一撃SQLです。
※@before, @after の内容は適宜読み替えてください。

-- 変数の定義
SET @before="before.jp";
SET @after="after.jp";
SET @scheme="http://";

-- wp_options siteurl行のoption_valueを更新
UPDATE wp_options SET option_value = CONCAT(@scheme, @after) WHERE option_name = 'siteurl';

-- wp_options home行のoption_valueを更新
UPDATE wp_options SET option_value = CONCAT(@scheme, @after) WHERE option_name = 'home';

-- 記事に書かれている画像タグの書き換え
UPDATE wp_posts SET post_content = REPLACE(post_content, @before, @after);

-- メディアに登録されるURLの書き換え
UPDATE wp_posts SET guid = REPLACE(guid, @bofore, @after);

Vagrant+シェルでRails開発サーバを作る

新規案件でRails開発サーバを準備する必要があり、Vagrantとシェルのプロビジョニングで作成したときのメモです。
プロビジョニングにシェルを使用したのは、開発用PCがWindowsのためです。
無理してchefとか使おうとすると、環境構築を楽にするための環境構築が大変になるというよくわからないことになりそうでしたので。

下記ページを大いにパクらせて参考にさせていただきました。多謝です!
Rails開発のための仮想環境をvagrantでつくる - Qiita

主にインストールされるもの

※CentOS7/MySQL5.7の罠は回避。

よし作ろう

前提:VirtualBoxVagrantはインストール済

1.boxファイルを取得
vagrant box add CentOS_6_7 https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
2.初期設定
cd ~
mkdir centos6-rails
cd centos6-rails
vagrant init CentOS_6_7
3.Vagrantfileを作成

下記のように書き換える

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  GUEST_RUBY_VERSION = '2.3.1'

  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "CentOS_6_7"
  config.vm.hostname = "centos6-rails"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 3000, host: 3000

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"
  config.vm.network "public_network", ip: "192.168.135.227"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    vb.gui = false
  
    # Customize the amount of memory on the VM:
    vb.memory = "4096"
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL

FUNCTION_INSTALL =<<EOS
function install {
  echo installing $1
  shift
  yum -y install "$@" >/dev/null 2>&1
}
EOS

  # development tools etc...
  config.vm.provision "shell", privileged: true, inline: <<-SHELL
    #{FUNCTION_INSTALL}
    yum -y update >/dev/null 2>&1

    install "development tools"  gcc-c++ glibc-headers openssl-devel readline libyaml-devel readline-devel zlib zlib-devel
    install "Git" git
    install "sqlite" sqlite sqlite-devel
    install "Nokogiri dependencies" libxml2 libxslt libxml2-devel libxslt-devel
    install "ImageMagick" ImageMagick ImageMagick-devel
    install "vim" vim-common vim-enhanced

    cp /etc/localtime /etc/localtime.org
    ln -sf  /usr/share/zoneinfo/Asia/Tokyo /etc/localtime
    echo "ZONE=\"Asia/Tokyo\"" > /etc/sysconfig/clock
    service crond restart
  SHELL

  # MySQL5.6
  config.vm.provision "shell", privileged: true, inline: <<-SHELL
    #{FUNCTION_INSTALL}
    yum install -y http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm >/dev/null 2>&1
    install "MySQL" mysql mysql-server mysql-devel
    chkconfig --add mysqld
    chkconfig --level 345 mysqld  on

    echo "Start and Initialize MySQL"
    service mysqld start >/dev/null 2>&1
    mysql -uroot <<SQL
-- SET ROOT PASSWORD --
UPDATE mysql.user SET Password=PASSWORD('vagrant') WHERE User='root';
-- REMOVE ANONYMOUS USERS --
DELETE FROM mysql.user WHERE User='';
-- REMOVE REMOTE ROOT --
DELETE FROM mysql.user
WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- REMOVE TEST DATABASE --
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- RELOAD PRIVILEGE TABLES --
FLUSH PRIVILEGES;
CREATE USER 'vagrant'@'localhost';
SET PASSWORD FOR 'vagrant'@'localhost' = PASSWORD('vagrant');
GRANT ALL PRIVILEGES ON *.* to 'vagrant'@'localhost';
SQL
  SHELL

  # memcached
  config.vm.provision "shell", privileged: true, inline: <<-SHELL
    #{FUNCTION_INSTALL}
    install "memcached" memcached memcached-devel
    chkconfig --add memcached
    chkconfig --level 345 memcached  on
    echo "Start and Initialize memcached"
    service memcached start >/dev/null 2>&1
  SHELL

  # rbenv
  config.vm.provision "shell", privileged: false, inline: <<-SHELL
    echo installing rbenv
    git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
    git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
    echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
    source ~/.bash_profile
    echo 'gem: --no-ri --no-rdoc' >> ~/.gemrc
    echo installing ruby#{GUEST_RUBY_VERSION}
    rbenv install #{GUEST_RUBY_VERSION}
    rbenv global #{GUEST_RUBY_VERSION}
    echo installing Bundler
    gem install bundler -N >/dev/null 2>&1
    echo installing ruby-gemset
    cd ~/.rbenv/plugins/
    git clone https://github.com/jf/rbenv-gemset.git    
  SHELL

  # ntp
  config.vm.provision "shell", privileged: true, inline: <<-SHELL
    #{FUNCTION_INSTALL}
    install "ntp" ntp
    chkconfig ntpd on
    echo "Start and Initialize ntp"
    service ntpd start >/dev/null 2>&1
  SHELL
end
4.起動&プロビジョニング
vagrant up

以上になります。

Windows環境でVagrant+Chefとか使おうとすると設定が思った以上に大変で、
危うく環境構築の手間を削減するための環境構築に手間をかけるという本末転倒なことになりかけていました。
トレンドにとらわれずに問題解決のために技術選定するって大切ですね。

Vagrentの基本的な使い方メモ

準備

1.仮想化支援機構の有効化

2.VirtualBoxのインストール

3.Vagrantのインストール

4.CentOSVirtualBoxへの登録

# 例
vagrant box add CentOS_6_3 https://dl.dropbox.com/sh/9rldlpj3cmdtntc/chqwU6EYaZ/centos-63-32bit-puppet.box

※公開box: http://www.vagrantbox.es/

5.Vagrant初期設定

> mkdir -p ~/Vagrant/centos6
> cd ~/Vagrent/centos6
> vagrant init CentOS_6_3
> ls # Vagrantfileファイルが存在することを確認

テキストエディタでVagrantfileを編集する。

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Authentication failure. Retrying が出るときはパスワード指定
  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"

  config.vm.box = "CentOS_6_3"

  #コメントアウトを外す
  config.vm.network "private_network", ip: "192.168.33.10"
end

Vagrantコマンド

# CentOS起動
vagrant up

# CentOS停止
vagrant halt

# サーバ廃棄
vagrant destroy

# boxファイルを作る
vagrant package

# ローカルのboxファイルを登録する
vagrant box add MyOS package.box

その他メモ

boxファイルの保存場所

Mac
/Users/<username>/.vagrant.d/boxes/
Windows
C:\Users\<username>\.vagrant.d\boxes\

日本語ドキュメント
http://lab.raqda.com/vagrant/index.html

Windows上でVirtualBox+Vagrant+CentOSによる仮想環境構築
http://qiita.com/hiroyasu55/items/11a4c996b0c62450940f