3.2. 양방향 플러그인: bitbucket-pr
개요
이 장에서는 Bitbucket Server 레포 하나의 pull request 를 위키와 주고받는 플러그인 bitbucket-pr 를 따라 만듭니다. 이 플러그인은 알림(/notify)을 뺀 끝점을 모두 씁니다. 설정 확인, 가져오기, 제목 보내기, 할 일(댓글 달기), AI 도구, 웹훅입니다. 단계마다 Bitbucket 을 흉내 내는 가짜 서버와 devharness 로 결과를 확인합니다.
완성된 코드는 MindWiki 레포의 plugins/bitbucket-pr 에 있습니다. 파일은 plugin.go(manifest 와 처리기), bitbucket.go(Bitbucket REST 클라이언트), main.go(띄우기) 셋입니다.
시작하기 전에
- 3.1. 가져오기 플러그인: kisa-notice를 마쳤다고 가정합니다. manifest · 커서 · devharness 사용법은 다시 설명하지 않습니다.
- devharness 로 따라 하려면 Bitbucket Server 나, 같은 REST 경로로 응답하는 가짜 서버가 필요합니다.
- 실제 서버를 쓰면 HTTP 접근 토큰이 필요합니다. 가져오기에는 읽기 권한, 제목 보내기와 댓글에는 쓰기 권한이 필요합니다.
- 이 장의 출력은 가짜 서버를
127.0.0.1:9202에 띄워 얻었습니다. 이 서버는plugin_test.go의 가짜 Bitbucket(fakeBitbucket)과 같은 모양으 로 응답합니다. pull request 셋(1 · 2 는 열림, 3 은 병합됨)이 있고, 한 쪽에 2건씩 응답하고, 토큰tok만 받습니다. - 아래 예시의 Bitbucket 주소는
http://bitbucket.example.com:7990, 프로젝트 키는OAI, 레포는demo입니다.
만들 것
| 끝점 | 하는 일 |
|---|---|
POST /config/verify | 토큰으로 레포를 읽어 설정을 확인합니다 |
POST /sync/pull | pull request 를 가져옵니다. 처음 뒤에는 바뀐 것만 읽습니다 |
POST /sync/push | 위키에서 고친 제목을 Bitbucket 에 씁니다 |
POST /actions/add_comment | 행에서 실행한 할 일로 pull request 에 댓글을 답니다 |
POST /tools/search_prs | 제목 낱말 · 번호로 pull request 를 찾습니다 |
POST /webhook | Bitbucket 의 pr:modified 알림을 받습니다 |
단계 1. 설정 칸과 비밀 둘 정하기
설치마다 다른 값은 설정 칸(config_schema)과 비밀값(secret_fields)으로 받습니다. 주소 · 프로젝트 · 레포는 설정 칸, 토큰과 웹훅 비밀은 비밀값입니다.
ConfigSchema: json.RawMessage(`{"type":"object",` +
`"required":["base_url","project","repo"],"properties":{` +
`"base_url":{"type":"string","format":"uri","title":"Bitbucket 주소","maxLength":200},` +
`"project":{"type":"string","title":"프로젝트 키","maxLength":64},` +
`"repo":{"type":"string","title":"레포","maxLength":128}}}`),
SecretFields: []plugin.SecretField{
{Name: "token", Title: plugin.I18n{"ko": "HTTP 접근 토큰", "en": "HTTP access token"},
Uses: []string{plugin.CapSync, plugin.CapActions, plugin.CapTools}},
{Name: "webhook_secret", Title: plugin.I18n{"ko": "웹훅 비밀", "en": "Webhook secret"},
Uses: []string{plugin.CapWebhooks}},
},
Uses 는 그 비밀을 어느 요청에 실을지 정합니다. 값은 capability 이름(sync · actions · tools · webhooks)입니다.
token은 가져오기 · 보내기 · 할 일 · 도구 요청에만 실립니다. 웹훅 요청에는 실리지 않습니다.webhook_secret은 웹훅 요청에만 실립니다./config/verify에는 언제나 모든 비밀이 실립니다.
devharness 는 -secrets-file 의 비밀을 모든 요청에 넣습니다. 위키는 uses 에 적은 끝점에만 넣습니다. 그래서 devharness 에서 되던 요청이 위키에서는 비밀이 없어 실패할 수 있습니다. 끝점마다 필요한 비밀을 uses 에 빠짐없이 적습니다.
단계 2. 설정 확인하기(/config/verify)
워크스페이스 관리자가 「확인하고 저장」을 누르면 위키는 /config/verify 를 호출합니다. 위키는 이 호출이 성공해야만 설정을 저장합니다. 플러그인은 여기서 토큰으로 레포를 한 번 읽어 봅니다. 모든 처리기가 같은 검사를 쓰도록 설정 읽기를 client 하나에 둡니다.
func (p *Plugin) client(r *plugin.Request) (*Client, error) {
var c config
if err := r.ConfigInto(&c); err != nil {
return nil, plugin.ErrInvalidInput("설정을 읽지 못했습니다", "base_url · project · repo 를 넣으세요")
}
var bad []plugin.FieldError
if !strings.HasPrefix(c.BaseURL, "http://") && !strings.HasPrefix(c.BaseURL, "https://") {
bad = append(bad, plugin.FieldError{Path: "/base_url", Message: "http:// 나 https:// 로 시작하는 주소"})
}
// /project · /repo 도 같은 방식으로 확인합니다.
if len(bad) > 0 {
return nil, plugin.ErrInvalidInput("설정이 맞지 않습니다", "칸마다 안내를 보고 고치세요", bad...)
}
token := r.Secrets["token"]
if token == "" {
return nil, plugin.ErrInvalidInput("HTTP 접근 토큰이 없습니다", "…",
plugin.FieldError{Path: "/token", Message: "필요합니다"})
}
return &Client{Base: c.BaseURL, Project: c.Project, Repo: c.Repo, Token: token, HTTP: p.HTTP}, nil
}
bitbucket.go 의 do 가 Bitbucket 의 응답을 프로토콜 code 로 바꿉니다. 401 은 auth, 403 · 400 은 permanent, 404 는 not_found, 그 밖은 retry 입니다. auth 가 세 번 이어지면 위키가 설치를 멈추고(paused_auth) 관리자에게 알립니다. Verify 는 레포가 없을 때의 not_found 를 칸 오류(/project · /repo)로 바꿔 돌려줍니다.