Git: Gitリポジトリの初期化:`git init` コマンドと .git ディレクトリ構造の詳細な解説
Gitリポジトリはバージョン管理の中核をなすものであり、すべてのコードの履歴、ブランチ、タグはリポジトリに保存されます。このレッスンでは、リポジトリの作成方法と管理方法について詳しく解説します。
1. Gitリポジトリの概要
Gitリポジトリとは、プロジェクト内のすべてのファイルとその完全な履歴を格納するデータベースのことです。
(1) Gitリポジトリとは何ですか?
Gitリポジトリとは、プロジェクトのファイルとバージョン履歴を含むディレクトリのことです。Gitリポジトリには、次のような特徴があります。
- 完全な履歴:すべてのコミットの完全なスナップショットを記録します
- ブランチのサポート:複数の並行開発ブランチを作成できます
- 分散型:各リポジトリは独立しており、完全な履歴が含まれている
- 効率的なストレージ:圧縮および重複排除技術を活用してスペースを節約します
(2) リポジトリを作成する2つの方法
graph TB
A[CreateGitWarehouse] --> B[git init<br/>Create a New Repository from Scratch]
A --> C[git clone<br/>Clone a Remote Repository]
B --> D[Empty Warehouse<br/>You need to add the files manually.]
C --> E[Complete Repository<br/>Includes all historical data]
style A fill:#e1f5ff
style B fill:#fff4e1
style C fill:#fff4e1
2つの方法の違い:
| 方法 | コマンド | 適用可能なシナリオ | 履歴を含む |
|---|---|---|---|
| 初期化 | git init |
新しいプロジェクトを作成 | ❌ 空のリポジトリ |
| クローン | git clone |
既存のプロジェクトに参加 | ✅ 完全な履歴 |
2. git init を使用してリポジトリを初期化する
git init コマンドは、通常のディレクトリを Git リポジトリに変換します。
(1) 初期化プロセス
graph LR
A[Create a Directory] --> B[Go to the Table of Contents]
B --> C[Run git init]
C --> D[Create .git Table of Contents]
D --> E[The warehouse was successfully created.]
style A fill:#e1f5ff
style E fill:#d4edda
(2) 基本的な使い方
# Method1:Initialize in the current directory
cd my-project
git init
# Method2:Create and initialize a new directory
git init my-project
▶ サンプル:新しいリポジトリの作成
# Steps1:Create a project directory
mkdir my-project
# Steps2:Go to the Table of Contents
cd my-project
# Steps3:InitializationGitWarehouse
git init
# Output:
# Initialized empty Git repository in /path/to/my-project/.git/
# Steps4:View Repository Status
git status
# Output:
# On branch main
# No commits yet
# nothing to commit (create/copy files and use "git add" to track)
# Steps5:View the directory structure
ls -la
# Output:
# total 0
# drwxr-xr-x 3 user group 4096 Jan 1 00:00 .
# drwxr-xr-x 3 user group 4096 Jan 1 00:00 ..
# drwxr-xr-x 7 user group 4096 Jan 1 00:00 .git
(3) 既存のプロジェクトで初期化を行う
すでにプロジェクトファイルがある場合は、プロジェクトディレクトリ内で直接初期化することができます:
# Go to the directory of the existing project
cd existing-project
# InitializationGitWarehouse
git init
# View Status(All existing files are untracked.)
git status
# Output:
# Untracked files:
# src/
# README.md
# package.json
git init は既存のファイルを変更せず、単に .git ディレクトリを作成するだけです。既存のファイルはすべて「追跡対象外」になります。
3. .git ディレクトリ構造
.git ディレクトリはGitリポジトリの中核であり、すべてのバージョン管理情報が格納されています。
(1) ディレクトリ構造の詳細な説明
.git/
├── HEAD # Current branch pointer
├── config # Local Configuration File
├── description # Repository Description (for GitWeb)
├── hooks/ # Hook Scripts Directory
│ ├── pre-commit.sample
│ └── post-commit.sample
├── info/ # Additional Information
│ └── exclude # Local Ignore Rules
├── objects/ # All Data Objects (Commits, Trees, Documents)
│ ├── info/
│ └── pack/
├── refs/ # Quote(Branch、Tags)
│ ├── heads/ # Local Branch
│ └── tags/ # Tags
└── index # Buffer Information(Documents)
(2) 重要書類に関する注意事項
| ファイル/ディレクトリ | 説明 | サンプル内容 |
|---|---|---|
| HEAD | 現在のブランチを指す | ref: refs/heads/main |
| config | ローカル設定 | リモートリポジトリのアドレス、ユーザー情報など |
| objects/ | すべてのデータオブジェクトを格納 | コミット、ツリー、ファイルのスナップショット(圧縮形式で格納) |
| refs/heads/ | ローカルブランチポインタ | ブランチごとに1つのファイルで、コミットハッシュが含まれている |
| refs/tags/ | タグポインタ | タグごとに1ファイル |
| インデックス | スタッシュ情報 | スタッシュ内のファイルの状態を記録します |
▶ サンプル:.git ディレクトリを表示する
# Steps1:View.gitTable of Contents
ls -la .git
# Output:
# -rw-r--r-- 1 user group 23 Jan 1 00:00 HEAD
# -rw-r--r-- 1 user group 137 Jan 1 00:00 config
# -rw-r--r-- 1 user group 73 Jan 1 00:00 description
# drwxr-xr-x 2 user group 4096 Jan 1 00:00 hooks
# drwxr-xr-x 2 user group 4096 Jan 1 00:00 info
# drwxr-xr-x 4 user group 4096 Jan 1 00:00 objects
# drwxr-xr-x 4 user group 4096 Jan 1 00:00 refs
# Steps2:ViewHEADDocuments
cat .git/HEAD
# Output:ref: refs/heads/main
# Steps3:View Profile
cat .git/config
# Output:
# [core]
# repositoryformatversion = 0
# filemode = true
# bare = false
# logallrefupdates = true
# Steps4:View the branch directory
ls -la .git/refs/heads
# Output:(Initially empty,After creating a commit, there will bemainDocuments)
(3) 「objects」ディレクトリの詳細な説明
objects このリポジトリには、SHA-1ハッシュをファイル名として、すべてのGitデータオブジェクトが格納されています:
objects/
├── 4a/ # Before hashing2"as" as the directory name
│ └── 8b2f... # After hashing38"as" as the filename
├── info/
└── pack/ # Packaging and Storage(Space-saving)
オブジェクトの種類:
- Blob:ファイルの内容
- ツリー:ディレクトリ構造
- コミット: コミットメッセージ
- タグ:タグ情報
.git ディレクトリ内のファイルは、その操作内容を完全に理解している場合を除き、手動で変更しないでください!誤った変更を行うと、リポジトリが破損する恐れがあります。
4. git clone を使ったリポジトリのクローン作成
git clone コマンドは、リモートリポジトリをローカルマシンにクローンするために使用されます。
(1) クローニングの役割
クローン作成では、以下の操作が行われます:
- 全履歴のダウンロード:すべてのコミット、ブランチ、タグが含まれます
- ローカルリポジトリを作成する:ローカルマシンに
.gitディレクトリを作成します - リモートを自動的にリンク:
originという名前のリモート参照を作成する - デフォルトブランチ:通常は
mainまたはmaster
(2) クローンコマンドの構文
# Basic Syntax
git clone <Warehouse Address>
# Clone to the specified directory
git clone <Warehouse Address> <Directory Name>
# Shallow Cloning(Clone Only RecentNNext Submission)
git clone --depth <In-Depth> <Warehouse Address>
# Clone a Single Branch
git clone -b <Branch Name> --single-branch <Warehouse Address>
▶ サンプル:GitHubリポジトリのクローン作成
# Method1:UsageHTTPSClone(Recommended for Beginners)
git clone https://github.com/user/repo.git
# Output:
# Cloning into 'repo'...
# remote: Enumerating objects: 100, done.
# remote: Counting objects: 100% (100/100), done.
# remote: Compressing objects: 100% (80/80), done.
# remote: Total 100 (delta 20), reused 100 (delta 20), pack-reused 0
# Receiving objects: 100% (100/100), done.
# Resolving deltas: 100% (20/20), done.
# Method 2: Use SSH Clone (requires SSH key configuration)
git clone git@github.com:user/repo.git
# Method3:Clone to the specified directory
git clone https://github.com/user/repo.git my-project
# Method4:Shallow Cloning(Clone Only Recent1Next Submission,Fast)
git clone --depth 1 https://github.com/user/repo.git
# Steps:Verify the cloning results
cd repo
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
(3) クローン作成後のディレクトリ構造
graph TB
A[Remote Repository<br/>github.com/user/repo] --> B[git clone]
B --> C[Local Warehouse]
C --> D[.git Table of Contents<br/>Complete History+Remote Configuration]
C --> E[Project Documents<br/>The latest version of the default branch]
D --> F[origin Remote References]
style A fill:#e1f5ff
style C fill:#d4edda
origin が自動的に作成されます。これを git remote -v から確認できます。
5. 倉庫の状況の確認
git status は、リポジトリの現在の状態を確認するための基本コマンドです。
(1) ファイルの状態の種類
graph LR
A[Document Status] --> B[Not tracked<br/>Untracked]
A --> C[Modified<br/>Modified]
A --> D[Saved<br/>Staged]
A --> E[Submitted<br/>Committed]
B -->|git add| D
C -->|git add| D
D -->|git commit| E
E -->|Edit File| C
style B fill:#fff3cd
style C fill:#ffe6e6
style D fill:#d4edda
style E fill:#c3e6cb
(2) ステータス説明表
| ステータス | 英語名 | 説明 | 次のアクション |
|---|---|---|---|
| 追跡対象外 | 追跡対象外 | 新規ファイル、Gitで追跡されていない | git add ステージング領域に追加 |
| 変更済み | 変更 | 追跡対象ファイルが変更されたが、ステージングには追加されていない | git add ステージング領域に追加 |
| ステージング済み | ステージング済み | ステージングに追加され、コミットの準備が整っています | git commit コミット |
| コミット済み | コミット済み | ローカルリポジトリにコミット済み | 作業を続行するか、プッシュするか |
▶ サンプル:リポジトリの状態の確認
# Steps1:Initialize the repository
mkdir demo && cd demo
git init
# Steps2:View Initial State(Empty Warehouse)
git status
# Output:
# On branch main
# No commits yet
# nothing to commit (create/copy files and use "git add" to track)
# Steps3:Create a New File
echo "# Demo Project" > README.md
# Steps4:View Status(Not tracked)
git status
# Output:
# On branch main
# No commits yet
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
# README.md
# nothing added to commit but untracked files present
# Steps5:Add to Stash
git add README.md
# Steps6:View Status(Saved)
git status
# Output:
# On branch main
# No commits yet
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
# new file: README.md
# Steps7:Submit
git commit -m "Initial commit"
# Steps8:View Status(Clean)
git status
# Output:
# On branch main
# nothing to commit, working tree clean
(3) ステータスの概要
-s オプションを使用すると、簡潔なステータス出力を表示できます:
git status -s
# Output Example:
# M modified-file.txt # Modified(On the leftMIndicates a temporary storage area,on the rightMIndicates workspace)
# A new-file.txt # New files that have been cached
# ?? untracked-file.txt # Untracked files
❓ よくある質問
git initとgit cloneの違いは何ですか?git init は、新しいプロジェクトに適した、まったく新しい空のリポジトリを作成します。一方、git clone は、既存のリモートリポジトリ(その履歴全体を含む)をコピーするため、既存のプロジェクトに参加する場合に適しています。git init を直接実行してください。Git は既存のファイルを変更することはなく、単に .git ディレクトリを作成するだけです。既存のファイルはすべて「追跡対象外」としてマークされます。git clone --depth 1 <url> を使用すると、最新のコミットのみをクローンするため、処理が高速になります。これは、最新のコードのみが必要で、履歴は不要な場合に適しています。📖 まとめ
- Gitリポジトリはバージョン管理の中核であり、プロジェクトファイルと完全な履歴が含まれています。
- リポジトリを作成するには、
git init(新規作成)とgit clone(クローン)の2つの方法があります。 .gitディレクトリには、HEAD、config、objects、refs など、すべてのバージョン管理情報が格納されています。- クローンを作成すると、履歴全体がダウンロードされ、ローカルリポジトリが作成され、リモートリポジトリ「origin」に自動的にリンクされます。
- ファイルには、「未追跡」、「変更済み」、「ステージング済み」、「コミット済み」の4つの状態があります。
git statusを使用してリポジトリの状態を確認し、ファイルがどのステージにあるかを確認します
📝 練習問題
-
基本演習(難易度:⭐):
my-first-repoという名前の Git リポジトリを作成し、.gitのディレクトリ構造を確認した上で、HEAD ファイルの目的を説明してください。 -
上級演習(難易度 ⭐⭐):リポジトリ内に README.md ファイルと src ディレクトリを作成してください。
git statusを使用してファイルの状態の変化を観察し、各状態の意味を記録してください。 -
課題(難易度:⭐⭐⭐):パブリックのGitHubリポジトリ(例:https://github.com/octocat/Hello-World.git)をクローンし、リモート設定(
git remote -v)を確認した上で、originの意味と目的を説明してください。