乐正

Actions speak louder than words.

从零搭建和配置OSX开发环境

对于每一名开发者来说,更换系统或者更换电脑的时候,都免不了花上不短的时间去折腾开 发环境的问题。我本人也是三番两次,深知这个过程的繁琐。所有,根据我自己以往的经验, 以及参考一下他人的意见,整理一下关于在Mac下做各种开发的配置,包含Java, Ruby, Vim, git, 数据库等等。欢迎补充与修正。

Terminal篇

这篇文章包含配置控制台环境,包括包管理工具, zsh, Vim, git的安装配置。

Homebrew, 你不能错过的包管理工具

包管理工具已经成为现在操作系统中不可缺少的一个重要工具了,它能大大减轻软件安装的 负担,节约我们的时间。Linux中常用的有yumapt-get工具,甚至Windows平台也 有Chocolatey这样优秀的工具,OSX平台自然有它独有的工具。

在OSX中,有两款大家常用的管理工具:Homebrew或者MacPorts。这两款工具都是为了解决同 样的问题——为OSX安装常用库和工具。Homebrew与MacPorts的主要区别是Homebrew不会破坏OSX 原生的环境,这也是我推荐Homebrew的主要原因。同时它安装的所有文件都是在用户独立空间内 的,这让你安装的所有软件对于该用户来说都是可以访问的,不需要使用sudo命令。

在安装Homebrew前,你需要前往AppStore下载并安装Xcode.

安装方式:

1
2
3
# OSX系统基本上都自带Ruby1.9
# 所以无需先安装Ruby,但是之后我们需要管理Ruby
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Homebrew常用命令:

1
2
3
4
5
6
7
8
9
10
brew list                 # 查看已经安装的包
brew update               # 更新Homebrew自身
brew doctor               # 诊断关于Homebrew的问题(Homebrew 有问题时请用它)
brew cleanup              # 清理老版本软件包或者无用的文件
brew show ${formula}      # 查看包信息
brew search ${formula}    # 按名称搜索
brew upgrade ${formula}   # 升级软件包
brew install ${formula}   # 按名称安装
brew uninstall ${formula} # 按名称卸载
brew pin/unpin ${formula} # 锁定或者解锁软件包版本,防止误升级

zsh,好用的shell

Shell程序就是Linux/UNIX系统中的一层外壳,几乎所有的应用程序都可以运行在Shell环境 下,常用的有bash, csh, zcsh等。在/etc/shells文件中可以查看系统中的各种shell。

1
2
3
4
5
6
7
8
9
10
11
12
cat /etc/shells

# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh

而zsh是OSX系统原生的shell之一,其功能强大,语法相对于bash更加友好和强大,所以推荐 使用zsh作为默认的shell。

1
2
# 切换zsh为默认shell
chsh -s $(which zsh)

如果你想使用最新的zsh,你可以使用Homebrew,此方法也会保留原生的zsh,防止你在某个 时刻需要它。

1
2
3
4
5
6
7
8
9
10
11
12
# 查看最新zsh信息
brew info zsh

# 安装zsh
brew install --disable-etcdir zsh

# 添加shell路径至/etc/shells文件中
# 将 /usr/local/bin/zsh 添加到下面文件中
sudo vim /etc/shells

# 更换默认shell
chsh -s /usr/local/bin/zsh

下面贴上我的zsh配置以供参考

我的zsh配置 (zshrc) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# modify the prompt to contain git branch name if applicable
git_prompt_info() {
  ref=$(git symbolic-ref HEAD 2> /dev/null)
  if [[ -n $ref ]]; then
    echo " %{$fg_bold[green]%}${ref#refs/heads/}%{$reset_color%}"
  fi
}
setopt promptsubst
export PS1='${SSH_CONNECTION+"%{$fg_bold[green]%}%n@%m:"}%{$fg_bold[blue]%}%c%{$reset_color%}$(git_prompt_info) %# '

# load our own completion functions
fpath=(~/.zsh/completion $fpath)

# completion
autoload -U compinit
compinit

# load custom executable functions
for function in ~/.zsh/functions/*; do
  source $function
done

# makes color constants available
autoload -U colors
colors

# enable colored output from ls, etc
export CLICOLOR=1

# history settings
setopt hist_ignore_all_dups inc_append_history
HISTFILE=~/.zhistory
HISTSIZE=4096
SAVEHIST=4096

# awesome cd movements from zshkit
setopt autocd autopushd pushdminus pushdsilent pushdtohome cdablevars
DIRSTACKSIZE=5

# Enable extended globbing
setopt extendedglob

# Allow [ or ] whereever you want
unsetopt nomatch

# vi mode
bindkey -v
bindkey "^F" vi-cmd-mode
bindkey jj vi-cmd-mode

# handy keybindings
bindkey "^A" beginning-of-line
bindkey "^E" end-of-line
bindkey "^R" history-incremental-search-backward
bindkey "^P" history-search-backward
bindkey "^Y" accept-and-hold
bindkey "^N" insert-last-word
bindkey -s "^T" "^[Isudo ^[A" # "t" for "toughguy"

# use vim as the visual editor
export VISUAL=vim
export EDITOR=$VISUAL

# load rbenv if available
if which rbenv &>/dev/null ; then
  eval "$(rbenv init - --no-rehash)"
fi

# load thoughtbot/dotfiles scripts
export PATH="$HOME/.bin:$PATH"

# mkdir .git/safe in the root of repositories you trust
export PATH=".git/safe/../../bin:$PATH"

# aliases
[[ -f ~/.aliases ]] && source ~/.aliases

# Local config
[[ -f ~/.zshrc.local ]] && source ~/.zshrc.local

好用的编辑器 Vim

对于Vim,无需溢美之词,作为与emacs并列的两大编辑器,早已经被无数人奉为经典。而它却 又以超长的学习曲线,使得很多人望而却步。长久以来,虽然拥有大量的插件,却缺少一个 确之有效的插件管理器。所幸,Vundle的出现解决了这个问题。

Vundle可以让你在配置文件中管理插件,并且非常方便的查找、安装、更新或者删除插件。 还可以帮你自动配置插件的执行路径和生成帮助文件。相对于另外一个管理工具pathogen, 可以说有着巨大的优势。

1
2
# vundle 安装和配置
git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
" 将下面配置文件加入到.vimrc文件中
set nocompatible " 必须
filetype off     " 必须

" 将Vundle加入运行时路径中(Runtime path)
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()

" 使用Vundle管理插件,必须
Plugin 'gmarik/Vundle.vim'

"
" 其他插件
"

call vundle#end() " 必须
filetype plugin indent on " 必须

最后,你只需要执行安装命令,即可以安装好所需的插件。

1
2
3
4
5
# 在vim中
:PluginInstall

# 在终端
vim +PluginInstall +qall

下面列出我的Vim插件和配置

Vim插件 (vimrc.bundles) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
if &compatible
  set nocompatible
end

filetype off
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

" Let Vundle manage Vundle
Bundle 'gmarik/vundle'

" Define bundles via Github repos
Bundle 'christoomey/vim-run-interactive'
Bundle 'croaky/vim-colors-github'
Bundle 'danro/rename.vim'
Bundle 'kchmck/vim-coffee-script'
Bundle 'kien/ctrlp.vim'
Bundle 'pbrisbin/vim-mkdir'
Bundle 'scrooloose/syntastic'
Bundle 'slim-template/vim-slim'
Bundle 'thoughtbot/vim-rspec'
Bundle 'tpope/vim-bundler'
Bundle 'tpope/vim-endwise'
Bundle 'tpope/vim-fugitive'
Bundle 'tpope/vim-rails'
Bundle 'tpope/vim-surround'
Bundle 'vim-ruby/vim-ruby'
Bundle 'vim-scripts/ctags.vim'
Bundle 'vim-scripts/matchit.zip'
Bundle 'vim-scripts/tComment'
Bundle "mattn/emmet-vim"
Bundle "scrooloose/nerdtree"
Bundle "Lokaltog/vim-powerline"
Bundle "godlygeek/tabular"
Bundle "msanders/snipmate.vim"
Bundle "jelera/vim-javascript-syntax"
Bundle "altercation/vim-colors-solarized"
Bundle "othree/html5.vim"
Bundle "xsbeats/vim-blade"
Bundle "Raimondi/delimitMate"
Bundle "groenewege/vim-less"
Bundle "evanmiller/nginx-vim-syntax"
Bundle "Lokaltog/vim-easymotion"
Bundle "tomasr/molokai"

if filereadable(expand("~/.vimrc.bundles.local"))
  source ~/.vimrc.bundles.local
endif

filetype on
Vim配置 (vimrc) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
" Use Vim settings, rather then Vi settings. This setting must be as early as
" possible, as it has side effects.
set nocompatible

" Highlight current line
au WinLeave * set nocursorline nocursorcolumn
au WinEnter * set cursorline cursorcolumn
set cursorline cursorcolumn

" Leader
let mapleader = ","

set backspace=2   " Backspace deletes like most programs in insert mode
set nobackup
set nowritebackup
set noswapfile    " http://robots.thoughtbot.com/post/18739402579/global-gitignore#comment-458413287
set history=50
set ruler         " show the cursor position all the time
set showcmd       " display incomplete commands
set incsearch     " do incremental searching
set laststatus=2  " Always display the status line
set autowrite     " Automatically :write before running commands
set confirm       " Need confrimation while exit
set fileencodings=utf-8,gb18030,gbk,big5

" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if (&t_Co > 2 || has("gui_running")) && !exists("syntax_on")
  syntax on
endif

if filereadable(expand("~/.vimrc.bundles"))
  source ~/.vimrc.bundles
endif

filetype plugin indent on

augroup vimrcEx
  autocmd!

  " When editing a file, always jump to the last known cursor position.
  " Don't do it for commit messages, when the position is invalid, or when
  " inside an event handler (happens when dropping a file on gvim).
  autocmd BufReadPost *
    \ if &ft != 'gitcommit' && line("'\"") > 0 && line("'\"") <= line("$") |
    \   exe "normal g`\"" |
    \ endif

  " Cucumber navigation commands
  autocmd User Rails Rnavcommand step features/step_definitions -glob=**/* -suffix=_steps.rb
  autocmd User Rails Rnavcommand config config -glob=**/* -suffix=.rb -default=routes

  " Set syntax highlighting for specific file types
  autocmd BufRead,BufNewFile Appraisals set filetype=ruby
  autocmd BufRead,BufNewFile *.md set filetype=markdown

  " Enable spellchecking for Markdown
  autocmd FileType markdown setlocal spell

  " Automatically wrap at 80 characters for Markdown
  autocmd BufRead,BufNewFile *.md setlocal textwidth=80
augroup END

" Softtabs, 2 spaces
set tabstop=2
set shiftwidth=2
set shiftround
set expandtab

" Display extra whitespace
set list listchars=tab:»·,trail:·

" Use The Silver Searcher https://github.com/ggreer/the_silver_searcher
if executable('ag')
  " Use Ag over Grep
  set grepprg=ag\ --nogroup\ --nocolor

  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'

  " ag is fast enough that CtrlP doesn't need to cache
  let g:ctrlp_use_caching = 0
endif

" Color scheme
colorscheme molokai
highlight NonText guibg=#060606
highlight Folded  guibg=#0A0A0A guifg=#9090D0

" Make it obvious where 80 characters is
set textwidth=80
set colorcolumn=+1

" Numbers
set number
set numberwidth=5

" Tab completion
" will insert tab at beginning of line,
" will use completion if not at beginning
set wildmode=list:longest,list:full
function! InsertTabWrapper()
    let col = col('.') - 1
    if !col || getline('.')[col - 1] !~ '\k'
        return "\<tab>"
    else
        return "\<c-p>"
    endif
endfunction
inoremap <Tab> <c-r>=InsertTabWrapper()<cr>
inoremap <S-Tab> <c-n>

" Exclude Javascript files in :Rtags via rails.vim due to warnings when parsing
let g:Tlist_Ctags_Cmd="ctags --exclude='*.js'"

" Index ctags from any project, including those outside Rails
map <Leader>ct :!ctags -R .<CR>

" Switch between the last two files
nnoremap <leader><leader> <c-^>

" Get off my lawn
nnoremap <Left> :echoe "Use h"<CR>
nnoremap <Right> :echoe "Use l"<CR>
nnoremap <Up> :echoe "Use k"<CR>
nnoremap <Down> :echoe "Use j"<CR>

" vim-rspec mappings
nnoremap <Leader>t :call RunCurrentSpecFile()<CR>
nnoremap <Leader>s :call RunNearestSpec()<CR>
nnoremap <Leader>l :call RunLastSpec()<CR>

" Run commands that require an interactive shell
nnoremap <Leader>r :RunInInteractiveShell<space>

" Treat <li> and <p> tags like the block tags they are
let g:html_indent_tags = 'li\|p'

" Open new split panes to right and bottom, which feels more natural
set splitbelow
set splitright

" Quicker window movement
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-h> <C-w>h
nnoremap <C-l> <C-w>l

" configure syntastic syntax checking to check on open as well as save
let g:syntastic_check_on_open=1
let g:syntastic_html_tidy_ignore_errors=[" proprietary attribute \"ng-"]

autocmd Syntax javascript set syntax=jquery " JQuery syntax support

set matchpairs+=<:>
set statusline+=%{fugitive#statusline()} "  Git Hotness

" Nerd Tree
let NERDChristmasTree=0
let NERDTreeWinSize=40
let NERDTreeChDirMode=2
let NERDTreeIgnore=['\~$', '\.pyc$', '\.swp$']
let NERDTreeShowBookmarks=1
let NERDTreeWinPos="right"
autocmd vimenter * if !argc() | NERDTree | endif " Automatically open a NERDTree if no files where specified
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif " Close vim if the only window left open is a NERDTree
nmap <F5> :NERDTreeToggle<cr>

" Emmet
let g:user_emmet_mode='i' " enable for insert mode

" Search results high light
set hlsearch

" nohlsearch shortcut
nmap -hl :nohlsearch<cr>
nmap +hl :set hlsearch<cr>

" Javascript syntax hightlight
syntax enable

" ctrap
set wildignore+=*/tmp/*,*.so,*.swp,*.zip     " MacOSX/Linux"
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'

nnoremap <leader>w :w<CR>
nnoremap <leader>q :q<CR>

" RSpec.vim mappings
map <Leader>t :call RunCurrentSpecFile()<CR>
map <Leader>s :call RunNearestSpec()<CR>
map <Leader>l :call RunLastSpec()<CR>
map <Leader>a :call RunAllSpecs()<CR>

" Vim-instant-markdown doesn't work in zsh
set shell=bash\ -i

" Snippets author
let g:snips_author = 'Yuez'

" Local config
if filereadable($HOME . "/.vimrc.local")
  source ~/.vimrc.local
endif

新世代的版本管理工具 git

Git是一个分散式版本控制软件。最初的目的是为了更好的管理Linux内核开发而设计。与CVS、 Subversion等集中式版本控制软件不同,Git不需要服务器端软件就可以发挥版本控制的作用。 使得代码的维护和发布变得非常方便。

Git库目录结构

  • hooks : 存储钩子文件夹
  • logs : 存储日志文件夹
  • refs : 存储指向各个分支指针的(SHA-1)的文件夹
  • objects : 存储git对象
  • config : 存储配置文件
  • HEAD : 指向当前分支的指针文件路径
1
2
# 安装git
brew install git

Git安装完毕后,只需要使用git config简单配置下用户名和邮箱就可以使用了。

为了使Git更好用,对Git做一些配置,.gitconfig文件中可以设置自定义命令等,.gitignore 文件是默认被忽略版本管理的文件。

(gitconfig) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[push]
  default = current
[color]
  ui = auto
[alias]
  aa = add --all
  ap = add --patch
  ca = commit --amend
  ci = commit -v
  co = checkout
  br = branch
  create-branch = !sh -c 'git push origin HEAD:refs/heads/$1 && git fetch origin && git branch --track $1 origin/$1 && cd . && git checkout $1' -
  delete-branch = !sh -c 'git push origin :refs/heads/$1 && git branch -D $1' -
  merge-branch = !git checkout master && git merge @{-1}
  pr = !hub pull-request
  st = status
  up = !git fetch origin && git rebase origin/master
[core]
  excludesfile = ~/.gitignore
  autocrlf = input
[merge]
  ff = only
[include]
  path = .gitconfig.local
[commit]
  template = ~/.gitmessage
[fetch]
  prune = true
[user]
  name = zgs225
  email = zgs225@gmail.com
[credential]
  helper = osxkeychain
[github]
  user = zgs225
(gitignore) download
1
2
3
4
5
6
7
8
9
10
*.DS_Store
*.sw[nop]
.bundle
.env
db/*.sqlite3
log/*.log
rerun.txt
tags
tmp/**/*
!tmp/cache/.keep

自动集成 ternimal 环境

感谢thoughtbot组织发布的开源项目,可 以轻松的完成上述配置。这是我fork项目的地址(https://github.com/zgs225/dotfiles), 欢迎fork并完善成属于你自己的配置。

安装步骤:

1
2
3
4
5
6
7
8
9
10
11
12
# 更改为zsh, 详细参考上面zsh部分
chsh -s $(which zsh)

# clone 源码
git clone https://github.com/zgs225/dotfiles.git

# 安装rcm
brew tap thoughtbot/formulae
brew install rcm

# 安装上述环境并且完成配置
rcup -d dotfiles -x README.md -x LICENSE -x Brewfile

语言篇

编程语言五花八门,它们各自的版本也是万别千差。各种语言之间或多或少都存在着向前, 或者向后的不兼容。因为版本不兼容导致的bug也是格外的招人烦。所以,在语言篇这篇,也 是侧重与到编程语言版本管理已经环境控制。

简洁优美的类Lisp语言 Ruby

以Ruby作为语言篇的开篇,足以看得出来我对Ruby的喜爱。虽然它有着这样或者那样令人诟 病的缺点,不过作为让我体会到Web世界美妙的第一门语言,我对Ruby一直有着别样的感情。

目前,Ruby的常用版本是1.9,2.1和最新的2.2。最新版本并不是完全向后兼容,所以如果你 的电脑中存在着老版本的Ruby项目,这时候又想切换到新版本中来,那可就头疼了。好在, 有像rvmrbenv这样的Ruby版本管理软件。它们各有优劣,而我喜欢更为自动化的rvm。

一个完整的Ruby环境包括Ruby解释器、安装的RubyGems以及它们的文档。rvm用gemsets的 概念,为每一个版本的Ruby提供一个独立的RubyGems环境。可以很方便的在不同的Ruby环境 中切换而不相互影响。

1
2
3
4
5
6
# 安装rvm
# 设置mpapis公钥
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

# 安装稳定版rvm
\curl -sSL https://get.rvm.io | bash -s stable

由于网络原因,可以将rvm的Ruby安装源修改为国内淘宝的Ruby镜像服务器。 该镜像服务器15分钟以此更新,尽量保证与官方同步。这样能提高安装速度。

1
2
# 出自 http://ruby.taobao.org
sed -i .bak 's!cache.ruby-lang.org/pub/ruby!ruby.taobao.org/mirrors/ruby!' $rvm_path/config/db

推荐一篇关于rvm的文章: https://ruby-china.org/wiki/rvm-guide

同样,由于网络原因,需要将RubyGems的安装源修改到镜像服务器上。

1
2
3
4
5
6
7
8
9
10
# 切换源
gem sources --remove https://rubygems.org/
gem sources -a https://ruby.taobao.org/

# 查看源列表
gem sources -l

*** CURRENT SOURCES ***

https://rubygems.org/

以上,你就拥有了一个相对舒适的Ruby开发环境,不用为版本和网络问题发愁。啊!天空都 清净了。

技术

« 操作系统笔记: 计算机系统概述 一名菜鸟IT项目经理的成长笔记 »

Comments