{"id":49563379,"url":"https://github.com/madsondeluna/howtogit","last_synced_at":"2026-05-03T10:47:41.349Z","repository":{"id":317295859,"uuid":"1010394936","full_name":"madsondeluna/howtogit","owner":"madsondeluna","description":"This repository serves as a refresher for Git commands and as a didactic resource to learn through a CLI-based approach, helping users understand concepts with practical, hands-on examples.","archived":false,"fork":false,"pushed_at":"2025-11-12T20:33:33.000Z","size":1341,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-05-03T10:47:21.928Z","etag":null,"topics":["git","git-commands","github","github-actions","how-to-git"],"latest_commit_sha":null,"homepage":"https://education.github.com/experiences/foundations_certificate","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/madsondeluna.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-06-29T01:17:24.000Z","updated_at":"2026-01-06T08:50:31.000Z","dependencies_parsed_at":"2025-10-01T08:30:51.343Z","dependency_job_id":null,"html_url":"https://github.com/madsondeluna/howtogit","commit_stats":null,"previous_names":["madsondeluna/howtogit"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/madsondeluna/howtogit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madsondeluna%2Fhowtogit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madsondeluna%2Fhowtogit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madsondeluna%2Fhowtogit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madsondeluna%2Fhowtogit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/madsondeluna","download_url":"https://codeload.github.com/madsondeluna/howtogit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/madsondeluna%2Fhowtogit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32566444,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-03T06:36:36.687Z","status":"ssl_error","status_checked_at":"2026-05-03T06:36:09.306Z","response_time":103,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["git","git-commands","github","github-actions","how-to-git"],"created_at":"2026-05-03T10:47:40.466Z","updated_at":"2026-05-03T10:47:41.326Z","avatar_url":"https://github.com/madsondeluna.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# How to Git\n\nA Quick GitHub Course / Um Curso Rápido de GitHub\n\n---\n\n\u003cp align=\"center\"\u003e\n\n\u003c!-- Linha 1 — meta + stack (for-the-badge, cores de marca, logos) --\u003e\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE)\n![Bilingual](https://img.shields.io/badge/PT%20%2F%20EN-Bilingual-0A66C2?style=for-the-badge)\n![Git](https://img.shields.io/badge/Git-F05032?logo=git\u0026logoColor=white\u0026style=for-the-badge)\n![GitHub](https://img.shields.io/badge/GitHub-181717?logo=github\u0026logoColor=white\u0026style=for-the-badge)\n![Bash](https://img.shields.io/badge/Bash-4EAA25?logo=gnu-bash\u0026logoColor=white\u0026style=for-the-badge)\n![Markdown](https://img.shields.io/badge/Markdown-000000?logo=markdown\u0026logoColor=white\u0026style=for-the-badge)\n![ASCII%20Art](https://img.shields.io/badge/ASCII%20Art-6B7280?logo=readme\u0026logoColor=white\u0026style=for-the-badge)\n\n\u003c!-- Linha 2 — informações do curso + automação --\u003e\n![Version](https://img.shields.io/badge/Version-2.0-2B6CB0?style=for-the-badge)\n![Updated](https://img.shields.io/badge/Updated-Nov_2025-00A3A3?style=for-the-badge)\n![Docs](https://img.shields.io/badge/Docs-PT%2FEN-0A66C2?style=for-the-badge)\n![Hands--on](https://img.shields.io/badge/Hands--on-Labs%20%2B%20CLI-F39C12?style=for-the-badge)\n![Scripts](https://img.shields.io/badge/Scripts-Bash--based-34495E?style=for-the-badge)\n\n\u003c/p\u003e\n\n---\n\n## PT-BR \u0026 EN-US\n\n**English:** This is a complete Git course taught in both English and Brazilian Portuguese. All learning materials, interactive CLI tools, and documentation are fully bilingual. The README is organized in two main sections: **first in English**, then **in Portuguese**. Use the table of contents below to jump directly to your preferred language.\n\n**Português:** Este é um curso completo de Git ministrado em inglês e português brasileiro. Todos os materiais de aprendizado, ferramentas CLI interativas e documentação são totalmente bilíngues. O README está organizado em duas seções principais: **primeiro em inglês**, depois **em português**. Use o índice abaixo para ir diretamente para seu idioma preferido.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/git-fundamentals.png\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n\u003e https://sysxplore.com/ \n\n\u003e Guia rápido para o dia-a-dia de de versionamento com Git e GitHub\n\n\u003e Quick guide for daily version control with Git and GitHub\n\n\u003e Uma dica? Imprime e cola na parede da sua mesa!!!\n\n\u003e A tip? Print it and stick it on your desk wall!!!\n\n---\n\n## Table of Contents | Índice\n\n### English Version\n- [About the Course (EN)](#about-the-course-english)\n- [Part 1: Fundamentals (EN)](#part-1-fundamentals)\n- [Part 2: Commands (EN)](#part-2-commands)\n- [Part 3: Practice (EN)](#part-3-practice)\n- [Real World Use Cases (EN)](#real-world-use-cases)\n- [Best Practices (EN)](#best-practices)\n- [Troubleshooting (EN)](#troubleshooting)\n- [External Resources (EN)](#external-resources)\n- [Contributing (EN)](#contributing)\n- [Found an Error? Report It! (EN)](#found-an-error-report-it)\n\n### Versão em Português\n- [Sobre o Curso (PT)](#sobre-o-curso-português)\n- [Parte 1: Fundamentos (PT)](#parte-1-fundamentos)\n- [Parte 2: Comandos (PT)](#parte-2-comandos)\n- [Parte 3: Prática (PT)](#parte-3-prática)\n- [Casos de Uso Reais (PT)](#casos-de-uso-reais)\n- [Melhores Práticas (PT)](#melhores-práticas)\n- [Solução de Problemas (PT)](#solução-de-problemas)\n- [Recursos Externos (PT)](#recursos-externos)\n- [Contribuindo (PT)](#contribuindo)\n- [Encontrou um Erro? Reporte! (PT)](#encontrou-um-erro-reporte)\n\n# ENGLISH VERSION\n\n---\n\n## About the Course (English)\n\nWelcome to the complete Git mini course! Learn from basics to advanced techniques, with theory, practice, and interactive tools.\n\n**What makes this course special:**\n\n- **Bilingual Content:** All materials, scripts, and CLI tools are available in both English and Portuguese\n- **Interactive Learning:** Hands-on CLI tools to practice Git commands safely\n- **Real-World Focus:** Practical examples and use cases from actual development workflows\n- **Progressive Learning:** From basic to advanced, with clear progression\n- **Open Source:** Free and open to contributions\n\n**All unsupervised learning CLI tools are bilingual!**\n\n---\n\n## Part 1: Fundamentals\n\n### What is Git?\n\n**Git** is a distributed version control system created by Linus Torvalds in 2005. It allows you to:\n\n- Track all changes made to your files over time\n- Work on different versions of your project simultaneously (branches)\n- Collaborate with others without overwriting their work\n- Go back to any previous version of your code at any time\n\n**Analogy:** Think of Git as a \"time machine\" for your files. You can:\n- See what changed and when\n- Go back to any point in the past\n- Create alternate realities (branches) to test ideas\n- Merge different timelines (merge)\n\n**Git is NOT:**\n- A cloud service (that's GitHub, GitLab, etc.)\n- Only for programmers (can be used for any text files)\n- Complicated (with practice it becomes natural)\n\n---\n\n### What is GitHub?\n\n**GitHub** is a web platform that hosts Git repositories in the cloud. It's like a \"social network for code\".\n\n**Main differences:**\n\n| Git | GitHub |\n|-----|--------|\n| Version control system | Hosting platform |\n| Works locally on your computer | Works in the cloud (online) |\n| Command-line software | Web interface + tools |\n| Free and open source | Free with paid features |\n| Created in 2005 | Created in 2008 |\n\n**What GitHub adds to Git:**\n- Remote storage (cloud backup)\n- Visual interface for code review\n- Pull Requests (collaborative code review)\n- Issues (task management)\n- Actions (task automation)\n- Pages (static site hosting)\n- Social collaboration (follow developers, star projects)\n\n**Alternatives to GitHub:**\n- GitLab\n- Bitbucket\n- Gitea\n- SourceForge\n\n---\n\n### Why use version control?\n\n**Problems without version control:**\n- \"Where's the version that worked?\"\n- \"Who made this change and why?\"\n- \"How do I merge my work with my colleague's?\"\n- \"I lost everything! No backup!\"\n- Folders full of: `project_v1`, `project_v2_final`, `project_v2_final_NOW_IT_WORKS`, `project_final_final`\n\n**Git Benefits:**\n1. **Complete history:** Every change is recorded with date, author, and reason\n2. **Parallel work:** Multiple people working simultaneously without conflicts\n3. **Safety:** Distributed backup - each clone is a complete backup\n4. **Safe experimentation:** Test ideas without fear of breaking what works\n5. **Traceability:** Discover when and why each line was modified\n6. **Reversibility:** Undo mistakes easily\n7. **Collaboration:** Work as a team in an organized way\n8. **Professionalism:** Software industry standard\n\n**Use cases:**\n- Software development (primary)\n- Technical documentation\n- System configurations\n- Articles and books (text)\n- Academic papers\n- Any project with multiple versions\n\n\u003e Workflow of how GitHub works\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/github-process-english.png\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n---\n\n### Essential Concepts\n\n\u003e Basic workflow with GitHub work (or shold if the users used it in the right way)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/GitHub-Flow.webp\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n**Repository:**\n- Folder containing your project and all Git history\n- Can be local (on your computer) or remote (GitHub, etc.)\n\n**Commit:**\n- A \"snapshot\" of your project at a specific moment\n- Each commit has: unique hash, author, date, descriptive message\n\n**Branch:**\n- An independent line of development\n- Allows working on features without affecting main code\n- Default branch: `main` (or `master` in older projects)\n\n**Merge:**\n- Combine changes from one branch into another\n- May generate conflicts that need manual resolution\n\n**Working Directory:**\n- The files you see and edit in your folder\n\n**Staging Area (Index):**\n- Intermediate area where you prepare files for commit\n- Allows selective commits (only some files)\n\n**Remote:**\n- Version of repository hosted elsewhere (GitHub, etc.)\n- Default name: `origin`\n\n**File states:**\n1. **Untracked:** Git is not tracking this file\n2. **Unmodified:** Tracked file, no changes since last commit\n3. **Modified:** File was modified but not in staging\n4. **Staged:** File ready to be committed\n\n---\n\n## Part 2: Commands\n\n---\n\n## Module 1: Basic Commands\n\n**For whom:** Beginners who never used Git\n\n**You'll learn:** Create repository, make commits, view history\n\n---\n\n### 1.1 Initial Setup\n\n| Command | Description |\n|---|---|\n| `git config --global user.name \"Your Name\"` | Set your name for all repositories |\n| `git config --global user.email \"your@email.com\"` | Set your email for all repositories |\n| `git config --list` | Show all configurations |\n| `git --version` | Show installed Git version |\n\n**Example:**\n```bash\ngit config --global user.name \"Madson Aragão\"\ngit config --global user.email \"madson@example.com\"\ngit config --global core.editor \"vim\"\n```\n\n---\n\n### 1.2 Create and Initialize\n\n| Command | Description |\n|---|---|\n| `git init` | Create new Git repository in current folder |\n| `git clone \u003curl\u003e` | Copy remote repository to your computer |\n\n**Example:**\n```bash\n# Create new project\nmkdir my-project\ncd my-project\ngit init\n\n# Clone existing project\ngit clone https://github.com/user/repository.git\n```\n\n---\n\n### 1.3 Status and Differences\n\n| Command | Description |\n|---|---|\n| `git status` | Show current state of files |\n| `git status -s` | Short status format |\n| `git diff` | Show unstaged changes |\n| `git diff --staged` | Show staged changes |\n\n**Example:**\n```bash\ngit status              # See what changed\ngit diff file.txt       # See specific changes\n```\n\n---\n\n### 1.4 Add and Commit\n\n| Command | Description |\n|---|---|\n| `git add \u003cfile\u003e` | Add specific file to staging |\n| `git add .` | Add all modified files |\n| `git add -A` | Add all (including deleted) |\n| `git commit -m \"message\"` | Create commit with message |\n| `git commit -am \"message\"` | Add + commit (tracked files only) |\n\n**Example:**\n```bash\n# Basic workflow\ngit add file.txt\ngit commit -m \"Add new file\"\n\n# Or all at once\ngit add .\ngit commit -m \"Update documentation\"\n```\n\n---\n\n### 1.5 View History\n\n| Command | Description |\n|---|---|\n| `git log` | Show complete commit history |\n| `git log --oneline` | Summarized history (1 line per commit) |\n| `git log --graph` | History with visual graph |\n| `git log -n 5` | Show last 5 commits |\n| `git show \u003chash\u003e` | Show details of specific commit |\n\n**Example:**\n```bash\ngit log --oneline --graph --all\ngit log --author=\"Madson\"\ngit log --since=\"2 weeks ago\"\n```\n\n---\n\n### 1.6 Remote Repositories\n\n| Command | Description |\n|---|---|\n| `git remote add origin \u003curl\u003e` | Connect local repository to remote |\n| `git remote -v` | List configured remotes |\n| `git push -u origin main` | Send commits to remote (first time) |\n| `git push` | Send commits to remote |\n| `git pull` | Fetch and merge changes from remote |\n\n**Example:**\n```bash\n# Connect to GitHub\ngit remote add origin https://github.com/user/repo.git\ngit push -u origin main\n\n# Then just\ngit push\ngit pull\n```\n\n---\n\n## Module 2: Intermediate Commands\n\n**For whom:** Those who know basics and want to work with branches and collaboration\n\n---\n\n### 2.1 Working with Branches\n\n| Command | Description |\n|---|---|\n| `git branch` | List all local branches |\n| `git branch -a` | List all branches (local + remote) |\n| `git branch \u003cname\u003e` | Create new branch |\n| `git checkout \u003cname\u003e` | Switch to another branch |\n| `git checkout -b \u003cname\u003e` | Create and switch to new branch |\n| `git switch \u003cname\u003e` | Switch branch (modern command) |\n| `git branch -d \u003cname\u003e` | Delete branch (if already merged) |\n| `git branch -D \u003cname\u003e` | Force delete branch |\n\n**Example:**\n```bash\n# Create feature\ngit checkout -b feature/login\n# ... work ...\ngit add .\ngit commit -m \"Implement login\"\n\n# Return to main\ngit checkout main\n```\n\n---\n\n### 2.2 Merge and Conflicts\n\n| Command | Description |\n|---|---|\n| `git merge \u003cbranch\u003e` | Merge specified branch into current |\n| `git merge --abort` | Cancel ongoing merge |\n| `git merge --no-ff \u003cbranch\u003e` | Merge without fast-forward (creates merge commit) |\n\n**Example:**\n```bash\ngit checkout main\ngit merge feature/login\n\n# If there are conflicts\n# 1. Edit files manually\n# 2. Remove conflict markers\n# 3. git add \u003cresolved-file\u003e\n# 4. git commit\n```\n\n---\n\n### 2.3 Stash (Save Temporarily)\n\n| Command | Description |\n|---|---|\n| `git stash` | Save changes temporarily |\n| `git stash push -m \"message\"` | Stash with descriptive message |\n| `git stash list` | List all stashes |\n| `git stash pop` | Recover last stash and remove from list |\n| `git stash apply` | Apply stash but keep in list |\n| `git stash drop` | Remove last stash |\n| `git stash clear` | Remove all stashes |\n\n**Example:**\n```bash\n# Quick context switch\ngit stash push -m \"WIP: working on login\"\ngit checkout hotfix\n# ... fix urgent bug ...\ngit checkout feature/login\ngit stash pop\n```\n\n---\n\n### 2.4 Undo Changes\n\n| Command | Description |\n|---|---|\n| `git restore \u003cfile\u003e` | Discard changes in file |\n| `git restore --staged \u003cfile\u003e` | Remove file from staging |\n| `git reset --soft HEAD~1` | Undo commit, keep changes staged |\n| `git reset --mixed HEAD~1` | Undo commit, unstage changes |\n| `git reset --hard HEAD~1` | Undo commit and discard changes |\n| `git revert \u003chash\u003e` | Create new commit undoing another |\n\n**Example:**\n```bash\n# Undo local changes\ngit restore file.txt\n\n# Undo last commit (keep changes)\ngit reset --soft HEAD~1\n\n# Undo specific commit (safe for shared)\ngit revert a1b2c3d\n```\n\n---\n\n### 2.5 Tags (Versions)\n\n| Command | Description |\n|---|---|\n| `git tag` | List all tags |\n| `git tag v1.0.0` | Create lightweight tag |\n| `git tag -a v1.0.0 -m \"Version 1.0\"` | Create annotated tag |\n| `git push origin v1.0.0` | Push tag to remote |\n| `git push origin --tags` | Push all tags |\n\n**Example:**\n```bash\ngit tag -a v1.0.0 -m \"First stable version\"\ngit push origin v1.0.0\n```\n\n---\n\n## Module 3: Advanced Commands\n\n**For whom:** Experienced developers who want to master Git\n\n---\n\n### 3.1 Rebase (Rewrite History)\n\n| Command | Description |\n|---|---|\n| `git rebase main` | Reapply current branch commits on top of main |\n| `git rebase -i HEAD~3` | Interactive rebase (edit last 3 commits) |\n| `git rebase --continue` | Continue rebase after resolving conflicts |\n| `git rebase --abort` | Cancel ongoing rebase |\n| `git pull --rebase` | Pull with rebase instead of merge |\n\n**When to use:**\n- Keep history linear and clean\n- Before creating Pull Request\n- Update feature branch with main\n\n**WARNING:** Don't rebase commits already pushed to remote!\n\n**Example:**\n```bash\ngit checkout feature/login\ngit rebase main\n\n# Clean history before PR\ngit rebase -i HEAD~5\n# In editor: squash, reword, drop\n```\n\n---\n\n### 3.2 Cherry-pick (Selective Commits)\n\n| Command | Description |\n|---|---|\n| `git cherry-pick \u003chash\u003e` | Apply specific commit to current branch |\n| `git cherry-pick \u003chash1\u003e \u003chash2\u003e` | Apply multiple commits |\n| `git cherry-pick --continue` | Continue after resolving conflicts |\n| `git cherry-pick --abort` | Cancel cherry-pick |\n\n**Example:**\n```bash\n# Take bugfix from one branch to another\ngit checkout main\ngit cherry-pick a1b2c3d\n```\n\n---\n\n### 3.3 Reflog (Recover Lost Commits)\n\n| Command | Description |\n|---|---|\n| `git reflog` | Show history of HEAD movements |\n| `git reflog show \u003cbranch\u003e` | Reflog of specific branch |\n| `git reset --hard \u003chash\u003e` | Go back to specific commit from reflog |\n\n**Example:**\n```bash\n# \"Lost\" commits after reset\ngit reflog\n# HEAD@{2}: commit: Implement feature X\ngit reset --hard HEAD@{2}  # Recover!\n```\n\n---\n\n### 3.4 Bisect (Find Bugs)\n\n| Command | Description |\n|---|---|\n| `git bisect start` | Start binary search for bug |\n| `git bisect bad` | Mark current commit as bad |\n| `git bisect good \u003chash\u003e` | Mark commit as good |\n| `git bisect reset` | End bisect |\n\n**Example:**\n```bash\ngit bisect start\ngit bisect bad                  # Current commit has bug\ngit bisect good v1.0.0          # v1.0.0 worked\n# Git will test commits in the middle\n# For each one you test and mark: git bisect good/bad\n```\n\n---\n\n### 3.5 Blame (Who Changed?)\n\n| Command | Description |\n|---|---|\n| `git blame \u003cfile\u003e` | Show who modified each line |\n| `git blame -L 10,20 \u003cfile\u003e` | Blame specific lines |\n| `git blame -C \u003cfile\u003e` | Detect copied lines |\n\n**Example:**\n```bash\ngit blame src/main.py -L 50,60\n```\n\n---\n\n### 3.6 Submodules\n\n| Command | Description |\n|---|---|\n| `git submodule add \u003curl\u003e \u003cpath\u003e` | Add repository as submodule |\n| `git submodule init` | Initialize submodules |\n| `git submodule update` | Update submodules |\n| `git clone --recursive \u003curl\u003e` | Clone with submodules |\n\n---\n\n### 3.7 Worktree (Multiple Directories)\n\n| Command | Description |\n|---|---|\n| `git worktree add \u003cpath\u003e \u003cbranch\u003e` | Create directory for branch |\n| `git worktree list` | List worktrees |\n| `git worktree remove \u003cpath\u003e` | Remove worktree |\n\n**Example:**\n```bash\n# Work on 2 branches simultaneously\ngit worktree add ../project-feature feature/new\ncd ../project-feature\n# Now you have 2 independent directories!\n```\n\n---\n\n### 3.8 Hooks (Automation)\n\n**Files in `.git/hooks/`:**\n- `pre-commit`: Execute before commit\n- `pre-push`: Execute before push\n- `post-merge`: Execute after merge\n\n**Example:**\n```bash\n# .git/hooks/pre-commit\n#!/bin/bash\nnpm test  # Run tests before allowing commit\n```\n\n---\n\n## Part 3: Practice\n\n---\n\n## Interactive Tools\n\nThis course includes interactive CLI tools to facilitate learning and using Git.\n\n---\n\n### 1. Interactive Tutorial\n\n**[git-learn.sh](scripts/git-learn.sh)** - Learn Git from scratch\n\n```bash\n./scripts/git-learn.sh\n```\n\n**Content:**\n- 12 progressive lessons (basic to intermediate)\n- Explanations in Portuguese and English\n- Guided practical exercise at the end\n- Creates real test repository\n\n**For whom:**\n- Total Git beginners\n- Those who want to understand concepts\n- Students learning programming\n\n---\n\n### 2. Interactive CLI\n\n**[git-cli.sh](scripts/git-cli.sh)** - Execute Git commands via menu\n\n```bash\n./scripts/git-cli.sh\n```\n\n**Features:**\n- 13 most common Git operations\n- Numbered menu interface\n- Confirmation for dangerous actions\n- Detects repository automatically\n- Shows current branch\n\n**For whom:**\n- Those who want to speed up common tasks\n- Beginners who haven't memorized commands yet\n- Quick daily use\n\n---\n\n### 3. Git Simulator\n\n**[git-simulator.sh](scripts/git-simulator.sh)** - Simulate Git operations without risk\n\n```bash\n./scripts/git-simulator.sh\n```\n\n**Features:**\n- Creates temporary test environment\n- Simulates complete Git workflow\n- Visualizes repository state\n- Practice without fear of mistakes\n- Environment is destroyed on exit\n\n**For whom:**\n- Those who want to practice without risk\n- Git classes and workshops\n- Test commands before using in real projects\n\n---\n\n### 4. Commands List\n\n**[list-of-comds-how2git.sh](scripts/list-of-comds-how2git.sh)** - Organized and commented commands\n\n```bash\ncat scripts/list-of-comds-how2git.sh\n# or\nvim scripts/list-of-comds-how2git.sh\n```\n\n**For whom:**\n- Quick reference\n- Copy and paste commands\n- Study syntax\n\n---\n\n## Real World Use Cases\n\n### Case 1: First day on project\n\n```bash\n# Clone repository\ngit clone https://github.com/company/project.git\ncd project\n\n# View branch structure\ngit branch -a\n\n# View recent commits\ngit log --oneline -10\n\n# Create your work branch\ngit checkout -b feature/my-task\n```\n\n---\n\n### Case 2: Complete feature\n\n```bash\n# Create branch\ngit checkout -b feature/login\n\n# Work...\ngit add .\ngit commit -m \"feat: add login screen\"\n\n# More work...\ngit commit -am \"feat: add validation\"\n\n# Update with main\ngit fetch origin\ngit rebase origin/main\n\n# Send for review\ngit push -u origin feature/login\n# Create Pull Request on GitHub\n```\n\n---\n\n### Case 3: Urgent production bug\n\n```bash\n# Save current work\ngit stash push -m \"WIP: login feature\"\n\n# Create hotfix\ngit checkout main\ngit pull origin main\ngit checkout -b hotfix/fix-critical-error\n\n# Fix...\ngit add .\ngit commit -m \"fix: correct authentication error\"\n\n# Send\ngit push -u origin hotfix/fix-critical-error\n\n# Return to work\ngit checkout feature/login\ngit stash pop\n```\n\n---\n\n### Case 4: Undo disaster\n\n```bash\n# \"I deleted everything with reset --hard!\"\ngit reflog\n# HEAD@{1}: reset: moving to HEAD~5\n# HEAD@{2}: commit: Implement important feature\n\n# Recover\ngit reset --hard HEAD@{2}\n# Everything back!\n```\n\n---\n\n### Case 5: Clean history before PR\n\n```bash\n# You have 10 messy commits\ngit log --oneline -10\n\n# Organize with interactive rebase\ngit rebase -i HEAD~10\n\n# In editor:\n# pick  -\u003e keep commit\n# squash -\u003e merge with previous\n# reword -\u003e change message\n# drop   -\u003e discard\n\n# Force update branch\ngit push --force-with-lease\n```\n\n---\n\n### Case 6: Resolve merge conflict\n\n```bash\ngit merge main\n# CONFLICT (content): Merge conflict in file.txt\n\n# Open file.txt and see:\n\u003c\u003c\u003c\u003c\u003c\u003c\u003c HEAD\nyour branch code\n=======\nmain code\n\u003e\u003e\u003e\u003e\u003e\u003e\u003e main\n\n# Edit manually, remove markers\n# Choose what to keep\n\ngit add file.txt\ngit commit -m \"Resolve merge conflict\"\n```\n\n---\n\n## Practical Examples\n\nDetailed examples of real scenarios:\n\n- **[Resolve Conflicts](examples/01-resolver-conflitos.md)** - Complete step by step\n- **[Create Pull Request](examples/02-criar-pull-request.md)** - Complete workflow\n- **[Undo Commits](examples/03-desfazer-commits.md)** - All techniques\n\n---\n\n## Popular Workflows\n\n### GitHub Flow (Simple)\n\n```\nmain (always deployable)\n  ├─ feature/login\n  ├─ feature/payment\n  └─ hotfix/critical-bug\n```\n\n**Rules:**\n1. `main` always working\n2. Branch per feature\n3. Pull Request to review\n4. Merge and deploy\n\n---\n\n### Gitflow (Complete)\n\n```\nmain (production)\n  └─ develop (development)\n      ├─ feature/new-feature\n      ├─ release/v1.2.0\n      └─ hotfix/correction\n```\n\n**Branches:**\n- `main`: production code\n- `develop`: next version\n- `feature/*`: new features\n- `release/*`: release preparation\n- `hotfix/*`: urgent fixes\n\n---\n\n### Trunk-Based (Fast)\n\n```\nmain (trunk)\n  ├─ feature-flags\n  └─ direct commits\n```\n\n**Characteristics:**\n- Direct commits to main\n- Short-lived branches (\u003c1 day)\n- Feature flags for incomplete features\n- Robust CI/CD\n\n---\n\n## Best Practices\n\n### Commit Messages\n\n**Conventional Commits:**\n```\ntype(scope): short description\n\nDetailed description (optional)\n\nBREAKING CHANGE: description (optional)\n```\n\n**Types:**\n- `feat`: new feature\n- `fix`: bug fix\n- `docs`: documentation\n- `style`: formatting\n- `refactor`: refactoring\n- `test`: tests\n- `chore`: maintenance\n\n**Example:**\n```bash\ngit commit -m \"feat(auth): add JWT authentication\n\nImplement login with JWT tokens\nAdd authentication middleware\nTokens expire after 24h\"\n```\n\n---\n\n### What NOT to commit\n\n**Never commit:**\n- Passwords, API keys, tokens\n- Environment files (`.env`)\n- Dependencies (`node_modules/`, `venv/`)\n- Build files (`dist/`, `build/`)\n- IDE files (`.idea/`, `.vscode/`)\n- Logs and temporary files\n\n**Use `.gitignore`:**\n```bash\n# .gitignore\n.env\nnode_modules/\n*.log\n.DS_Store\n```\n\n---\n\n### When to commit\n\n**Commit when:**\n- Complete and tested functionality\n- Bug fixed and verified\n- Refactoring that doesn't break anything\n- Updated documentation\n\n**Ideal size:**\n- Not too large (makes review difficult)\n- Not too small (clutters history)\n- One complete logical change\n\n---\n\n## Visual Cheatsheet\n\nFor quick visual reference, see:\n\n**[docs/cheatsheet.md](docs/cheatsheet.md)** - Diagrams and organized commands\n\n---\n\n## External Resources\n\n### Official Documentation\n- [Git Documentation](https://git-scm.com/doc) - Complete documentation\n- [Pro Git Book](https://git-scm.com/book/en/v2) - Free book\n\n### Interactive Tutorials\n- [Learn Git Branching](https://learngitbranching.js.org/) - Visual and interactive\n- [Git Visualizer](https://git-school.github.io/visualizing-git/) - Visualize commands\n\n### Guides\n- [GitHub Guides](https://guides.github.com/)\n- [Atlassian Git Tutorials](https://www.atlassian.com/git/tutorials)\n- [Git Cheat Sheet](https://education.github.com/git-cheat-sheet-education.pdf)\n\n### Visual Tools\n- [GitKraken](https://www.gitkraken.com/) - Visual Git client\n- [SourceTree](https://www.sourcetreeapp.com/) - Free client\n- [Git Extensions](https://gitextensions.github.io/) - For Windows\n\n---\n\n## Troubleshooting\n\n### Error: \"fatal: not a git repository\"\n\n```bash\n# You're not in a Git repository\ngit init  # To create new\n# OR\ncd /path/to/repository  # Go to existing repository\n```\n\n---\n\n### Error: \"Your branch is behind\"\n\n```bash\n# Your repository is outdated\ngit pull origin main\n```\n\n---\n\n### Error: \"CONFLICT (content): Merge conflict\"\n\n```bash\n# There are merge conflicts\ngit status  # See conflicting files\n# Edit files manually\ngit add \u003cresolved-file\u003e\ngit commit\n```\n\n---\n\n### Error: \"Permission denied (publickey)\"\n\n```bash\n# Configure SSH keys\nssh-keygen -t ed25519 -C \"your@email.com\"\n# Add key to GitHub\ncat ~/.ssh/id_ed25519.pub\n```\n\n---\n\n### \"I committed to wrong branch!\"\n\n```bash\ngit log  # Copy commit hash\ngit checkout correct-branch\ngit cherry-pick \u003chash\u003e\ngit checkout wrong-branch\ngit reset --hard HEAD~1\n```\n\n---\n\n### \"I want to undo everything!\"\n\n```bash\n# Uncommitted local changes\ngit restore .\n\n# Last commit (keep changes)\ngit reset --soft HEAD~1\n\n# Last commit (discard changes)\ngit reset --hard HEAD~1\n\n# If already pushed\ngit revert HEAD\n```\n\n---\n\n## Next Steps\n\n1. **Practice basic commands**\n   - Create test repository\n   - Make commits\n   - Create branches\n\n2. **Use interactive tools**\n   - Run `git-learn.sh` to learn\n   - Use `git-cli.sh` daily\n   - Test with `git-simulator.sh`\n\n3. **Work on real project**\n   - Contribute to open source\n   - Use Git in your projects\n   - Collaborate with others\n\n4. **Study advanced cases**\n   - Interactive rebase\n   - Cherry-pick\n   - Bisect for debugging\n\n5. **Configure your environment**\n   - Useful aliases\n   - Visual tools\n   - IDE integration\n\n---\n\n## Contributing\n\nThis is an open learning project. Contributions are welcome!\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for details.\n\n---\n\n## Found an Error? Report It!\n\nSince Git is infinite and many things are similar to each other, I definitely don't know everything. So, if anyone finds any error or has suggestions, feel free to open an issue and I'll fix it promptly. I even promise to buy you a chocolate as a reward for your contribution!\n\n### How to Open an Issue\n\n1. **Go to the repository on GitHub**\n   - Navigate to: https://github.com/madsondeluna/howtogit-1\n\n2. **Click on the \"Issues\" tab**\n   - Located at the top of the repository page\n\n3. **Click the green \"New issue\" button**\n\n4. **Fill in the issue details:**\n   - **Title:** Write a clear, concise title describing the problem or suggestion\n   - **Description:** Provide details about:\n     - What's wrong or what could be improved\n     - Where you found the error (which file, section, or command)\n     - Any screenshots if applicable\n     - Your suggestions for improvement\n\n5. **Submit:** Click \"Submit new issue\"\n\n**Example issue titles:**\n- \"Error in git rebase command example\"\n- \"Suggestion: Add section about git worktree\"\n- \"Typo in Portuguese version - Módulo 2\"\n\n---\n\n## License\n\nMIT License - see [LICENSE](LICENSE) for details.\n\n---\n\n## Author\n\n**Madson Aragão**\n\nCreated to help developers master Git in a practical and accessible way.\n\n---\n\n**Last updated:** 2025-11-05\n\n**Course version:** 2.0\n\n---\n\nThis playlist is curated for deep work and focused coding sessions, ideal for maintaining concentration while preparing commits. [Listen on Spotify](https://open.spotify.com/playlist/1wNirTC24xxOGVDAKf9sXu?si=27192d9d1e7e4c92)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/spotify.png\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n---\n\n# VERSÃO EM PORTUGUÊS\n\n---\n\n## Sobre o Curso (Português)\n\nBem-vindo ao curso completo de Git! Aprenda desde o básico até técnicas avançadas, com teoria, prática e ferramentas interativas.\n\n**O que torna este curso especial:**\n\n- **Conteúdo Bilíngue:** Todos os materiais, scripts e ferramentas CLI disponíveis em inglês e português\n- **Aprendizado Interativo:** Ferramentas CLI práticas para praticar comandos Git com segurança\n- **Foco no Mundo Real:** Exemplos práticos e casos de uso de workflows reais de desenvolvimento\n- **Aprendizado Progressivo:** Do básico ao avançado, com progressão clara\n- **Código Aberto:** Gratuito e aberto a contribuições\n\n**Todas as ferramentas CLI de aprendizado não supervisionado são bilíngues!**\n\n---\n\n## Parte 1: Fundamentos\n\n### O que é Git?\n\n**Git** é um sistema de controle de versão distribuído criado por Linus Torvalds em 2005. Ele permite que você:\n\n- Rastreie todas as mudanças feitas nos seus arquivos ao longo do tempo\n- Trabalhe em diferentes versões do seu projeto simultaneamente (branches)\n- Colabore com outras pessoas sem sobrescrever o trabalho delas\n- Volte para qualquer versão anterior do seu código a qualquer momento\n\n**Analogia:** Pense no Git como uma \"máquina do tempo\" para seus arquivos. Você pode:\n- Ver o que mudou e quando\n- Voltar para qualquer ponto no passado\n- Criar realidades alternativas (branches) para testar ideias\n- Mesclar diferentes linhas do tempo (merge)\n\n**Git NÃO é:**\n- Um serviço de nuvem (isso é GitHub, GitLab, etc.)\n- Apenas para programadores (pode ser usado para qualquer arquivo de texto)\n- Complicado (com prática se torna natural)\n\n---\n\n### O que é GitHub?\n\n**GitHub** é uma plataforma web que hospeda repositórios Git na nuvem. É como uma \"rede social para código\".\n\n**Diferenças principais:**\n\n| Git | GitHub |\n|-----|--------|\n| Sistema de controle de versão | Plataforma de hospedagem |\n| Funciona localmente no seu computador | Funciona na nuvem (online) |\n| Software de linha de comando | Interface web + ferramentas |\n| Gratuito e open source | Gratuito com recursos pagos |\n| Criado em 2005 | Criado em 2008 |\n\n**O que o GitHub adiciona ao Git:**\n- Armazenamento remoto (backup na nuvem)\n- Interface visual para revisar código\n- Pull Requests (revisão de código colaborativa)\n- Issues (gerenciamento de tarefas)\n- Actions (automação de tarefas)\n- Pages (hospedagem de sites estáticos)\n- Colaboração social (seguir desenvolvedores, estrelar projetos)\n\n**Alternativas ao GitHub:**\n- GitLab\n- Bitbucket\n- Gitea\n- SourceForge\n\n---\n\n### Por que usar controle de versão?\n\n**Problemas sem controle de versão:**\n- \"Onde está a versão que funcionava?\"\n- \"Quem fez essa mudança e por quê?\"\n- \"Como mesclo meu trabalho com o do meu colega?\"\n- \"Perdi tudo! Não tenho backup!\"\n- Pastas cheias de: `projeto_v1`, `projeto_v2_final`, `projeto_v2_final_AGORA_VAI`, `projeto_final_final`\n\n**Benefícios do Git:**\n1. **Histórico completo:** Toda mudança é registrada com data, autor e motivo\n2. **Trabalho paralelo:** Múltiplas pessoas trabalhando simultaneamente sem conflitos\n3. **Segurança:** Backup distribuído - cada clone é um backup completo\n4. **Experimentação segura:** Teste ideias sem medo de quebrar o que funciona\n5. **Rastreabilidade:** Descubra quando e por que cada linha foi modificada\n6. **Reversibilidade:** Desfaça erros facilmente\n7. **Colaboração:** Trabalhe em equipe de forma organizada\n8. **Profissionalismo:** Padrão da indústria de software\n\n**Casos de uso:**\n- Desenvolvimento de software (principal)\n- Documentação técnica\n- Configurações de sistema\n- Artigos e livros (texto)\n- Trabalhos acadêmicos\n- Qualquer projeto com múltiplas versões\n\n\u003e Fluxo de trabalho de como o GitHub funciona\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/github-process-english.png\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n---\n\n### Conceitos Essenciais\n\n\u003e Fluxo básico de trabalho com GitHub (ou deveria se os usuários usassem da forma correta)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/GitHub-Flow.webp\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n**Repositório (Repository):**\n- Pasta que contém seu projeto e todo o histórico Git\n- Pode ser local (no seu computador) ou remoto (GitHub, etc.)\n\n**Commit:**\n- Um \"snapshot\" (foto) do seu projeto em um momento específico\n- Cada commit tem: hash único, autor, data, mensagem descritiva\n\n**Branch:**\n- Uma linha de desenvolvimento independente\n- Permite trabalhar em features sem afetar o código principal\n- Branch padrão: `main` (ou `master` em projetos antigos)\n\n**Merge:**\n- Combinar mudanças de uma branch em outra\n- Pode gerar conflitos que precisam ser resolvidos manualmente\n\n**Working Directory:**\n- Os arquivos que você vê e edita na sua pasta\n\n**Staging Area (Index):**\n- Área intermediária onde você prepara arquivos para commit\n- Permite fazer commits seletivos (só alguns arquivos)\n\n**Remote:**\n- Versão do repositório hospedada em outro lugar (GitHub, etc.)\n- Nome padrão: `origin`\n\n**Estados de um arquivo:**\n1. **Untracked:** Git não está rastreando este arquivo\n2. **Unmodified:** Arquivo rastreado, sem mudanças desde último commit\n3. **Modified:** Arquivo foi modificado mas não está no staging\n4. **Staged:** Arquivo pronto para ser commitado\n\n---\n\n## Parte 2: Comandos\n\n---\n\n## Módulo 1: Comandos Básicos\n\n**Para quem:** Iniciantes que nunca usaram Git\n\n**Você vai aprender:** Criar repositório, fazer commits, ver histórico\n\n---\n\n### 1.1 Configuração Inicial\n\n| Comando | Descrição |\n|---|---|\n| `git config --global user.name \"Seu Nome\"` | Define seu nome para todos os repositórios |\n| `git config --global user.email \"seu@email.com\"` | Define seu email para todos os repositórios |\n| `git config --list` | Mostra todas as configurações |\n| `git --version` | Mostra a versão do Git instalada |\n\n**Exemplo:**\n```bash\ngit config --global user.name \"Madson Aragão\"\ngit config --global user.email \"madson@example.com\"\ngit config --global core.editor \"vim\"\n```\n\n---\n\n### 1.2 Criar e Inicializar\n\n| Comando | Descrição |\n|---|---|\n| `git init` | Cria um novo repositório Git na pasta atual |\n| `git clone \u003curl\u003e` | Copia um repositório remoto para seu computador |\n\n**Exemplo:**\n```bash\n# Criar novo projeto\nmkdir meu-projeto\ncd meu-projeto\ngit init\n\n# Clonar projeto existente\ngit clone https://github.com/usuario/repositorio.git\n```\n\n---\n\n### 1.3 Status e Diferenças\n\n| Comando | Descrição |\n|---|---|\n| `git status` | Mostra estado atual dos arquivos |\n| `git status -s` | Status resumido (formato curto) |\n| `git diff` | Mostra mudanças não staged |\n| `git diff --staged` | Mostra mudanças staged |\n\n**Exemplo:**\n```bash\ngit status              # Ver o que mudou\ngit diff arquivo.txt    # Ver mudanças específicas\n```\n\n---\n\n### 1.4 Adicionar e Commitar\n\n| Comando | Descrição |\n|---|---|\n| `git add \u003carquivo\u003e` | Adiciona arquivo específico ao staging |\n| `git add .` | Adiciona todos os arquivos modificados |\n| `git add -A` | Adiciona todos (incluindo deletados) |\n| `git commit -m \"mensagem\"` | Cria commit com mensagem |\n| `git commit -am \"mensagem\"` | Add + commit (só arquivos rastreados) |\n\n**Exemplo:**\n```bash\n# Workflow básico\ngit add arquivo.txt\ngit commit -m \"Adiciona novo arquivo\"\n\n# Ou tudo de uma vez\ngit add .\ngit commit -m \"Atualiza documentação\"\n```\n\n---\n\n### 1.5 Ver Histórico\n\n| Comando | Descrição |\n|---|---|\n| `git log` | Mostra histórico completo de commits |\n| `git log --oneline` | Histórico resumido (1 linha por commit) |\n| `git log --graph` | Histórico com gráfico visual |\n| `git log -n 5` | Mostra últimos 5 commits |\n| `git show \u003chash\u003e` | Mostra detalhes de um commit específico |\n\n**Exemplo:**\n```bash\ngit log --oneline --graph --all\ngit log --author=\"Madson\"\ngit log --since=\"2 weeks ago\"\n```\n\n---\n\n### 1.6 Repositórios Remotos\n\n| Comando | Descrição |\n|---|---|\n| `git remote add origin \u003curl\u003e` | Conecta repositório local ao remoto |\n| `git remote -v` | Lista remotos configurados |\n| `git push -u origin main` | Envia commits para remoto (primeira vez) |\n| `git push` | Envia commits para remoto |\n| `git pull` | Busca e mescla mudanças do remoto |\n\n**Exemplo:**\n```bash\n# Conectar ao GitHub\ngit remote add origin https://github.com/usuario/repo.git\ngit push -u origin main\n\n# Depois é só\ngit push\ngit pull\n```\n\n---\n\n## Módulo 2: Comandos Intermediários\n\n**Para quem:** Quem já sabe o básico e quer trabalhar com branches e colaboração\n\n---\n\n### 2.1 Trabalhando com Branches\n\n| Comando | Descrição |\n|---|---|\n| `git branch` | Lista todas as branches locais |\n| `git branch -a` | Lista todas as branches (local + remoto) |\n| `git branch \u003cnome\u003e` | Cria nova branch |\n| `git checkout \u003cnome\u003e` | Muda para outra branch |\n| `git checkout -b \u003cnome\u003e` | Cria e muda para nova branch |\n| `git switch \u003cnome\u003e` | Muda de branch (comando moderno) |\n| `git branch -d \u003cnome\u003e` | Deleta branch (se já foi merged) |\n| `git branch -D \u003cnome\u003e` | Força deleção de branch |\n\n**Exemplo:**\n```bash\n# Criar feature\ngit checkout -b feature/login\n# ... trabalhar ...\ngit add .\ngit commit -m \"Implementa login\"\n\n# Voltar para main\ngit checkout main\n```\n\n---\n\n### 2.2 Merge e Conflitos\n\n| Comando | Descrição |\n|---|---|\n| `git merge \u003cbranch\u003e` | Mescla branch especificada na atual |\n| `git merge --abort` | Cancela merge em andamento |\n| `git merge --no-ff \u003cbranch\u003e` | Merge sem fast-forward (cria commit de merge) |\n\n**Exemplo:**\n```bash\ngit checkout main\ngit merge feature/login\n\n# Se houver conflitos\n# 1. Edite os arquivos manualmente\n# 2. Remova os marcadores de conflito\n# 3. git add \u003carquivo-resolvido\u003e\n# 4. git commit\n```\n\n---\n\n### 2.3 Stash (Guardar Temporariamente)\n\n| Comando | Descrição |\n|---|---|\n| `git stash` | Salva mudanças temporariamente |\n| `git stash push -m \"mensagem\"` | Stash com mensagem descritiva |\n| `git stash list` | Lista todos os stashes |\n| `git stash pop` | Recupera último stash e remove da lista |\n| `git stash apply` | Aplica stash mas mantém na lista |\n| `git stash drop` | Remove último stash |\n| `git stash clear` | Remove todos os stashes |\n\n**Exemplo:**\n```bash\n# Mudança de contexto rápida\ngit stash push -m \"WIP: trabalhando no login\"\ngit checkout hotfix\n# ... corrige bug urgente ...\ngit checkout feature/login\ngit stash pop\n```\n\n---\n\n### 2.4 Desfazer Mudanças\n\n| Comando | Descrição |\n|---|---|\n| `git restore \u003carquivo\u003e` | Descarta mudanças em arquivo |\n| `git restore --staged \u003carquivo\u003e` | Remove arquivo do staging |\n| `git reset --soft HEAD~1` | Desfaz commit, mantém mudanças staged |\n| `git reset --mixed HEAD~1` | Desfaz commit, remove do staging |\n| `git reset --hard HEAD~1` | Desfaz commit e descarta mudanças |\n| `git revert \u003chash\u003e` | Cria novo commit desfazendo outro |\n\n**Exemplo:**\n```bash\n# Desfazer mudanças locais\ngit restore arquivo.txt\n\n# Desfazer último commit (mantém mudanças)\ngit reset --soft HEAD~1\n\n# Desfazer commit específico (seguro para compartilhado)\ngit revert a1b2c3d\n```\n\n---\n\n### 2.5 Tags (Versões)\n\n| Comando | Descrição |\n|---|---|\n| `git tag` | Lista todas as tags |\n| `git tag v1.0.0` | Cria tag leve |\n| `git tag -a v1.0.0 -m \"Versão 1.0\"` | Cria tag anotada |\n| `git push origin v1.0.0` | Envia tag para remoto |\n| `git push origin --tags` | Envia todas as tags |\n\n**Exemplo:**\n```bash\ngit tag -a v1.0.0 -m \"Primeira versão estável\"\ngit push origin v1.0.0\n```\n\n---\n\n## Módulo 3: Comandos Avançados\n\n**Para quem:** Desenvolvedores experientes que querem dominar Git\n\n---\n\n### 3.1 Rebase (Reescrever Histórico)\n\n| Comando | Descrição |\n|---|---|\n| `git rebase main` | Reaplica commits da branch atual sobre main |\n| `git rebase -i HEAD~3` | Rebase interativo (editar últimos 3 commits) |\n| `git rebase --continue` | Continua rebase após resolver conflitos |\n| `git rebase --abort` | Cancela rebase em andamento |\n| `git pull --rebase` | Pull com rebase em vez de merge |\n\n**Quando usar:**\n- Manter histórico linear e limpo\n- Antes de criar Pull Request\n- Atualizar feature branch com main\n\n**CUIDADO:** Não faça rebase de commits já enviados ao remoto!\n\n**Exemplo:**\n```bash\ngit checkout feature/login\ngit rebase main\n\n# Limpar histórico antes de PR\ngit rebase -i HEAD~5\n# No editor: squash, reword, drop\n```\n\n---\n\n### 3.2 Cherry-pick (Commits Seletivos)\n\n| Comando | Descrição |\n|---|---|\n| `git cherry-pick \u003chash\u003e` | Aplica commit específico na branch atual |\n| `git cherry-pick \u003chash1\u003e \u003chash2\u003e` | Aplica múltiplos commits |\n| `git cherry-pick --continue` | Continua após resolver conflitos |\n| `git cherry-pick --abort` | Cancela cherry-pick |\n\n**Exemplo:**\n```bash\n# Levar bugfix de uma branch para outra\ngit checkout main\ngit cherry-pick a1b2c3d\n```\n\n---\n\n### 3.3 Reflog (Recuperar Commits Perdidos)\n\n| Comando | Descrição |\n|---|---|\n| `git reflog` | Mostra histórico de movimentos do HEAD |\n| `git reflog show \u003cbranch\u003e` | Reflog de branch específica |\n| `git reset --hard \u003chash\u003e` | Volta para commit específico do reflog |\n\n**Exemplo:**\n```bash\n# \"Perdi\" commits após reset\ngit reflog\n# HEAD@{2}: commit: Implementa feature X\ngit reset --hard HEAD@{2}  # Recupera!\n```\n\n---\n\n### 3.4 Bisect (Encontrar Bugs)\n\n| Comando | Descrição |\n|---|---|\n| `git bisect start` | Inicia busca binária por bug |\n| `git bisect bad` | Marca commit atual como ruim |\n| `git bisect good \u003chash\u003e` | Marca commit como bom |\n| `git bisect reset` | Finaliza bisect |\n\n**Exemplo:**\n```bash\ngit bisect start\ngit bisect bad                  # Commit atual tem bug\ngit bisect good v1.0.0          # v1.0.0 funcionava\n# Git vai testando commits no meio\n# Para cada um você testa e marca: git bisect good/bad\n```\n\n---\n\n### 3.5 Blame (Quem Mudou?)\n\n| Comando | Descrição |\n|---|---|\n| `git blame \u003carquivo\u003e` | Mostra quem modificou cada linha |\n| `git blame -L 10,20 \u003carquivo\u003e` | Blame de linhas específicas |\n| `git blame -C \u003carquivo\u003e` | Detecta linhas copiadas |\n\n**Exemplo:**\n```bash\ngit blame src/main.py -L 50,60\n```\n\n---\n\n### 3.6 Submodules (Submódulos)\n\n| Comando | Descrição |\n|---|---|\n| `git submodule add \u003curl\u003e \u003cpath\u003e` | Adiciona repositório como submódulo |\n| `git submodule init` | Inicializa submódulos |\n| `git submodule update` | Atualiza submódulos |\n| `git clone --recursive \u003curl\u003e` | Clone com submódulos |\n\n---\n\n### 3.7 Worktree (Múltiplos Diretórios)\n\n| Comando | Descrição |\n|---|---|\n| `git worktree add \u003cpath\u003e \u003cbranch\u003e` | Cria diretório para branch |\n| `git worktree list` | Lista worktrees |\n| `git worktree remove \u003cpath\u003e` | Remove worktree |\n\n**Exemplo:**\n```bash\n# Trabalhar em 2 branches simultaneamente\ngit worktree add ../projeto-feature feature/nova\ncd ../projeto-feature\n# Agora você tem 2 diretórios independentes!\n```\n\n---\n\n### 3.8 Hooks (Automação)\n\n**Arquivos em `.git/hooks/`:**\n- `pre-commit`: Executa antes de commit\n- `pre-push`: Executa antes de push\n- `post-merge`: Executa após merge\n\n**Exemplo:**\n```bash\n# .git/hooks/pre-commit\n#!/bin/bash\nnpm test  # Roda testes antes de permitir commit\n```\n\n---\n\n## Parte 3: Prática\n\n---\n\n## Ferramentas Interativas\n\nEste curso inclui ferramentas CLI interativas para facilitar o aprendizado e uso do Git.\n\n---\n\n### 1. Tutorial Interativo\n\n**[git-learn.sh](scripts/git-learn.sh)** - Aprenda Git do zero\n\n```bash\n./scripts/git-learn.sh\n```\n\n**Conteúdo:**\n- 12 lições progressivas (básico ao intermediário)\n- Explicações em português e inglês\n- Exercício prático guiado ao final\n- Cria repositório de teste real\n\n**Para quem:**\n- Iniciantes totais em Git\n- Quem quer entender os conceitos\n- Estudantes aprendendo programação\n\n---\n\n### 2. CLI Interativo\n\n**[git-cli.sh](scripts/git-cli.sh)** - Execute comandos Git via menu\n\n```bash\n./scripts/git-cli.sh\n```\n\n**Funcionalidades:**\n- 13 operações Git mais comuns\n- Interface com menu numerado\n- Confirmação para ações perigosas\n- Detecta repositório automaticamente\n- Mostra branch atual\n\n**Para quem:**\n- Quem quer agilizar tarefas comuns\n- Iniciantes que ainda não decoraram comandos\n- Uso rápido no dia a dia\n\n---\n\n### 3. Simulador Git\n\n**[git-simulator.sh](scripts/git-simulator.sh)** - Simule operações Git sem risco\n\n```bash\n./scripts/git-simulator.sh\n```\n\n**Funcionalidades:**\n- Cria ambiente de teste temporário\n- Simula workflow completo de Git\n- Visualiza estado do repositório\n- Pratica sem medo de errar\n- Ambiente é destruído ao sair\n\n**Para quem:**\n- Quem quer praticar sem risco\n- Aulas e workshops de Git\n- Testar comandos antes de usar em projetos reais\n\n---\n\n### 4. Lista de Comandos\n\n**[list-of-comds-how2git.sh](scripts/list-of-comds-how2git.sh)** - Comandos organizados e comentados\n\n```bash\ncat scripts/list-of-comds-how2git.sh\n# ou\nvim scripts/list-of-comds-how2git.sh\n```\n\n**Para quem:**\n- Referência rápida\n- Copiar e colar comandos\n- Estudar sintaxe\n\n---\n\n## Casos de Uso Reais\n\n### Caso 1: Primeiro dia no projeto\n\n```bash\n# Clonar repositório\ngit clone https://github.com/empresa/projeto.git\ncd projeto\n\n# Ver estrutura de branches\ngit branch -a\n\n# Ver últimos commits\ngit log --oneline -10\n\n# Criar sua branch de trabalho\ngit checkout -b feature/minha-tarefa\n```\n\n---\n\n### Caso 2: Feature completa\n\n```bash\n# Criar branch\ngit checkout -b feature/login\n\n# Trabalhar...\ngit add .\ngit commit -m \"feat: adiciona tela de login\"\n\n# Mais trabalho...\ngit commit -am \"feat: adiciona validação\"\n\n# Atualizar com main\ngit fetch origin\ngit rebase origin/main\n\n# Enviar para revisão\ngit push -u origin feature/login\n# Criar Pull Request no GitHub\n```\n\n---\n\n### Caso 3: Bug urgente em produção\n\n```bash\n# Salvar trabalho atual\ngit stash push -m \"WIP: feature login\"\n\n# Criar hotfix\ngit checkout main\ngit pull origin main\ngit checkout -b hotfix/corrige-erro-critico\n\n# Corrigir...\ngit add .\ngit commit -m \"fix: corrige erro na autenticação\"\n\n# Enviar\ngit push -u origin hotfix/corrige-erro-critico\n\n# Voltar ao trabalho\ngit checkout feature/login\ngit stash pop\n```\n\n---\n\n### Caso 4: Desfazer desastre\n\n```bash\n# \"Deletei tudo com reset --hard!\"\ngit reflog\n# HEAD@{1}: reset: moving to HEAD~5\n# HEAD@{2}: commit: Implementa feature importante\n\n# Recuperar\ngit reset --hard HEAD@{2}\n# Tudo de volta!\n```\n\n---\n\n### Caso 5: Limpar histórico antes de PR\n\n```bash\n# Você tem 10 commits bagunçados\ngit log --oneline -10\n\n# Organizar com rebase interativo\ngit rebase -i HEAD~10\n\n# No editor:\n# pick  -\u003e manter commit\n# squash -\u003e mesclar com anterior\n# reword -\u003e mudar mensagem\n# drop   -\u003e descartar\n\n# Forçar atualização da branch\ngit push --force-with-lease\n```\n\n---\n\n### Caso 6: Resolver conflito de merge\n\n```bash\ngit merge main\n# CONFLICT (content): Merge conflict in arquivo.txt\n\n# Abrir arquivo.txt e ver:\n\u003c\u003c\u003c\u003c\u003c\u003c\u003c HEAD\ncódigo da sua branch\n=======\ncódigo da main\n\u003e\u003e\u003e\u003e\u003e\u003e\u003e main\n\n# Editar manualmente, remover marcadores\n# Escolher o que manter\n\ngit add arquivo.txt\ngit commit -m \"Resolve conflito de merge\"\n```\n\n---\n\n## Exemplos Práticos\n\nExemplos detalhados de cenários reais:\n\n- **[Resolver Conflitos](examples/01-resolver-conflitos.md)** - Passo a passo completo\n- **[Criar Pull Request](examples/02-criar-pull-request.md)** - Workflow completo\n- **[Desfazer Commits](examples/03-desfazer-commits.md)** - Todas as técnicas\n\n---\n\n## Workflows Populares\n\n### GitHub Flow (Simples)\n\n```\nmain (sempre deployável)\n  ├─ feature/login\n  ├─ feature/pagamento\n  └─ hotfix/bug-critico\n```\n\n**Regras:**\n1. `main` sempre funcionando\n2. Branch por feature\n3. Pull Request para revisar\n4. Merge e deploy\n\n---\n\n### Gitflow (Completo)\n\n```\nmain (produção)\n  └─ develop (desenvolvimento)\n      ├─ feature/nova-feature\n      ├─ release/v1.2.0\n      └─ hotfix/correcao\n```\n\n**Branches:**\n- `main`: código em produção\n- `develop`: próxima versão\n- `feature/*`: novas funcionalidades\n- `release/*`: preparação para release\n- `hotfix/*`: correções urgentes\n\n---\n\n### Trunk-Based (Rápido)\n\n```\nmain (trunk)\n  ├─ feature-flags\n  └─ commits diretos\n```\n\n**Características:**\n- Commits diretos em main\n- Branches de vida curta (\u003c1 dia)\n- Feature flags para funcionalidades incompletas\n- CI/CD robusto\n\n---\n\n## Melhores Práticas\n\n### Mensagens de Commit\n\n**Conventional Commits:**\n```\ntipo(escopo): descrição curta\n\nDescrição detalhada (opcional)\n\nBREAKING CHANGE: descrição (opcional)\n```\n\n**Tipos:**\n- `feat`: nova funcionalidade\n- `fix`: correção de bug\n- `docs`: documentação\n- `style`: formatação\n- `refactor`: refatoração\n- `test`: testes\n- `chore`: manutenção\n\n**Exemplo:**\n```bash\ngit commit -m \"feat(auth): adiciona autenticação JWT\n\nImplementa login com tokens JWT\nAdiciona middleware de autenticação\nExpira tokens após 24h\"\n```\n\n---\n\n### O que NÃO commitar\n\n**Nunca commite:**\n- Senhas, API keys, tokens\n- Arquivos de ambiente (`.env`)\n- Dependências (`node_modules/`, `venv/`)\n- Arquivos de build (`dist/`, `build/`)\n- Arquivos do IDE (`.idea/`, `.vscode/`)\n- Logs e temporários\n\n**Use `.gitignore`:**\n```bash\n# .gitignore\n.env\nnode_modules/\n*.log\n.DS_Store\n```\n\n---\n\n### Quando fazer commit\n\n**Faça commit quando:**\n- Funcionalidade completa e testada\n- Bug corrigido e verificado\n- Refatoração que não quebra nada\n- Documentação atualizada\n\n**Tamanho ideal:**\n- Nem muito grande (dificulta revisão)\n- Nem muito pequeno (polui histórico)\n- Uma mudança lógica completa\n\n---\n\n## Cheatsheet Visual\n\nPara referência rápida visual, veja:\n\n**[docs/cheatsheet.md](docs/cheatsheet.md)** - Diagramas e comandos organizados\n\n---\n\n## Recursos Externos\n\n### Documentação Oficial\n- [Git Documentation](https://git-scm.com/doc) - Documentação completa\n- [Pro Git Book](https://git-scm.com/book/en/v2) - Livro gratuito\n\n### Tutoriais Interativos\n- [Learn Git Branching](https://learngitbranching.js.org/) - Visual e interativo\n- [Git Visualizer](https://git-school.github.io/visualizing-git/) - Visualize comandos\n\n### Guias\n- [GitHub Guides](https://guides.github.com/)\n- [Atlassian Git Tutorials](https://www.atlassian.com/git/tutorials)\n- [Git Cheat Sheet](https://education.github.com/git-cheat-sheet-education.pdf)\n\n### Ferramentas Visuais\n- [GitKraken](https://www.gitkraken.com/) - Cliente Git visual\n- [SourceTree](https://www.sourcetreeapp.com/) - Cliente gratuito\n- [Git Extensions](https://gitextensions.github.io/) - Para Windows\n\n---\n\n## Solução de Problemas\n\n### Erro: \"fatal: not a git repository\"\n\n```bash\n# Você não está em um repositório Git\ngit init  # Para criar novo\n# OU\ncd /caminho/para/repositorio  # Ir para repositório existente\n```\n\n---\n\n### Erro: \"Your branch is behind\"\n\n```bash\n# Seu repositório está desatualizado\ngit pull origin main\n```\n\n---\n\n### Erro: \"CONFLICT (content): Merge conflict\"\n\n```bash\n# Há conflitos de merge\ngit status  # Ver arquivos conflitantes\n# Editar arquivos manualmente\ngit add \u003carquivo-resolvido\u003e\ngit commit\n```\n\n---\n\n### Erro: \"Permission denied (publickey)\"\n\n```bash\n# Configure SSH keys\nssh-keygen -t ed25519 -C \"seu@email.com\"\n# Adicione a chave ao GitHub\ncat ~/.ssh/id_ed25519.pub\n```\n\n---\n\n### \"Commitei na branch errada!\"\n\n```bash\ngit log  # Copie hash do commit\ngit checkout branch-correta\ngit cherry-pick \u003chash\u003e\ngit checkout branch-errada\ngit reset --hard HEAD~1\n```\n\n---\n\n### \"Quero desfazer tudo!\"\n\n```bash\n# Mudanças locais não commitadas\ngit restore .\n\n# Último commit (mantém mudanças)\ngit reset --soft HEAD~1\n\n# Último commit (descarta mudanças)\ngit reset --hard HEAD~1\n\n# Se já deu push\ngit revert HEAD\n```\n\n---\n\n## Próximos Passos\n\n1. **Pratique os comandos básicos**\n   - Crie repositório de teste\n   - Faça commits\n   - Crie branches\n\n2. **Use as ferramentas interativas**\n   - Execute `git-learn.sh` para aprender\n   - Use `git-cli.sh` no dia a dia\n   - Teste com `git-simulator.sh`\n\n3. **Trabalhe em projeto real**\n   - Contribua para open source\n   - Use Git em seus projetos\n   - Colabore com outras pessoas\n\n4. **Estude casos avançados**\n   - Rebase interativo\n   - Cherry-pick\n   - Bisect para debug\n\n5. **Configure seu ambiente**\n   - Aliases úteis\n   - Ferramentas visuais\n   - Integração com IDE\n\n---\n\n## Contribuindo\n\nEste é um projeto de aprendizado aberto. Contribuições são bem-vindas!\n\nVeja [CONTRIBUTING.md](CONTRIBUTING.md) para detalhes.\n\n---\n\n## Encontrou um Erro? Reporte!\n\nComo Git é infinito e muita coisa é parecida uma com a outra, definitivamente não sei tudo, logo, se alguém encontrar algum erro ou tiver sugestões, pode abrir uma issue que corrijo prontamente. Prometo até pagar um chocolate como recompensa pela contribuição.\n\n### Como Abrir uma Issue\n\n1. **Vá até o repositório no GitHub**\n   - Navegue até: https://github.com/madsondeluna/howtogit-1\n\n2. **Clique na aba \"Issues\"**\n   - Localizada no topo da página do repositório\n\n3. **Clique no botão verde \"New issue\"**\n\n4. **Preencha os detalhes da issue:**\n   - **Título:** Escreva um título claro e conciso descrevendo o problema ou sugestão\n   - **Descrição:** Forneça detalhes sobre:\n     - O que está errado ou o que pode ser melhorado\n     - Onde você encontrou o erro (qual arquivo, seção ou comando)\n     - Screenshots se aplicável\n     - Suas sugestões de melhoria\n\n5. **Enviar:** Clique em \"Submit new issue\"\n\n**Exemplos de títulos de issue:**\n- \"Erro no exemplo do comando git rebase\"\n- \"Sugestão: Adicionar seção sobre git worktree\"\n- \"Erro de digitação na versão em português - Módulo 2\"\n\n---\n\n## Licença\n\nMIT License - veja [LICENSE](LICENSE) para detalhes.\n\n---\n\n## Autor\n\n**Madson Aragão**\n\nCriado para ajudar desenvolvedores a dominar Git de forma prática e acessível.\n\n---\n\n**Última atualização:** 2025-11-05\n\n**Versão do curso:** 2.0\n\n---\n\nEsta playlist é selecionada para *deep work* e sessões de codificação, ideal para manter a concentração ao preparar *commits*. [Ouça no Spotify](https://open.spotify.com/playlist/1wNirTC24xxOGVDAKf9sXu?si=27192d9d1e7e4c92)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"imgs/spotify.png\" alt=\"XXXXXXXXX width=\"1000\" /\u003e\n\u003c/p\u003e\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmadsondeluna%2Fhowtogit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmadsondeluna%2Fhowtogit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmadsondeluna%2Fhowtogit/lists"}