> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# 部署与 Git 集成

> 查看部署历史、通过 Square Cloud GitHub App 关联仓库，或使用旧版 webhook 流程。

```go theme={null}
client := rest.NewClient(os.Getenv("SQUARECLOUD_API_KEY"))
defer client.Close()

api := rest.New(client)
```

## 列出部署历史

`api.GetApplicationDeployments(appID)` 返回 `[][]squarecloud.Deployment` —— **每个内层切片对应一次部署**。一组中的每个事件共享同一个 `ID`（提交 SHA-1，40 位十六进制字符），并贯穿生命周期状态：`pending → clone → commit → restarting → success | error`。

```go theme={null}
history, err := api.GetApplicationDeployments("abc123def456abc123def456")
if err != nil {
	panic(err)
}

for _, timeline := range history {
	last := timeline[len(timeline)-1]
	fmt.Printf("Deploy %s ended as %s\n", last.ID, last.State)

	for _, event := range timeline {
		if event.State == "clone" {
			fmt.Println("  cloned branch", event.Branch)
		}
		if event.State == "commit" {
			fmt.Println("  files", event.Files.Added, event.Files.Removed, event.Files.Modified)
		}
	}
}
```

<Note>
  `Branch` 仅在 `"clone"` 事件上填充，`Files`（`Added`、`Removed`、`Modified`）仅在 `"commit"` 事件上填充。
</Note>

## 查看当前配置

`api.GetApplicationCurrentDeployment(appID)` 返回一个 `squarecloud.DeploymentCurrent`，包含当前已配置的 GitHub App 关联。

```go theme={null}
current, err := api.GetApplicationCurrentDeployment("abc123def456abc123def456")
if err != nil {
	panic(err)
}

if current.App == nil {
	fmt.Println("no GitHub App linked")
} else {
	fmt.Println("linked to", current.App.FullName)
}
```

## 通过 Square Cloud GitHub App 关联（推荐）

`api.LinkApplicationGithubApp(appID, repoName, branch)` 通过官方 GitHub App 将一个 GitHub 仓库关联到应用。

```go theme={null}
err := api.LinkApplicationGithubApp("abc123def456abc123def456", "octocat/hello-world", "main")
if err != nil {
	panic(err)
}
```

要移除关联：

```go theme={null}
err := api.UnlinkApplicationGithubApp("abc123def456abc123def456")
```

<Warning>
  `LinkApplicationGithubApp` 和 `UnlinkApplicationGithubApp` 要求使用\*\*会话令牌（JWT）\*\*作为凭据 —— 这些 endpoint 不接受普通的 API 密钥。使用 `rest.WithToken(sessionToken)` 传入，或在构建客户端时使用它。
</Warning>

## 通过旧版 webhook 流程关联

`api.PostApplicationDeployWebhook(appID, accessToken)` 注册一个 GitHub 个人访问令牌（`ghp_*` 或 `github_pat_*`），并返回需要在 GitHub 上配置的 webhook URL。

```go theme={null}
webhookURL, err := api.PostApplicationDeployWebhook("abc123def456abc123def456", "ghp_xxx...")
if err != nil {
	panic(err)
}

fmt.Println("Configure GitHub to POST to:", webhookURL)
```

<Note>
  传入 token `"@"` 以移除已配置的 webhook。
</Note>

```go theme={null}
_, err := api.PostApplicationDeployWebhook("abc123def456abc123def456", "@")
```
