Как запустить репозиторий с github
Перейти к содержимому

Как запустить репозиторий с github

  • автор:

Syncing with GitHub

So far you used Git to create a repository called hello-world on your own computer, but no one else can see those files. Next, you will use GitHub to share the contents of your repository so others can collaborate. This involves creating an empty repository in GitHub, then linking it to your local repository.

Create an empty GitHub repository

Log into your GitHub account and create a new repository by clicking the + icon in the upper-right corner of any page, then selecting New repository.

add_new_repository

  • Name the repository “hello-world”
  • Add optional description
  • Ensure repository is set to “Public”
  • Click “Create repository”

Though not mandatory, choosing a license is an important part of openly sharing your creative work online. For help selecting an appropriate license see https://choosealicense.com/.

After creating the “hello-world” repository, GitHub will display the repository main web-page on your browser. This page contains information required to link your GitHub repository, remote , to the repository you created with Git on your own computer.

Linking your local repository to the GitHub repository (using SSH or HTTPS)

We need to set up a way for our local computer to authenticate with GitHub so that GitHub recognizes our computer as belonging to the same person who owns the GitHub repository.

GitHub removed password authentication on August 13, 2021. You have two options to connect your local machine to GitHub.

Option 1. Connecting with SSH

The repository SSH on GitHub

First, copy the URL from your GitHub repository. Move back to your shell application and enter the first command:

SSH Background and Setup

SSH is a security protocol widely used by many applications. You can use the following commands to connect your newly created repository or your existing repository to Github.

We will use SSH as our authentication method. SSH stands for Secure SHell protocol. SSH is a cryptographic network protocol that allows secure communication between computers using an otherwise insecure network.

What we will do now is the minimum required to set up the SSH keys and add the public key to a GitHub account.

## Advanced SSH —> A supplemental episode in this lesson discusses SSH and key pairs in more depth and detail.—>

The first thing we are going to do is check if this has already been done on the computer you’re on.

Keeping your keys secure
You shouldn’t really forget about your SSH keys, since they keep your account secure. It’s good practice to audit your secure shell keys every so often. Especially if you are using multiple computers to access your account.

We will run the list command ( ls ) to check what key pairs already exist on your computer. In our command we use the

as the shorthand for “my home directory.”

If you have not set up SSH, your output might look like this:

If SSH has been set up on the computer you’re using, the public and private key pairs will be listed. The file names are either id_ed25519 / id_ed25519.pub or id_rsa / id_rsa.pub depending on how the key pairs were set up.

If you do not have SSH set up, let’s set it up now. Use this command to create key pairs:

We want to use the default file, so just press Enter .

Your computer is now asking you for a passphrase to protect this SSH key pair. We recommend that you use a passphrase and that you make a note of it. There is no “reset my password” option for this setup. If you forget your passphrase, you have to delete your existing key pair and do this setup again. It’s not a big deal, but easier if you don’t have to repeat it.

After entering the same passphrase a second time, you will receive the confirmation

The “identification” is actually the private key. You should never share it. The public key is appropriately named. The “key fingerprint” is a shorter version of a public key.

Now we need to give our public key over to GitHub.

First, we need to copy the public key. Be sure to include the .pub at the end, otherwise you’re looking at the private key.

Copy that entire line of output, and we will paste the copied text into GitHub in the next step.

Now, going to GitHub.com, click on your profile icon in the top right corner to get the drop-down menu. Click “Settings,” then on the settings page, click “SSH and GPG keys,” on the left side “Account settings” menu. Click the “New SSH key” button on the right side. Now, you can add the title (A person might use the title “My 2021 work laptop,” just a little description to remind themselves which computer this public key connect to). Paste your SSH key into the field, and click the “Add SSH key” to complete the setup.

Now that we’ve set that up, let’s check our authentication from the command line.

Option 2. Connecting with HTTPS & GitHub Access Tokens

You can also use HTTPS protocol to connect your local repository to GitHub. Take a look at the following figure and find the commands you need to use to sync your local repository with Github. We will explain these commands in the rest of this section.

The repository HTTPS on GitHub

Now we are going to use the HTTPS protocol and GitHub access tokens (or Git Credential Manager, depending on your OS). GitHub access tokens are simple to obtain, but should be used with caution and should not be shared.

Step 1: link the repositories with “git remote add”

Enter the command below, replacing as appropriate.

This links your local Git repository to a remote one. The link indicates the location of the remote repository, which is nicknamed origin in this example. The nickname can be anything but Git convention is to refer to the remote repository as origin.

We can confirm that it is set up correctly with this command:

Step 2: synchronize the repositories with “git push”

The git push command can “push” our local content and tracking information to the GitHub repository, synchronizing the content. If you run git push right now, Git asks for your GitHub username and password. Even if you enter the correct username and password, the command will not work since support for password authentication was removed in 2021. To fix this error, you can use GitHub Access Tokens or use code editors that support API authentication. In this workshop, we use access tokens:

Step 3: Configure Access Token on GitHub

You can use token-based authentication in place of a password when performing Git operations. Github currently supports two types of personal access tokens: fine-grained personal access tokens and personal access tokens (classic). They recommend using fine-grained tokens whenever possible.

In the first step, we will create a personal Access Token on GitHub. Follow these steps to create one for your GitHub account:

  • Click on your GitHub profile icon on the top right corner and click on Settings
  • Choose Developer Settings on the menu on the left
  • Click fine-grained access tokens and Generate new token Add a specific note that will help you identify the scope of the access token
  • Choose the Expiration period from the drop down menu and select the scopes you want to grant the corresponding access to the generated access token. Make sure to select the minimum required scopes. For this workshop, public_repo should be enough.
  • Click on Generate Token

Now, a new page is opened in which you can see your personal access token and copy it.

Now, we need to run the following command to use this access token:

Pushing the local repository

Now, we have successfully established a connection between the two repositories. To synchronize (merge) the content of the remote and local repositories, we will have to “push” our local changes to the GitHub repository.

The nickname of our remote repository is “origin” and the default local branch name is “main”. The -u flag tells git to remember these parameters, so that next time we can simply run git push and Git will know what to do.

When we do a git push we will see Git “pushing” changes to the specified remote repository — in this case, on GitHub. Because our file is small this happens instantly, but it may take longer if you made many changes or are adding a very large repository. The git status command will indicate the status after “pushing” is complete.

This output lets us know where we are working (the main branch). We can also see that we have no changes to commit, and you’ll find a copy of the “index.md” file in your GitHub “hello-world” repository.

As mentioned earlier, synchronizing the local repository with its correponding remote repository involves merging the branches, specifically the main branches here. If the local branch is ahead of the remote one, the merge command should proceed without conflicts. However, If you have added a readme file or license file to your GitHub repository, the commit on GitHub will be ahead of your latest commit on the local main branch. In this case, you will need to pull the latest changes to synchronize the two repositories:

Pulling changes

When working with others or on multiple computers we need a way to pull all the remote changes back into our local repository. We can see how this works by adding a file to our GitHub repository, then “pulling” that change back to our computer.

Near the bottom of the “hello-world” repository on GitHub, there is a button to “Add a README” file to your repository. Click the button, enter some text, then scroll to the bottom and click “Commit new file” (The default commit message will be “Create README.md”, which is fine for our purposes).

It is good practice to add a README file briefly describing what the project is about. If the README is in the root directory GitHub will automatically display it like a cover page for your repository.

After adding a README on GitHub your local repository is out-of-sync with the remote repository. Let’s fix that by pulling the remote changes into the local repository with git pull .

The output shows that we have fast-forwarded our local repository to include the file README.md. We could confirm this by entering the ls command.

This section introduces some basic git commands but there are many others that may be useful in more complex and collaborative projects. For a more detailed introduction see the online Software Carpentry course Version control with Git.

To update the local repository but not merging any changes, you have two options. git remote update can update all of your branches set to track remote ones, while git fetch can update only the branch you are on.

if you need to sync the local main branch with the remote repository and there are no conflicting changes, you can use “git rebase” instead of merging. This means you can reapply your local commits on top of the latest commit from the remote repository. Rebasing can provide a cleaner commit history since it avoids creating merge commits. You can also use rebase to roll back to an earlier commit. However, this command should be used with caution when working on shared branches, as it modifies the commit history and can cause conflicts if multiple people are working on the same branch.

Adding locally hosted code to GitHub

If your code is stored locally on your computer and is tracked by Git or not tracked by any version control system (VCS), you can import the code to GitHub using GitHub CLI or Git commands.

Platform navigation

About adding existing source code to GitHub

If you have source code stored locally on your computer that is tracked by Git or not tracked by any version control system (VCS), you can add the code to GitHub by typing commands in a terminal. You can do this by typing Git commands directly, or by using GitHub CLI.

GitHub CLI is an open source tool for using GitHub from your computer’s command line. GitHub CLI can simplify the process of adding an existing project to GitHub using the command line. To learn more about GitHub CLI, see «About GitHub CLI.»

Note: If you’re most comfortable with a point-and-click user interface, consider adding your project with GitHub Desktop instead. For more information, see «Adding a repository from your local computer to GitHub Desktop.»

If your source code is tracked by a different VCS, such as Mercurial, Subversion, or Team Foundation Version Control, you must convert the repository to Git before you can add the project to GitHub.

  • «Importing a Subversion repository»
  • «Importing a Mercurial repository»
  • «Importing a Team Foundation Version Control repository»

Warning: Never git add , commit , or push sensitive information to a remote repository. Sensitive information can include, but is not limited to:

  • Passwords
  • SSH keys
  • API keys
  • Credit card numbers
  • PIN numbers

Initializing a Git repository

If your locally-hosted code isn’t tracked by any VCS, the first step is to initialize a Git repository. If your project is already tracked by Git, skip to «Importing a Git repository with the command line.»

Open Terminal Terminal Git Bash .

Navigate to the root directory of your project.

Initialize the local directory as a Git repository. By default, the initial branch is called main .

If you’re using Git 2.28.0 or a later version, you can set the name of the default branch using -b .

If you’re using Git 2.27.1 or an earlier version, you can set the name of the default branch using git symbolic-ref .

Add the files in your new local repository. This stages them for the first commit.

Commit the files that you’ve staged in your local repository.

Importing a Git repository with the command line

After you’ve initialized a Git repository, you can push the repository to GitHub, using either GitHub CLI or Git.

  • «Adding a local repository to GitHub with GitHub CLI»
  • «Adding a local repository to GitHub using Git»

Adding a local repository to GitHub with GitHub CLI

To create a repository for your project on GitHub, use the gh repo create subcommand. When prompted, select Push an existing local repository to GitHub and enter the desired name for your repository. If you want your project to belong to an organization instead of your user account, specify the organization name and project name with organization-name/project-name .

Follow the interactive prompts. To add the remote and push the repository, confirm yes when asked to add the remote and push the commits to the current branch.

Alternatively, to skip all the prompts, supply the path to the repository with the —source flag and pass a visibility flag ( —public , —private , or —internal ). For example, gh repo create —source=. —public . Specify a remote with the —remote flag. To push your commits, pass the —push flag. For more information about possible arguments, see the GitHub CLI manual.

Adding a local repository to GitHub using Git

Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»

At the top of your repository on GitHub.com’s Quick Setup page, click

to copy the remote repository URL.

Screenshot of the "Quick Setup" header in a repository. Next to the remote URL, an icon of two overlapping squares is highlighted with an orange outline.

Open Terminal Terminal Git Bash .

Change the current working directory to your local project.

Add the URL for the remote repository where your local repository will be pushed.

Push the changes in your local repository to GitHub.com.

Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»

At the top of your repository on GitHub.com’s Quick Setup page, click

to copy the remote repository URL.

Screenshot of the "Quick Setup" header in a repository. Next to the remote URL, an icon of two overlapping squares is highlighted with an orange outline.

Open Terminal Terminal Git Bash .

Change the current working directory to your local project.

In the Command prompt, add the URL for the remote repository where your local repository will be pushed.

Push the changes in your local repository to GitHub.com.

Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see «Creating a new repository.»

At the top of your repository on GitHub.com’s Quick Setup page, click

to copy the remote repository URL.

Screenshot of the "Quick Setup" header in a repository. Next to the remote URL, an icon of two overlapping squares is highlighted with an orange outline.

Open Terminal Terminal Git Bash .

Change the current working directory to your local project.

Add the URL for the remote repository where your local repository will be pushed.

Introduction

Project Destroyer

A “source code repository” is a place where code is stored. Developers love to use platforms like Github to ensure they have a remote place to store the code they’re working on.

Side note — If you’re coding, using Photoshop, editing videos, or doing any other work on a computer, back up your files daily and store them online if possible. You never know what might happen and you could end up losing days, weeks, even months of work if you don’t take the necessary steps to back up your files.

Anyways, with Github you can upload private or public repositories. If the repo is public anyone can take that code and use it.

If you’re into sneakers you’ve probably stumbled upon a Github link for some kind of script, whether that’s an Adidas account creator or a proxy tester. These scripts are usually open source and are created with the intention of helping others.

Getting Started

For this guide we will be using a python script created by DefNotAvg. This script is designed to scan supremenewyork.com for products that match the keywords input by the user. If it finds a product match it opens the product link in your browser. Useful, right?

In order to follow these steps successfully these basic requirements must be met.

2. A terminal emulator installed such as Terminal, Command Line, or Hyper.

3. A Github repository to clone and use.

4. Correct version of Python installed (or whatever language the code is written in.)

Once these requirements are met we’re ready to start. The first step to running a script from Github is to clone the git repository.

Clone the git repository

1. Navigate to the main page of the Github repo. For this example we’ll be using this link.

2. Select the green “Clone or download” button.

3. Select the clipboard icon to copy the link to your clipboard.

4. Open a terminal emulator on your desktop. If you’re on Mac the application “Terminal” should be installed by default. Windows users will have “Windows PowerShell” or “Command Prompt”. Another option is Hyper — a sleek cross-platform terminal emulator.

5. Change the directory to the place you’d like the files to be stored. You can do this by entering “cd” in the command line followed by the file path. For this example, we’ll store the files on our desktop by typing “cd desktop”. Click enter to submit the command. If you need further help with this click here.

6. Once you’ve navigated to the desired location type “git clone” , then paste the link you copied in step 2. Once you submit the command you’ll see something like the image below. A folder will appear in the location you specified in step 5.

7. Using the “cd” command you need to navigate to the folder that was just created. In this case that command is “cd Supreme-Link-Grabber”.

Running the script

This part of the guide vastly depends on the script you are trying to run.

There may be certain software packages that you need to install in order to run the script correctly. pip for Python and npm for Javascript are two great package management systems that will help you install software packages with ease.

If the repo contains a “README.MD” file you should read it and see if the developer included a guide on how to run the script. The Supreme Link Grabber README file states the following.

Ok, great. That’s telling us what the script does, how to run it, what version of Python we need, and what packages are required.

To run a python file type “python filename.py” into the command line then hit enter. The README for our code says that “main.py” should be run, so the command is “python main.py”.

The script will now run.

Issues and errors

You may find yourself frustrated if you’ve never done this before. That’s ok — the GREAT thing about coding is there’s an answer online for every single error. Sites like Stack Overflow allow users to submit code-related questions for others to answer.

Odds are the error you’re receiving isn’t special — someone else has run into the same problem before, and it’s been answered somewhere online. Every issue you’ll run into can be solved with a Google search.

If you have all of the necessary requirements and configuration set up, but you’re still receiving an error message it may be an issue within the code itself. If you’re trying to run a script that hasn’t been updated in 2 years it may simply not work anymore.

Github tracks when the last change was made to each file within the repo so you can get a better idea if the code you’re trying to use is updated or not.

Follow Project Destroyer on Twitter, and feel free to send us a message with any questions regarding this article. You can also reach us via the Contact page.

If you enjoyed this guide check out the other articles on our blog. These articles are loaded with practical advice like how to get multiple shoes shipped to the same address, where to get proxies, what servers are, and more.

2.5 Основы Git — Работа с удалёнными репозиториями

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

Вполне возможно, что удалённый репозиторий будет находиться на том же компьютере, на котором работаете вы. Слово «удалённый» не означает, что репозиторий обязательно должен быть где-то в сети или Интернет, а значит только — где-то ещё. Работа с таким удалённым репозиторием подразумевает выполнение стандартных операций отправки и получения, как и с любым другим удалённым репозиторием.

Просмотр удалённых репозиториев

Для того, чтобы просмотреть список настроенных удалённых репозиториев, вы можете запустить команду git remote . Она выведет названия доступных удалённых репозиториев. Если вы клонировали репозиторий, то увидите как минимум origin — имя по умолчанию, которое Git даёт серверу, с которого производилось клонирование:

Вы можете также указать ключ -v , чтобы просмотреть адреса для чтения и записи, привязанные к репозиторию:

Если у вас больше одного удалённого репозитория, команда выведет их все. Например, для репозитория с несколькими настроенными удалёнными репозиториями в случае совместной работы нескольких пользователей, вывод команды может выглядеть примерно так:

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

Обратите внимание на разнообразие протоколов, используемых при указании адреса удалённого репозитория; подробнее мы рассмотрим протоколы в разделе Установка Git на сервер главы 4.

Добавление удалённых репозиториев

В предыдущих разделах мы уже упоминали и приводили примеры добавления удалённых репозиториев, сейчас рассмотрим эту операцию подробнее. Для того, чтобы добавить удалённый репозиторий и присвоить ему имя (shortname), просто выполните команду git remote add <shortname> <url> :

Теперь вместо указания полного пути вы можете использовать pb . Например, если вы хотите получить изменения, которые есть у Пола, но нету у вас, вы можете выполнить команду git fetch pb :

Ветка master из репозитория Пола сейчас доступна вам под именем pb/master . Вы можете слить её с одной из ваших веток или переключить на неё локальную ветку, чтобы просмотреть содержимое ветки Пола. Более подробно работа с ветками рассмотрена в главе Ветвление в Git.

Получение изменений из удалённого репозитория — Fetch и Pull

Как вы только что узнали, для получения данных из удалённых проектов, следует выполнить:

Данная команда связывается с указанным удалённым проектом и забирает все те данные проекта, которых у вас ещё нет. После того как вы выполнили команду, у вас должны появиться ссылки на все ветки из этого удалённого проекта, которые вы можете просмотреть или слить в любой момент.

Когда вы клонируете репозиторий, команда clone автоматически добавляет этот удалённый репозиторий под именем «origin». Таким образом, git fetch origin извлекает все наработки, отправленные на этот сервер после того, как вы его клонировали (или получили изменения с помощью fetch). Важно отметить, что команда git fetch забирает данные в ваш локальный репозиторий, но не сливает их с какими-либо вашими наработками и не модифицирует то, над чем вы работаете в данный момент. Вам необходимо вручную слить эти данные с вашими, когда вы будете готовы.

Если ветка настроена на отслеживание удалённой ветки (см. следующий раздел и главу Ветвление в Git чтобы получить больше информации), то вы можете использовать команду git pull чтобы автоматически получить изменения из удалённой ветки и слить их со своей текущей. Этот способ может для вас оказаться более простым или более удобным. К тому же, по умолчанию команда git clone автоматически настраивает вашу локальную ветку master на отслеживание удалённой ветки master на сервере, с которого вы клонировали репозиторий. Название веток может быть другим и зависит от ветки по умолчанию на сервере. Выполнение git pull , как правило, извлекает (fetch) данные с сервера, с которого вы изначально клонировали, и автоматически пытается слить (merge) их с кодом, над которым вы в данный момент работаете.

Начиная с версии 2.27, команда git pull выдаёт предупреждение, если настройка pull.rebase не установлена. Git будет выводить это предупреждение каждый раз пока настройка не будет установлена.

Если хотите использовать поведение Git по умолчанию (простое смещение вперёд если возможно — иначе создание коммита слияния): git config —global pull.rebase «false»

Если хотите использовать перебазирование при получении изменений: git config —global pull.rebase «true»

Отправка изменений в удалённый репозиторий (Push)

Когда вы хотите поделиться своими наработками, вам необходимо отправить их в удалённый репозиторий. Команда для этого действия простая: git push <remote-name> <branch-name> . Чтобы отправить вашу ветку master на сервер origin (повторимся, что клонирование обычно настраивает оба этих имени автоматически), вы можете выполнить следующую команду для отправки ваших коммитов:

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

Просмотр удалённого репозитория

Если хотите получить побольше информации об одном из удалённых репозиториев, вы можете использовать команду git remote show <remote> . Выполнив эту команду с некоторым именем, например, origin , вы получите следующий результат:

Она выдаёт URL удалённого репозитория, а также информацию об отслеживаемых ветках. Эта команда любезно сообщает вам, что если вы, находясь на ветке master , выполните git pull , ветка master с удалённого сервера будет автоматически влита в вашу сразу после получения всех необходимых данных. Она также выдаёт список всех полученных ею ссылок.

Это был пример для простой ситуации и вы наверняка встречались с чем-то подобным. Однако, если вы используете Git более интенсивно, вы можете увидеть гораздо большее количество информации от git remote show :

Данная команда показывает какая именно локальная ветка будет отправлена на удалённый сервер по умолчанию при выполнении git push . Она также показывает, каких веток с удалённого сервера у вас ещё нет, какие ветки всё ещё есть у вас, но уже удалены на сервере, и для нескольких веток показано, какие удалённые ветки будут в них влиты при выполнении git pull .

Удаление и переименование удалённых репозиториев

Для переименования удалённого репозитория можно выполнить git remote rename . Например, если вы хотите переименовать pb в paul , вы можете это сделать при помощи git remote rename :

Стоит упомянуть, что это также изменит имена удалённых веток в вашем репозитории. То, к чему вы обращались как pb/master , теперь стало paul/master .

Если по какой-то причине вы хотите удалить удалённый репозиторий — вы сменили сервер или больше не используете определённое зеркало, или кто-то перестал вносить изменения — вы можете использовать git remote rm :

При удалении ссылки на удалённый репозиторий все отслеживаемые ветки и настройки, связанные с этим репозиторием, так же будут удалены.

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

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