Git ต้องการสิทธิ์เขียน (write permissions) บนไฟล์ในโฟลเดอร์ .git/ ภายในโฟลเดอร์โปรเจกต์ หาก command line Git เข้าถึงโฟลเดอร์นี้ไม่ได้ จะเกิด error Cannot open .git/FETCH_HEAD: Permission denied เมื่อพยายาม pull ไฟล์
คู่มือนี้อธิบายความหมาย สาเหตุ และตัวอย่างวิธีแก้ไข
Cannot open .git/FETCH_HEAD: Permission denied
Git repositories มีโฟลเดอร์พิเศษ .git/ ซึ่งเป็น hidden folder (ขึ้นต้นด้วยจุด ".") โฟลเดอร์นี้เก็บ metadata ของ repository: project-specific config, references, current HEAD และข้อมูลสำคัญอื่นๆ
Git ต้องการ read และ write access ไปยังโฟลเดอร์นี้ เพราะเนื้อหาจะเปลี่ยนเมื่อรันคำสั่งอย่าง git config และ git pull
ตัวอย่างสถานการณ์ (An Example Scenario)
Clone repository ck-git จาก GitHub มีไฟล์ README.md ใช้คำสั่ง:
sudo git clone https://github.com/Career-Karma-Tutorials/ck-git
เนื้อหา README.md เดิม:
# ck-git
ต้องการแก้ไขให้อธิบายชัดเจนกว่า เปลี่ยนเป็น:
# Career Karma Git Demo A repository with demo files for Career Karma's Git tutorials.
เพิ่มการเปลี่ยนแปลงเข้า staging area:
sudo git add README.md
Commit การเปลี่ยนแปลง:
sudo git commit -m "docs: Make README.md more descriptive"
ก่อน push จะ pull remote version เพื่อให้แน่ใจว่า up-to-date:
git pull
เกิด error:
error: cannot open .git/FETCH_HEAD: Permission denied
Error บอกว่า Git เข้าถึงไฟล์ config FETCH_HEAD ไม่ได้
วิธีแก้ไข (The Solution)
เรา clone repository ด้วยคำสั่ง sudo ทำให้ repository ถูก clone เป็น root user ไฟล์ใน repository จึงเป็นของ root user
ตรวจสอบด้วย ls -la:
total 8 drwxr-xr-x 4 root staff 128 Sep 17 07:15 . drwxr-xr-x+ 90 James staff 2880 Sep 17 07:15 .. drwxr-xr-x 12 root staff 384 Sep 17 07:15 .git -rw-r--r-- 1 root staff 1 Sep 17 07:15 README.md
ไฟล์ทั้งหมดเป็นของ "root" (group staff) เมื่อพยายาม pull โดยไม่ใช้ sudo error เกิดขึ้น เพราะ user account ปกติไม่มีสิทธิ์ modify ไฟล์ในโฟลเดอร์
แก้ไข: เปลี่ยน ownership ของไฟล์ในโฟลเดอร์ ด้วย chown:
sudo chown -R james:staff .
คำสั่งเปลี่ยน ownership ไฟล์และโฟลเดอร์ทั้งหมด รวมถึง .git/ ตอนนี้เราเป็นเจ้าของ directory และมี full access สามารถ pull ได้:
git pull
คำสั่งทำงานสำเร็จ คืนค่า:
Already up to date.
ตอนนี้ทราบว่า remote repository ไม่มีการเปลี่ยนแปลงตั้งแต่ clone
สรุป
Error Cannot open .git/FETCH_HEAD: Permission denied เกิดเมื่อพยายาม pull code จาก remote repository แต่ directory .git/ ในโฟลเดอร์โปรเจกต์เข้าถึงไม่ได้โดย current user
แก้ไข: ให้แน่ใจว่า current user มี read-write privileges ไปยัง Git repository ที่ทำงานอยู่