Git, GitHub, & GitHub Desktop for beginners

Coder Coder
1 Feb 202222:15

Summary

TLDRВ этом видео скрипте рассматриваются основы Git и GitHub, которые являются необходимыми инструментами для веб-разработчиков. Автор объясняет, что такое Git (система контроля версий), как работает локальный и удаленный репозиторий, и как использовать GitHub Desktop для более удобного интерфейса. Пошаговые инструкции включают создание репозитория, коммиты, игнорирование файлов, ветвление и слияние. Также упоминается использование pull request'ов для совместной работы в команде. Скрипт предназначен для демистификации этих инструментов и облегчения начальникам познания их использования.

Takeaways

  • 😀 Git и GitHub - необходимые инструменты для веб-разработчиков, которые упрощают жизнь и выглядят хорошо в резюме.
  • 🔧 Git - это система контроля версий, которая отслеживает изменения в файлах и позволяет сохранять различные версии файлов в разное время.
  • 👥 Git упрощает работу в команде, позволяя разработчикам работать над копией проекта на своих компьютерах и отправлять изменения в общий удаленный репозиторий.
  • 🌐 GitHub - это популярный сайт для хранения удаленных репозиториев Git, который предлагает бесплатный доступ и позволяет коллаборацию с другими пользователями.
  • 💻 GitHub Desktop - это программа, которая позволяет запускать Git на вашем компьютере и выполнять большинство команд через графический интерфейс.
  • 📝 Создание репозитория в GitHub Desktop включает в себя настройку имени, описания, пути локального хранения, файла README, .gitignore и лицензии.
  • 📁 Использование .gitignore позволяет игнорировать определенные файлы и папки, чтобы они не попадали в репозиторий.
  • ✅ Коммиты в Git - это 'точки сохранения', включающие набор изменений, которые вы хотите отслеживать, и требуют написания сообщения коммита.
  • 🔄 Push в Git - это процесс отправки ваших локальных коммитов в удаленный репозиторий на GitHub для синхронизации.
  • 🔄 Revert - возможность отменить изменения, сделанные в коммите, восстанавливая предыдущую версию файла.
  • 🌱 Ветвление (branching) в Git позволяет иметь несколько версий кодовой базы одновременно, что полезно для работы в команде и разработки различных функций.

Q & A

  • Что такое Git и как он помогает разработчикам?

    -Git - это система контроля версий, которая отслеживает изменения в файлах. Это полезно для разработчиков, поскольку позволяет сохранять различные версии файлов в разное время, откатываться к предыдущим версиям в случае ошибок и упрощает работу в команде, позволяя каждому работать с копией проекта на своем компьютере.

  • Какова разница между Git, GitHub и GitHub Desktop?

    -Git - это программа контроля версий. GitHub - это веб-сайт для хостинга репозиториев Git, совместной работы с другими пользователями и открытия репозиториев с открытым исходным кодом. GitHub Desktop - это графический интерфейс для работы с Git, который упрощает выполнение команд Git для начинающих.

  • Как создать новый репозиторий на GitHub Desktop?

    -Чтобы создать новый репозиторий на GitHub Desktop, нужно выбрать пункт меню 'File > New repository', ввести название и описание проекта, выбрать локальный путь для репозитория, определить, следует ли инициализировать репозиторий с файлом README, выбрать .gitignore и лицензию, а затем нажать 'Create repository'.

  • Что такое коммит и как его создать в GitHub Desktop?

    -Коммит - это 'точка сохранения' в разработке, которая включает в себя набор изменений в коде, которые вы хотите отслеживать. Для создания коммита в GitHub Desktop нужно перейти на вкладку 'Changes', отметить файлы, которые нужно добавить, ввести сообщение о коммите и нажать 'Commit to main'.

  • Как опубликовать локальный репозиторий на GitHub?

    -Чтобы опубликовать локальный репозиторий на GitHub, нужно нажать кнопку 'Publish this repository to GitHub' в GitHub Desktop. После этого откроется окно с названием репозитория и описанием, можно выбрать приватность репозитория и нажать 'Publish repository'.

  • Как настроить игнорирование файлов в Git?

    -Для игнорирования файлов в Git можно добавить их имена в файл .gitignore, который создается в корне репозитория. Можно добавлять отдельные имена файлов, использовать шаблоны с подстановочными символами, например, '*.txt' для игнорирования всех текстовых файлов.

  • Что такое ветвление (branching) в Git и как оно используется?

    -Ветвление в Git - это возможность иметь несколько версий кодовой базы одновременно. Каждая ветка представляет собой свою версию проекта, и разработчики могут работать в разных ветках, не мешая друг другу. После завершения работы в ветке, изменения обычно объединяются с основной веткой (main) с помощью операции 'слияния' (merge).

  • Как создать новую ветку в GitHub Desktop?

    -Для создания новой ветки в GitHub Desktop нужно выбрать пункт 'Branch > New branch' в верхнем меню, ввести название ветки и нажать 'Create branch'. Новая ветка будет создана на основе текущей ветки.

  • Как объединить изменения из одной ветки с основной веткой в Git?

    -Для объединения изменений из одной ветки с основной веткой нужно переключиться на основную ветку в GitHub Desktop, затем выбрать 'Branch > Merge into current branch', указать ветку, из которой нужно выполнить слияние, и нажать 'Create a merge commit'.

  • Что такое 'pull request' на GitHub и как он используется?

    -Pull request - это функция GitHub, которая позволяет разработчикам предложить свои изменения для слияния в основную ветку. Другие члены команды могут просмотреть предложенные изменения, внести свои предложения по исправлениям и утвердить слияние.

Outlines

00:00

😀 Введение в Git и GitHub

В этом параграфе представлены основы Git и GitHub, которые являются необходимыми инструментами для веб-разработчиков. Рассматриваются основные понятия, такие как коммиты, ветки, слияние и запросы на вытягивание, которые могут быть сложными для понимания вначале. Автор предлагает разгрузить аудиторию процедурой установки и использования этих инструментов, начиная с установок на компьютер и заканчивая отслеживанием изменений в коде. Также упоминается, что Git и GitHub упрощают жизнь разработчика и выглядят хорошо в резюме.

05:03

🔧 Настройка и использование GitHub Desktop

Второй параграф посвящён процессу создания и настройки локального репозитория с использованием GitHub Desktop. Обсуждается создание репозитория без пробелов в названии, добавление описания, выбор папки для хранения репозитория, включение README-файла для подробного описания проекта, а также выбор лицензии. Также рассматривается опция игнорирования файлов с помощью .gitignore и создание коммита для новых файлов. После этого происходит публикация репозитория на GitHub и обзор основных функций веб-сайта.

10:06

🛠 Работа с файлами и коммитами в Git

Третий параграф охватывает процесс работы с файлами в репозитории, включая добавление новых файлов, проигнорированных файлов и изменение существующих файлов. Рассматривается использование команды 'Commit' для сохранения изменений, а также публикация изменений на GitHub. Также здесь объясняется, как Git отслеживает изменения на уровне каждой строки кода и как можно восстановить удалённые файлы, используя функцию 'Revert changes in commit'.

15:07

🌟 Использование веток в Git для командной работы

В четвёртом параграфе автор вводит концепцию ветвления в Git, которая позволяет различным разработчикам работать над своими функциями или исправлениями в отдельных ветках. Поясняется, как создавать новые ветки, вносить изменения в них, а затем объединять эти ветки с основной веткой (main) с помощью слияния. Также кратко упоминается о процессе pull request на GitHub для обзора и одобрения изменений командой перед слиянием.

20:07

📚 Заключение и дальнейшие шаги

В заключительном параграфе автор резюмирует познавательный материал о Git и GitHub и подчёркивает их значимость для командной работы и управления версиями. Упоминается, что в следующих уроках будет рассмотрена настройка проектов для конкретного курса по адаптивному дизайну. Также автор предлагает дополнительные ресурсы, такие как видео о npm, и благодарит за просмотр.

Mindmap

Keywords

💡Git

Git - это система контроля версий, которая отслеживает изменения в файлах. В контексте видео это инструмент, который позволяет разработчикам сохранять различные версии своих файлов в различных точках времени. Это полезно для быстрого возврата к предыдущим версиям кода в случае ошибок, а также для работы в команде, позволяя каждому разработчику работать над своими копиями проектов на своих компьютерах.

💡GitHub

GitHub - это платформа, принадлежащая Microsoft, которая предоставляет удаленные репозитории для хранения проектов, обеспечивает коллективную работу и позволяет обнаруживать другие открытые репозитории. В видео это место, куда разработчики отправляют свои изменения кода из локального репозитория на сервер для дальнейшего обмена с коллегами.

💡Ветвление (Branching)

Ветвление в Git - это концепция, которая позволяет создавать отдельные линии разработки в рамках одного репозитория. В видео это используется для демонстрации того, как разработчики могут работать над разными функциями или исправлениями в отдельных ветках, а затем объединять их с основной веткой для интеграции изменений.

💡Коммит (Commit)

Коммит в Git - это 'точка сохранения', которая включает в себя набор изменений в коде, которые вы хотите отслеживать. В видео коммиты используются для записи изменений в файлы, таких как добавление нового файла или внесение изменений в существующий, с целью последующего отслеживания этих изменений.

💡Фorks и Pull Requests

Форки и запросы на вытягивание (Pull Requests) в GitHub - это механизмы, используемые для внесения изменений от пользователей, которые не являются основными разработчиками репозитория. В видео упоминается, что запросы на вытягивание позволяют другим членам команды проверять предложенные изменения и утверждать их перед объединением с основной веткой.

💡Локальный репозиторий (Local Repository)

Локальный репозиторий - это копия проекта, которая хранится на компьютере разработчика и подключена к Git. В видео это место, где разработчики вносят свои изменения в проект до отправки их в удаленный репозиторий.

💡Удаленный репозиторий (Remote Repository)

Удаленный репозиторий - это версия проекта, которая хранится онлайн, например, на GitHub. В видео это место, куда разработчики отправляют свои локальные изменения для обмена и интеграции с другими членами команды.

💡GitHub Desktop

GitHub Desktop - это графический интерфейс, который позволяет пользователям работать с Git без использования командной строки. В видео он используется для демонстрации процесса работы с Git и GitHub, включая создание репозитория, коммиты, ветвление и объединение.

💡README файл

README файл - это документ, который обычно содержит подробное описание проекта и отображается на GitHub. В видео упоминается, что создание README файла при инициализации репозитория является хорошей практикой для того, чтобы дать людям больше информации о вашем проекте.

💡.gitignore

.gitignore - это файл, который указывает Git на какие файлы и папки следует игнорировать и не добавлять их в репозиторий. В видео это используется для демонстрации того, как исключать файлы из отслеживания Git, например, временные файлы или файлы с личной информацией.

Highlights

Git和GitHub是任何网页开发者必须了解的工具,但它们的概念在初次学习时可能很难理解。

Git是一个版本控制系统,可以跟踪文件的变更。

Git允许开发者在代码中创建多个保存点,便于撤销错误更改。

使用Git可以简化团队协作,每个开发者可以在自己的计算机上工作。

GitHub是存储远程仓库的流行平台,由微软拥有,免费使用。

GitHub Desktop应用程序允许用户通过更直观的界面运行Git。

GitHub是网站,可以托管Git仓库,与其他用户协作,并发现其他开源仓库。

GitHub Desktop首次使用需要登录GitHub账户并设置全局Git配置。

创建Git仓库时,可以选择初始化README文件,忽略某些文件类型,以及选择许可证。

在GitHub Desktop中,可以通过“Changes”和“History”标签页查看文件变更和提交历史。

提交(commit)是开发过程中创建的保存点,包括一组想要跟踪的代码变更。

.gitignore文件允许开发者指定不希望Git跟踪的文件和文件夹。

使用通配符可以忽略特定类型的所有文件,例如所有文本文件。

Git跟踪每个文件的每一行代码的变更,包括文件的删除。

Git允许开发者撤销错误的删除操作,恢复到之前的状态。

分支(branch)是Git中的一个功能,允许同时进行多个版本的开发。

在团队开发中,使用分支可以避免混乱,将工作分离到不同的分支上。

完成分支上的工作后,可以通过合并(merge)将分支的更改添加到主分支。

GitHub上的拉取请求(pull request)功能允许团队成员审查代码更改,并在合并到主分支前批准。

Transcripts

play00:00

If you're learning to code, you've probably heard of Git and GitHub.

play00:04

These are some must-know tools for any web developer, but they're not the easiest thing

play00:08

to learn.

play00:09

They have concepts that are honestly hard to get the first time around: commits, branches,

play00:14

merging, pull requests, and other things.

play00:18

If you're having a hard time getting Git, don't worry.

play00:20

I'm going to demystify Git and GitHub.

play00:22

I'll show you the basics step by step, from installing them on your computer to tracking

play00:27

your code changes.

play00:28

Git and GitHub will make your life as a coder much easier, and they'll look good on your

play00:32

resume as well.

play00:33

So let’s get into it!

play00:34

Alright, so we've covered how to use VS Code, and now I'm going to show you how to use Git

play00:35

and GitHub.

play00:36

These tools are a must-know for any web developer.

play00:37

They'll make your coding life much easier, and they'll look good on your resume as well.

play00:38

To start off: what is Git?

play00:41

Git is a type of software called a version control system, which tracks changes to files.

play00:46

What this means is that it will detect all your code changes, and you can use it to record

play00:50

different versions of your files at different points in time.

play00:53

This is super helpful for developers for a number of reasons.

play00:57

For starters, having Git is kind of like having a giant set of save points.

play01:01

If you make a code change that you realize later on was a huge mistake, you can revert

play01:05

back to an older version of that file.

play01:08

Git also makes working on a team a lot easier.

play01:11

Each developer can work on a copy of the project on their own computer.

play01:15

This copy is stored in a folder connected to Git, which is called a local repository.

play01:20

The developers can then send their code changes up to the main remote repository which is

play01:24

stored online, and get code changes made by other developers.

play01:28

The most popular place to store your remote repository is GitHub, which is owned by Microsoft

play01:33

and is free to use.

play01:35

If you don't have a GitHub account yet, you can go to GitHub.com and sign up for a new

play01:40

account.

play01:42

Once you're signed up, we're going to use the GitHub Desktop app to run GitHub on our

play01:46

computer.

play01:47

To download it, go to desktop.github.com and download and install the program.

play01:53

Now I just want to take a minute to explain the differences between Git, GitHub, and GitHub

play01:59

Desktop, cause it can get kind of confusing!

play02:03

Git is the actual version control software.

play02:05

It was originally meant to run on the command line, and a lot of developers run Git this

play02:10

way.

play02:11

GitHub Desktop is a program that runs Git on your computer and allows you to do most

play02:15

of the Git command line commands, just through a more visual program interface.

play02:19

A quick note: I know a lot of people like using the command line to run Git commands.

play02:25

But for beginners, I've always felt that it's a little easier to use a tool like GitHub

play02:29

Desktop.

play02:30

If you're already familiar with Git and GitHub, you can of course use whichever tool you prefer.

play02:35

Lastly, GitHub is a website where you can host your Git repositories, collaborate with

play02:41

other users, and discover other open source repositories.

play02:45

Ok, back to the GitHub Desktop app.

play02:47

Once you've installed the app, go ahead and run it.

play02:51

The first thing you'll want to do in GitHub Desktop is to sign in to your GitHub account.

play02:56

Go to File > Options, and in the "Accounts" tab, click the "Sign in" button.

play03:01

It will prompt you to sign in using your browser, so go ahead and click "Continue with browser."

play03:07

Your default browser on your computer will try to log in to your GitHub account.

play03:11

Log in to GitHub if it's prompting you to.

play03:14

And, if you get a pop-up window that says "Choose an application to open the x-github-desktop-auth

play03:19

link," make sure GitHubDesktop is selected.

play03:23

Once you're signed in, your computer should go back to Github Desktop.

play03:27

And to make sure everything worked, go back to File > Options > Accounts, and you should

play03:32

see your GitHub username and profile picture on the right side.

play03:36

Now, we want to set our Global Git configuration.

play03:40

In the Options, go to the "Git" tab and you should see your GitHub username listed under

play03:44

Name, and a users.noreply.github.com email under Email.

play03:48

And under "Default branch" select either main or master.

play03:51

Master used to be the default branch on Git, but currently GitHub and other places are

play03:56

using "main" as the default, and it's what I use as well.

play04:00

Once your settings are set, make sure to click the "Save" button, even if you didn't make

play04:04

any changes on this screen.

play04:06

GitHub Desktop automatically populated these fields when you logged in, but you’ll still

play04:11

need to manually save them.

play04:13

Now, we're going to walk through the basics of a Git workflow with a test project.

play04:17

Feel free to follow along!

play04:20

First off, we want to create our repository.

play04:22

Go to File > New repository, and then in the Name field write the name of your test project.

play04:28

GitHub repos need to be named a string without spaces.

play04:31

So usually you would use hyphens between words, for example, I'll be naming this "test-repo."The

play04:37

Description field will let people who see your repository on GitHub know what it's about.

play04:41

The Local path is the folder where you want to create your repository.

play04:45

I use Windows, and generally put my repos in the "Documents/GitHub" folder, but you

play04:49

can choose another location if you prefer.

play04:52

Then, check the box asking if you want to initialize this repository with a README file.

play04:58

This file lets you write a more detailed description about your project that will show up on GitHub,

play05:02

and you can always edit it later.

play05:05

This is optional but in general it's a pretty good idea to have one.

play05:09

The Git ignore field lets you select types of files that you don't want to add to the

play05:13

repository.

play05:14

I usually leave this at "None" and then ignore files later on while I'm coding-- we'll get

play05:19

to that later in this video.

play05:20

The License field tells people what they are allowed to do with your code in the repository.

play05:26

Since a lot of open source exists on GitHub, most people select the MIT License which allows

play05:31

people to copy, distribute, and modify your code.

play05:34

If you leave it blank, your project will be licensed with standard copyright.

play05:38

You can read more about open source licensing at ChooseALicense.com

play05:43

Once all your options are selected, click "Create repository."

play05:47

It may take a few seconds, but GitHub Desktop should create and automatically load the repository.

play05:52

Let's take a look at the Desktop app.

play05:56

At the top under the menu bar, you'll see another bar with information about your repository.

play06:01

On the left is the current repository that's open.

play06:05

Next to it is what branch you're currently on.

play06:07

We'll talk a bit more later about working with branches, but for now, just know that

play06:10

a branch is one version of the codebase, and you can have multiple branches.

play06:15

Then at the end it tells you that you can publish this repository to GitHub, which we

play06:19

will do a little later on.

play06:22

Under the repository bar is the main panel which has a left sidebar.

play06:27

The sidebar has two tabs, the first is the Changes tab.

play06:30

This is currently blank since we haven't added any files or made any code changes yet.

play06:35

And the history tab which has an "initial commit" with the files generated by GitHub

play06:39

Desktop when we created this repo.

play06:42

If you have the "Changes" tab selected, at the very bottom of the sidebar is the commits

play06:47

panel.

play06:48

A commit is the "save point" that you can create during development that includes a

play06:52

set of code changes that you want to track.

play06:54

Let's start making some code changes to see what happens in Git.

play06:58

In your VS Code, go to File > Open Folder and select the location where you created

play07:03

your GitHub repository.

play07:05

If you see an alert message from VS Code saying "Git not found," this is asking if you want

play07:11

to download the original version of Git that runs on the command line.

play07:14

You can either dismiss the alert, or if you think you might use Git on the command line

play07:18

at some point, you can click the "Download Git" button to download and install it.

play07:24

If you do decide to download and install Git for the command line, I'm going to show you

play07:28

the settings I use for Git.

play07:31

For most of the settings I will go with whatever is pre-selected.

play07:35

But most importantly, for the default editor used by Git, I set that to VS Code instead

play07:39

of Vim because I like VS Code.

play07:41

And the other settings is for the name of the initial branch when you're making a new

play07:45

repo, I want to override the default branch name and use "main."

play07:50

And for everything else I just hit the "Next" button and then finish installing.

play07:54

Now let's create a new file.

play07:56

Click the "New file" icon in the left sidebar and create an index.html file.

play08:00

In the file, type in an exclamation point and tab to use Emmet to create boilerplate

play08:05

HTML markup, and save.

play08:06

If you go back to GitHub Desktop, you'll see that in the left sidebar under the "Changes"

play08:11

tab will be the index.html file.

play08:14

And there's a green plus icon on the other side of the filename.

play08:17

This means that Git has detected a new file, and wants to add it to your repository and

play08:21

track any future changes.

play08:23

On the right panel you'll see the actual code changes that you made in the index.html file.

play08:27

Right now we've added new code, which is why the lines of code are highlighted in green.You'll

play08:32

also see a checked checkbox to the left of the filename.

play08:36

Checking this box will "stage" the file, which means that you want to include this file change

play08:40

in your next commit.Now let's create our commit to add the index.html file to the repository.

play08:47

In the bottom commit section, there is a field where you can add what we call a commit message

play08:51

describing what the change is.

play08:53

GitHub Desktop has automatically populated the field with text saying "Create index.html".

play08:59

You can keep this as your commit message, or write your own.

play09:02

There's also a larger description field under it, where you can optionally write a longer

play09:07

description.

play09:09

At the bottom is a button saying "Commit to main".

play09:12

This means that clicking it will create a commit on your main branch.

play09:16

This matches the "current branch" up at the top of the main panel.

play09:20

Click the button to create the commit.After we commit, the "Changes" tab is empty.

play09:25

And if we click on the "History" tab in the left sidebar, we'll see that commit that we

play09:29

just made, along with the code changes from that commit.

play09:33

You may have noticed up at the top on the right a panel that says "Publish this repository

play09:37

to GitHub."

play09:39

Since we created this repository locally, it won't exist on GitHub until we publish

play09:43

it.

play09:45

Click the button to publish it.

play09:46

A window will pop up, with the name of the repository and the description.

play09:50

And there's a checkbox for if you want to keep the repo private.

play09:54

I'm just going to keep this private since it's not for any real code.

play09:58

Then click "Publish repository" and it will get published to your GitHub account.

play10:01

Let's go to the GitHub website and see how our repository looks.

play10:06

If you go to GitHub.com, login if it prompts you to.

play10:09

Then click on your avatar in the top right and navigate to "Your repositories."

play10:13

When you see the "test-repo" repository click on that and it will load.

play10:18

Let me point out a few things that are good to get familiar with.

play10:22

In the top left is your username, followed by a slash, then "test-repo."

play10:26

This tells you what repository you're currently in, and it will also be listed in the URL.In

play10:32

the main part of the webpage GitHub will load the most recent commit message which should

play10:35

be "Create index.html."

play10:38

And it has a 6-digit code that is the hash for that specific commit.

play10:42

Every time you create a commit, Git will automatically create a random hash, which is a long string

play10:46

of letters and numbers, that serves as the unique ID for that commit.

play10:51

If you click on the 6 digit code, it will load that commit, and you can see the really

play10:55

long string in the URL and on the right side.

play10:59

Going back to the test-repo repository, next to the hash is how long ago the commit was

play11:04

made, and then at the end is the total number of commits.

play11:07

Under the top bar, GitHub will also display the files currently in the repository, which

play11:12

right now is only the index.html file.

play11:15

As we add more files you'll see them all in this area.

play11:18

And if you click on the filename, GitHub will load the actual code in that file.

play11:23

You can even edit and delete the file right in GitHub.

play11:25

I wouldn't actually recommend doing this since it's better to manage your code in VS Code.

play11:30

But it's nice that the access is there.

play11:32

We'll look at a few more things in GitHub in a little bit, but for now let's go back

play11:36

to VS Code.

play11:37

So far we've added files to our repository.

play11:40

But there might be files and folders that you create that you actually don't want Git

play11:44

to track.

play11:46

Let's say you're keeping some notes or something in a text file called random.txt that's in

play11:50

your project.

play11:51

You want those notes there but you don't want them to be public in your repository.

play11:56

In GitHub Desktop, what you can do is uncheck that box.

play11:59

That will make sure that the file won't be included in any commits.

play12:03

However, it can be kind of annoying to keep seeing that filename all the time.

play12:08

So you can actually have Git ignore files and folders.

play12:11

If you right-click the file and select "Ignore file (add to .gitignore)" you'll see that

play12:15

random.txt has disappeared.

play12:17

And there's a new file that Git has detected and wants to add to the repository: .gitignore.

play12:22

And in the right panel we can see that it contains "random.txt".

play12:26

And if we look in VS Code and open the .gitignore file, we'll see the "random.txt" line.

play12:32

In gitignore files, you can ignore individual files and folders by adding each one on a

play12:37

separate line.

play12:38

Let's test this out.

play12:40

In the gitignore file, add another line that says "random123.txt" and save it.

play12:45

Then in VS Code create a file with that exact file name.

play12:48

Going back to GitHub Desktop, it has not added the random123.txt file since we ignored it.

play12:55

As you might imagine, it can get a bit tedious to have to manually write each file name in

play13:00

the gitignore file.

play13:02

One thing that can help with that is that you can use the wildcard when writing the

play13:06

filename.

play13:07

So let's go back to the gitignore file and delete everything that's there.

play13:10

Then add "\*.txt" to ignore all text files.

play13:15

Now in GitHub Desktop, we don't have either of the text files showing up, and we can see

play13:19

the wildcard in the gitignore file.

play13:21

Just be very careful when using the wildcard to ignore file types, in case you might want

play13:26

to include a file of that type in the future sometime.

play13:30

Let's make a new commit with a commit message that says "Ignore text files".

play13:34

Then double-check to make sure the .gitignore file is checked, and click "Commit to main."

play13:39

In the top on the right we can see the panel saying "Push origin."

play13:44

What "origin" is, is it refers to the remote repository that we published on GitHub.

play13:49

So when we push commits in our local repo to origin, they will get pushed to the origin

play13:53

repository which is on GitHub.

play13:56

Let's click "Push origin."

play13:58

It usually takes a few seconds.

play14:00

Now let's go back to GitHub and the main "test-repo" repository page.

play14:04

We can see that it looks a bit different now!

play14:07

The most recent commit is the "Ignore text files" one, and it has a new hash.

play14:11

And the total number of commits has gone up.

play14:14

And we can see the .gitignore file is now on GitHub too.

play14:19

We've covered adding new files to the Git repository.

play14:23

Another thing Git will keep track of is changes made to existing files.

play14:26

Let's see how this looks.

play14:29

In VS Code, open the index.html file and let's add some content to the body:

play14:33

I'm adding an h1 tag with some text, "Hello here is our website" and a paragraph tag saying

play14:38

"Here is some cool new content!"

play14:40

Save it, and let's see what this looks like in GitHub Desktop.

play14:44

Now, in the left sidebar the index.html file is showing up, and instead of that green plus

play14:49

icon that we saw when adding new files, there's a yellow dot icon.

play14:53

This signifies that Git has detected modifications in that file.

play14:58

Then in the right panel we can see the new text that we just added.

play15:01

And it's highlighted in green, meaning that it's code that has been added.

play15:07

So let's make a commit.

play15:08

I'll make the commit message something like "Added content to index.html."

play15:12

Now we'll commit it to the main branch, and push to origin.

play15:15

And if we look in GitHub, we'll see that commit we just made, and clicking on it will show

play15:17

us again, the green highlighted code we added to index.html.One thing to note about Git

play15:18

is that it tracks changes on each line of code.

play15:19

If we click on the "History" tab we can see the 4 commits that we have in this repo, with

play15:22

the most recent on top.

play15:25

And if we go back to GitHub.com to the repository page, we can see the same history up there

play15:29

if we click on the "4 commits" link on the right side, again with the newest commits

play15:34

on top, and the oldest ones on the bottom.

play15:37

Git will also track if you delete files.

play15:41

Let's test this out.

play15:42

In VS Code, go ahead and delete the index.html file!

play15:46

Now, going back to GitHub Desktop, we see the index.html file is showing up under "Changes."

play15:51

It has a red minus symbol icon to indicate that this file has been deleted.

play15:56

And in the right panel all the code in the file is highlighted in red, meaning it's been

play16:00

removed.

play16:01

Let's make a commit, with the commit message saying that we deleted index.html.

play16:06

Commit it, and then push to origin.

play16:08

If we check out GitHub, it'll show that most recent commit, and clicking on the commit,

play16:12

it tells us that the file was indeed deleted.

play16:15

But what if we realize that we really need that index.html file?!

play16:19

Not to worry, this is one of the ways that Git can really save your life.

play16:24

In GitHub Desktop, in the "History" tab, right-click the commit where we deleted index.html.

play16:29

And select "Revert changes in commit."

play16:32

Now we see that Git has automatically created a new commit saying that it has reverted the

play16:36

previous commit.

play16:38

And looking at more details in the right panel, it tells us the hash of the commit that was

play16:43

reverted, and it's added back the index.html file and all 16 lines of code.

play16:48

Whew!

play16:49

Now if we click the "Push origin" button, everything will be back to normal.

play16:51

In VS Code, the index.html file will be back.

play16:55

And in GitHub if we refresh, we can see the commit reverting it, and the index.html file

play16:59

is also back where it belongs.

play17:02

Now there is one more area in Git that I'd like to cover.

play17:05

And that is branching.

play17:07

In Git a branch is one version of the codebase, and a repo can have multiple branches going

play17:11

at the same time.

play17:13

So far, all the work that we've done in Git, and all the commits that we've made have been

play17:17

on the one main branch.

play17:19

If you're just working by yourself you can probably get away with doing everything on

play17:23

main.

play17:24

But if you're on a team with multiple developers all working on the same codebase, it would

play17:29

be quite chaotic to have everyone working on the same branch, especially if more than

play17:34

one person makes changes to the same file.

play17:37

So most teams will separate work into different branches.

play17:40

You might have one developer fixing a bug on the homepage working in a branch called

play17:44

homepage-bug.

play17:46

Then there might be another developer building a new feature on the careers page working

play17:50

in another branch called careers.

play17:53

Each of those branches will be created off the main branch, so they will have the most

play17:56

up to date code from main.

play17:58

Then they'll each work on their own branches locally.

play18:02

When the developers are done with their work, they will merge their branch back into the

play18:07

main branch.

play18:08

This type of workflow is considered best practice when you're working on a team.

play18:13

So even though in this course we can do all our work on the main branch, I wanted to show

play18:18

you a little bit of what working with different branches looks like.

play18:22

In GitHub Desktop, in the top menu, navigate to Branch > New branch.

play18:27

Let's give it a name of "feature-1".

play18:30

And you'll notice under the Name field is a note saying that the new branch will be

play18:33

based on the current branch, which is main.

play18:36

Then click "Create branch".

play18:38

Now up at the top GitHub Desktop has the feature-1 branch listed as our current branch.

play18:44

Let's make some demo code changes in this branch.

play18:47

In VS Code, create a new file called "feature1.html" to keep things simple.

play18:53

And in the file hit exclamation point and enter to use the Emmet shortcut to add boilerplate

play18:57

HTML.

play18:58

Then save the file.

play19:00

And back in GitHub Desktop, we want to add feature1.html to our repo.

play19:05

In the commit panel at the bottom we'll just leave that default commit message of "Create

play19:09

feature1.html" and hit the button to commit this change to the feature-1 branch.

play19:13

Now, in GitHub Desktop, let's switch our current branch back to the main branch.

play19:18

If we go back to VS Code, the feature1.html file won't exist.

play19:23

This is because it was created in the feature-1 branch, and so it doesn't exist yet on the

play19:28

main branch.

play19:30

Git will keep the codebase files updated depending on what you are loading.

play19:35

So let's pretend that we've now finished all the development work on the feature-1 branch,

play19:38

and we want to deploy it to our website.

play19:41

We need to add our changes from the feature-1 branch to the main branch in what's called

play19:46

a merge in Git.

play19:48

To merge feature-1 into main, in GitHub Desktop, first make sure that you are currently in

play19:52

the main branch.

play19:54

Then in the top menu, navigate to Branch > Merge into current branch.

play19:58

And select the feature-1 branch.

play20:01

So what this is saying is that we will merge all the commits from the feature-1 branch

play20:04

into the main branch.

play20:07

click the button saying "Create a merge commit".

play20:09

This will merge in the code from feature-1 into main, and the change will be automatically

play20:14

put into a new commit on the main branch.

play20:18

Now if we load the History tab, we can see the "Create feature1.html" commit message

play20:23

listed as the most recent commit on the main branch.

play20:27

Now click the "Push origin" button up at the top to update GitHub.

play20:32

In GitHub, if we load the repository page, we can now see that the commit creating feature1.html

play20:37

is the most recent commit, and the file exists on the main branch.

play20:42

One last thing to note, if you're working on a team that uses GitHub, new branches are

play20:46

typically merged into the main branch through a feature on GitHub called pull requests.

play20:51

This allows other people on the team to check the code changes and approve them before merging

play20:56

them into main.

play20:58

This helps to prevent any mistakes from being added.

play21:01

So what you would do is make your code changes and commit onto the feature-1 branch.

play21:07

Then instead of merging feature-1 into main in GitHub Desktop like we did last time, you

play21:11

would publish the feature-1 branch up to GitHub.

play21:15

Then on GitHub you would create the pull request for other people on your team to review and

play21:20

either approve or suggest code changes.

play21:24

If the changes are approved, your team member can then merge your changes into main.

play21:28

Again, this is mainly if you're on a team.

play21:31

We're not going to be working with multiple branches or pull requests in this course.

play21:36

But I wanted to make sure that you know that they exist because they're common practice

play21:39

when you're working on a team.

play21:40

Next up, we'll be setting up our project files for the actual course!

play21:41

I'll be showing you how to set it up from a blank folder and create a new Git repo for

play21:42

it, so you won't be needing this test-repo one anymore.

play21:43

And that's it for the basics of Git and GitHub!

play21:44

This video is actually from my course, Responsive Design for Beginners.

play21:47

You can find out more info about it down in the description.

play21:51

If you like these explainer type videos, you might also enjoy my other video on npm in

play21:55

15 minutes.

play21:56

And as always, thanks for watching and we'll see you in the next one.

Rate This

5.0 / 5 (0 votes)

Related Tags
GitGitHubВеб-разработкаУрокиКодированиеВерсионное управлениеРепозиторииКоммитыВетвленияПул-реквесты
Do you need a summary in English?