Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

เชี่ยวชาญ Open-Source Repository ด้วย Best Practices บนบรรทัดคำสั่ง

การทำงานร่วมกันอย่างมีประสิทธิภาพ โดยเฉพาะใน Open Source เริ่มจากการจัดระเบียบที่ดี กฎทั่วไป "One Issue, One Pull Request" เป็นแนวทางที่ดี

แทนที่จะเปิด Issue กว้างๆ เช่น "Fix all broken links in documentation" ควรแยกเป็น Issues เล็กๆ จำนวนมาก — เช่น แยกตาม Section หรือ Page — ทำให้ Contributor หลายคนเข้ามาช่วยได้พร้อมกัน (Parallelize) แทนที่จะรอคนเดียวทำนานๆ

Issues เล็กยังช่วย Maintainer เห็นความคืบหน้า ชัดเจนว่า Part ไหนเสร็จ Part ไหนยัง — ลดโอกาสพลาดงาน นำไปสู่ Bug หรือ Security Vulnerability ภายหลัง

แต่ถ้าเปิด Issues ใหญ่ๆ ไปแล้ว มี PR เข้ามาบ้าง Merge บ้าง ยังไม่รู้ว่าเริ่ม/จบที่ไหน? ต้องเรียกคืนความเป็นระเบียบ — โชคดีที่มี CLI Tools ช่วย Scan, Sort, ทำความเข้าใจ Repo ที่وضุ่ง

1. Interactive Search-and-Replace ด้วย Vim

:%s/\<word\>/newword/gc
  • % = ทุกบรรทัดในไฟล์
  • s = Substitute
  • \<word\> = Match คำเต็ม (Whole word)
  • g = Global (ทุกครั้งที่เจอ)
  • c = Confirm แต่ละครั้ง (ปลอดภัย) — ลบ c ออกจะเร็วแต่อาจผิด

markdown-link-check มี CLI ดีเยี่ยม ใช้บ่อยจนทำเป็น Bash Alias Function:

# ใน .bashrc
function mlc() {
  find $1 -name \*.md -exec markdown-link-check -p {} \;
}

ใช้งาน: mlc <folder>

3. หา Subdirectories ที่เป็น/ไม่ใช่ Git Repo ด้วย find

พิมพ์ Subdirectories ที่มี .git (คือ Git Repo):

find . -maxdepth 1 -type d -exec test -e '{}/.git' ';' -printf "is git repo: %p\n"

พิมพ์ Subdirectories ที่ ไม่ใช่ Git Repo (ใช้ ! นิยาม):

find . -maxdepth 1 -type d -exec test '!' -e '{}/.git' ';' -printf "not git repo: %p\n"

4. Clone หลาย Git Repositories จากรายการ ด้วย xargs

มีไฟล์ repos.txt ไว้ SSH URL ทีละบรรทัด (SSH Keys ตั้งค่าแล้ว):

xargs -n1 git clone < repos.txt

Clone ทุก Repo ในรายการเข้าโฟลเดอร์ปัจจุบัน — เหมาะสำหรับ Setup ใหม่, Cloud Instances, Dockerfiles

5. แสดงหมายเลข Issues จำนวนมาก ด้วย jot

เคยต้องแยก Issue ใหญ่ 1 ตัว กลาย 37 Issues (#275-#312) — พิมพ์เลขทีละตัวนานมาก จึงใช้ jot (apt install athena-jot)

jot 37 275 312

พิมพ์เลข 275 ถึง 312 ทีละบรรทัด — Pipe ไป awk ทำให้เป็นรูปแบบ Issue Reference:

jot 37 275 312 | awk '{printf "#"$0", "}'
# ผลลัพธ์: #275, #276, #277, ... #312

GitHub จะแปลงเป็น Link อัตโนมัติ — ใช้ใน PR Description หรือ Comment ได้เลย

jot ยังสร้าง Random/Redundant Data สำหรับ Dev/Testing ได้อีก

CLI-Powered Open Source Organization

Repo ที่จัดระเบียบดี = Project ที่ดูแลดี ใช้ CLI Superpowers นี้เพื่อจัดการ Open Source ให้มีระเบียบ มีประสิทธิภาพ และโปร่งใส!