Program LOG

勉強した内容をまとめ中。。。間違ってたら教えて。。。

Chefでオレオレ証明書を作成して簡易的にhttpsのアクセスを有効にする

フロントサイド用の環境構築がひと段落したので、
今度は、サーバーサイドの環境構築をもっと作りこんでいきたいと思います。
本日の題材も開発環境だとよくあると思いますが、HTTPSのアクセスを簡易的に行うようにする為、
SSL自己証明書(オレオレ証明書と言ったりしますが・・・w)を作成する事があると思います。
まぁ、認証が正常にされないので、ブラウザからアラートがおきますが・・・w
それを今回はChefで作成できるようにしちゃいたいと思います。

コマンド1発!オレオレ証明書

色んなサイトを見ましたが、実は一発でコマンドを実行すると、
オレオレ証明書を作成する事が出来る事が判明!
そのコマンドをレシピに記載しておき、今後も使えるようにしていきたいと思います。

まず、今回は開発用で、本番では使用しないので、別のレシピを作成したいと思います。
ssl.rbというファイルをrecipesに作成して記述していきます。

package "mod_ssl" do
    action :install
end

strength = 2048
serial = 0
days = 365
subject = "/C=JP/CN=localhost"
crt_file = "/etc/pki/tls/certs/localhost.crt"
key_file = "/etc/pki/tls/private/localhost.key"
crt_and_key_file = "/etc/pki/tls/private/localhost.crt_and_key"

bash "create_self_signed_cerficiate" do
  code <<-EOH
    openssl req -new -newkey rsa:#{strength} -sha1 -x509 -nodes \
      -set_serial #{serial} \
      -days #{days} \
      -subj "#{subject}" \
      -out "#{crt_file}" \
      -keyout "#{key_file}" &&
    cat "#{crt_file}" "#{key_file}" >> "#{crt_and_key_file}" &&
    chmod 400 "#{key_file}" "#{crt_and_key_file}"
  EOH
  creates crt_and_key_file
  notifies :reload, 'service[httpd]'
end

実はたったこれだけ・・・・w
これでいつものようにknife soloを実行します。

$ knife solo cook develop
Running Chef on develop...
Checking Chef version...
DL is deprecated, please use Fiddle
・・・中略・・・
  * package[mod_ssl] action install
    - install version 2.2.15-30.el6.centos of package mod_ssl

Recipe: develop::sslbash[create_self_signed_cerficiate] action run
    - execute "bash"  "/tmp/chef-script20140706-5421-1ly8kml"

これだけでは、httpsにはアクセス出来ないので、アクセスできるように、
VurtualHostの設定を行いたいと思います。
今までのchefを正常に実行していれば、以下のように設定されています。

$ vagrant ssh
[vagrant@localhost ~]$ sudo vim /etc/httpd/conf.d/vhost.conf
NameVirtualHost *:80
<VirtualHost *:80>
  ServerName develop.jp
  DocumentRoot /var/www/html/
  ErrorLog /var/log/php_error.log
  TransferLog /var/log/php_access.log
  <Directory /var/www/html/>
    AllowOverride all
    Order allow,deny
    allow from all
  </Directory>
</VirtualHost>

<VirtualHost *:80>
  ServerName php.develop.jp
  DocumentRoot /usr/share/phpMyAdmin/
  ErrorLog /var/log/php_error.log
  TransferLog /var/log/php_access.log
  <Directory /usr/share/phpMyAdmin/>
    AllowOverride all
    Order allow,deny
    allow from all
  </Directory>
</VirtualHost>

そこに以下を追記します。

NameVirtualHost *:443
<VirtualHost *:443>
    ServerName develop.jp
    DocumentRoot /var/www/html/
    ErrorLog logs/ssl_error_test_log
    CustomLog logs/ssl_access_test_log combined
    LogLevel warn
    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCertificateFile /etc/pki/tls/certs/localhost.crt
    SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
    <Directory /var/www/html/>
        AllowOverRide ALL
    </Directory>
</VirtualHost>

追記したら、httpdを再起動します。

[vagrant@localhost ~]$ sudo service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain for ServerName
                                                           [  OK  ]

これで「https://develop.jp/」に接続できるはずです。
Chromeアクセスした時に「このサイトのセキュリティ・・・」って出てくれば正常に完了しています。
今回は、オレオレ証明書をchefで一発作成って感じで行いました。
この一発コマンドはchef以外でも使えるので重宝しそうです!

次回は、phpmyadminのセットアップなど、もっと開発環境の充実をはかりたいと思います。

使用環境

ChefでSass+Compass+Coffee+Gruntの実行環境を作る(2)

さて、前回はchefでrbenvを用いたrubyのインストール。
sassとcopassのインストールを行いました。
今回はnodeのバージョン管理とインストール、gruntやcoffeeのインストールを
行えるようにしたいと思います。

前回はこちら

Nodejsをインストールしよう!

さて、nodejsをインストールしていきたいと思います。
nodejsを簡単にインストールしてもいいんですが、
rbenvのようなバージョン管理が出来たらとても便利ですので、
そのあたりを探しながらChefに落としていこうと思います。

・・・・・・検索中・・・・・・

どうやら、nodebrewってのが簡単らしい・・・!
入れてみますか!

nodebrewを入れてみる。

nodebrewをインストールしたことも無いのに、いきなりchefで実行しちゃおうって
危険な香りがしますが、やっちゃおうかと思いますw
早速node.rbって新しいレシピを作成しました。
そちらに書いていきたいと思います。

#ファイルをクローン
git "/home/vagrant/nodebrew" do
  repository "https://github.com/hokaccha/nodebrew.git"
  revision   "master"
  user       "vagrant"
  group      "vagrant"
  action     :sync
  not_if "ls /home/vagrant/nodebrew"
end
#nodebrewのインストール
bash "nodebrew_setup" do
  not_if "ls /home/vagrant/.nodebrew"
  user "root"
  code <<-EOL
   su vagrant -l -c 'perl /home/vagrant/nodebrew/nodebrew setup'
   su vagrant -l -c 'echo 'export PATH="$HOME/.nodebrew/current/bin:$PATH"' >> /home/vagrant/.bash_profile'
  EOL
end

インストール自体は数行で書けるみたいなので、これでうまくいってくれればいいなぁ・・・。
さて実行!

$ knife solo cook develop
・・・中略・・・
Starting Chef Client, version 11.12.4
Compiling Cookbooks...
Converging 2 resources
Recipe: develop::node
  * git[/home/vagrant/nodebrew] action sync
    - clone from https://github.com/hokaccha/nodebrew.git into /home/vagrant/nodebrew
    - checkout ref 8cec3cd23b38c5b95c5ceedb1dccc7eee92e5e5c branch master
  * bash[nodebrew_setup] action run
    - execute "bash"  "/tmp/chef-script20140628-6770-j7ukgx"

うまく入りました!
実はログは取れなかったんですが、「https://raw.github.com/hokaccha/nodebrew/master/nodebrew」へ
なぜかアクセスできなかったので、ちょっとやり方を変えて実行しました。

一応正常に入っているか確認の為、バージョン確認をしておきます。

[vagrant@localhost ~]$ nodebrew -v
nodebrew 0.7.4

Usage:
    nodebrew help                         Show this message
    nodebrew install             Download and install a  (compile from source)
    nodebrew install-binary      Download and install a  (binary file)
    nodebrew uninstall           Uninstall a version
    nodebrew use                 Use 
    nodebrew list                         List installed versions
    nodebrew ls                           Alias for `list`
    nodebrew ls-remote                    List remote versions
    nodebrew ls-all                       List remote and installed versions
    nodebrew alias          Set alias to version
    nodebrew unalias                 Remove alias
    nodebrew clean  | all        Remove source file
    nodebrew selfupdate                   Update nodebrew
    nodebrew migrate-package     Install global NPM packages contained in  to current version
    nodebrew exec  --   Execute  specified 

Example:
    nodebrew install v0.10.22     Install a specific version number
    nodebrew use v0.10.22         Use a specific version number

入っているようです!
それでは、続いてインストールをしちゃいましょう!
「nodebrew install v0.10.22」とコマンドを実行すればいいらしいんですが、
非常に時間がかかるので、バイナリインストールというのを行います。

bash "nodebrew_setup" do
  not_if "ls /home/vagrant/.nodebrew/node/v0.10.22/"
  user "root"
  code <<-EOL
   su vagrant -l -c 'nodebrew install-binary v0.10.22'
   su vagrant -l -c 'nodebrew use v0.10.22'
  EOL
end

それでは実行したいと思います。

$ knife solo cook develop
・・・中略・・・
Recipe: develop::node
  * git[/home/vagrant/nodebrew] action sync (skipped due to not_if)
  * bash[nodebrew_setup] action run (skipped due to not_if)
  * bash[nodebrew_setup] action run
    - execute "bash"  "/tmp/chef-script20140628-7797-1u9gzak"

正常に処理が終わったようですので、nodeがインストールされているか確認しておきます。

[vagrant@localhost ~]$ node -v
v0.10.22

来ました!!!
正常にインストールされています!
これでgrunt+coffeescriptのインストールが行う準備が整いました!

CoffeeScriptをインストール

vagrantユーザーとしてインストールしてしまっていたので、
npm_packageを使用する事が出来ない状態にはまってしまいました。
今さら変更したくないので、bashでインストールしちゃおうかと思います。

bash "coffeeInstall" do
  not_if "ls /root/.coffeeInstall_check"
  user "root"
  code <<-EOL
   su vagrant -l -c 'npm install -g coffee-script'
  EOL
end
bash "coffeeInstall_check" do
  not_if 'ls /root/.coffeeInstall_check'
  user        "root"
  code <<-EOL
    echo "rbenv_setup" > /root/.coffeeInstall_check
    chown 400 /root/.coffeeInstall_check
  EOL
end

それでは実行したいと思います。

$ knife solo cook develop
・・・中略・・・
Starting Chef Client, version 11.12.4
Compiling Cookbooks...
Converging 4 resources
Recipe: develop::grunt
  * gem_package[sass] action install (up to date)
  * gem_package[compass] action install (up to date)
  * bash[coffeeInstall] action run
    - execute "bash"  "/tmp/chef-script20140628-9190-15g4h38"

  * bash[coffeeInstall_check] action run
    - execute "bash"  "/tmp/chef-script20140628-9190-1bjs20i"
    
Running handlers:
Running handlers complete

Chef Client finished, 2/4 resources updated in 3.44067835 seconds

正常にインストール出来ているか確認しておきます。

[vagrant@localhost ~]$ coffee -v
CoffeeScript version 1.7.1

はい!問題なくインストール出来ていました!
それでは最後にgruntjsをインストールしておきます。

Grunt.jsをインストール

先ほどと同様に、grunt.jsもインストールします。

bash "gruntInstall" do
  not_if "ls /root/.gruntInstall_check"
  user "root"
  code <<-EOL
   su vagrant -l -c 'npm install -g grunt-cli'
  EOL
end
#判定用
bash "gruntInstall_check" do
  not_if 'ls /root/.gruntInstall_check'
  user        "root"
  code <<-EOL
    echo "rbenv_setup" > /root/.gruntInstall_check
    chown 400 /root/.gruntInstall_check
  EOL
end

coffeeと同じように、問題なく実行されるはずです!

$ knife solo cook develop
・・・中略・・・
  * bash[gruntInstall] action run
    - execute "bash"  "/tmp/chef-script20140628-9680-q7vd9k"

  * bash[gruntInstall_check] action run
    - execute "bash"  "/tmp/chef-script20140628-9680-xww112"

バージョンの確認をしておきます。

[vagrant@localhost ~]$ grunt
grunt-cli: The grunt command line interface. (v0.1.13)

はい!正常にはいっています。
前回と今回にわたって、Chefでruby+nodeをインストールし、
目的のSass+Compass+Coffee+Gruntとインストール関係は以上で完了となりました!
次回は、実際に開発する上で便利な方法を考えながら、作成したいと思います。
vagrantのプロビジョニングをchefでやったり、
ファイル管理に関しても考えてみたいと思います。

使用環境

ChefでSass+Compass+Coffee+Gruntの実行環境を作る(1)

さて、前回の記事でWindows+CygwinユーザーにはNodejsの実行がしづらいので、
Vagrant上に作ってしまえばいいんじゃないのかと思いました。
ただ、開発の都度セットアップするのがめんどいので、
Chefで流せるようにしちゃえばいいんだと思い、今回作成してみました!
今後の為に・・・記事に残しておきたいと思います。

Vagrantの環境を作成

まずは、Vagrantを作成する環境作り、これはいままで通りなので、コマンドだけ残しておきます。

$ mkdir develop
$ cd ./develop
$ vagrant init centos
$ vi ./Vagrantfile
vi) config.vm.network "private_network", ip: "192.168.33.14"
$ vagrant up
#鍵認証
$ vagrant ssh-config --host develop >> ~/.ssh/config
#接続テスト
$ ssh develop
Welcome to your Vagrant-built virtual machine.
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.

#リポジトリの作成と仮想マシンにchefを用意
$ knife solo init chef-lepo
$ cd chef-lepo
$ knife solo prepare develop

サーバーサイドを先に構築

今回は、以前作成したPHP+Mysql+Apacheのchefを流用して、サーバーサイドを先に構築しておきます。
作成した内容は、下記ページを確認してください。
windows+CygwinでChef - 目次 - Program LOG

今作成したchef-lepoディレクトリ内の「site-cookbooks」に「develop」クックブックをコピーしておきます。
次に、以前作成したものを実行しておきましょう。
nodeのdevelop.jsonの編集も忘れずに!
準備が出来たら、いつものを実行します。

$ knife solo cook develop
・・・中略・・・
Running handlers:
Running handlers complete

Chef Client finished, 21/21 resources updated in 57.005617181 seconds

新しくレシピを作成する。

フロントサイド用のレシピを作成します。
まず、rubyのバージョンが低いのが気になるので、rubyのバージョンをrbenvを入れて、
バージョン管理出来るようにしたいと思います。
今回のレシピは、「ruby.rb」としました。

rbenvを使ってrubyをインストールする。

まずは、gitクローンを行います。
その為、gitをインストールしておく必要がありますので、gitからインストールしましょう。

#gitのインストール
package "git" do
	action :install
end

#.rbenvをcloneする
git "/home/vagrant/.rbenv" do
  repository "https://github.com/sstephenson/rbenv.git"
  revision   "master"
  user       "vagrant"
  group      "vagrant"
  action     :sync
end
# セットアップを行う
bash "rbenv_setup" do
  not_if "ls /root/.rbenv_setup"
  user "root"
  code <<-EOL
   echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
   echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
   exec $SHELL -l
  EOL
end
#判定用
bash "rbenv_setup_check" do
  not_if 'ls /root/.rbenv_setup'
  user        "root"
  code <<-EOL
    echo "rbenv_setup" > /root/.rbenv_setup
    chown 400 /root/.rbenv_setup
  EOL
end

#ディレクトリ~/.rbenv/plugins/を作成して、このディレクトリにruby-buildをgit cloneする。
directory "/home/vagrant/.rbenv/plugins" do
  owner  "vagrant"
  group  "vagrant"
  action :create
end
git "/home/vagrant/.rbenv/plugins/ruby-build" do
  repository "https://github.com/sstephenson/ruby-build.git"
  revision   "master"
  user       "vagrant"
  group      "vagrant"
  action     :sync
end

これでrbenvはセットアップされるはずですので、実行確認してみましょう。

$ knife solo cook develop
・・・中略・・・
Starting Chef Client, version 11.12.4
Compiling Cookbooks...
Converging 1 resources
Recipe: develop::ruby
  * package[git] action install
    - install version 1.7.1-3.el6_4.1 of package git
  * git[/home/vagrant/.rbenv] action sync
    - clone from https://github.com/sstephenson/rbenv.git into /home/vagrant/.rbenv
    - checkout ref 13a474c4e9c3305179b364723349fc49b3e935e3 branch master

  * bash[rbenv_setup] action run
    - execute "bash"  "/tmp/chef-script20140622-4950-1q9pew3"

  * bash[rbenv_setup_check] action run
    - execute "bash"  "/tmp/chef-script20140622-4950-10m9ydg"

  * directory[/home/vagrant/.rbenv/plugins] action create
    - create new directory /home/vagrant/.rbenv/plugins
    - change owner from '' to 'vagrant'
    - change group from '' to 'vagrant'

  * git[/home/vagrant/.rbenv/plugins/ruby-build] action sync
    - clone from https://github.com/sstephenson/ruby-build.git into /home/vagrant/.rbenv/plugins/ruby-build
    - checkout ref d3d5fe03dcff305a442688d3f7322b6b29924cd4 branch master

念のため、バージョン確認をしておきたいと思います。

$ ssh develop
Last login: Sun Jun 22 05:57:05 2014 from 192.168.33.1
Welcome to your Vagrant-built virtual machine.
[vagrant@localhost ~]$ rbenv -v
rbenv 0.4.0-98-g13a474c

問題なくはいってました!
次は、rubyをインストールしておきます。

#opensslのインストール
package "openssl-devel" do
  action :install
end
#rbenvで2.0.0-p481のインストール
bash "rubyp481_install" do
  not_if { ::File.exists? "/home/vagrant/.rbenv/versions/2.0.0-p353" }
  user "root"
  code <<-EOL
   su vagrant -l -c 'rbenv install 2.0.0-p481'
   su vagrant -l -c 'rbenv rehash'
   su vagrant -l -c 'rbenv global 2.0.0-p481'
  EOL
end

それでは実行したいと思います。

$ knife solo cook develop
・・・中略・・・
  * bash[rubyp481_install] action run
    - execute "bash"  "/tmp/chef-script20140622-7477-rb2cfk"


Running handlers:
Running handlers complete

正常に入ったようです。
userがvagrantじゃないとダメなのに、rootでしか実行されなくてはまりましたw
しょうがないので、上記のように実行する事に!
これで、rubyのバージョンが変わってればOKって事ですね!

$ ssh develop
[vagrant@localhost ~]$ ruby -v
ruby 2.0.0p481 (2014-05-08 revision 45883) [x86_64-linux]

これで、正常にインストールが完了しました。

gemでsassとcompassをインストール!

さて、それでは、rubyが入ったので、sassとcompassをインストールしたいと思います。
また、今回は、grunt.rbというレシピを作成しました。
こちらのファイルで、sassやcompassのインストールをしていきたいと思います。
下記を書いていきます。

%w[sass compass].each do |pkg|
	gem_package pkg do
	    action :install
	end
end

nodeの設定を変更して、早速実行しましょう!

$ knife solo cook develop
・・・中略・・・
Starting Chef Client, version 11.12.4
Compiling Cookbooks...
Converging 2 resources
Recipe: develop::grunt
  * gem_package[sass] action install
    - install version 3.3.8 of package sass

  * gem_package[compass] action install
    - install version 0.12.6 of package compass


Running handlers:
Running handlers complete

Chef Client finished, 2/2 resources updated in 52.555326905 seconds

無事に入ったようなので、バージョンを確認しておきたいと思います。

$ ssh develop
Last login: Sun Jun 22 08:10:37 2014 from 10.0.2.2
Welcome to your Vagrant-built virtual machine.
[vagrant@localhost ~]$ sass -v
Sass 3.3.8 (Maptastic Maple)
[vagrant@localhost ~]$ compass -v
Compass 0.12.6 (Alnilam)
Copyright (c) 2008-2014 Chris Eppstein
Released under the MIT License.
Compass is charityware.
Please make a tax deductable donation for a worthy cause: http://umdf.org/compass

ここまでで取り合えず、sass+compassまではインストールできました。
引き続き、CoffeeとGruntをインストールしたいと思います。
ちょっと長くなってきちゃいましたので、続きは次回行いたいと思います。

使用環境

今さら聞けないcoffeescript入門

Sassに関しては、今までいじってきた事があったのですが、
CoffeeScriptに関しては皆無状態・・・w
なんとな~くSassっぽくJavaScriptを書けるって事くらいしか知識がありません。
それすらもあっているのどうか・・・?w
って事で今回は、Gruntを導入したので、せっかくだから、Coffeeも勉強していきたいと思います。
実際には、jQueryを使いたいんで、上手く組み込めるのか?も合わせて勉強したいと思います。

そもそもCoffeeScriptって何?

色んなサイトを見ると、一番多い説明として、
JavaScriptのコードを生成(変換)する為の便利なrubyライクなスクリプト言語
JavaScriptに比べると3分の1くらいのボリューム感で記述が可能らしいです。
自動的にコンパイルする手段がいくつもあるので、手間無く導入する事が可能みたいです。
また、調べると、jQueryとの共存が可能らしい!これはいい情報です。

CoffeeScriptのインストール

CoffeeScriptはNodejsで作られているため、Nodeをインストールしておいて下さい。
これは、前回までにやっているので、ここでは説明をはぶきます。
またもやNode・・・WindowsCygwinユーザーだとしんどいw
今回はコマンドプロンプトで以下のように実行します。

$ npm install -g coffee-script

Nodeのインストールが終わっていれば、これだけでインストールは完了です!
一応正常にインストール出来ているかバージョンを確認してみましょう!

$ coffee -v
CoffeeScript version 1.7.1

コンパイルしてみよう。

まずは、テスト的に「hello.coffee」ってファイルを作成します。
そのファイルに、以下のような一行を書いてみましょう!

alert "hello world!"

作成が完了したら、以下のコマンドを実行します。

$ coffee -c hello.coffee

エラーが帰ってこない場合は、問題なく「hello.js」というファイルが生成されているはずです。
変換後の内容を確認したいと思います。

// Generated by CoffeeScript 1.7.1
(function() {
  alert("hello world!");

}).call(this);

とまぁ、非常に簡単でしたねw

これだけじゃ、つまらないので、どんな所が便利なのか、
簡単な構文を元に書いてみたいと思います。
といっても、Javascriptをそんなに使って開発する事が最近無いので、
もっと実践的に使いたいって事で、jQueryを書いてみたいと思います。

CoffeeScriptjQuery

表題のとおり、CoffeeScriptjQueryを使ってみたいと思います。
まずは、普通によくあるような構文をjQueryで書いてみたいと思います。

普通に書いたjQuery構文

$(function(){
    //jQuery Start!
    $name = $("#name").val();
    $('#btn').click(function(){
        alert ("こんにちは"+name+"です");    
    });
});

まぁ、普通にこんなのはありますよね?
coffeeで書くと以下のようになります。

$ ->
    # jQuery Start!
    var name = $("#name").val()
    $('#btn').click ->
        alert "こんにちは#{name}です!"

コンパイルすると、以下のように出力されます。

// Generated by CoffeeScript 1.7.1
(function() {
  $(function() {
    var name;
    name = $("#name").val();
    return $('#btn').click(function() {
      return alert("こんにちは" + name + "です!");
    });
  });

}).call(this);

だいぶスッキリ書けるのが分かってきました!
基本的な構文は一緒なので、慣れてしまえば問題なく入れそうな気がします。
構文に関しては、railsのサイトに提供されていたり、ドットインストールを参考にしてもらえれば
簡単に分かると思います。
Rubyで採用されていたので、簡略的に記述できるのはなんとなくわかっていましたが、
varがいらないとか、インデント構文になっていたりと非常に簡略的になりますね!

さて、Coffeeを導入したら、ますますWindows+Cygwinユーザーには、
Nodejsの存在が微妙にうざくなってきましたw
Cygwinで動作しないので、gruntjsで自動コンパイルを行う為に、
コマンドプロンプトを常時起動しておかないといけない・・・。

やっぱり、vagrantでgruntの実行環境を用意した方がいいんかなぁ・・・?w
基本的に、PHPプログラマーだったから、こんな悩みなんて無かったんだがw

phpの開発環境を作成するChefを作成しましたが、
Sass+Compass+Coffee+Grunt環境を一発作成するChefを書いてしまって、
プロビジョニングで、自動的に監視コンパイルしてくれる状況にしてしまえばいいかも・・・。

次回作成してみたいと思います!

使用環境

CygwinでGruntjsを使ってみる

前回GRUNT.jsをインストールする所まで終わりました。
今回は、実際に使用してみたり、使えるプラグインなんかを試してみたいと思います。

前回までのおさらい

前回は、nodejsをcygwinに入れようとして、「npm init」ですごいハマリ、
あきらめかけた時に、package.jsonを自作して、gruntのインストールかましたら、
普通にいけたって感じでしたね。
cygwinでは限界があるのか!?って思ったんですけど、その辺はコマンドプロンプトか、
試してないですが、MinGWでは実行できるんじゃねーかと思います。
まぁ、ひとまずインストールが出来てたんで、Cygwinでどこまで出来るか、試してみようと思います。

Gruntfile.jsを作成しよう

まずは、どんな自動タスクを実行させるか、Gruntfile.jsファイルに記載していきます。
package.jsonと同じ階層に今回は作成しました。
まずは、以下のように、記述します。
このfunctionの中に色々書いていく事になります。

module.exports = function(grunt){
}

pluginのインストール

今回はsassのコンパイルを自動化できるようにしたいと思います。
まずは、インストールから行います。

$ npm install grunt-contrib-sass --save-dev
npm WARN package.json test-project@0.1.0 No description
npm WARN package.json test-project@0.1.0 No repository field.
npm WARN package.json test-project@0.1.0 No README data
grunt-contrib-sass@0.7.3 node_modules\grunt-contrib-sass
├── dargs@0.1.0
├── which@1.0.5
├── win-spawn@2.0.0
├── async@0.2.10
└── chalk@0.4.0 (ansi-styles@1.0.0, has-color@0.1.7, strip-ansi@0.1.1)

次に、インストールしたプラグインのロード設定をGruntfile.jsにします。

module.exports = function(grunt){
  //プラグインのロード
  grunt.loadNpmTasks('grunt-contrib-sass');
}

続いて、configを設定して、コンパイルするファイルの指定と、
出力先の指定を行います。

module.exports = function(grunt){
  //config
  grunt.initConfig({
    sass: {
      dist: {
              files: {
                 'source/css/style.css': 'source/sass/style.sass'
              }
          }
      }
  });
  //plugin load
  grunt.loadNpmTasks('grunt-contrib-sass');
}

最後に、taskの実行内容を作成します。

module.exports = function(grunt){
  //config
  grunt.initConfig({
    sass: {
      dist: {
              files: {
                 'source/css/style.css': 'source/sass/style.sass'
              }
          }
      }
  });
  //plugin load
  grunt.loadNpmTasks('grunt-contrib-sass');
  //tasks
  grunt.registerTask('default', ['sass']);
}

これで、準備は完了しました。
以下のように実行するタスクが走ってくれます。

$ grunt
Running "sass:dist" (sass) task

C:\Users\takumi-main\Desktop\dev\grunt>#!/usr/bin/env bash
文字化け文字化け文字化け文字化け文字化け文字化け文字化け

C:\Users\takumi-main\Desktop\dev\grunt>set -e
文字化け文字化け文字化け文字化け文字化け文字化け文字化け

C:\Users\takumi-main\Desktop\dev\grunt>[ -n "$RBENV_DEBUG" ]   && set -x
文字化け文字化け文字化け文字化け文字化け文字化け

C:\Users\takumi-main\Desktop\dev\grunt>program="${0##*/}"
文字化け文字化け文字化け文字化け文字化け文字化け

C:\Users\takumi-main\Desktop\dev\grunt>if [ "$program" = "ruby" ]; then

んー大量の文字化け・・・早くもエラー発生していました。。。
ちなみに、コマンドプロンプトで実行すると、以下のようになります。

> grunt
Running "sass:dist" (sass) task
File source/css/style.css created.

Done, without errors.

早くも結論が・・・もうGruntをやる場合は、Cygwinはダメですね・・・。
ローカルでやる場合は、コマンドプロンプトでやり、
Cygwinをどうしても使いたい場合は、実行環境用にVagrantを作成して、
共有ディレクトリをコンパイル先にしておく等のちょっとしたコツが必要になるかもしれません。

ひとまず、コマンドプロンプトで実行する事は出来ました。
このように、プラグインをインストールして、その設定をGruntfile.jsに書き込み、
「grunt」コマンドでタスクを実行するっていう感じの流れになります。

また、今回のタスクだけであれば、compassだけで十分って事になりますが、
今回紹介したタスクは、入門編として一部紹介しただけとなります。
これ以外にも、簡単に色んなタスクを実行する事が出来ますので、お試しあれ!

使用環境

CygwinでGruntjsをインストール

前回の記事で、Compass+Sassを行いました!
CygwinでSass+Compassをインストール - Program LOG
そこで、今回はCygwinでGruntjsを使ってみようと思います。
1年位前から色んなブログですでに紹介されており、
ドットインストールでも紹介されていたので、調べるのに苦労はなさそうw
って思ったら、Cygwinでnode使うのにすげーーーーハマッタw

Grunt.jsって?

色んな事を自動化してくれるビルドツールです。
例えば、Webサイトの表示速度を気にすると、CSSJavaScriptのminify、gzipCSS Sprite、
画像の最適化などの面倒な作業が発生します。
この間やった、Compassでsassのコンパイル処理もGruntがやってくれたりします。

なんとなく概要は分かったので、ひとまずインストールしてみたいと思います。
Grunt.jsをインストールするには、nodejsが必要なので、node.jsからインストールしていきます。

Node.jsのインストール

nodeJSのインストーラーは公式サイトからダウンロードできます。

f:id:aimtaku:20140614102616p:plain

「INSTALL」ボタンからダウンロードしたら、
ガイダンスにしたがって、インストールをしちゃいましょう!

インストールが完了したら、「npm」コマンドが実行できるはずなので、
試してみたいと思います。

$ npm -v
/cygdrive/c/Program Files/nodejs/npm: line 2: $'\r': command not found
/cygdrive/c/Program Files/nodejs/npm: line 4: $'\r': command not found
/cygdrive/c/Program Files/nodejs/npm: line 5: syntax error near unexpected token `$'in\r''
'cygdrive/c/Program Files/nodejs/npm: line 5: `case `uname` in

ん?・・・エラーw改行コード?w
ちょっと調べたら、似た現象の人を発見しました!
Node.jsをWindowsインストーラで入れたら、Cygwinのシェルでnpmがエラーになる - 死ぬまでの暇潰し
ありがたかった・・・w改行コードをCRLFからLFに変更して保存しなおします。

$ npm -v
cygwin warning:
  MS-DOS style path detected: C:\Program Files\nodejs/node.exe
  Preferred POSIX equivalent is: /cygdrive/c/Program Files/nodejs/node.exe
  CYGWIN environment variable option "nodosfilewarning" turns off this warning.
  Consult the user's guide for more details about POSIX paths:
    http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
1.4.9

おー!案外簡単にいけました!

Grunt.jsのインストール

先ほどインストールしたNode.jsからインストールします。

$ npm install -g grunt-cli
npm http GET https://registry.npmjs.org/grunt-cli
npm http 200 https://registry.npmjs.org/grunt-cli
npm http GET https://registry.npmjs.org/grunt-cli/-/grunt-cli-0.1.13.tgz
npm http 200 https://registry.npmjs.org/grunt-cli/-/grunt-cli-0.1.13.tgz
npm http GET https://registry.npmjs.org/nopt
npm http GET https://registry.npmjs.org/findup-sync
npm http GET https://registry.npmjs.org/resolve
npm http 200 https://registry.npmjs.org/findup-sync
・・・中略・・・
npm http GET https://registry.npmjs.org/lru-cache/-/lru-cache-2.5.0.tgz
npm http 200 https://registry.npmjs.org/sigmund
npm http 200 https://registry.npmjs.org/lru-cache/-/lru-cache-2.5.0.tgz
npm http GET https://registry.npmjs.org/sigmund/-/sigmund-1.0.0.tgz
npm http 200 https://registry.npmjs.org/sigmund/-/sigmund-1.0.0.tgz
C:\Users\takumi-main\AppData\Roaming\npm\grunt -> C:\Users\takumi-main\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt
grunt-cli@0.1.13 C:\Users\・・・\AppData\Roaming\npm\node_modules\grunt-cli
├── resolve@0.3.1
├── nopt@1.0.10 (abbrev@1.0.5)
└── findup-sync@0.1.3 (lodash@2.4.1, glob@3.2.11)

イケタっぽい?
gruntを実行します。

$ grunt
grunt-cli: The grunt command line interface. (v0.1.13)

ん?・・・これでいいのか?w色んなサイトを見るとコレでいいらしい・・w
・・・おーなるほど!
grunt.jsは本体もプラグイン扱いらしく、package.jsonで本体をインストールするらしいw

package.jsonを作成する。

grantを使用するには、package.jsonというファイルを作成しなければなりません。
これはプロジェクトを管理する為のメタファイルになります。
こちらは、プロジェクトのディレクトリにアクセスして、
下記のコマンドを実施する事によって作成してくれます。

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install  --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.

コマンドを実施したとしても、作成してくれません。。。
・・・ってか、対話形式でプロジェクトについて聞かれるはずなのに、
何も聞いてくれない・・・・何だこれw
package.jsonのかわりに、npm-debug.logってのが出来てました。

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'init' ]
2 info using npm@1.4.9
3 info using node@v0.10.28
4 error Error: EINVAL, invalid argument
4 error     at new Socket (net.js:156:18)
4 error     at process.stdin (node.js:664:19)
4 error     at read (C:\Program Files\nodejs\node_modules\npm\node_modules\read\lib\read.js:18:36)
4 error     at PromZard.prompt (C:\Program Files\nodejs\node_modules\npm\node_modules\init-package-json\node_modules\promzard\promzard.js:214:3)
4 error     at PromZard.L (C:\Program Files\nodejs\node_modules\npm\node_modules\init-package-json\node_modules\promzard\promzard.js:177:21)
4 error     at PromZard.walk (C:\Program Files\nodejs\node_modules\npm\node_modules\init-package-json\node_modules\promzard\promzard.js:146:5)
4 error     at PromZard.loaded (C:\Program Files\nodejs\node_modules\npm\node_modules\init-package-json\node_modules\promzard\promzard.js:90:8)
4 error     at PromZard. (C:\Program Files\nodejs\node_modules\npm\node_modules\init-package-json\node_modules\promzard\promzard.js:57:10)
4 error     at fs.js:266:14
4 error     at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:105:5
5 error If you need help, you may report this *entire* log,
5 error including the npm and node versions, at:
5 error     http://github.com/npm/npm/issues
6 error System Windows_NT 6.1.7601
7 error command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "init"
8 error cwd C:\Users\takumi-main\Desktop\dev\grunt
9 error node -v v0.10.28
10 error npm -v 1.4.9
11 error syscall uv_pipe_open
12 error code EINVAL
13 error errno 18
14 verbose exit [ 18, true ]

よくわからん・・・・w色々ググってみる・・・。
日本のサイトにいいのが無い・・・海外では似た現象があったみたいだが・・・
ちなみに、「node」だけで「enter」しても以下のようになる。

$ node

net.js:156
    this._handle.open(options.fd);
                 ^
Error: EINVAL, invalid argument
    at new Socket (net.js:156:18)
    at process.stdin (node.js:664:19)
    at startup (node.js:145:16)
    at node.js:906:3

何か、Socketが上手くいってないっぽいっすな!ちょっと前進?
色々調べたら、Windowsでnodeは出来るけど、Cygwinには対応してないよー!って、きついお言葉が・・・orz
しょうがない・・・アンインストールして、仮想マシンに入れるか・・・?
それともwindows版をそのまま使うか・・・?悩むw

ちょっと寄り道してnodistってバージョン管理ツールを使ってみる

色んなバージョンで試してみようって思って、バージョン管理を探してみたら、あったw
下記コマンドで、クローンして使います。

$ git clone git://github.com/marcelklehr/nodist.git

パスを通して、以下のコマンドを、コマンドプロンプトで実行。

$ nodist -v
0.4.8

インストールできてますね!
次に、アップデートしておきます。

$ nodist update

色々走った上で、nodejsもインストールされます。
最新の安定版node.jsをインストールするには、以下。

$ nodist stable

バージョンを指定する場合は、以下のようにします。

$ nodist + v0.11.11
0.11.11
$ node -v
v0.10.29
$ nodist ls
> 0.10.29
   0.11.11

おー入ったっぽい!それでは、先ほどのが解決しているっていう噂の、
0.11バージョンを指定していみたいと思います。

$ nodist (use) v0.11.11
Version spec didn't match any available version.
Sorry.

・・・・・・・・・・・チーン。
オワタ・・・・wもう折れましたw
正直折れたぞー!w
って事で、もうCygwinでnodeはやらない!これでfix!w
じゃあどうするって感じなんですが、、、
ためしに、package.jsonを自作したら、それでいけちゃったので、
取り合えずnpm initはスルーする方向で・・・w

久々に未解決のままになってしまいましたが、今回は無理だった!って事でご容赦を!
ってかだーれーかー解決方法しってたらおせーてー!w

かなり折れてしまったので、今回は、ここまでで・・・
次回、Gruntの操作をしてみます。

使用環境

  • ホストOS: Windows7 x64
  • Cygwin : Cygwin64
  • ruby : 2.1.2p95
  • VirtualBox: 4.3.10
  • Vagrant: 1.5.2

CygwinでSass+Compassをインストール

何でいまさら!って思ったんですが、
最近色々勉強していて、Cygwinでrbevnなどを入れて、Rubyの管理を行うようになりました。
って事は、いままでプロンプトでやってたsassなどもCygwinで出来るって事だよな?って思い
Sassだけ入れてもあまり面白く無いので、Sass+Compassを入れて、フロント開発環境を整えてみようと思います!
実は、意外とハマってますw

Cygwinにrbenvをインストールに関しては下記のページで解説していますので、
確認してみてください!
windowsでrbenv - Program LOG

Sassのインストール

今更なので、Sassの解説はしませんが・・・。
Sassはgemでインストールするので、以下のコマンドを一発流せばいけます。

$ gem install sass
DL is deprecated, please use Fiddle
Fetching: sass-3.3.8.gem (100%)
Successfully installed sass-3.3.8
Parsing documentation for sass-3.3.8
Installing ri documentation for sass-3.3.8
Done installing documentation for sass after 6 seconds
1 gem installed

これでインストールは完了しました!
正常に入っているか、バージョンの確認を一応やっておきます。

$ sass -v
Sass 3.3.8 (Maptastic Maple)

はい!問題なく入っておりました!
一応watchして、動作確認!

$ sass --watch sass:css
>>> Sass is watching for changes. Press Ctrl-C to stop.
      write css/style.css
[Listen warning]:
  Listen will be polling for changes. Learn more at https://github.com/guard/listen#polling-fallback.
>>> Change detected to: sass/style.sass
      write css/style.css

ん?Warningが出てますなw
正常にコンパイルは出来てるけども、listenってのが足らないらしいです。
一応入れておきました。

$ gem install listen
DL is deprecated, please use Fiddle
Fetching: rb-fsevent-0.9.4.gem (100%)
Successfully installed rb-fsevent-0.9.4
Fetching: rb-inotify-0.9.5.gem (100%)
・・・中略・・・
Installing ri documentation for rb-fsevent-0.9.4
Parsing documentation for rb-inotify-0.9.5
Installing ri documentation for rb-inotify-0.9.5
Done installing documentation for listen, rb-fsevent, rb-inotify after 1 seconds
3 gems installed

再度watchを実行します。

$ sass --watch sass:css
>>> Sass is watching for changes. Press Ctrl-C to stop.
NoMethodError: undefined method `_log' for Listen::Adapter::Windows:Class
  Use --trace for backtrace.

ん?w今度は、Listenでこけた?w
なんだよー!って事で一応調べてみる。

$ listen --trace
ERROR: listen start was called with arguments ["--trace"]
Usage: "listen start".

なんだこれ?w色々調べたが、ちょっと分からんかったので、
未解決ですが、一旦listenとはおさらばしちゃいましたw
まぁ、取り合えずコンパイルは通ったしね・・・w

Compassのインストール

さて、気を取り直して、compassのインストールをやっちぇしまいたいと思います。

$ gem i compass
DL is deprecated, please use Fiddle
Fetching: sass-3.2.19.gem (100%)
Successfully installed sass-3.2.19
Fetching: chunky_png-1.3.1.gem (100%)
・・・中略・・・
Parsing documentation for fssm-0.2.10
Installing ri documentation for fssm-0.2.10
Parsing documentation for sass-3.2.19
Installing ri documentation for sass-3.2.19
Done installing documentation for chunky_png, compass, fssm, sass after 9 seconds
4 gems installed

次はバージョンの確認を行っておきます。

$ compass -v
Compass 0.12.6 (Alnilam)
Copyright (c) 2008-2014 Chris Eppstein
Released under the MIT License.
Compass is charityware.
Please make a tax deductable donation for a worthy cause: http://umdf.org/compass

さて、お次は、プロジェクトを作ってみたいと思います。

$ compass create compass
directory compass/
directory compass/sass/
directory compass/stylesheets/
   create compass/config.rb
   create compass/sass/screen.scss
   create compass/sass/print.scss
   create compass/sass/ie.scss
   create compass/stylesheets/ie.css
   create compass/stylesheets/print.css
   create compass/stylesheets/screen.css

*******************************************
Congratulations! Your compass project has been created.

You may now add and edit sass stylesheets in the sass subdirectory of your project.

Sass files beginning with an underscore are called partials and won't be
compiled to CSS, but they can be imported into other sass stylesheets.

You can configure your project by editing the config.rb configuration file.

You must compile your sass stylesheets into CSS when they change.
This can be done in one of the following ways:
  1. To compile on demand:
     compass compile [path/to/project]
  2. To monitor your project for changes and automatically recompile:
     compass watch [path/to/project]

More Resources:
  * Website: http://compass-style.org/
  * Sass: http://sass-lang.com
  * Community: http://groups.google.com/group/compass-users/

To import your new stylesheets add the following lines of HTML (or equivalent) to your webpage:

  
  

さくっと作成されました!
ちょっといじってみたいと思います。

$ compass compile
unchanged sass/ie.scss
unchanged sass/print.scss
overwrite stylesheets/screen.css

正常にいきました!
先ほどエラーが出てしまったWatchもやってみたいと思います。

$ compass watch
>>> Change detected at 19:43:55 to: screen.scss
overwrite stylesheets/screen.css
>>> Compass is polling for changes. Press Ctrl-C to Stop.

おおお?こっちだと出ないんだwいいかもw
ちょっと修正してみます。

$ compass watch
>>> Change detected at 19:43:55 to: screen.scss
overwrite stylesheets/screen.css
>>> Compass is polling for changes. Press Ctrl-C to Stop.
ArgumentError on line ["500"] of /cygdrive/c/pik/.rbenv/versions/2.1.2/lib/ruby/2.1.0/pathname.rb: different prefix: "//cygdrivecUserstakumi-mainDesktopdevgruntcompasssassscreen.scss" and "/cygdrive/c/Users/takumi-main/Desktop/dev/grunt/compass/sass"
Run with --trace to see the full backtrace

うぉw何かまたエラーw調査開始・・・
どうやら、ちょっとファイルをいじる必要があるみたいです。
「/lib/fssm/pathname.rb」を探して、修正する必要があるみたいです。
多分WindowsLinuxの違いですねこれ・・・よくあるセパレーター問題ってやつw
rbenvで入れているので、自分の場合は以下にありました。
「/cygdrive/c/pik/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/fssm-0.2.10/lib/fssm/」

26行目に以下のようなコードがあります。

array[0] += File::SEPARATOR if path[0, 3] =~ SEPARATOR_PAT

それを以下のように修正します。

array[0] += File::SEPARATOR if path[0, 3] =~ SEPARATOR_PAT unless path [0, 1] == File::SEPARATOR

その後、再度、compass watchを実行し、screen.scssを修正してみます。。。

$ compass watch
>>> Change detected at 19:53:27 to: screen.scss
overwrite stylesheets/screen.css
>>> Compass is polling for changes. Press Ctrl-C to Stop.
>>> Change detected at 19:53:34 to: screen.scss
overwrite stylesheets/screen.css

おー!うまくいった!w
ってか、さっきのエラーもセパレーター問題じゃないのか?って思うw
まぁCompassで実行できればいいさっ・・・w

さて、今回はCompass+Sassのインストールを行いました。
実は、さくっと入れてお遊びでもって思ってたんですが、意外にハマってしまったw
なので、今回はこのへんで終わり!w

次回はGrunt.jsを使ってみようって思ってます。
最近のフロント開発現場で良く耳にするので、さすがに知っておかなければと思います。。。

使用環境