# wiki +delete

> **前置条件：** 先阅读 [`../../gitlink-shared/SKILL.md`](../../gitlink-shared/SKILL.md) 了解认证、全局参数和安全规则。
> **⚠️ 危险操作** — 删除操作**无法撤销**，执行前必须确认用户意图。

删除指定的 Wiki 页面。⚠️ **此操作不可逆！**

## 命令

```bash
# 删除 Wiki 页面
gitlink-cli wiki +delete --title "Old Page"

# 删除指定仓库的 Wiki 页面
gitlink-cli wiki +delete --owner Gitlink --repo forgeplus --title "Outdated"

# 删除前先确认（推荐）
gitlink-cli wiki +view --title "Page to Delete"  # 先查看内容
gitlink-cli wiki +delete --title "Page to Delete"  # 再删除
```

## 参数

| 参数 | Short | 必填 | 说明 |
|------|-------|------|------|
| `--title` | `-t` | **是** | 要删除的 Wiki 页面标题 |
| `--owner` | | 否 | 仓库所有者（自动从 git remote 解析） |
| `--repo` | | 否 | 仓库名称（自动从 git remote 解析） |
| `--format` | | 否 | 输出格式: `json`/`table`/`yaml` |
| `--debug` | | 否 | 开启调试输出 |

## 返回字段

### Table 格式

| 列名 | 说明 |
|------|------|
| `message` | 操作结果消息 |

### JSON 格式

```json
{
  "ok": true,
  "data": {
    "message": "Wiki page deleted successfully"
  }
}
```

## Workflow

1. **Confirm** the page title to delete.
2. **Warning** that this operation is **irreversible**.
3. **Optional**: View current content with `wiki +view` for final verification.
4. **Execute** `gitlink-cli wiki +delete --title "<page title>"`.
5. **Report** the deletion result.

> [!DANGER]
> **删除操作无法撤销！** 建议执行前先备份内容：
> ```bash
> gitlink-cli wiki +view --title "Page" > backup.md
> gitlink-cli wiki +delete --title "Page"
> ```

## API

```
DELETE https://gateway.gitlink.org.cn/api/wiki/open/deleteWiki
Body: {
  "owner": "...",
  "repo": "...",
  "projectId": 123,
  "pageName": "<title>",
  "message": ""
}
```

**工作流程**：
1. CLI 获取 `project_id`
2. 调用 Gateway API 删除页面
3. 验证删除是否成功（尝试获取页面）
4. 返回删除结果

**删除验证逻辑**：
- 如果删除 API 返回成功 → 删除成功
- 如果删除 API 失败，尝试获取页面：
  - 页面不存在 → 删除成功
  - 页面仍存在 → 删除失败

## 使用场景

### 场景 1: 删除过时文档

```bash
# 查看过时内容
gitlink-cli wiki +view --title "Old API Reference"

# 确认后删除
gitlink-cli wiki +delete --title "Old API Reference"
```

### 场景 2: 清理测试页面

```bash
# 列出所有页面
gitlink-cli wiki +list

# 删除测试页面
gitlink-cli wiki +delete --title "Test Page 1"
gitlink-cli wiki +delete --title "Test Page 2"
gitlink-cli wiki +delete --title "Test Page 3"
```

### 场景 3: 批量删除（谨慎！）

```bash
#!/bin/bash
# 批量删除包含特定关键词的页面

for title in $(gitlink-cli wiki +list --format json | jq -r ".data[].title"); do
    # 删除包含 "Draft" 的页面
    if [[ "$title" == *"Draft"* ]]; then
        echo "Deleting draft page: $title"
        gitlink-cli wiki +delete --title "$title"
    fi
done
```

### 场景 4: 删除前备份

```bash
#!/bin/bash
# 安全删除工作流：先备份再删除

title="Page to Delete"

# 1. 备份内容
gitlink-cli wiki +view --title "$title" --format json | \
  jq -r ".data.content_decoded" > "${title}-backup.md"

# 2. 确认删除
read -p "Backup created at ${title}-backup.md. Delete now? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    gitlink-cli wiki +delete --title "$title"
    echo "Page deleted. Backup saved at ${title}-backup.md"
else
    echo "Deletion cancelled."
fi
```

### 场景 5: 条件删除

```bash
#!/bin/bash
# 根据页面内容决定是否删除

title="Deprecated Feature"

# 获取页面内容
content=$(gitlink-cli wiki +view --title "$title" --format json | \
           jq -r ".data.content_decoded")

# 检查是否包含"已废弃"标记
if [[ "$content" == *"此功能已废弃"* ]]; then
    echo "Page is deprecated. Deleting..."
    gitlink-cli wiki +delete --title "$title"
else
    echo "Page is still active. Not deleting."
fi
```

## 删除验证

### 方法 1: 尝试查看页面

```bash
# 删除后验证
gitlink-cli wiki +delete --title "Test Page"

# 尝试查看（应该返回 404）
gitlink-cli wiki +view --title "Test Page"
# 预期输出：Error: 404 Not Found
```

### 方法 2: 列出所有页面

```bash
# 删除前列出
gitlink-cli wiki +list
# 包含: "Test Page"

gitlink-cli wiki +delete --title "Test Page"

# 删除后列出
gitlink-cli wiki +list
# 不包含: "Test Page"
```

### 方法 3: 统计页面数量

```bash
# 删除前
before=$(gitlink-cli wiki +list --format json | jq ".meta.total_count")
echo "Pages before: $before"

# 删除
gitlink-cli wiki +delete --title "Old Page"

# 删除后
after=$(gitlink-cli wiki +list --format json | jq ".meta.total_count")
echo "Pages after: $after"
echo "Deleted: $((before - after)) page(s)"
```

## 常见问题

### Q: 删除后能否恢复？

**A:** **不能**。GitLink Wiki 不提供版本历史或回收站功能。

**建议**：
1. 删除前务必备份：`gitlink-cli wiki +view --title "Page" > backup.md`
2. 考虑使用重命名代替删除：`gitlink-cli wiki +update --page "Old" --title "Old-Archived"`
3. 如有备份，可重新创建：`gitlink-cli wiki +create --title "Page" --file backup.md`

### Q: 删除失败提示 "page not found"？

**A:** 页面不存在或已被删除。

**解决方法**：
```bash
# 查看现有页面
gitlink-cli wiki +list

# 确认页面标题正确（区分大小写）
gitlink-cli wiki +delete --title "Correct-Title"
```

### Q: 删除后页面链接还能访问吗？

**A:** 访问已删除页面会返回 **404 Not Found**。

如果有外部链接指向该页面，需要：
1. 更新外部链接
2. 或创建同名新页面
3. 或设置重定向（GitLink Wiki 不支持，需手动更新）

### Q: 能否批量删除所有页面？

**A:** **可以，但极其危险！**

```bash
#!/bin/bash
# ⚠️ 危险操作：删除所有 Wiki 页面

read -p "⚠️  This will delete ALL wiki pages. Continue? (yes/NO) " -r
if [[ "$REPLY" == "yes" ]]; then
    for title in $(gitlink-cli wiki +list --format json | jq -r ".data[].title"); do
        echo "Deleting: $title"
        gitlink-cli wiki +delete --title "$title"
    done
    echo "All pages deleted."
else
    echo "Cancelled."
fi
```

### Q: 删除操作需要什么权限？

**A:** 需要：
- **项目写入权限**（Maintainer 或 Owner 角色）
- **有效的认证 Token**

如果权限不足：
```bash
# 403 Forbidden → 检查权限
# 401 Unauthorized → 运行 gitlink-cli auth login
```

### Q: 如何防止误删除？

**A:** 建议：
1. **删除前备份**：总是先备份内容
2. **使用别名**：创建安全删除别名
3. **确认操作**：删除前再次确认
4. **文档规范**：制定删除流程文档

## 错误处理

| 错误 | 原因 | 解决方案 |
|------|------|----------|
| `required flag --title is missing` | 未指定页面标题 | 添加 `--title "Page Title"` |
| `page not found` | 页面不存在 | 使用 `wiki +list` 查看可用页面 |
| `401 Unauthorized` | 未登录或 Token 过期 | 运行 `gitlink-cli auth login` |
| `403 Forbidden` | 无权限删除 Wiki | 检查是否有项目写入权限 |
| `failed to delete` | 删除操作失败 | 检查网络连接和 API 可用性 |

## 安全措施

### 1. 删除前备份脚本

```bash
#!/bin/bash
# safe-delete.sh - 安全删除 Wiki 页面

title="$1"

if [ -z "$title" ]; then
    echo "Usage: ./safe-delete.sh '<Page Title>'"
    exit 1
fi

# 1. 检查页面是否存在
if ! gitlink-cli wiki +view --title "$title" >/dev/null 2>&1; then
    echo "Error: Page '$title' does not exist."
    exit 1
fi

# 2. 备份内容
backup_file="${title}-backup-$(date '+%Y%m%d-%H%M%S').md"
gitlink-cli wiki +view --title "$title" --format json | \
  jq -r ".data.content_decoded" > "$backup_file"

echo "✓ Backup created: $backup_file"

# 3. 显示预览
echo ""
echo "Page content preview:"
head -n 10 "$backup_file"
echo "..."

# 4. 确认删除
read -p "Delete '$title' now? (yes/NO) " -r
echo
if [[ "$REPLY" == "yes" ]]; then
    gitlink-cli wiki +delete --title "$title"
    if [ $? -eq 0 ]; then
        echo "✓ Page deleted. Backup saved at: $backup_file"
    else
        echo "✗ Deletion failed. Backup available at: $backup_file"
    fi
else
    echo "✗ Deletion cancelled. Backup saved at: $backup_file"
fi
```

### 2. 创建删除日志

```bash
#!/bin/bash
# deleted-pages.log - 记录所有删除操作

log_file="wiki-deletion-log.txt"
title="$1"

# 记录删除操作
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Deleted: $title" >> "$log_file"

# 执行删除
gitlink-cli wiki +delete --title "$title"

echo "Deletion logged to: $log_file"
```

### 3. 使用 Git 追踪删除

如果 Wiki 内容也在 Git 中管理：

```bash
# 1. Git commit 删除前的状态
git add docs/
git commit -m "Backup before wiki deletion: $title"

# 2. 执行删除
gitlink-cli wiki +delete --title "$title"

# 3. 记录删除
echo "Deleted $title on $(date)" >> wiki-deletions.log
```

## 最佳实践

### 1. 删除前检查清单

在删除 Wiki 页面前，确保：

- [ ] 已备份页面内容
- [ ] 确认页面不再需要
- [ ] 更新了相关链接
- [ ] 通知了相关团队成员
- [ ] 有权限执行删除操作

### 2. 替代删除的方案

**考虑使用重命名代替删除**：

```bash
# 不删除，而是重命名为"已归档"
gitlink-cli wiki +update --page "Old Feature" --title "Archived-Old-Feature"

# 或在页面顶部添加废弃标记
gitlink-cli wiki +update --title "Old Feature" \
  --add "\n\n---\n\n⚠️ **此页面已废弃，请勿使用。**"
```

### 3. 批量删除的安全流程

```bash
#!/bin/bash
# 安全批量删除工作流

# 1. 列出待删除页面
declare -a pages_to_delete=(
    "Test-Page-1"
    "Test-Page-2"
    "Draft-Document"
)

# 2. 创建备份目录
backup_dir="wiki-backup-$(date '+%Y%m%d-%H%M%S')"
mkdir -p "$backup_dir"

# 3. 备份所有页面
for title in "${pages_to_delete[@]}"; do
    filename=$(echo "$title" | sed 's/[^a-zA-Z0-9_-]/_/g').md
    gitlink-cli wiki +view --title "$title" --format json | \
      jq -r ".data.content_decoded" > "$backup_dir/$filename"
    echo "Backed up: $title"
done

# 4. 确认删除
echo ""
echo "Backup created at: $backup_dir"
read -p "Delete all ${#pages_to_delete[@]} pages now? (yes/NO) " -r
echo

if [[ "$REPLY" == "yes" ]]; then
    # 5. 执行删除
    for title in "${pages_to_delete[@]}"; do
        gitlink-cli wiki +delete --title "$title"
        echo "Deleted: $title"
    done
    echo "✓ All pages deleted. Backups saved at: $backup_dir"
else
    echo "✗ Cancelled. Backups available at: $backup_dir"
fi
```

### 4. 监控删除操作

```bash
#!/bin/bash
# 监控 Wiki 页面数量变化

# 记录当前页面数量
current_count=$(gitlink-cli wiki +list --format json | jq ".meta.total_count")
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Current page count: $current_count" >> wiki-monitor.log

# 如果页面数量异常减少，发出警告
if [ -f "previous-count.txt" ]; then
    previous_count=$(cat previous-count.txt)
    if [ "$current_count" -lt "$previous_count" ]; then
        echo "⚠️  Warning: Page count decreased from $previous_count to $current_count"
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] WARNING: Count decreased: $previous_count -> $current_count" >> wiki-monitor.log
    fi
fi

echo "$current_count" > previous-count.txt
```

## 完整示例

### 示例：清理过时文档

```bash
#!/bin/bash
# 完整的文档清理工作流

# 1. 定义过时页面列表
declare -a outdated_pages=(
    "Legacy-API-v1"
    "Deprecated-Feature-X"
    "Old-Installation-Guide"
)

# 2. 创建备份
backup_dir="wiki-cleanup-backup-$(date '+%Y%m%d')"
mkdir -p "$backup_dir"

echo "=== Wiki Cleanup Process ==="
echo "Backing up outdated pages..."

for title in "${outdated_pages[@]}"; do
    if gitlink-cli wiki +view --title "$title" >/dev/null 2>&1; then
        filename=$(echo "$title" | sed 's/[^a-zA-Z0-9_-]/_/g').md
        gitlink-cli wiki +view --title "$title" --format json | \
          jq -r ".data.content_decoded" > "$backup_dir/$filename"
        echo "✓ Backed up: $title"
    else
        echo "✗ Skipped (not found): $title"
    fi
done

# 3. 确认删除
echo ""
echo "Outdated pages to delete:"
printf "  - %s\n" "${outdated_pages[@]}"
echo ""
read -p "Proceed with deletion? (yes/NO) " -r
echo

if [[ "$REPLY" == "yes" ]]; then
    echo "Deleting outdated pages..."

    for title in "${outdated_pages[@]}"; do
        if gitlink-cli wiki +delete --title "$title" 2>/dev/null; then
            echo "✓ Deleted: $title"
        else
            echo "✗ Failed (already deleted?): $title"
        fi
    done

    echo ""
    echo "✓ Cleanup completed. Backups saved at: $backup_dir"
    echo "Remaining pages: $(gitlink-cli wiki +list --format json | jq '.meta.total_count')"
else
    echo "✗ Cleanup cancelled. Backups available at: $backup_dir"
fi
```

## References

- [gitlink-wiki](../SKILL.md)
- [wiki +create](wiki-create.md) — 创建 Wiki 页面
- [wiki +update](wiki-update.md) — 更新 Wiki 页面
- [wiki +list](wiki-list.md) — 列出 Wiki 页面
- [gitlink-shared](../../gitlink-shared/SKILL.md)
