0% found this document useful (0 votes)
2 views

Git & GitHub

Git is a distributed version control system that enables multiple developers to collaborate on projects by tracking changes and managing different versions of code. The document outlines various Git commands, workflows, and techniques for effective version control, including stashing, merging, rebasing, and cherry-picking. Additionally, it covers GitHub functionalities such as creating repositories, adding collaborators, and handling pull requests to facilitate collaboration in software development.

Uploaded by

potosad380
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Git & GitHub

Git is a distributed version control system that enables multiple developers to collaborate on projects by tracking changes and managing different versions of code. The document outlines various Git commands, workflows, and techniques for effective version control, including stashing, merging, rebasing, and cherry-picking. Additionally, it covers GitHub functionalities such as creating repositories, adding collaborators, and handling pull requests to facilitate collaboration in software development.

Uploaded by

potosad380
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

GIT & GITHUB

Git is a distributed version control system (VCS) used to track


changes in code or files over time. It allows multiple developers to
collaborate on projects by managing different versions of a project,
ensuring that changes are recorded, and enabling easy rollback or
branching for experimentation.

A version control system (VCS) is a tool that helps manage changes to


files, allowing users to track revisions, collaborate with others, and
maintain a history of changes to files or code. It helps prevent data
loss, facilitates collaboration, and enables easy code review and
merging of different contributions.

Version control systems (VCS) can be categorized into three main


types:

1.​Local Version Control Systems:​

○​ This is the simplest type where the version history is


stored on a local machine.
○​ Example: RCS (Revision Control System).
○​ It's not ideal for collaboration as it lacks centralized or
distributed features.
2.​Centralized Version Control Systems (CVCS):​

○​ In this system, a central server stores the version history,


and users check out copies of the files from that server.
○​ Multiple developers can collaborate, but the central server
is a single point of failure.
○​ Example: Subversion (SVN), CVS.
3.​Distributed Version Control Systems (DVCS):​

○​ In DVCS, every user has a complete local copy of the entire


repository, including the full history of the project.
○​ This allows developers to work offline, and it’s more
resilient to server failures.
○​ Example: Git, Mercurial, Bazaar.
Each type has its strengths and is chosen based on the needs of the
project and the team. Git, being a distributed version control system,
is particularly popular for its flexibility and speed.

Configuring git ~
git config --global core.autocrlf true

git config --help

Chain of command:
mkdir Moon
cd Moon
git init
ls -> Printing file and folder​
ls -a -> Print Hidden file or folder
rm -rf .git in a Unix-like system (e.g., Linux, macOS) deletes the
.git directory and all its contents recursively and forcefully.
git status
git add . -> add all files​
git add *.txt -> add all files matching .txt
git commit -m “texting”
git commit -a -m “skipping the staging area”
rm file2.txt -> removing file
git ls-files in Git lists the files currently tracked by the Git
repository in the index (staging area).
mv file1.txt main.js in a Unix-like system (e.g., Linux, macOS)
renames or moves the file file1.txt to main.js.
gimv file1.txt main.js
git status -s -> short status
git diff --staged
git log
git log --oneline
git show commit_id
git show HEAD
git show HEAD~1 ( 1 step behind )
git show HEAD: file_name
git restore --staged file1.js || .
git restore –-source=HEAD~1 file1.js -> after commit
git bisect start
git switch​
.gitignore ->
git branch <branch-name>
git switch -c <branch-name>
git checkout -b <branch-name>
git branch <branch-name>
git merge --abort
git restore --source=feature/send-email --toc.txt
git remote (-v)
git branch
git fetch -> origin -> branch_name
git branch -vv ( to find out divergence )
git switch
git branch -d feature/change-password
git branch -r
git reset or git reset <file-name> ( stage [add kora ] gula ke unstage
niwe ase )

eta holo je ami commit


vule kore fhelsi, now ami commit theke previous committed stage e
chole aste cachi tokon
-> onek step
pichone jodi jaite cai tokon.

git reset --hard dhile code base (like vs code ) theke o sob changes
gula chole jabee

The command echo hello > file1.txt in a Unix-like system (e.g., Linux,
macOS) writes the word "hello" to a file named file1.txt.
echo world >> file1.txt will append text into the file

git restore is your tool to undo uncommitted changes—either in the


working directory (your edits) or the index (staged files).

In Git, branches are independent lines of development within a


repository. They allow you to work on different features, fixes, or
experiments separately from the main codebase (often the "main" or
"master" branch). You can create, switch, merge, or delete branches as
needed.

Stashing in Git and Code Management

Stashing in Git allows you to temporarily save uncommitted code


changes and restore them later. This is useful when you need to switch
branches, pull updates, or work on something else without committing
your incomplete work.

🔹 Stash Changes:
git stash

-> Saves uncommitted changes and reverts to the last commit.

🔹 Stash with Message:


git stash push -m "your message"

🔹 List Stashes:
git stash list

🔹 Apply Stash (Keep in List):


git stash apply stash@{n}

🔹 Apply & Remove Stash:


git stash pop

🔹 Delete Specific Stash:


git stash drop stash@{n}

🔹 Clear All Stashes:


git stash clear

💡 Use Case:
●​ Temporarily save changes without committing.
●​ Switch branches without losing work.
●​ Avoid merge conflicts before pulling updates.

🚀 Best for: Quick save points, emergency fixes, clean workflow.

git reset --hard HEAD~1 - Explanation

This command resets your branch to the previous commit and deletes all
changes in your working directory permanently

Undoing a Faulty Merge, Squash Merging, Rebasing, and


Cherry-Picking in Git

These Git techniques help you manage commits efficiently when dealing
with merges, history cleanups, and selective changes.
1️⃣ Undoing a Faulty Merge
Sometimes, after merging branches, you might realize the merge was a
mistake. Here’s how to undo it:

Option 1: If the Merge is Not Yet Pushed


git reset --hard HEAD~1

🔹 This removes the merge commit completely and resets the branch to
the previous commit.​
⚠️ Warning: This will discard uncommitted changes.

Option 2: If the Merge is Already Pushed

If you’ve already pushed the faulty merge, a reset isn’t ideal because
it rewrites history. Instead, use:

git revert -m 1 <merge_commit_hash>

🔹 This creates a new commit that undoes the merge safely.​


🔹 The -m 1 flag tells Git to keep the main branch’s changes while
removing the merged branch’s changes.

To find the merge commit hash, use:

git log --oneline

2️⃣ Squash Merging


Squash merging combines multiple commits into one before merging,
keeping history clean.
Steps to Squash Merge:
Checkout the main branch:​
git checkout main

1.​

Merge the feature branch with squash:​


git merge --squash feature-branch

2.​

Commit the squashed changes:​


git commit -m "Merged feature-branch as a single commit"

3.​

Push the changes:​


git push origin main

4.​

🔹 This keeps the commit history clean by preventing a long list of


small commits.

3️⃣ Rebasing (Rewriting Commit History)


Rebasing rewrites commit history to create a linear project history.

Use Case:

If you have a feature branch that is behind main, you can rebase
instead of merging.

Steps to Rebase:
Checkout your feature branch:​
git checkout feature-branch

1.​Rebase onto the latest main:


a.​ git rebase main
2.​Resolve conflicts (if any), then continue:
a.​git add .
b.​git rebase --continue
3.​Push with force (if already pushed before rebasing):
a.​git push --force

🔹 This moves your commits on top of the latest main commits, making
history cleaner than a merge.

4️⃣ Cherry-Picking (Selecting Specific Commits)


Cherry-picking allows you to pick specific commits from one branch and
apply them to another.

Steps to Cherry-Pick a Commit:


Find the commit hash:​
git log --oneline
Example output:​
a1b2c3d Fix login bug
d4e5f6g Add new API endpoint

1.​

Checkout the target branch:​


git checkout main

2.​

Cherry-pick the desired commit:​


git cherry-pick a1b2c3d

3.​

Push the changes:​


git push origin main

4.​
🔹 This applies only the selected commit without merging the entire
branch.

🚀 Summary Table
Action Command Use Case

Undo Merge git reset --hard Undo a merge before


(Local) HEAD~1 pushing

Undo Merge git revert -m 1 Undo a pushed merge


(Pushed) <commit> safely

Squash Merge git merge --squash Merge multiple commits


as one

Rebase git rebase main Rewrite commit history


cleanly

Cherry-Pick git cherry-pick Pick specific commits


<commit> to apply

—---------------------------------------------------------------------

git clone git_link Folder_NAME_IF_YOU_WANT

Let’s dive into Git and GitHub! I’ll break this down into the sections
you’ve outlined, explaining each concept clearly and concisely. This
will be a practical guide to get you comfortable with version control
and collaboration. Ready? Let’s go!

---

### 01 Introduction
Git is a distributed version control system that tracks changes in
your code, allowing multiple people to work on a project
simultaneously without overwriting each other’s work. GitHub is a
platform built on top of Git that hosts repositories (repos) online,
making collaboration and sharing easy. Think of Git as the tool and
GitHub as the cloud hub where your work lives.

---

### 02 Workflows
A Git workflow defines how you and your team use Git to manage
changes. Common workflows include:
- **Centralized Workflow**: One main branch (e.g., `main`), everyone
works directly on it.
- **Feature Branch Workflow**: Each new feature gets its own branch,
merged into `main` when done.
- **Gitflow**: Uses multiple branches like `main`, `develop`, and
feature branches for structured development.
Pick a workflow based on your team size and project complexity. For
beginners, start with the Feature Branch Workflow.

---

### 03 Creating a GitHub Repository


1. Log in to GitHub (github.com).
2. Click the “+” icon in the top-right corner, then select “New
repository.”
3. Name your repo, add a description (optional), and choose public or
private.
4. Optionally initialize with a README, .gitignore, or license.
5. Click “Create repository.” Done! You now have a remote repo.

---

### 04 Adding Collaborators


1. Go to your repo on GitHub.
2. Click “Settings” > “Collaborators and teams.”
3. Enter the GitHub username or email of the person you want to add.
4. Set their permission level (e.g., Write, Admin).
5. Send the invite. They’ll need to accept it to collaborate.
---

### 05 Cloning a Repository


Cloning copies a remote repo to your local machine:
1. On GitHub, click the green “Code” button and copy the HTTPS/SSH
URL.
2. Open your terminal and run:
```bash
git clone <URL>
```
3. Navigate into the folder:
```bash
cd <repo-name>
```
Now you have a local copy to work with!

---

### 06 Fetching
Fetching retrieves updates from the remote repo without merging them
into your local work:
```bash
git fetch origin
```
Use this to see what’s new on the remote (e.g., `origin/main`) without
affecting your local branches.

---

### 07 Pulling
Pulling fetches updates *and* merges them into your current branch:
```bash
git pull origin main
```
Run this when you want to sync your local branch with the remote
(e.g., `main`).

---
### 08 Pushing
Pushing sends your local commits to the remote repo:
1. Stage changes: `git add .`
2. Commit: `git commit -m "Your message"`
3. Push:
```bash
git push origin <branch-name>
```
Replace `<branch-name>` with your current branch (e.g., `main` or
`feature-x`).

---

### 09 Storing Credentials


Tired of typing your username/password? Store them securely:
- On Windows/Mac/Linux, use Git’s credential helper:
```bash
git config --global credential.helper cache
```
Or for permanent storage:
```bash
git config --global credential.helper store
```
- Alternatively, use SSH keys (generate via `ssh-keygen`, add to
GitHub under Settings > SSH and GPG keys).

---

### 10 Sharing Tags


Tags mark specific commits (e.g., for releases):
1. Create a tag:
```bash
git tag v1.0
```
2. Push it to GitHub:
```bash
git push origin v1.0
```
3. Push all tags: `git push origin --tags`.

---

### 11 Releases
Releases are GitHub’s way to package tagged versions:
1. Go to your repo > “Releases” tab.
2. Click “Draft a new release.”
3. Enter the tag (e.g., `v1.0`), title, and description.
4. Optionally attach files (e.g., binaries).
5. Publish! Users can now download it.

---

### 12 Sharing Branches


To share a branch:
1. Create a branch locally:
```bash
git checkout -b feature-x
```
2. Push it to GitHub:
```bash
git push origin feature-x
```
Others can now see and pull it with `git fetch` and `git checkout
feature-x`.

---

### 13 Collaboration Workflow


A typical collaboration flow:
1. Clone the repo.
2. Create a feature branch (`git checkout -b my-feature`).
3. Work, commit, and push (`git push origin my-feature`).
4. Open a pull request (PR) on GitHub.
5. Team reviews, merges into `main`, and repeats.
---

### 14 Pull Requests


PRs let you propose and review changes:
1. Push your branch to GitHub.
2. Go to your repo > “Pull requests” > “New pull request.”
3. Select your branch and the target branch (e.g., `main`).
4. Add a title/description, then create the PR.
5. Collaborators review, comment, and merge.

---

### 15 Resolving Conflicts


Conflicts happen when changes clash. To resolve:
1. Pull the latest changes: `git pull origin main`.
2. Git will flag conflicts in files.
3. Open the files, manually fix the conflicting sections (marked with
`<<<<<<<` and `>>>>>>>`).
4. Stage and commit: `git add .`, `git commit`.
5. Push: `git push origin <branch>`.

---

### 16 Issues
Issues track tasks or bugs:
1. Go to your repo > “Issues” tab.
2. Click “New issue,” add a title and description.
3. Assign it to someone or add labels/milestones.
4. Close it when resolved.

---

### 17 Labels
Labels categorize issues/PRs (e.g., “bug,” “enhancement”):
1. Go to “Issues” > “Labels.”
2. Create or edit labels with names, colors, and descriptions.
3. Apply them to issues/PRs for organization.
---

### 18 Milestones
Milestones group issues into goals (e.g., “v1.0 Release”):
1. Go to “Issues” > “Milestones.”
2. Create a milestone with a title, due date, and description.
3. Link issues/PRs to it.

---

### 19 Contributing to Open Source Projects


1. Fork the repo on GitHub (click “Fork”).
2. Clone your fork: `git clone <fork-URL>`.
3. Create a branch, make changes, and push.
4. Open a PR from your fork to the original repo.
5. Follow the project’s contribution guidelines.

---

### 20 Keeping a Forked Repository Up to Date


1. Add the original repo as a remote:
```bash
git remote add upstream <original-repo-URL>
```
2. Fetch updates: `git fetch upstream`.
3. Merge into your branch: `git merge upstream/main`.
4. Push: `git push origin main`.

---

### 21 Collaboration Using VS Code


VS Code has built-in Git support:
1. Open your repo folder in VS Code.
2. Use the Source Control view to stage, commit, and push.
3. Install the “GitHub Pull Requests and Issues” extension for PRs and
issues directly in VS Code.

---
### 22 Collaboration Using GitKraken
GitKraken is a visual Git client:
1. Open your repo in GitKraken.
2. Use the GUI to branch, commit, push, and pull.
3. Manage PRs and collaborate with its GitHub integration.

---

### Exercises
1. Create a GitHub repo, clone it, and push a “Hello World” file.
2. Add a collaborator and have them push a change.
3. Create a branch, make a PR, and merge it.
4. Fork a public repo, update it, and submit a PR.

---

### Summary
Git and GitHub are powerful tools for version control and
collaboration. Git handles the local tracking and branching, while
GitHub adds remote storage, PRs, and team features. Start small—clone,
commit, push—then explore branches, PRs, and open-source
contributions. Practice makes perfect!

Let me know if you want to dive deeper into any section or try a
hands-on example!

Collaboration
Cloning a repository
-> git clone url
Syncing with remotes
-> git fetch origin master
-> git fetch origin
-> git fetch
-> git pull
-> git push origin master
-> git push
Sharing tags
-> git push origin v1.0
-> git push origin —delete v1.0
Sharing branches
-> git branch -r
-> git branch -vv
-> git push -u origin bugfix
-> git push -d origin bugfix
Managing remotes
-> git remote
-> git remote add upstream url
-> git remote rm upstream

—---------------------------------------------------------------------

Let's break down Revert, Reset, and Squash Commits in a simple way!

1. Revert Changes

●​ What is it?​
Reverting is like undoing a commit but keeping the history
intact.​
It creates a new commit that reverses the changes of an old
commit.​

●​ When to Use:​
Use git revert when you want to undo a change without losing
history. It's helpful for fixing mistakes in previous commits.​

How it Works: Suppose you have this history:​



A --- B --- C (commit C has a mistake)
To revert commit C, you run:​

git revert C
Git will create a new commit C', which reverses the changes from C:​

A --- B --- C --- C' (commit C' reverts C's changes)

●​
●​ Key Point:​
Reverting doesn’t delete the original commit, it just creates a
new one that undoes the changes.​

2. Reset

●​ What is it?​
git reset is like rewinding your history to a previous commit.
It can affect your working directory and commit history.​

●​ Types of Reset:​

Soft Reset (--soft)​


This keeps all your changes staged (ready to be committed again) but
rewinds the commit history.​

git reset --soft <commit-hash>
Example:​

A --- B --- C (reset to A)

○​ After --soft reset, all the changes from B and C are staged
as if they were just made.​

Mixed Reset (--mixed)​


This keeps your changes in your working directory, but unstages them
(so they’re not ready for commit).​

git reset --mixed <commit-hash>
○​

Hard Reset (--hard)​


This removes all changes, both staged and in your working directory,
and resets everything to a previous commit.​

git reset --hard <commit-hash>

○​ Be careful with --hard because it loses data.​

●​ When to Use:​

○​ Use git reset when you want to go back to an earlier state,


and optionally modify or delete commits.
○​ --soft: You want to keep changes but rewind history.
○​ --mixed: You want to keep your changes but unstage them.
○​ --hard: You want to completely discard changes and reset
everything.

3. Squash Commits

●​ What is it?​
Squashing commits means combining multiple commits into one.
This helps keep your commit history clean and readable,
especially when you've made small, incremental changes.​

●​ When to Use:​

○​ Use squashing when you want to clean up your commit history


before pushing changes to the main branch or a shared
repository.
○​ It's great for combining several small commits that don’t
need to be tracked individually.

How it Works: Suppose you have a history like this:​



A --- B --- C --- D
If you want to squash commits B, C, and D into a single commit, you
run:​

git rebase -i HEAD~4
This opens an editor where you’ll see something like this:​

pick A
pick B
pick C
pick D

Change it to:​

pick A
squash B
squash C
squash D

After saving and exiting the editor, Git will combine B, C, and D into
a single commit. The history will look like:​

A --- BCD (a new squashed commit)

●​
●​ Key Point:​

○​ Squashing rewrites history and combines commits, so it’s


best to do it before pushing changes to the remote repo.
Once pushed, it can be more complicated to squash commits on
a shared branch.

Summary

●​ Revert Changes: Create a new commit that undoes the changes of a


specific commit. Keeps history intact.
●​ Reset: Move back to a previous commit. Can affect history and
working directory. Be careful with --hard.
●​ Squash Commits: Combine multiple commits into one, making your
commit history cleaner and more readable.

No worries! Let’s break Cherry-Picking down in the simplest way


possible.

What is Cherry-Picking?

Cherry-picking allows you to pick a specific commit from one branch


and apply it to another branch without merging everything.

Think of it like this:​


🍒 Imagine you have a tree full of commits (branches). Instead of
taking the whole branch (merge), you pick only one commit
(cherry-picking).

Example Scenario

Let’s say you have this Git history:

main: A --- B --- C --- D

feature: \--- E --- F

●​ You realize commit E contains a useful bug fix, and you only want
that commit in main (without bringing F).
●​ Instead of merging feature into main, you cherry-pick commit E:

How to Cherry-Pick?

1.​Find the commit hash (from feature branch): git log --oneline
feature
Example output:​

​ -> f5d3c21 (HEAD -> feature) Add feature F

-> e7b4a62 Fix bug (commit E)

-> d2a8c09 Update UI

The commit hash for E is e7b4a62.

2.​Switch to the main branch: git checkout main


3.​Cherry-pick commit E onto main: git cherry-pick e7b4a62
4.​Resolve conflicts (if any), then continue: git cherry-pick
--continue​

5.​Push changes to GitHub: git push origin main

Final Result

Now, only commit E is added to main, without bringing F:

main: A --- B --- C --- D --- E'

feature: \--- E --- F

(E' is the same as E but applied to main.)

When to Use Cherry-Picking?

✅ When you only need one or a few commits from another branch​
✅ When merging the entire branch is not needed or possible​
✅ When applying hotfixes or urgent bug fixes from one branch to
another
Key Takeaways

🔹 Merging brings all commits from one branch → another.​


🔹 Cherry-Picking brings only the specific commit(s) you choose.​
🔹 Useful for picking bug fixes or specific features without merging
everything.

Bonus Tip: Cherry-Pick Multiple Commits

You can also cherry-pick multiple commits at once:

git cherry-pick commit1 commit2 commit3

You might also like