Curso de Git desde Cero - Aprende Git
Aprende Git con este curso. Git es una herramienta ampliamente utilizada en el mundo del desarrollo de software para crear, registrar y rastrear los cambios realizados en un proyecto y sus distintas versiones. Aprenderás los comandos más comunes y el flujo de trabajo con Git y Github desde cero, así como los comandos y casos de uso más comunes a la hora de trabajar en equipo, incluyendo el uso del stash, cherry-pick y solución de conflictos en un repositorio. ✏️ Curso Creado por: Pedro Plasencia. YouTube: @programacion-es Instagram: https://www.instagram.com/programacion.es/ Twitter: https://twitter.com/program_es Sitio Web: https://programacion-es.dev/redes/ ⭐️ Contenido ⭐️ ⌨️ (00:00:00) - Introducción ⌨️ (00:01:18) - ¿Qué es Git y qué es un SCV? ⌨️ (00:04:33) - Instalación ⌨️ (00:05:36) - Git en VSCode ⌨️ (00:08:20) - Configuración inicial ⌨️ (00:09:53) - Inicializar un repositorio local (git init) ⌨️ (00:11:11) - Estados de un archivo en Git ⌨️ (00:12:11) - Git add y git status ⌨️ (00:15:01) - Git commit ⌨️ (00:17:05) - Modificando un archivo ⌨️ (00:19:01) - Información de un commit ⌨️ (00:19:53) - Git log ⌨️ (00:21:33) - Git checkout ⌨️ (00:23:24) - Git tag ⌨️ (00:26:02) - Git diff ⌨️ (00:27:07) - ¿Qué hacer si me equivoco? (git restore y git reset) ⌨️ (00:29:48) - Git revert ⌨️ (00:31:39) - Git commit amend ⌨️ (00:32:53) - Trabajo en equipo en git: ramas ⌨️ (00:36:47) - Git stash ⌨️ (00:42:31) - Git cherry-pick ⌨️ (00:45:01) - Git merge ⌨️ (00:46:50) - Solucionar conflictos en Git ⌨️ (00:53:32) - Repositorios remotos con GitHub ⌨️ (00:55:05) - Git remote y git push ⌨️ (00:56:08) - Git pull y git fetch ⌨️ (00:57:28) - Eliminar archivos o directorios ⌨️ (00:58:41) - El archivo README.md ⌨️ (01:00:58) - El archivo .gitignore ⌨️ (01:03:38) - Git clone ⌨️ (01:04:25) - Alternativas a GitHub y buenas prácticas ⌨️ (01:06:54) - Comentarios finales ⭐️ Enlaces a recursos mencionados ⭐️ 🔗 Descargar git: https://git-scm.com/downloads 🔗 Github: https://github.com/ 🔗 Bitbucket: https://bitbucket.org/ 🔗 Gitlab: https://about.gitlab.com/ 🔗 Git flow: https://danielkummer.github.io/git-flow-cheatsheet/ 🔗 Conventional commits: conventionalcommits.org/es/v1.0.0/ 🔗 Plantillas gitignore: https://github.com/github/gitignore 🔗 Github de programación en español: https://github.com/pedrovelasquez9 🔗 Guía simple de comandos git: https://rogerdudler.github.io/git-guide/ 💻 Con freeCodeCamp puedes aprender a programar gratis y alcanzar tu meta de obtener un empleo como desarrollador: https://www.freecodecamp.org/espanol/ ✍️ Lee cientos de artículos de programación de forma gratuita: https://www.freecodecamp.org/espanol/news/ 🎥 Suscríbete a nuestro canal para encontrar más videos y cursos de programación: https://www.youtube.com/freecodecampespanol?sub_confirmation=1
Curso de Git desde Cero - Aprende Git
Introduction to Git
Overview of the Course
- The course introduces Git, a version control system that tracks changes in projects, essential for software development.
- Created by Pedro Placencia, a web developer passionate about teaching the Spanish-speaking community programming concepts.
- The course covers fundamental concepts such as repositories, commits, branches, and states.
Importance of Git
- Emphasizes learning Git from scratch and understanding the difference between Git and GitHub.
- Explains version control through an analogy of managing thesis drafts to illustrate how versions are tracked.
Understanding Version Control
Conceptualizing Version Control
- Describes how manual tracking of document revisions can lead to disorganization with multiple file versions.
- Highlights the need for a centralized system to manage different versions efficiently.
Benefits of Using Version Control Systems
- Discusses how version control systems automate tracking changes and corrections over time.
- Applies the concept to coding projects, emphasizing organization whether working solo or in teams.
Git as a Leading Version Control System
Features of Git
- Illustrates how Git allows for organized work on projects with historical records of changes made.
- Introduces terms like tags, branches, and commit messages that enhance project management within Git.
Repositories in Git
- Defines a repository as the storage location for code along with its change history.
Setting Up Your Environment
Installing Git
- Before creating a repository, users must install Git on their machines; links provided for downloading based on operating systems (macOS, Windows, Linux).
Working Without Online Accounts
Introduction to Git and Local Environment
Setting Up Git Locally
- You can work with Git in your local environment without an account, which is the focus of this introductory session before creating a repository on GitHub.
- Familiarizing yourself with the terminal is emphasized over using visualization software; understanding command-line operations is crucial for effective use of Git.
- After installing Git, you can open Visual Studio Code and access the terminal, where options like PowerShell or Git Bash may appear depending on your setup.
Creating a Project Directory
- A directory named "git project" will be created on the desktop, and an HTML file (Index.html) will be structured within it.
- It's important to configure user information after installing Git since it tracks changes associated with specific users.
Configuring User Information
- The first step post-installation involves setting up user details using
git config --global, including username and email for commit metadata.
- This configuration helps team members identify who made changes when collaborating on remote repositories.
Initializing a Repository
Starting Your First Repository
- To initialize a new repository in your project directory, execute
git init, which creates a hidden.gitfolder that manages version control data.
- Newly created files will show as untracked (indicated by 'U') until they are added to the staging area for tracking.
Understanding File States in Git
- Files in Git can exist in three states:
- Staged: Ready for the next commit after modifications.
- Modified: Changes have been made but not yet staged.
- Committed: Changes are saved as a new version in the repository.
Adding Files to Staging Area
Preparing Files for Commit
- Once files are modified, they need to be staged using commands like
git add .to include all untracked files for the next commit.
Git Workflow and Commit Process
Managing Files in Git
- It is recommended to add each modified file individually to maintain control over what will be included in the next commit, such as adding
index.jsalongside other files.
- Using
git statusprovides an overview of the repository's state, including information about branches and changes made to files.
- The default branch created with a new repository is called "master," which indicates that there are no commits yet, but changes are ready for confirmation.
Adding and Committing Changes
- New files without prior references are marked as new by Git, indicating they need to be added for tracking.
- After running
git status, it shows that we are still on the master branch with untracked files likeindex.html.
- The command
git add <file>is used to start tracking a file. This step is crucial before committing any changes.
Understanding Commits
- To confirm changes permanently in the repository, use
git commit -m "<message>", where the message describes what was done in this commit.
- Writing clear commit messages helps track project history effectively, especially when working collaboratively on features or bug fixes.
Best Practices for Commit Messages
- It's advisable to write all commit messages in English for consistency; local tests can be conducted in Spanish if needed.
Tracking Changes Over Time
- Visual Studio Code highlights modifications compared to previous versions tracked by Git, aiding developers in identifying changes easily.
- If necessary, changes can be discarded using
git restore <file>, reverting it back to its last committed state.
Confirming Changes and Version Control
- Each time a change is confirmed with a new commit (
git addfollowed bygit commit), it updates the repository's history while maintaining version control.
- Every commit includes metadata such as the branch name and a unique hash identifier that allows users to revert back or review specific commits later.
Analyzing Repository Changes
Understanding Git Commit History and Version Control
Exploring Git Log
- The
git logcommand provides a detailed history of commits in the repository, showing the chronological order of changes made.
- Each commit entry includes metadata such as the author's name, email, and the date when the change was confirmed, which is useful for tracking contributions.
- For a more concise view, using
git log --onelinedisplays each commit with its hash and message in a single line format.
Navigating Commits
- The current status can be checked by looking at the latest commit message; for example, "New section in web" indicates recent changes.
- To revert to a previous state, use
git checkout <commit_hash>, allowing users to explore earlier versions of files within their project.
Branching and Experimentation
- By default, users start on the Master branch but can create new branches for experimental changes without affecting the main codebase.
- Users can make temporary changes while on an older commit version and later decide whether to merge these changes back into Master.
Using Tags for Version Control
- Instead of relying solely on commit hashes (which are cumbersome), tags provide a more user-friendly way to mark stable versions of code.
- Creating a tag with
git tag <tag_name>allows developers to easily return to that specific version if needed.
Managing Tags
- After making changes or confirming updates, reverting back to a tagged version can be done using
git checkout <tag_name>.
- If necessary, tags can be deleted using
git tag -d <tag_name>, which removes references from the repository's history.
Comparing Commits
Understanding Git: Managing Changes and Revisions
Comparing Commits
- The discussion begins with comparing differences between two commits, specifically commit f8a546 and c013449.
- It highlights that one commit contains only the body while the other includes an additional section in the body.
Undoing Changes
- When a mistake is made, one can simply delete the line or use
git restoreto discard changes if the file hasn't been staged for commit.
- If changes have been staged,
git restore --staged <file>can be used to unstage modifications without losing them.
Resetting Changes
- To undo both staging and changes,
git reset HEADresets to the current state of the active branch (Master).
- A checkout command can revert a specific file back to its last committed state on Master.
Reverting Commits
- If a commit has already been made and needs to be undone,
git revert <commit>allows for reverting changes while maintaining history.
- The process involves editing a default message in an editor or using
--no-editto keep it unchanged.
Amending Commits
- To add forgotten changes to an existing commit, use
git add <file>followed bygit commit --amend.
- This updates the previous commit instead of creating a new one, allowing for corrections without cluttering history.
Branch Management in Git
Creating and Switching Branches
- The main branch (Master) is typically reserved for production-ready code; development occurs on separate branches like 'develop'.
- Use
git checkout -b <branch-name>to create and switch to a new branch simultaneously.
Listing Branches
Understanding Git Branching and Stashing
Git Branching Basics
- In a typical team workflow, there are at least two main branches: Master and Develop. The Develop branch contains the application version that is currently under development, with features ready for testing.
- Once the Develop branch is tested successfully, a merge occurs into the Master branch to publish the code in production.
- When adding new features or fixing bugs, it is best practice to create a new branch from Develop. This allows developers to work independently without affecting the stability of either Master or Develop.
- For example, creating a feature branch can be done using
git checkout -b feature/myNewFeature, allowing developers to make changes freely in their own branches.
Importance of Isolated Development
- Each developer can work on different features simultaneously in their respective branches while keeping the base branches stable. This isolation is crucial for effective teamwork in Git.
- A common scenario arises when a developer needs to assist a teammate but has uncommitted changes. Instead of committing unfinished work, they can use
git stashto temporarily save their changes.
Using Git Stash
- The
git stashcommand saves modified files into a temporary stack (stash), allowing developers to switch branches without losing progress on current tasks.
- By default,
git stashonly stashes tracked files; untracked files require additional commands likegit stash -u.
Applying Stashed Changes
- After helping a teammate and returning to their original branch, developers can apply stashed changes using
git stash pop, which also removes those changes from the stash list.
- Alternatively, if they want to keep the stashed changes while applying them back into their working directory, they can use
git stash apply.
Managing Multiple Stashes
- Developers can view all stashes with
git stash list. If multiple stashes exist, specific ones can be applied using identifiers likestash@0.
- Creating a new branch from an existing stash is possible with commands like
git stash branch feature/myStashFeature, which helps maintain organization when managing multiple tasks.
Cleaning Up Stashes
Understanding Git Commands for Team Collaboration
Eliminating Unwanted Commits
- The speaker discusses the importance of eliminating unnecessary commits using
stash clear, which helps maintain a clean codebase when working in teams.
Utilizing Cherry Pick for Specific Changes
- Introduction to the
cherry-pickcommand, useful for bringing specific commits from one branch to another without merging entire branches.
- A scenario is presented where a developer needs to bring a footer commit from the
developbranch into their feature branch due to shared code dependencies.
Merging Feature Branches into Develop
- Once development on a feature is complete, it’s crucial to merge changes back into the
developbranch. The process begins with ensuring all changes are committed and up-to-date.
- The speaker explains how to perform a merge using
git merge, updating thedevelopbranch with new features while maintaining code integrity.
Best Practices After Merging
- After merging, it's recommended to delete feature branches that are no longer needed using
git branch -d, keeping the repository organized and free of unused branches.
- Emphasizes maintaining only essential branches (like
developormaster) in repositories before project delivery.
Handling Merge Conflicts
- Discusses common occurrences of merge conflicts when multiple developers work on overlapping features, highlighting that resolving these conflicts is part of collaborative development.
Resolving Merge Conflicts in Git
Understanding Merge Conflicts
- When code blocks are edited simultaneously, Git identifies conflicts and provides options to resolve them. The console indicates a conflict in the
index.htmlfile due to failed automatic merging.
- The console highlights potential conflict areas within the code, which can occur multiple times in one file or across different files.
Steps to Resolve Conflicts
- During a merge process, if conflicts arise, Git will show both changes: the current change from the
developbranch and the incoming change from another feature branch.
- Visual Studio offers options to accept either the current change (from
develop), the incoming change (from another branch), or both. The choice depends on project context.
- If unsure about which block of code to keep due to team contributions, it's advisable to consult with teammates for clarity before making a decision.
Finalizing Changes After Conflict Resolution
- Once a decision is made regarding which changes to keep, confirm the resolution by staging and committing changes using
git addfollowed bygit commit.
- After resolving conflicts and committing changes, you can view your commit history with
git log, confirming that all issues have been addressed properly.
Pushing Changes to Remote Repository
- To upload your local repository changes to platforms like GitHub, create a new repository on GitHub and follow instructions based on whether it’s a new or existing project.
- Use
git remote add <alias> <repository-url>command to link your local project with the remote repository. The alias can be any name you choose for reference.
Synchronizing Local and Remote Repositories
- To push specific branches like
developto your remote repository, use commands such asgit push origin develop, ensuring that all relevant files are uploaded correctly.
Understanding Remote Repositories and Git Commands
Fetching Metadata from Remote Repositories
- The
fetchcommand retrieves all metadata from a remote repository, syncing branches without applying any changes to the local repository.
- Any changes made locally (commits) remain in the local repository until a
pushis executed to send them to the remote repository.
Managing Files and Changes
- Deleting files (e.g.,
index.js) requires a commit to confirm the deletion within the context of the repository.
- Moving files or changing structures also counts as changes that need confirmation through commits.
Importance of README and .gitignore Files
README File
- The
README.mdfile serves as documentation for your project, allowing you to provide descriptions and titles for better understanding.
- When uploaded, it becomes visible in the remote repository, serving as an entry point for users interested in your project.
.gitignore File
- The
.gitignorefile lists files or directories (likenode_modules) that should not be tracked by Git, preventing unnecessary uploads to remote repositories.
- This file helps manage what gets pushed to remote repositories, ensuring only relevant files are included.
Cloning Existing Repositories
- To work on an existing online repository, use the clone URL (ending with
.git) with the commandgit clone, which creates a local copy of the main branch.
Platforms Supporting Git Repositories
Git Workflow Best Practices
Overview of Gitflow
- The recommended workflow for managing repositories is Gitflow, which aligns with the practices discussed throughout the video.
- Key branches in this workflow include
developandmaster, along with feature branches, hotfixes, and release versions that can be merged intodevelopand subsequently intomaster.
Useful Tools for Git Management
- A helpful library is introduced that defines aliases for various tasks, such as initializing Gitflow and creating feature branches. This streamlines the process of merging features into
developand preparing releases formaster.
Commit Message Standards
- The speaker advocates for using conventional commit messages to provide clarity on changes made. Their approach simplifies the standard while still being contextually relevant.
- Each commit message starts with a type indicator (e.g., "feat" for features or "hotfix") followed by a description in English, enhancing understanding of repository updates.
Additional Resources
- Links to simplified command guides are provided in the description to help users review basic commands covered in the video.