Git: Gitリポジトリのクローン作成とリモートコラボレーションの始め方

クローンとは、すべてのファイル、ブランチ、およびコミット履歴のすべてを含む、Gitリポジトリの完全なコピーをリモートサーバーから取得するプロセスです。これは、チームとの共同作業における最初のステップとなります。

1. クローニングの概要

(1) クローンとは何ですか?

クローンとは、リモートリポジトリを丸ごとローカルマシンにコピーするプロセスです。ZIPアーカイブのダウンロードとは異なり、クローンでは以下の内容を含む完全なGitリポジトリが取得されます:

(2) クローンとダウンロードの違い

「ZIPファイルをダウンロードすればいいじゃないか」とよく聞かれます。では、この2つを比較してみましょう:

アクション 内容 履歴を確認できますか? 変更をプッシュできますか? バージョンを切り替えることができますか?
git clone リポジトリ全体
ZIPファイルをダウンロード ファイルのスナップオットのみ

(3) クローニングのユースケース

クローン機能は、主に次のような場面で使用されます:



2. git clone コマンド

(1) 基本的な構文

git clone コマンドの基本構文:

BASH
# Clone to the current directory(Automatically create a folder with the same name)
git clone <Warehouse Address>

# Clone to the specified directory
git clone <Warehouse Address> <Directory Name>

(2) クローン作成のプロセス

クローン作成の全プロセスは以下の通りです:

100%
sequenceDiagram
    participant L as Local Warehouse
    participant R as Remote Server
    
    L->>R: 1. Initiate a Cloning Request
    R->>L: 2. Send Repository Metadata
    R->>L: 3. Send All Objects(Documents、Submit)
    R->>L: 4. Send Branch Information
    L->>L: 5. CreateoriginRemote Association
    L->>L: 6. Check out the default branch
    L->>L: 7. Cloning Complete

▶ サンプル:GitHubリポジトリのクローン作成

BASH
# CloneReactProject(HTTPSMethod)
git clone https://github.com/facebook/react.git

# Output Information:
# Cloning into 'react'...
# remote: Enumerating objects: 156789, done.
# remote: Counting objects: 100% (156789/156789), done.
# remote: Compressing objects: 100% (456/456), done.
# remote: Total 156789 (delta 12345), reused 156333 (delta 12000), pack-reused 0
# Receiving objects: 100% (156789/156789), 45.67 MiB | 5.23 MiB/s, done.
# Resolving deltas: 100% (123456/123456), done.

# Clone to the specified directory
git clone https://github.com/facebook/react.git my-react-project

# Clone to the current directory(Pay attention to the last point)
git clone https://github.com/facebook/react.git .

▶ サンプル:クローン作成後の情報の確認

BASH
# Clone the repository
git clone https://github.com/user/demo.git
cd demo

# View Remote Repository Associations
git remote -v
# origin  https://github.com/user/demo.git (fetch)
# origin  https://github.com/user/demo.git (push)

# View All Branches(Including remote branches)
git branch -a
# * main
#   remotes/origin/HEAD -> origin/main
#   remotes/origin/main
#   remotes/origin/develop
#   remotes/origin/feature

# View Commit History
git log --oneline -5
# a1b2c3d (HEAD -> main, origin/main, origin/HEAD) Update README
# e4f5g6h Add new feature
# i7j8k9l Fix bug in login
# m0n1o2p Initial commit


3. クローン作成のオプション

(1) 浅いクローン作成

大規模なプロジェクトの場合、フルクローンは時間がかかり、多くのストレージ容量を必要とすることがあります。シャロークローンでは、最新のコミットのみがダウンロードされます:

BASH
# Clone only the most recent commit
git clone --depth 1 <Warehouse Address>

# Clone RecentNNext Submission
git clone --depth 10 <Warehouse Address>

浅いクローニングの特徴:

(2) 単一分枝クローニング

特定のブランチだけが必要な場合は、そのブランチだけをクローンすることができます:

BASH
# Clone only the specified branch
git clone --branch main --single-branch <Warehouse Address>

# Abbreviated form
git clone -b main --single-branch <Warehouse Address>

(3) 再帰的クローン作成

プロジェクトにサブモジュールが含まれている場合は、それらを再帰的にクローンする必要があります:

BASH
# Recursive Cloning,Clone all submodules at the same time
git clone --recursive <Warehouse Address>

# If you have already cloned it,Submodules can be initialized individually
git clone <Warehouse Address>
cd <Table of Contents>
git submodule update --init --recursive

(4) クローニングオプションの比較

オプション 説明 ダウンロード 活用例
オプションなし 完全クローン すべて 日常の開発
--depth 1 浅いクローン 最新のコミットのみ CI/CD、デプロイ
--single-branch 単一ブランチ ブランチのみを指定 特定のブランチのみ
--recursive 再帰的クローン サブモジュールを含む プロジェクトにサブモジュールがある
--bare ベアメタルサーバー ワークスペースなし サーバーイメージ

▶ サンプル:大規模プロジェクトの浅いクローン作成

BASH
# LinuxFull Kernel Cloning(3GB+,It takes a long time)
git clone https://github.com/torvalds/linux.git
# Cloning into 'linux'...
# Receiving objects: 100% (8234567/8234567), 3.45 GiB | 1.23 MiB/s, done.

# Shallow CloningLinuxKernel(100MB+,Fast)
git clone --depth 1 https://github.com/torvalds/linux.git
# Cloning into 'linux'...
# Receiving objects: 100% (12345/12345), 156.78 MiB | 5.67 MiB/s, done.

# View Historical Differences
cd linux
git log --oneline
# Only1Next Submission(Shallow Cloning)

# Fully cloned repository
git log --oneline | wc -l
# 1M+ Next Submission


4. リモートアドレス

(1) プロトコル種別

Git は、リモートリポジトリにアクセスするための複数のプロトコルをサポートしています:

100%
graph TB
    A[Remote Repository Address] --> B[HTTPSAgreement]
    A --> C[SSHAgreement]
    A --> D[GitAgreement]
    A --> E[Local Path]
    
    B --> B1[https://github.com/user/repo.git]
    C --> C1[git@github.com:user/repo.git]
    D --> D1[git://github.com/user/repo.git]
    E --> E1[/path/to/repo.git]
    
    style B fill:#d4edda
    style C fill:#c3e6cb
    style D fill:#fff3cd
    style E fill:#f8d7da

(2) HTTPS 対 SSH

最も一般的に使用されているプロトコルは、HTTPSとSSHの2つです:

機能 HTTPS SSH
住所の形式 https://github.com/user/repo.git git@github.com:user/repo.git
設定の難易度 簡単、設定は不要 SSHキーの生成と設定が必要
認証方法 ユーザー名 + パスワード/トークン SSHキー
プッシュ操作 毎回認証情報が必要 パスワードは不要
ファイアウォール 問題なし、ポート443を使用 ブロックされる可能性がある、ポート22を使用
おすすめのシナリオ 初心者、たまにしか使わない方 日常的な開発、自動化

(3) 個人用アクセストークンの使用

2021年より、GitHubではパスワードによる認証がサポートされなくなりました。パーソナルアクセストークンを使用する必要があります:

BASH
# Use when cloningToken
git clone https://<token>@github.com/user/repo.git

# Or enter it when sending the push notificationTokenAs a password
git clone https://github.com/user/repo.git
# Username: your-username
# Password: ghp_xxxxxxxxxxxx(UsageToken)

▶ サンプル:異なるプロトコルを用いたクローニング

BASH
# HTTPSMethod(Recommended for Beginners)
git clone https://github.com/facebook/react.git

# SSHMethod(Recommended for Experienced Developers)
git clone git@github.com:facebook/react.git

# GitAgreement(Read-only,Used less frequently)
git clone git://github.com/facebook/react.git

# Local Path(Clone the local repository)
git clone /path/to/local/repo.git

# Clone from another user's directory on the same server
git clone file:///home/otheruser/project.git


5. クローニング後の設定

(1) 自動的に作成された関連付け

クローンが完了すると、Git は自動的に以下の設定を作成します:

100%
graph TB
    A[Cloned repository] --> B[.gitTable of Contents]
    A --> C[Workspace Files]
    A --> D[Remote Associationorigin]
    
    B --> B1[All Commit History]
    B --> B2[All Branch Information]
    B --> B3[Profile]
    
    D --> D1[fetchAddress]
    D --> D2[pushAddress]
    D --> D3[Default Branch Tracking]
    
    style A fill:#e1f5ff
    style D fill:#d4edda

(2) リモート情報の表示

BASH
# View the name of the remote repository
git remote
# origin

# View Details
git remote -v
# origin  https://github.com/user/repo.git (fetch)
# origin  https://github.com/user/repo.git (push)

# View details about a remote repository
git remote show origin
# * remote origin
#   Fetch URL: https://github.com/user/repo.git
#   Push  URL: https://github.com/user/repo.git
#   HEAD branch: main
#   Remote branches:
#     main     tracked
#     develop  tracked
#   Local branch configured for 'git pull':
#     main merges with remote main
#   Local ref configured for 'git push':
#     main pushes to main (up to date)

(3) クローンされたブランチ

「cloning」コマンドは、すべてのリモートブランチを取得しますが、チェックアウトするのはデフォルトのブランチのみです:

BASH
# View local branches
git branch
# * main  (Only the default branch)

# View All Branches(Including remote)
git branch -a
# * main
#   remotes/origin/HEAD -> origin/main
#   remotes/origin/main
#   remotes/origin/develop
#   remotes/origin/feature-login

# Create a local branch to track a remote branch
git checkout -b develop origin/develop
# Or use the abbreviation
git checkout develop
# Branch 'develop' set up to track remote branch 'develop' from 'origin'.
# Switched to a new branch 'develop'

▶ サンプル:クローン作成後のワークフロー全体

BASH
# 1. Clone the repository
git clone https://github.com/user/project.git
cd project

# 2. View Status
git status
# On branch main
# Your branch is up to date with 'origin/main'.

# 3. View Remote Information
git remote -v

# 4. View All Branches
git branch -a

# 5. Switch to another branch
git checkout develop

# 6. View Commit History
git log --oneline --graph --all -10

# 7. Get the latest updates
git pull origin main

❓ よくある質問

Q ZIPファイルのクローン作成とダウンロードの根本的な違いは何ですか?
A クローンを作成すると、履歴全体、ブランチ情報、バージョン管理のメタデータを含む完全なGitリポジトリが作成されます。これにより、履歴の確認、バージョン間の切り替え、ブランチの作成、変更のプッシュを行うことができます。一方、ZIPファイルをダウンロードしても、ファイルのスナップショットが提供されるだけであり、バージョン管理機能は含まれていないため、Gitの操作は一切行うことができません。
Q 大規模なリポジトリのクローン作成が遅い場合、どうすればよいですか?
A 浅いクローン --depth 1 を使用すれば、最新のコミットのみをダウンロードできるため、処理が大幅に高速化されます。特定のブランチのみが必要な場合は、--single-branch オプションを使用してください。また、GitHubのfastgitミラーなど、国内のミラーサイトを利用することで、処理を高速化することもできます。
Q クローンした後、リモートリポジトリにプッシュするにはどうすればよいですか?
A プッシュ権限が必要です。パブリックリポジトリはクローンすることしかできず、プッシュすることはできません。権限が設定されているリポジトリの場合、HTTPSを使用する際はユーザー名とトークンを入力するか、SSHを使用する際はSSHキーを設定する必要があります。プッシュコマンドは git push origin <分支名> です。
Q プライベートリポジトリをクローンするにはどうすればよいですか?
A プライベートリポジトリには認証が必要です。HTTPSの場合はユーザー名とパーソナルアクセストークンを、SSHの場合は設定済みのSSH鍵を使用してください。アカウントにアクセス権限があることを確認してください。そうでない場合、「認証に失敗しました」というメッセージが表示されます。
Q 「fatal: 宛先パスがすでに存在します」というエラーが表示された場合はどうすればよいですか?
A ターゲットディレクトリはすでに存在しています。既存のディレクトリを削除して再度クローンを作成するか、別のディレクトリにクローンを作成する git clone <地址> <新目录名>、あるいは既存のディレクトリに移動して git pull を実行して更新してください。

📖 まとめ


📝 練習問題

  1. 基本演習:GitHub上の「Hello-World」リポジトリをクローンし、リモート情報とすべてのブランチを確認し、クローン後のディレクトリ構造を把握する。

  2. 応用演習:大規模なプロジェクト(Reactなど)のフルクローンとシャロークローン --depth 1 を比較し、ダウンロード時間と.gitディレクトリのサイズを比較した上で、シャロークローンの活用シーンを理解する。

  3. 課題:リポジトリをローカルにクローンし、それを別のリモートリポジトリにプッシュする方法(例:GitHubからクローンしてGitLabにプッシュする)について調査し、リモートリポジトリの管理およびマルチリモート設定について理解を深める。

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%