從零搭建和配置OSX開發環境

對於每一名開發者來講,更換系統或者更換電腦的時候,都免不了花上不短的時間去折騰開 發環境的問題。我本人也是三番兩次,深知這個過程的繁瑣。全部,根據我本身以往的經驗, 以及參考一下他人的意見,整理一下關於在Mac下作各類開發的配置,包含Java, Ruby, Vim, git, 數據庫等等。歡迎補充與修正。javascript

 Terminal篇

這篇文章包含配置控制檯環境,包括包管理工具, zsh, Vim, git的安裝配置。css

Homebrew, 你不能錯過的包管理工具

包管理工具已經成爲如今操做系統中不可缺乏的一個重要工具了,它能大大減輕軟件安裝的 負擔,節約咱們的時間。Linux中經常使用的有yumapt-get工具,甚至Windows平臺也 有Chocolatey這樣優秀的工具,OSX平臺天然有它獨有的工具。html

在OSX中,有兩款你們經常使用的管理工具:Homebrew或者MacPorts。這兩款工具都是爲了解決同 樣的問題——爲OSX安裝經常使用庫和工具。Homebrew與MacPorts的主要區別是Homebrew不會破壞OSX 原生的環境,這也是我推薦Homebrew的主要緣由。同時它安裝的全部文件都是在用戶獨立空間內 的,這讓你安裝的全部軟件對於該用戶來講都是能夠訪問的,不須要使用sudo命令。html5

在安裝Homebrew前,你須要前往AppStore下載並安裝Xcode.java

安裝方式:jquery

1
2 3 
# OSX系統基本上都自帶Ruby1.9 # 因此無需先安裝Ruby,可是以後咱們須要管理Ruby ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 

Homebrew經常使用命令:nginx

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。git

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。github

1
2 
# 切換zsh爲默認shell chsh -s $(which zsh) 

若是你想使用最新的zsh,你可使用Homebrew,此方法也會保留原生的zsh,防止你在某個 時刻須要它。sql

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開發環境,不用爲版本和網絡問題發愁。啊!天空都 清淨了。

http://yuez.me/cong-ling-da-jian-he-pei-zhi-osxkai-fa-huan-jing/

相關文章
相關標籤/搜索