Перейти к содержимому

Как обновить код на github

  • автор:

Русские Блоги

Git — это система управления версиями с открытым исходным кодом, мы можем использовать Git для загрузки кода в GitHub. В то же время, GitHub поддерживает только Git как единственный формат хранилища для хостинга.

Сгенерируйте ключ ssh локально

Передача между вашим локальным Git-репозиторием и GitHub-репозиторием зашифрована через SSH, поэтому нам нужно настроить информацию для аутентификации и использовать следующую команду для генерации SSH-ключа:

После этого вам будет предложено подтвердить путь и ввести пароль. Мы используем возврат каретки по умолчанию полностью. В случае успеха папка .ssh будет сгенерирована в корневом каталоге пользователя, щелкните внутри, откройте id_rsa.pub и скопируйте ключ внутрь.

Добавьте ключ ssh в GitHub

Откройте Github и перейдите в раздел «Учетная запись»> «Настройки»

Выберите слева ключи SSH и GPG, затем нажмите кнопку Новый ключ SSH, название, чтобы установить заголовок, вы можете заполнить и вставить ключ, созданный на вашем компьютере.

Создать репозиторий на GitHub

Нажмите «Новый репозиторий», как показано ниже:

После заполните тест (имя удаленного хранилища) в имени репозитория, сохраните другие настройки по умолчанию и нажмите кнопку «Создать репозиторий», чтобы успешно создать новый репозиторий Git:
 После успешного создания отображается следующая информация:
Мы успешно создали склад на GitHub.

Локальная загрузка

Перед загрузкой мы используем Git для настройки информации о пользователе и запускаем следующую команду:

Затем мы входим в файл, куда хотим выгрузить код, и выполняем команду для инициализации локального хранилища:

Затем добавьте все локальные коды в область временного хранения:

Добавить информацию о заметке:

Привязка к удаленному складу (требуется только в первый раз)

Отправить код на удаленный склад

Получить код с другого компьютера

Сначала сгенерируйте ключ ssh на ПК и добавьте его на свой GitHub.
Код извлечения:

Обновить код

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

Добавьте код в область подготовки:

-A указывает, что все отслеживаемые изменения и удаления файлов и вновь добавленные неотслеживаемые файлы добавляются во временную область хранения. Добавить информацию о заметке:

Отправить код на удаленный склад

постскриптум

С тех пор, управление филиалом еще не использовалось, и я заполню его после того, как стану опытным.
Я также благодарю новичка за помощь в использовании GitGit Remote Repository (Github), Подавляющее большинство статей приходят отсюда.

Интеллектуальная рекомендация

[Передача] класс для масштабирования в соответствии с динамическими центрами

См. Кто-то здесь, чтобы представить класс ротатора Bartek Drozdz, который может повернуть дисплей в соответствии с динамической центральной точкой. Я чувствую себя очень легко. Скачать Адрес: [URL] ht.

Микросервисная архитектура Spring Cloud-Message Bus

Микросервисная архитектура Spring Cloud-Message Bus 1. Что такое шина сообщений Из-за изменений в информации о конфигурации или других операциях управления требуется шина сообщений. Шина сообщений озн.

Закрытие в JavaScript

Закрытие в Дж Общее понимание закрытия: область внешней функции доступна из одной функции. Мы можем сделать простое понимание закрытия в функцию «определенного в функции», конечно, также м.

Quic Faction Combat (3) Заявка на сертификат LetSERRYPT и автоматическое обновление

После развертывания кластера QUIC исходный сертификат HTTPS истек, и я попытался переустановить/обновить сертификат. Let’s Encrypt Это бесплатный товар для автоматического выпуска сертификата HT.

update my repository on github

I just went up to github the project that was working locally on my computer. everything went well and I could upload all my files .. now I would like to know how I can update my repository if I make some changes to my project locally try the following commands:

I think I’m forgetting something, or I’m using the commands incorrectly, what would be the correct way?

4 Answers 4

Zin Myo Swe's user avatar

Your work flow for ensuring that your changes are added correctly to your remote github repo in «normal» cases should follow these stages ..

Will always tell you what is uncommitted and what needs to be «added» (staged) for committing to your local repo. In fact git will hint to you what it thinks is the next step in your work flow

Works in Windows if use the Windows git-bash.exe It uses mingW64 emulator to simulate linux environment. It’s very good at it.

You need to commit whatever changes yout want to keep — locally before you can «push» your changes to your github repo remotely ie only after you have told git where your remote git repo is .

Usually the default name for your remote repo on github is given as «origin». But I have been using specific alias branch names which in your case is «myGitHubOrBitBucketRepo»

This command will push your committed changes (aka snap shots in git speak) to YourGitAppRepo.git on github.com onto the master branch and if master on your remote repo is not ahead of your local branch and it is just a couple of commits behind — github.com will accept this push

The -u is the same as —track which means that your local branch positioned @ HEAD will be tracking the master branch at your remote alias myGitHubOrBitBucketRep

In steps 4 & 5 you will have to use a userId and passWord to interact with your remote repo on GitHub.com

From now on git status will actually tell you whether you are behind or ahead of your remote github repo because of the —track (ing) option you had done in your push

Another useful command to use from this point onwards will be

Over here bitbucketFrmWin is my alias for my remote bitbucket repo AsOf16Jan2018 is a branch that I am no longer interested master is my current main branch which I push my changes to from my local repo.

The —all option will also display your local & your «remotes»

Of note is the following * CurrAsOf18Jan2018 50d1fc6 [remotes/bitbucketFrmWin/master: behind 5]

The asterik * that is the HEAD of my local branch or at which commit on that branch I am on. Usually it is always at the tip or the HEAD i.e. why it is called the «head»

CurrAsOf18Jan2018 is my local main branch and importantly it is saying that my local is already ahead of my remote branch by 5 commits — it is out of date so I need to update my remote with a «git push»

For now that is just one side of this story. If your remote repo goes ahead then another work-flow would be

That is altogether another post.

And here is a succinct image which I found courtesy Oliver Steele that displays another version of the basic git workflow life-cycle of versioning Another Git WorkFlow cycle courtesy Oliver Steele @ osteele.com

Updating a Local Repository With Changes From a GitHub Repository

Moreover, several team members can work on the same project using the Git local repositories. However, developers need to update the local repository with a GitHub remote repository whenever they make changes.

This study illustrated the procedure for updating a Git local repository with changes from a hosting server GitHub repository.

Updating a Local Repository With Changes From a Hosting Server GitHub Repository

For updating a local repository with changes from a GitHub repository, first, navigate to the local repository. Clone the Git local repository and execute the “$ git pull origin <branch-name>” command to update the Git local repository.

Let’s implement the above-stated step!

Step 1: Navigate to Git Local Repository

Move to the Git directory where desired remote repository exists:

Step 2: Clone Git Remote Repository
To clone the Git remote repository to the Git local repository, execute the given below command along with the remote URL:

According to the below-given output, our remote repository is cloned successfully:

Step 3: Pull Repository
Now, update the local repository with remote repository changes by executing the “git pull origin” command with the local branch name:

As you can see, the local repository is updated with remote repository changes:

That’s it! We have offered the procedure to update the local Git repository with changes from a hosting server GitHub repository.

Conclusion

To update a local repository with changes from a hosting server GitHub repository, firstly, move to the local repository. Then, clone the Git local repository by executing the “$ git clone <remote-url>” command. Lastly, run the “$ git pull origin <branch-name>” command to update the Git local repository. This study illustrated the procedure for updating a local repository with changes from a hosting server Github repository.

About the author

Maria Naz

I hold a master’s degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.

Updating GitHub repository using Git Commit

MALAY JOSHI

Git is primarily a version control system and a staple in any software development project. It usually serves 2 main purposes: code backup and code versioning.

The common trouble is that Git can be tricky to use. There are times where versions and branches are out of sync and you spend serious time just trying to push your code to GitHub using it with all efforts going in vain. Even worse, not knowing how exactly certain commands work could easily lead to accidentally deleting or overwriting bits of code.

That’s why I’ve prepared this tutorial, to teach you how to properly use Git so as that you can get started with updating your GitHub repository using it.

Install and setup

Download Git Bash from the following link: https://git-scm.com/downloads

Once you install Git Bash in your system, launch it and type the following code:

Note: Please enter your email id and username in place of entries filled by me

First situation: When you want to update GitHub repository owned by you and located at your own GitHub account

Note: Execute all the following steps in Git Bash

A) First choose a location in your local system (let us say “/c/Users/barcode/Desktop”) where you would like to clone/copy your GitHub repository.

Then using Git Bash, change your current working directory to this desired/selected location by using “cd” command.

B) Next, clone your GitHub repository to the selected location (let us say I wish to update this “https://github.com/malayjoshi13/Describe” repository of mine) by using “git clone” command.

Note: You have to use this step (B) just for the first time to clone your desired repository (present in your GitHub) to your local machine. After that follow all steps except this step until you are updating/committing in that same cloned repository.

C) Now move inside “Describe” folder of repository cloned in your local system by using “cd” command.

D) Before moving ahead let us understand the role of “git remote”. This command will help you to view all urls (and also help to add a new url to some new shortname, will see in later section) of cloned GitHub repositories referenced to some word, like:

From above it is clear that url of our GitHub repository (which we have freshly cloned in our system) is referenced as shortname “origin”. Then from now what all actions you have to perform (like fetching, deleting, committing, staging, etc) with this url, will be done by using this shortname “origin” and not the whole url.

E) Now to ensure that your local copy/cloned GitHub repository (owned by you and located in your own GitHub repository) is up to date, you have to use the “git fetch” command alongwith shortname “origin”.

This command will fetch all new changes/commits (if any) made to the remote repository whose url is stored in shortname “origin”.

F) Before pushing a new commit to the cloned repository, you have to delete any changes made by mistake or intentionally after the latest commit pushed to the remote GitHub repository by using “git reset” command.

This is done to make changes/commit to the cloned repository right from the latest state in which the remote repository exists currently.

G) Next to create and switch to a new branch use the git checkout command.

In first-time execution it will create a new branch called “new-update” and then from second execution onward this command will be used to switch from the “main” branch to the “new-update” branch.

A separate branch is created so as to not directly make changes/committing to the main branch of remote GitHub repository without finally assuring changes to be perfect.

H) Now you can do whatever changes you want to make in the cloned repository located at your local system. These changes includes like updating the file’s content, renaming file(s), deleting/adding new file(s), etc.

Once we are done with all changes in the cloned repository, the next step is to execute the “git add” command which adds new or changed files to the Git staging area by taking snapshot of the changes done in the cloned version (an intermediate stage between the cloned repository and the remote GitHub repository).

I) Next step is to execute the “git commit” command, which will commit/save history of snapshot(s) of changes made during step (H) in the cloned repository.

In addition to saving history, this command also enable us to write a message about what the commit/update is all about.

J) Now using the git push command, you will be able to upload content of the local cloned repository (on which you are working currently) back to its original remote GitHub repository.

You have to use the shortname “origin” where we referenced the url in step (D) to specify the path of original remote GitHub repository were you want to make the final changes.

K) Now open the remote repository (where you pushed the changes) in the browser and then click on “Compare and Pull request” button located in the notification pop up at the top of page.

L) Next follow the green buttons one by one and keep on agreeing to merge the pull request, and after successfully merging the commit, click on “delete the branch” button.

M) With this, you have successfully updated GitHub repository owned and present in your GitHub account by using Git commit.

Second situation: When you want to update GitHub repository owned by some other person and present in your GitHub account

Note: Execute all the following steps in Git Bash

A) Go to the GitHub account of the user from where you want to fork the repository.

Then on the top right corner, click on “the Fork” button to fork that original repository from the GitHub account of that user to your own GitHub account.

B) Choose a location in your local system where you would like to clone that forked GitHub repository (like I selected the “/c/Users/barcode/Desktop” location).

Now change your current working directory to your desired location by using “cd” command in Git Bash.

C) Next, clone the repository (which you forked from some other person) located in your GitHub account to the selected location in your local system. (let us say I want to update this “https://github.com/malayjoshi13/demo” GitHub repository that I forked from “https://github.com/malay1931025/demo”) by using “git clone” command.

Note: You have to use this step (C) just for the first time to clone your desired repository (present in your GitHub) to your local machine. After that follow all steps except this step until you are updating/committing in that same cloned repository (forked from another person’s GitHub account).

D) Now move inside “demo” folder of the repository cloned in your local system by using “cd” command.

E) Now we use the “git remote add” command to add the location of the original remote GitHub repository (located in the GitHub account of some other user) where we want to finally commit changes by referencing the url of that repository to the shortname “upstream”.

After executing this code, “git remote” will have two paths added:

i) One is the path of the repository (let us say repository “describe”) owned by some other user and forked to your GitHub account → referenced by the shortname “origin”

ii) Another path is of that same repository (let us say repository “describe”) owned and present in GitHub of some other user → referenced by the shortname “upstream”

Note: shortname “upstream” has url of remote repository where final changes will be merged.

F) Now to ensure that your local copy/cloned GitHub repository (forked from some other person’s GitHub account) is up to date, you have to use the “git fetch” command alongwith shortname “upstream”. This command will fetch all new changes/commits (if any) made to the remote repository whose url is stored in shortname “upstream”.

Note: Unlike step (E) of first situation here we are not using shortname “origin” because this time the final changes are aimed to be happen in url https://github.com/malay1931025/demo of repository owned and present in GitHub account of some other person referenced by shortname “upstream”.

On other hand, shortname “origin” for this situation has url https://github.com/malayjoshi13/demo.git of repository in GitHub of other person and forked to your GitHub account.

G) Before pushing a new commit to the cloned repository, you have to delete any changes made by mistake or intentionally after the latest commit pushed to the remote GitHub repository) by using “git reset” command.

This is done to start making changes/commit to the cloned repository right from the latest state in which the remote repository exists currently.

H) Now you have to create a new branch and switch from “main” branch to that newly formed branch named by using “git checkout” command.

I) Then do the required changes in cloned repository and once done, stage these changes by using “git add” command.

J) Next using “git commit” command commit files in the staging area. You can also write a message about what the commit/update is all about.

K) Now using the git push command, you will be able to upload content of the local cloned repository (on which you are working currently) back to its original remote GitHub repository.

You have to use the shortname “origin” where we referenced the url https://github.com/malayjoshi13/demo.git in step (D) to specify the path of repository (present in your GitHub account) forked from GitHub account of some other user.

Note: However, unlike the first situation discussed above, here “git push origin new-update” do a little magic.

Here the changes go from local cloned repository to repository located in your GitHub account (which is a forked version of the original repository of some other user) as directed by the “git push origin new-update” command.

Then from your GitHub account, the changes can be merged to the GitHub repository of another user where we want to commit changes finally (will see this below).

L) After pushing changes to forked repository present in your GitHub account, go to your GitHub account, open a pull request, and wait for your changes to be merged into another user’s repository.

With this you have learned basics of using Git commands to update GitHub repository using Git Bash CLI.

Please feel free to post any questions in the comments below, and I will try to answer them to the best of my knowledge.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

https://czena.vyvod-iz-zapoya-na-domu-voronezh.ru/