

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 迁移到 Amazon CodeCommit
迁移到 CodeCommit

您可以通过多种方法将 Git 存储库迁移到 CodeCommit 存储库：克隆、镜像、迁移所有或部分分支等。您也可以将计算机上的本地、非版本控制内容迁移到 CodeCommit。

以下主题演示了迁移存储库的一些方法。您的步骤可能会有所不同，具体取决于存储库的类型、样式或复杂性以及您针对迁移内容和方式所做的决定。对于非常大的存储库，您可能需要考虑[增量迁移](how-to-push-large-repositories.md)。

**注意**  
您可以从其他版本控制系统（例如 Perforce、Subversion、TFS 等）迁移到 CodeCommit，但必须先迁移到 Git。  
有关更多选项，请参阅 Git 文档。  
或者，您可以阅读 Scott Chacon 和 Ben Straub 编写的 [Pro Git](http://git-scm.com/book/en/v2/Git-and-Other-Systems-Migrating-to-Git) 图书中的*迁移到 Git* 部分。

**Topics**
+ [

# 将 Git 仓库迁移到 Amazon CodeCommit
](how-to-migrate-repository-existing.md)
+ [将内容迁移到 CodeCommit](how-to-migrate-repository-local.md)
+ [以增量方式迁移存储库](how-to-push-large-repositories.md)

# 将 Git 仓库迁移到 Amazon CodeCommit


您可以将现有 Git 仓库迁移到 CodeCommit 仓库。本主题中的过程将演示如何将托管在另一个 Git 存储库上的项目迁移到 CodeCommit。在该过程中，您将：
+ 完成所需的初始设置 CodeCommit。
+ 创建 CodeCommit 存储库。
+ 克隆存储库并将其推送到 CodeCommit。
+ 查看 CodeCommit 存储库中的文件。
+ 与您的团队共享 CodeCommit 存储库。

**Topics**
+ [

## 步骤 0：需要进行设置才能访问 CodeCommit
](#how-to-migrate-existing-setup)
+ [

## 步骤 1：创建 CodeCommit 存储库
](#how-to-migrate-existing-create)
+ [

## 第 2 步：克隆存储库并推送到 CodeCommit 存储库
](#how-to-migrate-existing-clone)
+ [

## 步骤 3：查看中的文件 CodeCommit
](#how-to-migrate-existing-view)
+ [

## 步骤 4：共享 CodeCommit 存储库
](#how-to-migrate-existing-share)

## 步骤 0：需要进行设置才能访问 CodeCommit


在将存储库迁移到之前 CodeCommit，必须为本地计算机创建和配置一个 IAM 用户， CodeCommit 并配置本地计算机以进行访问。您还应安装 Amazon CLI 来管理 CodeCommit。尽管你可以在没有它的情况下执行大多数 CodeCommit 任务，但在命令行或终端上使用 Git 时，它 Amazon CLI 提供了灵活性。

如果您已经做好了准备 CodeCommit，则可以直接跳到[步骤 1：创建 CodeCommit 存储库](#how-to-migrate-existing-create)。

**创建和配置用于访问的 IAM 用户 CodeCommit**

1. 前往 [http://aws.amazon.com](https://www.amazonaws.cn/)，并选择**注册**，创建一个 Amazon Web Services 账户。

1. 创建 IAM 用户或使用您的 Amazon Web Services 账户中的现有用户。确保您具有与该 IAM 用户关联的访问密钥 ID 和秘密访问密钥。有关更多信息，请参阅[在 Amazon Web Services 账户中创建 IAM 用户](https://docs.amazonaws.cn/IAM/latest/UserGuide/Using_SettingUpUser.html)。
**注意**  
CodeCommit 要求 Amazon Key Management Service。如果您使用的是现有的 IAM 用户，请确保该用户没有明确拒绝所要求的 Amazon KMS 操作的策略 CodeCommit。有关更多信息，请参阅 [Amazon KMS 和加密](encryption.md)。

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. 在 IAM 控制台的导航窗格中，选择**用户**，然后选择要配置 CodeCommit 访问权限的 IAM 用户。

1. 在 **Permissions** 选项卡上，选择 **Add Permissions**。

1. 在 **Grant permissions (授予权限)** 中，选择 **Attach existing policies directly (直接附加现有策略)**。

1. 从策略列表中，选择**AWSCodeCommitPowerUser**或其他托管策略进行 CodeCommit 访问。有关更多信息，请参阅 [Amazon 的托管策略 CodeCommit](security-iam-awsmanpol.md)。

   选择要附加的策略后，选择**下一步：审核**以审核要附加到 IAM 用户的策略列表。如果列表正确，选择 **Add permissions**。

    有关 CodeCommit 托管策略以及与其他群组和用户共享仓库访问权限的更多信息，请参阅[共享存储库](how-to-share-repository.md)和[的身份验证和访问控制 Amazon CodeCommit](auth-and-access-control.md)。

**要安装和配置 Amazon CLI**

1. 在您的本地计算机上，下载并安装 Amazon CLI。这是通过命令行与交互 CodeCommit 的先决条件。我们建议您安装 Amazon CLI 版本 2。它是的最新主要版本 Amazon CLI ，支持所有最新功能。它是唯一支持使用根账户、联合访问权限或临时证书的版本**git-remote-codecommit**。 Amazon CLI 

   有关更多信息，请参阅[使用 Amazon 命令行界面进行设置](https://docs.amazonaws.cn/cli/latest/userguide/cli-chap-getting-set-up.html)。
**注意**  
CodeCommit 仅适用于 1.7.38 及更高 Amazon CLI 版本。作为最佳实践，请安装或升级 Amazon CLI 到可用的最新版本。要确定 Amazon CLI 您安装了哪个版本，请运行**aws --version**命令。  
要将旧版本的升级 Amazon CLI 到最新版本，请参阅[安装 Amazon Command Line Interface](https://docs.amazonaws.cn/cli/latest/userguide/installing.html)。

1. 运行此命令以验证的 CodeCommit 命令 Amazon CLI 是否已安装。

   ```
   aws codecommit help
   ```

   此命令返回 CodeCommit 命令列表。

1.  Amazon CLI 使用**configure**命令配置配置文件，如下所示：。

   ```
   aws configure
   ```

   出现提示时，指定要与之 Amazon 配合使用的 IAM 用户的访问 Amazon 密钥和私有访问密钥 CodeCommit。另外，请务必指定存储库的 Amazon Web Services 区域 存在位置，例如`us-east-2`。系统提示指定默认输出格式时，指定 `json`。例如，如果您正在为 IAM 用户配置相关配置文件：

   ```
   AWS Access Key ID [None]: Type your IAM user Amazon access key ID here, and then press Enter
   AWS Secret Access Key [None]: Type your IAM user Amazon secret access key here, and then press Enter
   Default region name [None]: Type a supported region for CodeCommit here, and then press Enter
   Default output format [None]: Type json here, and then press Enter
   ```

   有关创建和配置用于的配置文件的更多信息 Amazon CLI，请参阅以下内容：
   + [命名配置文件](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-files.html)
   + [在中使用 IAM 角色 Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-role.html)
   + [设置命令](https://docs.amazonaws.cn/cli/latest/reference/set.html)
   + [使用轮换凭证连接到 Amazon CodeCommit 存储库](temporary-access.md)

   要连接到存储库或其他存储库中的资源 Amazon Web Services 区域，必须 Amazon CLI 使用默认的区域名称重新配置。支持的默认区域名称 CodeCommit 包括：
   + us-east-2
   + us-east-1
   + eu-west-1
   + us-west-2
   + ap-northeast-1
   + ap-southeast-1
   + ap-southeast-2
   + ap-southeast-3
   + me-central-1
   + eu-central-1
   + ap-northeast-2
   + sa-east-1
   + us-west-1
   + eu-west-2
   + ap-south-1
   + ap-south-1
   + ca-central-1
   + us-gov-west-1
   + us-gov-east-1
   + eu-north-1
   + ap-east-1
   + me-south-1
   + cn-north-1
   + cn-northwest-1
   + eu-south-1
   + ap-northeast-3
   + af-south-1
   + il-central-1

   有关 CodeCommit 和的更多信息 Amazon Web Services 区域，请参阅[区域和 Git 连接端点](regions.md)。有关 IAM、访问密钥和秘密密钥的更多信息，请参阅‭[如何获取凭证？](https://docs.amazonaws.cn/IAM/latest/UserGuide/IAM_Introduction.html#IAM_SecurityCredentials)和[管理 IAM 用户的访问密钥](https://docs.amazonaws.cn/IAM/latest/UserGuide/ManagingCredentials.html)。有关 Amazon CLI 和配置文件的更多信息，请参阅[命名配置文件](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-files.html)。

接下来，您必须安装 Git。
+ **对于 Linux、macOS 或 Unix**：

  要处理 CodeCommit 存储库中的文件、提交和其他信息，必须在本地计算机上安装 Git。 CodeCommit 支持 Git 版本 1.7.9 及更高版本。Git 版本 2.28 支持为初始提交配置分支名称。我们建议使用最新版本的 Git。

  要安装 Git，建议您访问 [Git 下载](http://git-scm.com/downloads)等网站。
**注意**  
Git 是一个不断发展的平台，会定期进行更新。有时，功能更改可能会影响其工作方式 CodeCommit。如果您在使用特定版本的 Git 时遇到问题 CodeCommit，请查看中的信息[故障排除](troubleshooting.md)。
+ **对于 Windows：**

  要处理 CodeCommit 存储库中的文件、提交和其他信息，必须在本地计算机上安装 Git。 CodeCommit 支持 Git 版本 1.7.9 及更高版本。Git 版本 2.28 支持为初始提交配置分支名称。我们建议使用最新版本的 Git。

  要安装 Git，建议访问 [Git for Windows](https://gitforwindows.org/) 等网站。如果您使用此链接安装 Git，则可以接受除以下设置之外的所有安装默认设置：
  + 在**调整 PATH 环境**步骤中出现提示时，从命令行中选择使用 Git 的选项。
  + （可选）如果您打算将 HTTPS 与中包含的凭据帮助程序一起使用， Amazon CLI 而不是为其配置 Git 凭据 CodeCommit，请在 “**配置额外选项**” 页面上，确保清除 “**启用 Git 凭据管理器**” 选项。仅当 IAM 用户配置 Git 凭证时，Git 凭证管理器 CodeCommit 才与兼容。有关更多信息，请参阅[适用于使用 Git 凭证的 HTTPS 用户](setting-up-gc.md)和[Windows 版 Git：我安装了 Windows 版 Git，但在访问我的存储库时被系统拒绝 (403)](troubleshooting-ch.md#troubleshooting-windowshttps)。
**注意**  
Git 是一个不断发展的平台，会定期进行更新。有时，功能更改可能会影响其工作方式 CodeCommit。如果您在使用特定版本的 Git 时遇到问题 CodeCommit，请查看中的信息[故障排除](troubleshooting.md)。

CodeCommit 同时支持 HTTPS 和 SSH 身份验证。要完成设置，您必须为 CodeCommit （HTTPS，建议大多数用户使用）、访问时使用的 SSH 密钥对 CodeCommit （SSH）、**git-remote-codecommit**（建议使用联合访问的用户使用）或 Amazon CLI （HTTPS）中包含的凭据助手配置 Git 凭证。
+ 有关在所有支持的操作系统上设置 Git 凭证的信息，请参阅[步骤 3：创建 Git 凭据，以便通过 HTTPS 连接到 CodeCommit](setting-up-gc.md#setting-up-gc-iam)。
+ 有关在 Linux、macOS 或 Unix 上设置 SSH 的信息，请参阅[SSH 和 Linux、macOS 或 Unix：为 Git 设置公钥和私钥以及 CodeCommit](setting-up-ssh-unixes.md#setting-up-ssh-unixes-keys-unixes)。
+  有关在 Windows 上设置 SSH 的信息，请参阅[第 3 步：为 Git 设置公钥和私钥以及 CodeCommit](setting-up-ssh-windows.md#setting-up-ssh-windows-keys-windows)。
+ 对于 **git-remote-codecommit**，请参阅[使用的 HTTPS 连接 Amazon CodeCommit 的设置步骤 git-remote-codecommit](setting-up-git-remote-codecommit.md)。
+ 有关 Linux、macOS 或 Unix 上的凭证助手，请参阅[设置凭证助手（Linux、macOS 或 Unix）](setting-up-https-unixes.md#setting-up-https-unixes-ch-config)。
+ 有关在 Windows 上设置凭证辅助程序的信息，请参阅[设置凭证辅助程序 (Windows)](setting-up-https-windows.md#setting-up-https-windows-ch-config)。

## 步骤 1：创建 CodeCommit 存储库


在本节中，您将使用 CodeCommit 控制台创建用于本教程其余部分的 CodeCommit 存储库。要使用创建存储库，请参阅[创建存储库 (Amazon CLI)](how-to-create-repository.md#how-to-create-repository-cli)。 Amazon CLI 

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在区域选择器中，选择要创建存储库 Amazon Web Services 区域 的位置。有关更多信息，请参阅 [区域和 Git 连接端点](regions.md)。

1. 在**存储库**页面上，选择**创建存储库**。

1. 在**创建存储库**页面上的**存储库名称**中，为存储库输入名称。
**注意**  
存储库名称区分大小写。名称在 Amazon Web Services 区域 中对于 Amazon Web Services 账户必须唯一。

1. （可选）在**描述**中，输入存储库的描述。这可以帮助您及其他用户了解存储库的用途。
**注意**  
“描述”字段在控制台中显示“Markdown”，并接受所有 HTML 字符和有效的 Unicode 字符。如果您是使用`GetRepository`或的应用程序开发人员，`BatchGetRepositories` APIs 并且计划在 Web 浏览器中显示存储库描述字段，请参阅 [CodeCommit API 参考](https://docs.amazonaws.cn/codecommit/latest/APIReference/)。

1. （可选）选择 **Add t** ag，向存储库添加一个或多个存储库标签（可帮助您组织和管理 Amazon 资源的自定义属性标签）。有关更多信息，请参阅 [在中标记存储库 Amazon CodeCommit](how-to-tag-repository.md)。

1. （可选）展开**其他配置**以指定是使用默认密钥 Amazon 托管式密钥 还是您自己的客户托管密钥来加密和解密此存储库中的数据。如果您选择使用自己的客户托管密钥，则必须确保该密钥在您创建存储库 Amazon Web Services 区域 的地方可用，并且该密钥处于活动状态。有关更多信息，请参阅 [Amazon Key Management Service 以及 Amazon CodeCommit 存储库的加密](encryption.md)。

1. （可选）如果此存储库包含 **Java 或 Python 代码，并且您想让 CodeGuru Reviewer 对其进行分析，请选择 “启用 Java 和 Python 版 Ama** zon CodeGuru Reviewer”。 CodeGuru Reviewer 使用多个机器学习模型来查找代码缺陷，并对拉取请求提出改进和修复建议。有关更多信息，请参阅 [https://docs.amazonaws.cn/codeguru/latest/reviewer-ug/Welcome.html](https://docs.amazonaws.cn/codeguru/latest/reviewer-ug/Welcome.html)。

1. 选择**创建**。

![\[创建用于将 Git 仓库迁移到的仓库 CodeCommit\]](http://docs.amazonaws.cn/codecommit/latest/userguide/images/codecommit-create-repo-migrate-existing.png)


创建后，存储库将显示在**存储库**列表中。在 URL 列中，选择复制图标，然后选择用于连接到 CodeCommit 的协议（SSH 或 HTTPS）。复制 URL。

例如，如果您为仓库命名，*MyClonedRepository*并且在美国东部（俄亥俄州）地区使用带有 HTTPS 的 Git 凭证，则 URL 如下所示：

```
https://git-codecommit.us-east-2.amazonaws.com/MyClonedRepository
```

稍后在[第 2 步：克隆存储库并推送到 CodeCommit 存储库](#how-to-migrate-existing-clone)中您将需要该 URL。

## 第 2 步：克隆存储库并推送到 CodeCommit 存储库


在本部分中，您将 Git 存储库克隆到本地计算机，从而创建所谓的本地存储库。然后，您将本地存储库的内容推送到您之前创建的 CodeCommit 存储库。

1. 在本地计算机上的终端或命令提示符下，运行带有将远程存储库的裸副本克隆到名为的新文件夹中的`--mirror`选项*aws-codecommit-demo*。**git clone**这是仅用于迁移的裸存储库。它不是用于与中迁移的存储库进行交互的本地存储库。 CodeCommit您可以稍后在迁移完成后再 CodeCommit 创建。

   以下示例将 GitHub (*https://github.com/awslabs/aws-demo-php-simple-app.git*) 上托管的演示应用程序克隆到名为的目录中的本地存储库。*aws-codecommit-demo*

   ```
   git clone --mirror https://github.com/awslabs/aws-demo-php-simple-app.git aws-codecommit-demo
   ```

1. 切换到您执行克隆操作的目录。

   ```
   cd aws-codecommit-demo
   ```

1. 运行**git push**命令，指定目标 CodeCommit 存储库的 URL 和名称以及**--all**选项。（这是您在[步骤 1：创建 CodeCommit 存储库](#how-to-migrate-existing-create)中复制的 URL）。

   例如，如果您为存储库命名*MyClonedRepository*并设置为使用 HTTPS，则将运行以下命令：

   ```
   git push https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyClonedRepository --all
   ```
**注意**  
**--all** 选项仅推送该存储库的所有分支。它不会推送其他引用，例如标签。如果您想要推送标签，请等待初始推送完成，然后再次推送，这次使用 **--tags** 选项：  

   ```
   git push ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyClonedRepository --tags
   ```
有关更多信息，请参阅 Git 网站上的 [Git 推送](https://git-scm.com/docs/git-push)。有关推送大型存储库的信息，特别是一次性推送所有引用的情况（例如，使用 **--mirror** 选项），请参阅[以增量方式迁移存储库](how-to-push-large-repositories.md)。

将存储库迁移到后，可以删除该*aws-codecommit-demo*文件夹及其内容 CodeCommit。要创建包含所有正确引用的本地存储库，以便在中使用存储库 CodeCommit，请运行不带`--mirror`选项的`git clone`命令：

```
git clone https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyClonedRepository
```

## 步骤 3：查看中的文件 CodeCommit


推送目录内容后，您可以使用 CodeCommit 控制台快速查看该存储库中的所有文件。

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在**存储库**中，选择存储库的名称（例如*MyClonedRepository*）。

1. 在存储库中查看分支、克隆 URLs、设置等的文件。  
![\[中克隆存储库的视图 CodeCommit\]](http://docs.amazonaws.cn/codecommit/latest/userguide/images/codecommit-cloned-repo-url.png)

## 步骤 4：共享 CodeCommit 存储库


在中创建存储库时 CodeCommit，会生成两个端点：一个用于 HTTPS 连接，另一个用于 SSH 连接。两者都能提供安全的网络连接。您的用户可以使用这两种协议中的任何一种。不管您向用户推荐哪种协议，这两种终端节点都保持有效。在与他人共享您的存储库之前，您必须创建允许其他用户访问该存储库的 IAM policy。向您的用户提供下述访问说明。

**为存储库创建客户托管策略**

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. 在 **Dashboard** 导航区域中选择 **Policies**，然后选择 **Create Policy**。

1. 在**创建策略**页面上，选择**导入管理型策略**。

1. 在**导入管理型策略**页面的**筛选策略**中，输入 **AWSCodeCommitPowerUser**。选择策略名称旁的按钮，然后选择**导入**。

1. 在**创建策略**页面上，选择 **JSON**。将 CodeCommit 操作`Resource`行的 “\$1” 部分替换为 CodeCommit 存储库的 Amazon 资源名称 (ARN)，如下所示：

   ```
   "Resource": [
    "arn:aws:codecommit:us-east-2:111111111111:MyDemoRepo"
    ]
   ```
**提示**  
**要查找 CodeCommit 仓库的 ARN，请转到 CodeCommit 控制台，从列表中选择仓库名称，然后选择 “设置”。**有关更多信息，请参阅 [查看存储库详细信息](how-to-view-repository-details.md)。

   若要将该策略应用到多个存储库，请通过指定其 ARN 将各个存储库添加为资源。在每个资源语句之间加上逗号，如下所示：

   ```
   "Resource": [
    "arn:aws:codecommit:us-east-2:111111111111:MyDemoRepo",
    "arn:aws:codecommit:us-east-2:111111111111:MyOtherDemoRepo"
    ]
   ```

   完成编辑后，选择**查看策略**。

1. 在 “**查看策略**” 页面的 “**名称**” 中，输入策略的新名称（例如*AWSCodeCommitPowerUser-MyDemoRepo*）。（可选）提供此策略的描述。

1. 选择**创建策略**。

要管理对您的存储库的访问，请为其用户创建一个 IAM 组、向该组添加 IAM 用户，然后附加在上一步中创建的客户管理型策略。附上访问所需的任何其他策略，例如 IAMUserSSHKeys 或IAMSelfManageServiceSpecificCredentials。

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. 在 **Dashboard** 导航区域中选择 **Groups**，然后选择 **Create New Group**。

1. 在**设置组名**页面上的**组名**中，为组输入名称（例如，*MyDemoRepoGroup*），然后选择**下一步**。请考虑在组名称中包含存储库名称。
**注意**  
该名称必须在 Amazon Web Services 账户间保持唯一。

1. 选中您在上一节中创建的客户托管策略旁边的复选框（例如，**AWSCodeCommitPowerUser-MyDemoRepo**）。

1. 在 **Review** 页面上，选择 **Create Group**。IAM 将使用已附加的指定策略创建此组。此组会显示在与您的 Amazon Web Services 账户关联的组列表中。

1. 从列表中选择您的组。

1. 在组摘要页面上，选择**用户** 选项卡，然后选择**向组添加多个用户**。在显示与您的 Amazon Web Services 账户关联的所有用户的列表中，选中要允许其访问 CodeCommit 存储库的用户旁边的复选框，然后选择**添加用户**。
**提示**  
您可以使用搜索框快速地按名称查找用户。

1. 添加用户后，关闭 IAM 控制台。

创建要 CodeCommit 使用您配置的策略组和策略进行访问的 IAM 用户后，请向该用户发送连接到存储库所需的信息。

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在区域选择器中，选择存储库的创建 Amazon Web Services 区域 位置。存储库特定于 Amazon Web Services 区域。有关更多信息，请参阅 [区域和 Git 连接端点](regions.md)。

1. 在 **Repositories (存储库)** 页面上，选择要共享的存储库。

1. 在**克隆 URL** 中，选择您希望用户使用的协议。这会复制连接协议的克隆 URL。

1. 向您的用户发送克隆 URL 以及任何其他说明，例如安装 Amazon CLI、配置配置文件或安装 Git。请确保包含连接协议（例如 HTTPS）的配置信息。

# 将本地或非版本化内容迁移到 Amazon CodeCommit
将内容迁移到 CodeCommit

本主题中的过程向您介绍如何将计算机上的现有项目或本地内容迁移到 CodeCommit 存储库。在该过程中，您将：
+ 完成所需的初始设置 CodeCommit。
+ 创建 CodeCommit 存储库。
+ 将本地文件夹置于 Git 版本控制之下，然后将该文件夹的内容推送到 CodeCommit 存储库。
+ 查看 CodeCommit 存储库中的文件。
+ 与您的团队共享 CodeCommit 存储库。

**Topics**
+ [

## 步骤 0：需要进行设置才能访问 CodeCommit
](#how-to-migrate-local-setup)
+ [

## 步骤 1：创建 CodeCommit 存储库
](#how-to-migrate-local-create)
+ [

## 步骤 2：将本地内容迁移到 CodeCommit 存储库
](#how-to-migrate-local-version)
+ [

## 步骤 3：查看中的文件 CodeCommit
](#how-to-migrate-local-view)
+ [

## 步骤 4：共享 CodeCommit 存储库
](#how-to-migrate-local-share)

## 步骤 0：需要进行设置才能访问 CodeCommit


在将本地内容迁移到之前 CodeCommit，必须为本地计算机创建和配置一个 IAM 用户， CodeCommit 并配置您的本地计算机以进行访问。您还应安装 Amazon CLI 来管理 CodeCommit。尽管你可以在没有它的情况下执行大多数 CodeCommit 任务，但在使用 Git 时，它 Amazon CLI 提供了灵活性。

如果您已经做好了准备 CodeCommit，则可以直接跳到[步骤 1：创建 CodeCommit 存储库](#how-to-migrate-local-create)。

**创建和配置用于访问的 IAM 用户 CodeCommit**

1. 前往 [http://aws.amazon.com](https://www.amazonaws.cn/)，并选择**注册**，创建一个 Amazon Web Services 账户。

1. 创建 IAM 用户或使用您的 Amazon Web Services 账户中的现有用户。确保您具有与该 IAM 用户关联的访问密钥 ID 和秘密访问密钥。有关更多信息，请参阅[在 Amazon Web Services 账户中创建 IAM 用户](https://docs.amazonaws.cn/IAM/latest/UserGuide/Using_SettingUpUser.html)。
**注意**  
CodeCommit 要求 Amazon Key Management Service。如果您使用的是现有的 IAM 用户，请确保该用户没有明确拒绝所要求的 Amazon KMS 操作的策略 CodeCommit。有关更多信息，请参阅 [Amazon KMS 和加密](encryption.md)。

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. **在 IAM 控制台的导航窗格中，选择 Users，然后选择要配置 CodeCommit 访问权限的 IAM 用户。**

1. 在 **Permissions** 选项卡上，选择 **Add Permissions**。

1. 在 **Grant permissions (授予权限)** 中，选择 **Attach existing policies directly (直接附加现有策略)**。

1. 从策略列表中，选择**AWSCodeCommitPowerUser**或其他托管策略进行 CodeCommit 访问。有关更多信息，请参阅 [Amazon 的托管策略 CodeCommit](security-iam-awsmanpol.md)。

   选择要附加的策略后，选择**下一步：审核**以审核要附加到 IAM 用户的策略列表。如果列表正确，选择 **Add permissions**。

    有关 CodeCommit 托管策略以及与其他群组和用户共享仓库访问权限的更多信息，请参阅[共享存储库](how-to-share-repository.md)和[的身份验证和访问控制 Amazon CodeCommit](auth-and-access-control.md)。

**要安装和配置 Amazon CLI**

1. 在您的本地计算机上，下载并安装 Amazon CLI。这是通过命令行与交互 CodeCommit 的先决条件。我们建议您安装 Amazon CLI 版本 2。它是的最新主要版本 Amazon CLI ，支持所有最新功能。它是唯一支持使用根账户、联合访问权限或临时证书的版本**git-remote-codecommit**。 Amazon CLI 

   有关更多信息，请参阅[使用 Amazon 命令行界面进行设置](https://docs.amazonaws.cn/cli/latest/userguide/cli-chap-getting-set-up.html)。
**注意**  
CodeCommit 仅适用于 1.7.38 及更高 Amazon CLI 版本。作为最佳实践，请安装或升级 Amazon CLI 到可用的最新版本。要确定已安装的 Amazon CLI 版本，请运行**aws --version**命令。  
要将旧版本的升级 Amazon CLI 到最新版本，请参阅[安装 Amazon Command Line Interface](https://docs.amazonaws.cn/cli/latest/userguide/installing.html)。

1. 运行此命令以验证的 CodeCommit 命令 Amazon CLI 是否已安装。

   ```
   aws codecommit help
   ```

   此命令返回 CodeCommit 命令列表。

1.  Amazon CLI 使用**configure**命令配置配置文件，如下所示：。

   ```
   aws configure
   ```

   出现提示时，指定要与之 Amazon 配合使用的 IAM 用户的访问 Amazon 密钥和私有访问密钥 CodeCommit。另外，请务必指定存储库的 Amazon Web Services 区域 存在位置，例如`us-east-2`。系统提示指定默认输出格式时，指定 `json`。例如，如果您正在为 IAM 用户配置相关配置文件：

   ```
   AWS Access Key ID [None]: Type your IAM user Amazon access key ID here, and then press Enter
   AWS Secret Access Key [None]: Type your IAM user Amazon secret access key here, and then press Enter
   Default region name [None]: Type a supported region for CodeCommit here, and then press Enter
   Default output format [None]: Type json here, and then press Enter
   ```

   有关创建和配置用于的配置文件的更多信息 Amazon CLI，请参阅以下内容：
   + [命名配置文件](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-files.html)
   + [在中使用 IAM 角色 Amazon CLI](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-role.html)
   + [设置命令](https://docs.amazonaws.cn/cli/latest/reference/set.html)
   + [使用轮换凭证连接到 Amazon CodeCommit 存储库](temporary-access.md)

   要连接到存储库或其他存储库中的资源 Amazon Web Services 区域，必须 Amazon CLI 使用默认的区域名称重新配置。支持的默认区域名称 CodeCommit 包括：
   + us-east-2
   + us-east-1
   + eu-west-1
   + us-west-2
   + ap-northeast-1
   + ap-southeast-1
   + ap-southeast-2
   + ap-southeast-3
   + me-central-1
   + eu-central-1
   + ap-northeast-2
   + sa-east-1
   + us-west-1
   + eu-west-2
   + ap-south-1
   + ap-south-1
   + ca-central-1
   + us-gov-west-1
   + us-gov-east-1
   + eu-north-1
   + ap-east-1
   + me-south-1
   + cn-north-1
   + cn-northwest-1
   + eu-south-1
   + ap-northeast-3
   + af-south-1
   + il-central-1

   有关 CodeCommit 和的更多信息 Amazon Web Services 区域，请参阅[区域和 Git 连接端点](regions.md)。有关 IAM、访问密钥和秘密密钥的更多信息，请参阅‭[如何获取凭证？](https://docs.amazonaws.cn/IAM/latest/UserGuide/IAM_Introduction.html#IAM_SecurityCredentials)和[管理 IAM 用户的访问密钥](https://docs.amazonaws.cn/IAM/latest/UserGuide/ManagingCredentials.html)。有关 Amazon CLI 和配置文件的更多信息，请参阅[命名配置文件](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-files.html)。

接下来，您必须安装 Git。
+ **对于 Linux、macOS 或 Unix**：

  要处理 CodeCommit 存储库中的文件、提交和其他信息，必须在本地计算机上安装 Git。 CodeCommit 支持 Git 版本 1.7.9 及更高版本。Git 版本 2.28 支持为初始提交配置分支名称。我们建议使用最新版本的 Git。

  要安装 Git，建议您访问 [Git 下载](http://git-scm.com/downloads)等网站。
**注意**  
Git 是一个不断发展的平台，会定期进行更新。有时，功能更改可能会影响其工作方式 CodeCommit。如果您在使用特定版本的 Git 时遇到问题 CodeCommit，请查看中的信息[故障排除](troubleshooting.md)。
+ **对于 Windows：**

  要处理 CodeCommit 存储库中的文件、提交和其他信息，必须在本地计算机上安装 Git。 CodeCommit 支持 Git 版本 1.7.9 及更高版本。Git 版本 2.28 支持为初始提交配置分支名称。我们建议使用最新版本的 Git。

  要安装 Git，建议访问 [Git for Windows](https://gitforwindows.org/) 等网站。如果您使用此链接安装 Git，则可以接受除以下设置之外的所有安装默认设置：
  + 在**调整 PATH 环境**步骤中出现提示时，从命令行中选择使用 Git 的选项。
  + （可选）如果您打算将 HTTPS 与中包含的凭据帮助程序一起使用， Amazon CLI 而不是为其配置 Git 凭据 CodeCommit，请在 “**配置额外选项**” 页面上，确保清除 “**启用 Git 凭据管理器**” 选项。仅当 IAM 用户配置 Git 凭证时， CodeCommit Git 凭证管理器才兼容。有关更多信息，请参阅[适用于使用 Git 凭证的 HTTPS 用户](setting-up-gc.md)和[Windows 版 Git：我安装了 Windows 版 Git，但在访问我的存储库时被系统拒绝 (403)](troubleshooting-ch.md#troubleshooting-windowshttps)。
**注意**  
Git 是一个不断发展的平台，会定期进行更新。有时，功能更改可能会影响其工作方式 CodeCommit。如果您在使用特定版本的 Git 时遇到问题 CodeCommit，请查看中的信息[故障排除](troubleshooting.md)。

CodeCommit 同时支持 HTTPS 和 SSH 身份验证。要完成设置，您必须配置 Git 凭据 CodeCommit （HTTPS，建议大多数用户使用）、访问时使用的 SSH 密钥对 **git-remote-codecommit** (SSH) CodeCommit、（建议使用联合访问的用户使用）或中包含的凭证助手。 Amazon CLI
+ 有关在所有支持的操作系统上设置 Git 凭证的信息，请参阅[步骤 3：创建 Git 凭据，以便通过 HTTPS 连接到 CodeCommit](setting-up-gc.md#setting-up-gc-iam)。
+ 有关在 Linux、macOS 或 Unix 上设置 SSH 的信息，请参阅[SSH 和 Linux、macOS 或 Unix：为 Git 设置公钥和私钥以及 CodeCommit](setting-up-ssh-unixes.md#setting-up-ssh-unixes-keys-unixes)。
+  有关在 Windows 上设置 SSH 的信息，请参阅[第 3 步：为 Git 设置公钥和私钥以及 CodeCommit](setting-up-ssh-windows.md#setting-up-ssh-windows-keys-windows)。
+ 对于 **git-remote-codecommit**，请参阅[使用的 HTTPS 连接 Amazon CodeCommit 的设置步骤 git-remote-codecommit](setting-up-git-remote-codecommit.md)。
+ 有关 Linux、macOS 或 Unix 上的凭证助手，请参阅[设置凭证助手（Linux、macOS 或 Unix）](setting-up-https-unixes.md#setting-up-https-unixes-ch-config)。
+ 有关在 Windows 上设置凭证辅助程序的信息，请参阅[设置凭证辅助程序 (Windows)](setting-up-https-windows.md#setting-up-https-windows-ch-config)。

## 步骤 1：创建 CodeCommit 存储库


在本节中，您将使用 CodeCommit 控制台创建用于本教程其余部分的 CodeCommit 存储库。要使用创建存储库，请参阅[创建存储库 (Amazon CLI)](how-to-create-repository.md#how-to-create-repository-cli)。 Amazon CLI 

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在区域选择器中，选择要创建存储库 Amazon Web Services 区域 的位置。有关更多信息，请参阅 [区域和 Git 连接端点](regions.md)。

1. 在**存储库**页面上，选择**创建存储库**。

1. 在**创建存储库**页面上的**存储库名称**中，为存储库输入名称。
**注意**  
存储库名称区分大小写。名称在 Amazon Web Services 区域 中对于 Amazon Web Services 账户必须唯一。

1. （可选）在**描述**中，输入存储库的描述。这可以帮助您及其他用户了解存储库的用途。
**注意**  
“描述”字段在控制台中显示“Markdown”，并接受所有 HTML 字符和有效的 Unicode 字符。如果您是使用`GetRepository`或的应用程序开发人员，`BatchGetRepositories` APIs 并且计划在 Web 浏览器中显示存储库描述字段，请参阅 [CodeCommit API 参考](https://docs.amazonaws.cn/codecommit/latest/APIReference/)。

1. （可选）选择 **Add t** ag，向存储库添加一个或多个存储库标签（可帮助您组织和管理 Amazon 资源的自定义属性标签）。有关更多信息，请参阅 [在中标记存储库 Amazon CodeCommit](how-to-tag-repository.md)。

1. （可选）展开**其他配置**以指定是使用默认密钥 Amazon 托管式密钥 还是您自己的客户托管密钥来加密和解密此存储库中的数据。如果您选择使用自己的客户托管密钥，则必须确保该密钥在您创建存储库 Amazon Web Services 区域 的地方可用，并且该密钥处于活动状态。有关更多信息，请参阅 [Amazon Key Management Service 以及 Amazon CodeCommit 存储库的加密](encryption.md)。

1. （可选）如果此存储库包含 **Java 或 Python 代码，并且您想让 CodeGuru Reviewer 对其进行分析，请选择 “启用 Java 和 Python 版 Ama** zon CodeGuru Reviewer”。 CodeGuru Reviewer 使用多个机器学习模型来查找代码缺陷，并对拉取请求提出改进和修复建议。有关更多信息，请参阅 [https://docs.amazonaws.cn/codeguru/latest/reviewer-ug/Welcome.html](https://docs.amazonaws.cn/codeguru/latest/reviewer-ug/Welcome.html)。

1. 选择**创建**。

创建后，存储库将显示在**存储库**列表中。在 URL 列中，选择复制图标，然后选择用于连接到 CodeCommit 的协议（HTTPS 或 SSH）。复制 URL。

例如，如果您为存储库命名*MyFirstRepo*并且使用的是 HTTPS，则网址将如下所示：

```
https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyFirstRepo
```

稍后在[步骤 2：将本地内容迁移到 CodeCommit 存储库](#how-to-migrate-local-version)中您将需要该 URL。

## 步骤 2：将本地内容迁移到 CodeCommit 存储库


现在您已经有了 CodeCommit 仓库，可以在本地计算机上选择一个目录将其转换为本地 Git 存储库。可以使用 **git init** 命令将现有的非版本控制内容转化为 Git 存储库，或在尚无任何文件或内容的情况下初始化一个新的空存储库。

1. 在本地计算机上的终端或命令行中，进入要用作存储库源的目录。

1. 运行以下命令将 Git 配置为使用名为 **main** 的默认分支：

   ```
   git config --local init.defaultBranch main
   ```

   您也可以运行以下命令，将所有新创建的存储库的默认分支名称设置为 **main**：

   ```
   git config --global init.defaultBranch main
   ```

1. 运行 **git init** 命令在该目录中初始化 Git 版本控制。这会在启用版本控制跟踪的目录的根目录中创建一个 .git 子目录。.git 文件夹还包含存储库的所有必需元数据。

   ```
   git init
   ```

1. 运行以下命令，检查初始化目录的状态：

   ```
   git status
   ```

   添加要置于版本控制之下的文件。在本教程中，将运行带 `.` 说明符的 `git add` 命令来添加该目录中的所有文件。有关其他选项的信息，请参阅 Git 文档。

   ```
   git add .
   ```

1. 为添加的文件创建一个带有提交消息的提交。

   ```
   git commit -m "Initial commit"
   ```

1. 运行**git push**命令，指定目标 CodeCommit 存储库的 URL 和名称以及`--all`选项。（这是您在[步骤 1：创建 CodeCommit 存储库](#how-to-migrate-local-create)中复制的 URL。）

   例如，如果您为存储库命名*MyFirstRepo*并设置为使用 HTTPS，则将运行以下命令：

   ```
   git push https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyFirstRepo --all
   ```

## 步骤 3：查看中的文件 CodeCommit


推送目录内容后，您可以使用 CodeCommit 控制台快速查看存储库中的所有文件。

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在**存储库**中，从列表中选择存储库的名称（例如*MyFirstRepository*）。

1. 查看存储库中的分支、克隆 URLs、设置等文件。

## 步骤 4：共享 CodeCommit 存储库


在中创建存储库时 CodeCommit，会生成两个端点：一个用于 HTTPS 连接，另一个用于 SSH 连接。两者都能提供安全的网络连接。您的用户可以使用这两种协议中的任何一种。不管您向用户推荐哪种协议，这两种终端节点都保持有效。在与他人共享您的存储库之前，您必须创建允许其他用户访问该存储库的 IAM policy。向您的用户提供下述访问说明。

**为存储库创建客户托管策略**

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. 在 **Dashboard** 导航区域中选择 **Policies**，然后选择 **Create Policy**。

1. 在**创建策略**页面上，选择**导入管理型策略**。

1. 在**导入管理型策略**页面的**筛选策略**中，输入 **AWSCodeCommitPowerUser**。选择策略名称旁的按钮，然后选择**导入**。

1. 在**创建策略**页面上，选择 **JSON**。将 CodeCommit 操作`Resource`行的 “\$1” 部分替换为 CodeCommit 存储库的 Amazon 资源名称 (ARN)，如下所示：

   ```
   "Resource": [
    "arn:aws:codecommit:us-east-2:111111111111:MyDemoRepo"
    ]
   ```
**提示**  
**要查找 CodeCommit 仓库的 ARN，请转到 CodeCommit 控制台，从列表中选择仓库名称，然后选择 “设置”。**有关更多信息，请参阅 [查看存储库详细信息](how-to-view-repository-details.md)。

   若要将该策略应用到多个存储库，请通过指定其 ARN 将各个存储库添加为资源。在每个资源语句之间加上逗号，如下所示：

   ```
   "Resource": [
    "arn:aws:codecommit:us-east-2:111111111111:MyDemoRepo",
    "arn:aws:codecommit:us-east-2:111111111111:MyOtherDemoRepo"
    ]
   ```

   完成编辑后，选择**查看策略**。

1. 在 “**查看策略**” 页面的 “**名称**” 中，输入策略的新名称（例如*AWSCodeCommitPowerUser-MyDemoRepo*）。（可选）提供此策略的描述。

1. 选择**创建策略**。

要管理对您的存储库的访问，请为其用户创建一个 IAM 组、向该组添加 IAM 用户，然后附加在上一步中创建的客户管理型策略。附加访问所需的任何其他策略，例如 `IAMSelfManageServiceSpecificCredentials` 或 `IAMUserSSHKeys`。

1. 登录 Amazon Web Services 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.amazonaws.cn/iam/)。

1. 在 **Dashboard** 导航区域中选择 **Groups**，然后选择 **Create New Group**。

1. 在**设置组名**页面上的**组名**中，为组输入名称（例如，*MyDemoRepoGroup*），然后选择**下一步**。请考虑在组名称中包含存储库名称。
**注意**  
该名称必须在 Amazon Web Services 账户间保持唯一。

1. 选中您在上一节中创建的客户托管策略旁边的复选框（例如，**AWSCodeCommitPowerUser-MyDemoRepo**）。

1. 在 **Review** 页面上，选择 **Create Group**。IAM 将使用已附加的指定策略创建此组。此组会显示在与您的 Amazon Web Services 账户关联的组列表中。

1. 从列表中选择您的组。

1. 在组摘要页面上，选择**用户** 选项卡，然后选择**向组添加多个用户**。在显示与您的 Amazon Web Services 账户关联的所有用户的列表中，选中要允许其访问 CodeCommit 存储库的用户旁边的复选框，然后选择**添加用户**。
**提示**  
您可以使用搜索框快速地按名称查找用户。

1. 添加用户后，关闭 IAM 控制台。

创建用于 CodeCommit 使用您配置的策略组和策略进行访问的 IAM 用户后，请向该用户发送连接到存储库所需的信息。

1. 在 [https://console.aws.amazon.com/codesuite/codemmit](https://console.amazonaws.cn/codesuite/codecommit/home) /home 打开 CodeCommit 控制台。

1. 在区域选择器中，选择存储库的创建 Amazon Web Services 区域 位置。存储库特定于 Amazon Web Services 区域。有关更多信息，请参阅 [区域和 Git 连接端点](regions.md)。

1. 在 **Repositories (存储库)** 页面上，选择要共享的存储库。

1. 在**克隆 URL** 中，选择您希望用户使用的协议。这会复制连接协议的克隆 URL。

1. 向您的用户发送克隆 URL 以及任何其他说明，例如安装 Amazon CLI、配置配置文件或安装 Git。请确保包含连接协议（例如 HTTPS）的配置信息。

# 以增量方式迁移存储库
以增量方式迁移存储库

迁移到时 Amazon CodeCommit，可以考虑按增量或区块推送存储库，以减少间歇性网络问题或网络性能下降导致整个推送失败的可能性。通过使用类似此处包含的脚本进行增量推送，您可以重新启动迁移，并只推送先前推送失败的提交。

本主题中的过程向您展示如何创建和运行以增量方式迁移存储库的脚本，该脚本将只重新推送那些推送失败的增量提交，直到迁移完成。

编写这些说明时，假定您已完成[设置 ](setting-up.md)和[创建 存储库](how-to-create-repository.md)中的步骤。

**Topics**
+ [

## 步骤 0：确定是否需要增量迁移
](#how-to-push-large-repositories-determine)
+ [

## 步骤 1：安装必备组件并将 CodeCommit 存储库添加为远程存储库
](#how-to-push-large-repositories-prereq)
+ [

## 步骤 2：创建用于增量迁移的脚本
](#how-to-push-large-repositories-createscript)
+ [

## 步骤 3：运行脚本并逐步迁移到 CodeCommit
](#how-to-push-large-repositories-runscript)
+ [

## 附录：示例脚本 `incremental-repo-migration.py`
](#how-to-push-large-repositories-sample)

## 步骤 0：确定是否需要增量迁移


要确定存储库的整体大小以及是否需要增量迁移，可以考虑以下几个因素。首先要考虑的当然是存储库中项目的整体大小。存储库的累积历史记录等因素也会对大小产生影响。就算存储库的各个资产并不大，但如果它包含多年的历史记录和分支，其整体大小也可能非常大。您可以通过多种策略来更简单、更高效地迁移这些存储库。例如，可以在克隆具有长期开发历史的存储库时使用浅克隆策略，也可以关闭大型二进制文件的增量压缩。您可以通过查阅 Git 文档来研究选项，也可以选择使用本主题中包含的示例脚本 (`incremental-repo-migration.py`) 来设置和配置以增量推送方式迁移存储库。

如果您满足以下一个或多个条件，则可能需要配置增量推送：
+ 您要迁移的存储库具有五年以上的历史。
+ 您的 Internet 连接存在间歇性中断、丢包、响应缓慢或其他服务中断问题。
+ 存储库的整体大小大于 2 GB，并且您打算迁移整个存储库。
+ 存储库包含压缩率不高的大型项目或二进制文件，例如具有超过五个跟踪版本的大型映像文件。
+ 您之前曾尝试迁移到 CodeCommit 并收到 “内部服务错误” 消息。

就算上述条件都不成立，您也可以选择增量推送。

## 步骤 1：安装必备组件并将 CodeCommit 存储库添加为远程存储库


您可以创建自己的自定义脚本，它有自己的必备组件。如果您使用本主题中包括的示例，则必须：
+ 安装其必备组件。
+ 将存储库克隆到本地计算机。
+ 将 CodeCommit 存储库添加为要迁移的存储库的远程存储库。

**设置为运行 incremental-repo-migration .py**

1.  在本地计算机上，安装 Python 2.6 或更高版本。有关更多信息以及最新版本的信息，请参阅 [Python 网站](https://www.python.org/downloads/)。

1. 在同一台计算机上安装 GitPython，这是一个用于与 Git 存储库交互的 Python 库。有关更多信息，请参阅 [ GitPython 文档。](http://gitpython.readthedocs.org/en/stable/)

1.  使用 **git clone --mirror** 命令克隆要迁移到本地计算机的存储库。在终端（Linux、macOS 或 Unix）或命令提示符 (Windows) 中，使用 **git clone --mirror** 命令为该存储库创建一个本地存储库，包括要在其中创建本地存储库的目录。例如，要将名为*MyMigrationRepo*、URL 为的 Git 仓库克隆*https://example.com/my-repo/*到名为的目录*my-repo*：

   ```
   git clone --mirror https://example.com/my-repo/MyMigrationRepo.git my-repo
   ```

   您应会看到类似以下内容的输出，这表示存储库已被克隆到名为 my-repo 的本地空存储库中：

   ```
   Cloning into bare repository 'my-repo'...
   remote: Counting objects: 20, done.
   remote: Compressing objects: 100% (17/17), done.
   remote: Total 20 (delta 5), reused 15 (delta 3)
   Unpacking objects: 100% (20/20), done.
   Checking connectivity... done.
   ```

1. 将目录更改为刚才克隆的存储库的本地存储库（例如）。*my-repo*从该目录，使用 **git remote add *DefaultRemoteName* *RemoteRepositoryURL*** 命令添加 CodeCommit 存储库作为远程存储库的本地存储库。
**注意**  
在推送大型存储库时，请考虑使用 SSH 而不是 HTTPS。在推送较大的更改、大量更改或大型存储库时，长时间运行的 HTTPS 连接通常会因为网络问题或防火墙设置而提前终止。有关设置 SSH CodeCommit 的更多信息，请参阅[适用于 Linux、macOS 或 Unix 上的 SSH 连接](setting-up-ssh-unixes.md)或[适用于 Windows 上的 SSH 连接](setting-up-ssh-windows.md)。

    例如，使用以下命令为名为的远程 CodeCommit存储库为名 MyDestinationRepo 为的远程存储库添加 SSH 端点`codecommit`：

   ```
   git remote add codecommit ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDestinationRepo
   ```
**提示**  
由于这是克隆存储库，已使用默认的远程存储库名称 (`origin`)。您必须使用其他的远程存储库名称。虽然示例使用了 `codecommit`，但您可以使用任意名称。使用 **git remote show** 命令查看为本地存储库设置的远程存储库的列表。

1. 使用 **git remote -v** 命令显示本地存储库的提取和推送设置，确认它们设置正确。例如：

   ```
   codecommit  ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDestinationRepo (fetch)
   codecommit  ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDestinationRepo (push)
   ```
**提示**  
如果您仍看到其他远程存储库的提取和推送条目（例如，origin 的条目），请使用 **git remote set-url --delete** 命令删除它们。

## 步骤 2：创建用于增量迁移的脚本


编写这些步骤时，假定您使用的是 `incremental-repo-migration.py` 示例脚本。

1. 打开一个文本编辑器，将[示例脚本](#how-to-push-large-repositories-sample)的内容粘贴到一个空文档中。

1. 将文档保存到某个文档目录中 (而不是本地存储库的工作目录)，并将其命名为 `incremental-repo-migration.py`。确保选择的目录是在本地环境或路径变量中配置的目录，以便您能够在命令行或终端中运行该 Python 脚本。

## 步骤 3：运行脚本并逐步迁移到 CodeCommit


 现在，您已经创建了`incremental-repo-migration.py`脚本，您可以使用它以增量方式将本地存储库迁移到存储库。 CodeCommit 默认情况下，该脚本以 1000 个提交为批次推送提交，并尝试将运行该脚本时所在目录的 Git 设置用作本地存储库和远程存储库的设置。如果需要，您可以使用 `incremental-repo-migration.py` 中包含的选项配置其他设置。

1. 在终端或命令提示符中，切换到要迁移的本地存储库的目录。

1. 从该目录运行以下命令：

   ```
   python incremental-repo-migration.py
   ```

1. 脚本运行并在终端或命令提示符中显示进度。一些大型存储库在显示进度时会有延迟。如果单次推送失败三次，脚本将停止运行。然后，您可以重新运行脚本，它会从失败的批次继续。您可以重新运行脚本，直到所有推送成功并且迁移完成。

**提示**  
您可以在任意目录中运行 `incremental-repo-migration.py`，前提是您用 `-l` 和 `-r` 选项指定了要使用的本地和远程存储库设置。例如，要使用任意目录中的脚本将位于 /tmp/ 的本地存储库迁移*my-repo*到昵称的远程存储库：*codecommit*  

```
python incremental-repo-migration.py -l "/tmp/my-repo" -r "codecommit" 
```
 您可能还需要使用 `-b` 选项来更改增量推送时使用的默认批处理大小。例如，如果您定期推送具有经常发生更改的超大二进制文件的存储库，并且在网络带宽受限的位置执行操作，则您可能需要使用 `-b` 选项将批处理大小更改为 500 而不使用 1000。例如：  

```
python incremental-repo-migration.py -b 500
```
这将以 500 个提交为批次增量推送本地存储库。如果您在迁移存储库时决定再次更改批次大小（例如，在推送失败后，您决定减小批次大小），请记得使用 `-c` 选项删除批次标签，然后再使用 `-b` 重置批次大小：  

```
python incremental-repo-migration.py -c
python incremental-repo-migration.py -b 250
```

**重要**  
推送失败后重新运行脚本时，请勿使用 `-c` 选项。`-c` 选项会删除用于对提交进行批处理的标签。仅当您想要更改批处理大小并重新开始时，或者您决定不再使用该脚本时，才能使用 `-c` 选项。

## 附录：示例脚本 `incremental-repo-migration.py`


为方便您参考，我们开发了一个用于增量推送存储库的示例 Python 脚本 `incremental-repo-migration.py`。该脚本是一个开源代码示例，按原样提供。

```
# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Amazon Software License (the "License").
# You may not use this file except in compliance with the License. A copy of the License is located at
#    http://aws.amazon.com/asl/
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for
# the specific language governing permissions and limitations under the License.

#!/usr/bin/env python

import os
import sys
from optparse import OptionParser
from git import Repo, TagReference, RemoteProgress, GitCommandError


class PushProgressPrinter(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=""):
        op_id = op_code & self.OP_MASK
        stage_id = op_code & self.STAGE_MASK
        if op_id == self.WRITING and stage_id == self.BEGIN:
            print("\tObjects: %d" % max_count)


class RepositoryMigration:
    MAX_COMMITS_TOLERANCE_PERCENT = 0.05
    PUSH_RETRY_LIMIT = 3
    MIGRATION_TAG_PREFIX = "codecommit_migration_"

    def migrate_repository_in_parts(
        self, repo_dir, remote_name, commit_batch_size, clean
    ):
        self.next_tag_number = 0
        self.migration_tags = []
        self.walked_commits = set()
        self.local_repo = Repo(repo_dir)
        self.remote_name = remote_name
        self.max_commits_per_push = commit_batch_size
        self.max_commits_tolerance = (
            self.max_commits_per_push * self.MAX_COMMITS_TOLERANCE_PERCENT
        )

        try:
            self.remote_repo = self.local_repo.remote(remote_name)
            self.get_remote_migration_tags()
        except (ValueError, GitCommandError):
            print(
                "Could not contact the remote repository. The most common reasons for this error are that the name of the remote repository is incorrect, or that you do not have permissions to interact with that remote repository."
            )
            sys.exit(1)

        if clean:
            self.clean_up(clean_up_remote=True)
            return

        self.clean_up()

        print("Analyzing repository")
        head_commit = self.local_repo.head.commit
        sys.setrecursionlimit(max(sys.getrecursionlimit(), head_commit.count()))

        # tag commits on default branch
        leftover_commits = self.migrate_commit(head_commit)
        self.tag_commits([commit for (commit, commit_count) in leftover_commits])

        # tag commits on each branch
        for branch in self.local_repo.heads:
            leftover_commits = self.migrate_commit(branch.commit)
            self.tag_commits([commit for (commit, commit_count) in leftover_commits])

        # push the tags
        self.push_migration_tags()

        # push all branch references
        for branch in self.local_repo.heads:
            print("Pushing branch %s" % branch.name)
            self.do_push_with_retries(ref=branch.name)

        # push all tags
        print("Pushing tags")
        self.do_push_with_retries(push_tags=True)

        self.get_remote_migration_tags()
        self.clean_up(clean_up_remote=True)

        print("Migration to CodeCommit was successful")

    def migrate_commit(self, commit):
        if commit in self.walked_commits:
            return []

        pending_ancestor_pushes = []
        commit_count = 1

        if len(commit.parents) > 1:
            # This is a merge commit
            # Ensure that all parents are pushed first
            for parent_commit in commit.parents:
                pending_ancestor_pushes.extend(self.migrate_commit(parent_commit))
        elif len(commit.parents) == 1:
            # Split linear history into individual pushes
            next_ancestor, commits_to_next_ancestor = self.find_next_ancestor_for_push(
                commit.parents[0]
            )
            commit_count += commits_to_next_ancestor
            pending_ancestor_pushes.extend(self.migrate_commit(next_ancestor))

        self.walked_commits.add(commit)

        return self.stage_push(commit, commit_count, pending_ancestor_pushes)

    def find_next_ancestor_for_push(self, commit):
        commit_count = 0

        # Traverse linear history until we reach our commit limit, a merge commit, or an initial commit
        while (
            len(commit.parents) == 1
            and commit_count < self.max_commits_per_push
            and commit not in self.walked_commits
        ):
            commit_count += 1
            self.walked_commits.add(commit)
            commit = commit.parents[0]

        return commit, commit_count

    def stage_push(self, commit, commit_count, pending_ancestor_pushes):
        # Determine whether we can roll up pending ancestor pushes into this push
        combined_commit_count = commit_count + sum(
            ancestor_commit_count
            for (ancestor, ancestor_commit_count) in pending_ancestor_pushes
        )

        if combined_commit_count < self.max_commits_per_push:
            # don't push anything, roll up all pending ancestor pushes into this pending push
            return [(commit, combined_commit_count)]

        if combined_commit_count <= (
            self.max_commits_per_push + self.max_commits_tolerance
        ):
            # roll up everything into this commit and push
            self.tag_commits([commit])
            return []

        if commit_count >= self.max_commits_per_push:
            # need to push each pending ancestor and this commit
            self.tag_commits(
                [
                    ancestor
                    for (ancestor, ancestor_commit_count) in pending_ancestor_pushes
                ]
            )
            self.tag_commits([commit])
            return []

        # push each pending ancestor, but roll up this commit
        self.tag_commits(
            [ancestor for (ancestor, ancestor_commit_count) in pending_ancestor_pushes]
        )
        return [(commit, commit_count)]

    def tag_commits(self, commits):
        for commit in commits:
            self.next_tag_number += 1
            tag_name = self.MIGRATION_TAG_PREFIX + str(self.next_tag_number)

            if tag_name not in self.remote_migration_tags:
                tag = self.local_repo.create_tag(tag_name, ref=commit)
                self.migration_tags.append(tag)
            elif self.remote_migration_tags[tag_name] != str(commit):
                print(
                    "Migration tags on the remote do not match the local tags. Most likely your batch size has changed since the last time you ran this script. Please run this script with the --clean option, and try again."
                )
                sys.exit(1)

    def push_migration_tags(self):
        print("Will attempt to push %d tags" % len(self.migration_tags))
        self.migration_tags.sort(
            key=lambda tag: int(tag.name.replace(self.MIGRATION_TAG_PREFIX, ""))
        )
        for tag in self.migration_tags:
            print(
                "Pushing tag %s (out of %d tags), commit %s"
                % (tag.name, self.next_tag_number, str(tag.commit))
            )
            self.do_push_with_retries(ref=tag.name)

    def do_push_with_retries(self, ref=None, push_tags=False):
        for i in range(0, self.PUSH_RETRY_LIMIT):
            if i == 0:
                progress_printer = PushProgressPrinter()
            else:
                progress_printer = None

            try:
                if push_tags:
                    infos = self.remote_repo.push(tags=True, progress=progress_printer)
                elif ref is not None:
                    infos = self.remote_repo.push(
                        refspec=ref, progress=progress_printer
                    )
                else:
                    infos = self.remote_repo.push(progress=progress_printer)

                success = True
                if len(infos) == 0:
                    success = False
                else:
                    for info in infos:
                        if (
                            info.flags & info.UP_TO_DATE
                            or info.flags & info.NEW_TAG
                            or info.flags & info.NEW_HEAD
                        ):
                            continue
                        success = False
                        print(info.summary)

                if success:
                    return
            except GitCommandError as err:
                print(err)

        if push_tags:
            print("Pushing all tags failed after %d attempts" % (self.PUSH_RETRY_LIMIT))
        elif ref is not None:
            print("Pushing %s failed after %d attempts" % (ref, self.PUSH_RETRY_LIMIT))
            print(
                "For more information about the cause of this error, run the following command from the local repo: 'git push %s %s'"
                % (self.remote_name, ref)
            )
        else:
            print(
                "Pushing all branches failed after %d attempts"
                % (self.PUSH_RETRY_LIMIT)
            )
        sys.exit(1)

    def get_remote_migration_tags(self):
        remote_tags_output = self.local_repo.git.ls_remote(
            self.remote_name, tags=True
        ).split("\n")
        self.remote_migration_tags = dict(
            (tag.split()[1].replace("refs/tags/", ""), tag.split()[0])
            for tag in remote_tags_output
            if self.MIGRATION_TAG_PREFIX in tag
        )

    def clean_up(self, clean_up_remote=False):
        tags = [
            tag
            for tag in self.local_repo.tags
            if tag.name.startswith(self.MIGRATION_TAG_PREFIX)
        ]

        # delete the local tags
        TagReference.delete(self.local_repo, *tags)

        # delete the remote tags
        if clean_up_remote:
            tags_to_delete = [":" + tag_name for tag_name in self.remote_migration_tags]
            self.remote_repo.push(refspec=tags_to_delete)


parser = OptionParser()
parser.add_option(
    "-l",
    "--local",
    action="store",
    dest="localrepo",
    default=os.getcwd(),
    help="The path to the local repo. If this option is not specified, the script will attempt to use current directory by default. If it is not a local git repo, the script will fail.",
)
parser.add_option(
    "-r",
    "--remote",
    action="store",
    dest="remoterepo",
    default="codecommit",
    help="The name of the remote repository to be used as the push or migration destination. The remote must already be set in the local repo ('git remote add ...'). If this option is not specified, the script will use 'codecommit' by default.",
)
parser.add_option(
    "-b",
    "--batch",
    action="store",
    dest="batchsize",
    default="1000",
    help="Specifies the commit batch size for pushes. If not explicitly set, the default is 1,000 commits.",
)
parser.add_option(
    "-c",
    "--clean",
    action="store_true",
    dest="clean",
    default=False,
    help="Remove the temporary tags created by migration from both the local repo and the remote repository. This option will not do any migration work, just cleanup. Cleanup is done automatically at the end of a successful migration, but not after a failure so that when you re-run the script, the tags from the prior run can be used to identify commit batches that were not pushed successfully.",
)

(options, args) = parser.parse_args()

migration = RepositoryMigration()
migration.migrate_repository_in_parts(
    options.localrepo, options.remoterepo, int(options.batchsize), options.clean
)
```