emacs 開發環境配置(1)——golang開發環境

1、參考

emacs系列文章目錄——更新inghtml

Becoming an emacs gophergit

Emacs Golang開發環境配置指南github

Stop debugging Go with Println and use Delve insteadgolang

Delve調試器sql

極簡Emacs開發環境配置shell

2、安裝golang包

2.1 goimports

Command goimports updates your Go import lines, adding missing ones and removing unreferenced ones.express

對於代碼中引入的第三方模塊,自動更新json

goimports命令能自動格式化代碼,自動添加、移除imports,並且與Emacs集成良好。能夠替代官方gofmt命令。segmentfault

GO111MODULE=on go get -u golang.org/x/tools/cmd/goimports

2.2 godef

Godef, given an expression or a location in a source file, prints the location of the definition of the symbol referred to.api

對於代碼中的函數引用,能夠查看原始定義位置
godef命令能在Go源碼變量、函數定義間跳轉,是查看變量、函數、文件定義的好助手

GO111MODULE=on go get -u github.com/rogpeppe/godef

2.3 gocode

An autocompletion daemon for the Go programming language

自動補全代碼
gocode命令能爲代碼自動補全提供後臺支持,是EmacsGo代碼補全必不可少的backend

GO111MODULE=on go get -u github.com/nsf/gocode

3、安裝emacs包

包名 描述 其餘
auto-Complete An Intelligent auto-completion extension for Emacs https://github.com/auto-compl...
go-mode Emacs mode for the Go programming language https://github.com/dominikh/g...
go-complete Native Go completion for Emacs https://github.com/vibhavp/go...
go-autocomplete auto-complete-mode backend for go-mode https://melpa.org/#/go-autoco...
autopair Automagically pair braces and quotes in emacs like TextMate https://github.com/joaotavora...
;; Init the auto complete modules
(ac-config-default)
(global-auto-complete-mode t)
(require 'go-autocomplete)

;; Enable auto-complete
(auto-complete-mode 1)

;; Define keymaps
(define-key ac-mode-map (kbd "M-TAB") 'auto-complete)
(global-set-key (kbd"C-c C-c") 'godef-jump)

;; Set some quick config vals
(setq ac-auto-start 1)
(setq ac-auto-show-menu 0.8)

;; Just to make sure go tools are enabled
(add-to-list 'exec-path "~/go/bin")

;; Automatically format code on save
(setq gofmt-command "goimports")
(add-hook 'before-save-hook 'gofmt-before-save)
(add-hook 'go-mode-hook 'auto-complete-for-go)

4、go-mode的命令

4.1 imports區域

(1) go-goto-imports, 跳轉到imports區域

image.png

(2) go-import-add, 添加新的import aaa

image.png

(3) go-remove-unused-imports, 刪除再也不使用的包

image.png

4.2 godef

(1) go-jump,跳轉到表達式的定義

image.png

(2) godef-jump-other-window,新建窗口,並跳轉到表達式定義

image.png

4.3 function

(1) go-goto-arguments, 跳轉到函數的參數

image.png

(2) go-goto-docstring 跳轉到函數的說明文檔,若是沒有說明文檔,會建立

image.png

(3) go-goto-function, 跳轉到函數func關鍵字,通常用於在函數文檔中,跳轉到函數代碼

image.png

(4) go-goto-function-name, 跳轉到函數名稱處

image.png

(5) go-goto-return-values, 跳轉到函數定義中的返回值處

image.png

(6) go-goto-method-receiver, 跳轉到函數的調用者處

image.png

4.4 其餘

(1) pop-tag-mark, 回退到前一個光標位置

image.png

(2) beginning-of-defun, 跳轉到函數的初始位置(適合函數之間的跳轉)

image.png

(3) end-of-defun, 跳轉到函數的結束位置

image.png

5、快捷鍵綁定

5.1 函數跳轉和回退

;; Godef jump key binding                                                                   
(global-set-key (kbd "M-,") 'godef-jump)                                                  
(global-set-key (kbd "M-.") 'pop-tag-mark)

5.2 代碼塊的跳轉

C-M-a 跳轉到上一個函數

C-M-e 跳轉到下一個函數

5.3 代碼註釋

M-;能夠實現多行註釋與解註釋

image.png

6、debug

6.1 安裝

GO111MODULE=on go get -u github.com/go-delve/delve/cmd/dlv

➜  ~ dlv version
Delve Debugger
Version: 1.6.0
Build: $Id: 8cc9751909843dd55a46e8ea2a561544f70db34d $

6.2 基本命令

➜  ~ dlv -h
Delve is a source level debugger for Go programs.

Delve enables you to interact with your program by controlling the execution of the process,
evaluating variables, and providing information of thread / goroutine state, CPU register state and more.

The goal of this tool is to provide a simple yet powerful interface for debugging Go programs.

Pass flags to the program you are debugging using `--`, for example:

`dlv exec ./hello -- server --config conf/config.toml`

Usage:
  dlv [command]

Available Commands:
  attach      Attach to running process and begin debugging.
  connect     Connect to a headless debug server.
  core        Examine a core dump.
  dap         [EXPERIMENTAL] Starts a TCP server communicating via Debug Adaptor Protocol (DAP).
  debug       Compile and begin debugging main package in current directory, or the package specified.
  exec        Execute a precompiled binary, and begin a debug session.
  help        Help about any command
  run         Deprecated command. Use 'debug' instead.
  test        Compile test binary and begin debugging program.
  trace       Compile and begin tracing program.
  version     Prints version.

Flags:
      --accept-multiclient               Allows a headless server to accept multiple client connections.
      --allow-non-terminal-interactive   Allows interactive sessions of Delve that don't have a terminal as stdin, stdout and stderr
      --api-version int                  Selects API version when headless. New clients should use v2. Can be reset via RPCServer.SetApiVersion. See Documentation/api/json-rpc/README.md. (default 1)
      --backend string                   Backend selection (see 'dlv help backend'). (default "default")
      --build-flags string               Build flags, to be passed to the compiler. For example: --build-flags="-tags=integration -mod=vendor -cover -v"
      --check-go-version                 Checks that the version of Go in use is compatible with Delve. (default true)
      --disable-aslr                     Disables address space randomization
      --headless                         Run debug server only, in headless mode.
  -h, --help                             help for dlv
      --init string                      Init file, executed by the terminal client.
  -l, --listen string                    Debugging server listen address. (default "127.0.0.1:0")
      --log                              Enable debugging server logging.
      --log-dest string                  Writes logs to the specified file or file descriptor (see 'dlv help log').
      --log-output string                Comma separated list of components that should produce debug output (see 'dlv help log')
      --only-same-user                   Only connections from the same user that started this instance of Delve are allowed to connect. (default true)
  -r, --redirect stringArray             Specifies redirect rules for target process (see 'dlv help redirect')
      --wd string                        Working directory for running the program.

Additional help topics:
  dlv backend  Help about the --backend flag.
  dlv log      Help about logging flags.
  dlv redirect Help about file redirection.

Use "dlv [command] --help" for more information about a command.

6.3 dlv子命令

命令 說明
dlv attach Attach to running process and begin debugging 調試正在運行的進程
dlv connect Connect to a headless debug server 鏈接到遠端的debug服務器
dlv core Examine a core dump
dlv dap [EXPERIMENTAL] Starts a TCP server communicating via Debug Adaptor Protocol (DAP)
dlv debug Compile and begin debugging main package in current directory, or the package specified
dlv exec Execute a precompiled binary, and begin a debug session
dlv help Deprecated command. Use 'debug' instead
dlv test Compile test binary and begin debugging program
dlv trace Compile and begin tracing program
dlv version Prints version

6.4 dlv debug子命令

(dlv) help
The following commands are available:

Running the program:
    call ------------------------ Resumes process, injecting a function call (EXPERIMENTAL!!!)
    continue (alias: c) --------- Run until breakpoint or program termination.
    next (alias: n) ------------- Step over to next source line.
    rebuild --------------------- Rebuild the target executable and restarts it. It does not work if the executable was not built by delve.
    restart (alias: r) ---------- Restart process.
    step (alias: s) ------------- Single step through program.
    step-instruction (alias: si)  Single step a single cpu instruction.
    stepout (alias: so) --------- Step out of the current function.

Manipulating breakpoints:
    break (alias: b) ------- Sets a breakpoint.
    breakpoints (alias: bp)  Print out info for active breakpoints.
    clear ------------------ Deletes breakpoint.
    clearall --------------- Deletes multiple breakpoints.
    condition (alias: cond)  Set breakpoint condition.
    on --------------------- Executes a command when a breakpoint is hit.
    trace (alias: t) ------- Set tracepoint.

Viewing program variables and memory:
    args ----------------- Print function arguments.
    display -------------- Print value of an expression every time the program stops.
    examinemem (alias: x)  Examine memory:
    locals --------------- Print local variables.
    print (alias: p) ----- Evaluate an expression.
    regs ----------------- Print contents of CPU registers.
    set ------------------ Changes the value of a variable.
    vars ----------------- Print package variables.
    whatis --------------- Prints type of an expression.

Listing and switching between threads and goroutines:
    goroutine (alias: gr) -- Shows or changes current goroutine
    goroutines (alias: grs)  List program goroutines.
    thread (alias: tr) ----- Switch to the specified thread.
    threads ---------------- Print out info for every traced thread.

Viewing the call stack and selecting frames:
    deferred --------- Executes command in the context of a deferred call.
    down ------------- Move the current frame down.
    frame ------------ Set the current frame, or execute command on a different frame.
    stack (alias: bt)  Print stack trace.
    up --------------- Move the current frame up.

Other commands:
    config --------------------- Changes configuration parameters.
    disassemble (alias: disass)  Disassembler.
    edit (alias: ed) ----------- Open where you are in $DELVE_EDITOR or $EDITOR
    exit (alias: quit | q) ----- Exit the debugger.
    funcs ---------------------- Print list of functions.
    help (alias: h) ------------ Prints the help message.
    libraries ------------------ List loaded dynamic libraries
    list (alias: ls | l) ------- Show source code.
    source --------------------- Executes a file containing a list of delve commands
    sources -------------------- Print list of source files.
    types ---------------------- Print list of types

Type help followed by a command for full documentation.

斷點相關命令:

命令 描述
break (alias: b) 建立新的斷點
breakpoints (alias: bp) 輸出當前斷點信息
clear 取消斷點
clearall 取消多個斷點
condition (alias: cond) 設置斷點條件
on 在斷點中執行命令
trace (alias: t) 設置追蹤點

程序執行相關命令:

命令 說明
call 恢復進程,注入函數調用
continue (alias: c) 繼續執行,一直到程序結束或者下一個斷點
next (alias: n) 繼續執行下一行代碼
rebuild 從新編譯源代碼,而且從新運行,若是不是用dlv構建,沒法從新運行
restart (alias: r) 從新運行
step (alias: s)) 單步執行
step-instruction (alias: si) 單步,一條CPU指令
stepout (alias: so) 退出當前函數

7、dlv使用

7.1 源碼查看

示例 說明
list TestPrint 查看函數TestPrint的源代碼
list print_test.go:8 查看文件print_test.go第8行的代碼
funcs TestPrint 查看函數TestPrint的具體位置

7.2 dlv test

(1) 進入dlv test

示例 說明
dlv test -- -test.run ^TestPrint1$ 只測試具體函數,須要注意:此時須要先進入對應的目錄中, image.png
dlv test ./test image.png

(2) 斷點的設置與撤銷

示例 說明
break print1_test.go:8 斷點經過設置具體的文件+行號 image.png
breakpoints image.png
clear 1 image.png
clearall image.png

7.3 實際debug

(1) 進入測試

# 進入測試目錄
cd projectDir/test

# 測試具體的函數
dlv test -- -test.run TestESParse

(2) 設置斷點

Type 'help' for list of commands.
(dlv) b esql.go:318
Breakpoint 1 set at 0x182c398 for  ./esql.go:318
(dlv) b esqlCheck.go:138
Breakpoint 2 set at 0x1839cd2 for ./esqlCheck.go:138

(3) 執行程序

continue

(4) 查看當前的執行狀態

命令 說明
args 查看當前的全部參數
args arg1 查看參數arg1
print arg1 打印參數arg1
相關文章
相關標籤/搜索