נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
20
חלקPart 3: קוד נקי ו-OOPClean code & OOP כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Git ו-GitHubGit & GitHub

commit, branch, merge, push ו-README טוב.

commit, branch, merge, push and a good README.

01למה Git?Why Git?

בלי כלי, שומרים גרסאות בשמות כמו shelf_final_v2.py. Git עושה את זה כמו שצריך: כל commit הוא תמונת מצב עם הסבר, ואפשר לחזור לכל אחת. Git רץ על המחשב שלכם; GitHub הוא אתר שמאחסן את המאגר ברשת. מתקינים מ-git-scm.com (ב-Mac הוא לרוב כבר מותקן), ומגדירים שם ומייל פעם אחת:

Without a tool, you keep versions with names like shelf_final_v2.py. Git does it properly: each commit is a snapshot with an explanation, and you can return to any of them. Git runs on your computer; GitHub is a website that hosts the repo online. Install from git-scm.com (on a Mac it's often already there), and set your name and email once:

Terminal
git config --global user.name "Noa Levi"
git config --global user.email "noa@example.com"
git --version
פלט לדוגמהSample output
git version 2.43.0
אנלוגיה מהחייםReal-life analogy

Git הוא כמו כפתור "שמור משחק" במשחק מחשב: לפני הבוס שומרים, ואם נכשלים, חוזרים בדיוק לשם בלי להתחיל הכול מחדש.

Git is like a game's "save" button: save before the boss, and if you lose, go back exactly there without starting over.

טעות נפוצהCommon mistake

מריצים פקודת git מחוץ למאגר.

Running a git command outside a repository.

Terminal
git status
מה הטרמינל עונהWhat the terminal says
fatal: not a git repository (or any of the parent directories): .git
בעברית פשוטה: In plain words: fatal: not a git repository: התיקייה עדיין לא מאגר. מריצים git init (או נכנסים עם cd לתיקיית הפרויקט הנכונה).fatal: not a git repository: this folder isn't a repo yet. Run git init (or cd into the right project folder).

02המאגר וה-commit הראשוןThe repo and the first commit

שלושה צעדים. git init הופך את התיקייה למאגר. git add shelf.py מכניס את הקובץ לאזור ההכנה, ו-git commit -m "..." שומר תמונת מצב עם הודעה. git status אומר בכל רגע מה המצב. הפקודות כאן רצו באמת:

Three steps. git init turns the folder into a repository. git add shelf.py puts the file in the staging area area, and git commit -m "..." saves a snapshot with a message. git status tells you the state at any moment. These commands really ran:

Terminal
git init -b main
git status --short
git add shelf.py
git status --short
git commit -m 'Add shelf script'
פלטOutput
$ git init -b main
Initialized empty Git repository in /Users/you/python-course/.git/
$ git status --short
?? shelf.py
$ git add shelf.py
$ git status --short
A  shelf.py
$ git commit -m 'Add shelf script'
[main (root-commit) 9e42e21] Add shelf script
 1 file changed, 3 insertions(+)
 create mode 100644 shelf.py
אנלוגיה מהחייםReal-life analogy

staging הוא כמו עגלה בסופר: add שם מוצרים בעגלה, ו-commit הוא הקופה. אפשר למלא את העגלה בהדרגה ולשלם פעם אחת.

Staging is like a supermarket cart: add puts items in the cart, and commit is the checkout. Fill the cart gradually, pay once.

טעות נפוצהCommon mistake

מנסים commit בלי להוסיף קודם.

Trying to commit without adding first.

Terminal
git commit -m 'Add shelf'
מה הטרמינל עונהWhat the terminal says
On branch main

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	shelf.py

nothing added to commit but untracked files present (use "git add" to track)
בעברית פשוטה: In plain words: nothing added to commit but untracked files present: ה-staging ריק. קודם git add shelf.py (או git add . לכל הקבצים).nothing added to commit but untracked files present: staging is empty. First git add shelf.py (or git add . for everything).

03היסטוריה ושינוייםHistory and changes

שיניתם קובץ? git diff מראה בדיוק אילו שורות נוספו (+) והוסרו (-). אחרי commit נוסף, git log --oneline מראה את ההיסטוריה: מזהה קצר והודעה לכל commit. הודעה טובה מתחילה בפועל ומסבירה מה השתנה: "Sort books by title", ולא "fix".

Changed a file? git diff shows exactly which lines were added (+) and removed (-). After another commit, git log --oneline shows the history: a short id and a message per commit. A good message starts with a verb and says what changed: "Sort books by title", not "fix".

Terminal
git diff
git commit -qam 'Add Matilda and sort by title'
git log --oneline
פלטOutput
$ git diff
diff --git a/shelf.py b/shelf.py
index a300ba2..0562b04 100644
--- a/shelf.py
+++ b/shelf.py
@@ -1,3 +1,3 @@
-shelf = ["Dune", "Emma"]
-for b in shelf:
+shelf = ["Dune", "Emma", "Matilda"]
+for b in sorted(shelf):
     print(b)
$ git commit -qam 'Add Matilda and sort by title'
$ git log --oneline
b5da417 Add Matilda and sort by title
9e42e21 Add shelf script
אנלוגיה מהחייםReal-life analogy

git log הוא כמו יומן מסע: כל רשומה אומרת איפה הייתם ומה עשיתם. הודעה כמו "עשיתי דברים" לא תעזור לאף אחד בעוד חודש.

git log is like a travel journal: each entry says where you were and what you did. An entry like "did stuff" helps nobody a month later.

טעות נפוצהCommon mistake

מצפים לראות ב-git diff שינוי שכבר נוסף ל-staging.

Expecting git diff to show a change that's already staged.

Terminal
git add shelf.py
git diff
git diff --staged --stat
מה הטרמינל עונהWhat the terminal says
$ git add shelf.py
$ git diff
$ git diff --staged --stat
 shelf.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
בעברית פשוטה: In plain words: git diff ריק: הוא מראה רק שינויים שעוד לא ב-staging. לשינויים שכבר הוספתם: git diff --staged.git diff is empty: it shows only changes not yet staged. For staged changes: git diff --staged.

04.gitignore.gitignore

לא כל קובץ צריך להיכנס להיסטוריה. הסביבה הווירטואלית גדולה ונוצרת מחדש, __pycache__ נוצר לבד, וקובץ עם סיסמה או מפתח API לעולם לא נכנס ל-Git: גם אם תמחקו אחר כך, הוא נשאר בהיסטוריה. כותבים את התבניות בקובץ `.gitignore`:

Not every file belongs in history. The virtual environment is big and can be recreated, __pycache__ appears on its own, and a file with a password or API key never goes into Git: even if you delete it later, it stays in history. Write the patterns in a `.gitignore` file:

.gitignore
.venv/
__pycache__/
*.pyc
.env
shelf.db
Terminal
git status --short --untracked-files=all
פלטOutput
?? .gitignore
?? shelf.py
אנלוגיה מהחייםReal-life analogy

.gitignore הוא כמו רשימת "לא לארוז" לטיסה: אין טעם לסחוב את מה שאפשר לקנות שם, ואת מה שמסוכן אסור להעלות למטוס בכלל.

.gitignore is like a "don't pack" list for a flight: no point lugging what you can buy there, and dangerous things never go on board.

טעות נפוצהCommon mistake

מוסיפים לקוד מפתח סודי, וכך הוא נשמר בהיסטוריה לתמיד.

Putting a secret key in the code, so it's saved in history forever.

config.py
API_KEY = "sk-live-1234"
import os
assert "API_KEY" not in open(__file__).read().split("import os")[0], "a secret is written in the code: keep it in .env and read it with os.environ"
מה Python עונהWhat Python says
Traceback (most recent call last):
  File "/Users/you/python-course/config.py", line 3, in <module>
    assert "API_KEY" not in open(__file__).read().split("import os")[0], "a secret is written in the code: keep it in .env and read it with os.environ"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: a secret is written in the code: keep it in .env and read it with os.environ
בעברית פשוטה: In plain words: AssertionError: a secret is written in the code: ...: שומרים סודות בקובץ .env שמופיע ב-.gitignore, וקוראים אותם עם os.environ. נראה איך במפגש 33.AssertionError: a secret is written in the code: ...: keep secrets in a .env file listed in .gitignore and read them with os.environ. We'll see how in session 33.

05ענפים ומיזוגBranches and merging

ענף מאפשר לנסות רעיון בלי לסכן את הקוד שעובד. יוצרים ענף, עושים בו commits, וכשהרעיון מוכן חוזרים ל-main וממזגים. אם הרעיון לא הצליח, פשוט לא ממזגים. כך עובדים בכל צוות פיתוח.

A branch lets you try an idea without risking working code. Create a branch, commit on it, and when the idea's ready go back to main and merge. If it didn't work out, just don't merge. Every dev team works this way.

Terminal
git switch -c sort-books
# edit shelf.py in VS Code and save
git commit -qam 'Sort books by title'
git switch main
git merge sort-books
git log --oneline --graph
פלטOutput
$ git switch -c sort-books
Switched to a new branch 'sort-books'
# (shelf.py edited and saved)
$ git commit -qam 'Sort books by title'
$ git switch main
Switched to branch 'main'
$ git merge sort-books
Updating 9e42e21..f11f710
Fast-forward
 shelf.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git log --oneline --graph
* f11f710 Sort books by title
* 9e42e21 Add shelf script
אנלוגיה מהחייםReal-life analogy

ענף הוא כמו טיוטה של מכתב: כותבים, מוחקים ומנסים בחופשיות, ורק כשמרוצים מעתיקים לגרסה שנשלחת.

A branch is like drafting a letter: write, erase and experiment freely, and only when happy copy it into the version that gets sent.

טעות נפוצהCommon mistake

עוברים ענף כשיש שינויים שעוד לא נשמרו ומתנגשים.

Switching branches with unsaved changes that conflict.

Terminal
git switch other
מה הטרמינל עונהWhat the terminal says
error: Your local changes to the following files would be overwritten by checkout:
	shelf.py
Please commit your changes or stash them before you switch branches.
Aborting
בעברית פשוטה: In plain words: error: Your local changes ... would be overwritten by checkout: Git מגן על העבודה שלכם. קודם commit (או git stash לשמירה זמנית), ואז עוברים.error: Your local changes ... would be overwritten by checkout: Git protects your work. Commit first (or git stash to set it aside), then switch.

06להעלות ל-GitHubPushing to GitHub

ב-GitHub נרשמים, לוחצים New repository, ומקבלים כתובת. מחברים אליה את המאגר המקומי פעם אחת, ומאז git push מעלה commits חדשים ו-git pull מוריד שינויים של אחרים. בפעם הראשונה ההתחברות נעשית בדפדפן או דרך VS Code (Sign in with GitHub). VS Code גם מציג את כל זה בלשונית Source Control.

On GitHub you sign up, click New repository, and get an address. Connect your local repo to it once, and from then on git push uploads new commits and git pull downloads others' changes. The first time, you sign in through the browser or VS Code (Sign in with GitHub). VS Code also shows all this in the Source Control tab.

Terminal
git remote add origin https://github.com/noa/shelf.git
git push -u origin main
פלט לדוגמהSample output
Enumerating objects: 6, done.
Writing objects: 100% (6/6), 612 bytes | 612.00 KiB/s, done.
To https://github.com/noa/shelf.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.
אנלוגיה מהחייםReal-life analogy

GitHub הוא כמו כספת בענן לדפדפת השמורה שלכם: אם המחשב נגנב, הכול עדיין שם, וגם חברים יכולים לקבל עותק.

GitHub is like a cloud safe for your saved binder: if the laptop is stolen, it's all still there, and friends can get a copy too.

טעות נפוצהCommon mistake

מוסיפים remote בשם שכבר קיים.

Adding a remote with a name that already exists.

Terminal
git remote add origin https://github.com/noa/shelf2.git
מה הטרמינל עונהWhat the terminal says
error: remote origin already exists.
בעברית פשוטה: In plain words: error: remote origin already exists.: כבר יש origin. לשינוי הכתובת: git remote set-url origin <url>.error: remote origin already exists.: there's already an origin. To change the address: git remote set-url origin <url>.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich