> ## 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` を返します — **デプロイごとに 1 つの内側スライス** です。グループ内のすべてのイベントは同じ `ID`（コミットの SHA-1、40 文字の 16 進数）を共有し、`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)` は、現在設定されている GitHub App のリンク情報を含む `squarecloud.DeploymentCurrent` を返します。

```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）** を必要とします — これらのエンドポイントでは通常の API キーは受け付けられません。`rest.WithToken(sessionToken)` で渡すか、セッショントークンでクライアントを構築してください。
</Warning>

## レガシーの webhook フローによるリンク

`api.PostApplicationDeployWebhook(appID, accessToken)` は、GitHub の Personal Access Token（`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>
  設定済みの webhook を削除するには、トークンとして `"@"` を渡します。
</Note>

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