Advance your journey
Содержание:
- Our Learning Paths
- Saving changes to the repository: git add and git commit
- Как проанализировать рынок фотостудий с помощью Python (1/3). Парсинг данных
- Repo-to-repo collaboration: git push
- Не хочу Visual Studio Code: 7 open source альтернатив
- GitHub Actions
- Использование
- git init templates
- GitHub
- Вариант 1. Я уже знаком с терминалом
- Configuration & set up: git config
- «Конституция» для разработчиков: как страничка на GitHub помогает нам не ругаться уже год
- Our most popular courses
- Step 4. Open a Pull Request
- The git config editor — core.editor
- Bare repositories — git init —bare
Our Learning Paths
First Day on GitHub
Welcome to GitHub! We’re so glad you’re here. We know it can look overwhelming at first, so we’ve put together a few of our favorite courses for people logging in for the first time
-
What is GitHub?
-
Introduction to GitHub
-
Git Handbook
First Week on GitHub
After you’ve mastered the basics, learn some of the fun things you can do on GitHub. From GitHub Pages to building projects with your friends, this path will give you plenty of new ideas.
-
Discover GitHub Pages
-
GitHub Pages
-
Reviewing pull requests
DevOps with GitHub Actions
Learn how to do DevOps on GitHub with the power of GitHub Actions! This path will guide you through leveraging GitHub Actions to go from code to cloud.
-
GitHub Actions: Hello World
-
GitHub Actions: Continuous Integration
-
GitHub Actions: Publish to GitHub Packages
Saving changes to the repository: git add and git commit
Now that you have a repository cloned or initialized, you can commit file version changes to it. The following example assumes you have set up a project at . The steps being taken in this example are:
- Change directories to
- Create a new file with contents ~»test content for git tutorial»~
- git add to the repository staging area
- Create a new commit with a message describing what work was done in the commit
After executing this example, your repo will now have added to the history and will track future updates to the file.
This example introduced two additional git commands: and . This was a very limited example, but both commands are covered more in depth on the git add and pages. Another common use case for is the option. Executing will take any changed and untracked files in the repo and add them to the repo and update the repo’s working tree.
Как проанализировать рынок фотостудий с помощью Python (1/3). Парсинг данных
В интернете огромное количество открытых данных. При правильном сборе и анализе информации можно решить важные бизнес-задачи. Например, стоит ли открыть свой бизнес?
С таким вопросом ко мне обратились клиенты, желающие получить аналитику рынка услуг фотостудий
Для них было важно понять: стоит ли открывать фотостудию, где отрыть, какая площадь помещения, сколько залов открыть вначале, в какой месяц лучше стартовать и многие другие вопросы.
По итогу выполнения проекта написал серию статей с подробным поэтапным описанием выполняемых задач, используемых инструментов и полученных результатов. В данной статье, первой из трех, опишу планирование и написание парсинга на Python.
Во второй статье опишу алгоритм взаимодействия парсинга с базой данных и обновления данных.
В третьей статье рассмотрю процесс анализа собранных данных и ответы на вопросы клиента, желающего открыть фотостудию
Repo-to-repo collaboration: git push
It’s important to understand that Git’s idea of a “working copy” is very different from the working copy you get by checking out source code from an SVN repository. Unlike SVN, Git makes no distinction between the working copies and the central repository—they’re all full-fledged Git repositories.
This makes collaborating with Git fundamentally different than with SVN. Whereas SVN depends on the relationship between the central repository and the working copy, Git’s collaboration model is based on repository-to-repository interaction. Instead of checking a working copy into SVN’s central repository, you push or pull commits from one repository to another.
Of course, there’s nothing stopping you from giving certain Git repos special meaning. For example, by simply designating one Git repo as the “central” repository, it’s possible to replicate a centralized workflow using Git. This is accomplished through conventions rather than being hardwired into the VCS itself.
Bare vs. cloned repositories
If you used in the previous «Initializing a new Repository» section to set up your local repository, your repository is already configured for remote collaboration. will automatically configure your repo with a remote pointed to the Git URL you cloned it from. This means that once you make changes to a file and commit them, you can those changes to the remote repository.
If you used to make a fresh repo, you’ll have no remote repo to push changes to. A common pattern when initializing a new repo is to go to a hosted Git service like Bitbucket and create a repo there. The service will provide a Git URL that you can then add to your local Git repository and to the hosted repo. Once you have created a remote repo with your service of choice you will need to update your local repo with a mapping. We discuss this process in the Configuration & Set Up guide below.
If you prefer to host your own remote repo, you’ll need to set up a «Bare Repository.» Both and accept a argument. The most common use case for bare repo is to create a remote central Git repository
Не хочу Visual Studio Code: 7 open source альтернатив
Перевод
В этом переводе расскажем про альтернативные редакторы кода, которые ничуть не уступают VS Code, а при грамотном подборе расширений даже превосходят его.
Редактор Visual Studio Code, также известный как VS Code работает на Linux, Windows и macOS. Он занимает промежуточное положение между простым текстовым редактором исходного кода и интегрированной средой разработки (IDE), которая управляет всей вашей кодовой базой. Функциональность VS Code можно расширить с помощью плагинов. Это надёжный редактор кода, который может достойно побороться с проприетарными конкурентами.
Изначально VS Code был создан как open source продукт. Однако его готовые сборки распространяются под проприетарной лицензией Microsoft. Но не всё так плохо.
GitHub Actions
Create a GitHub Action and use it in a workflow.
GitHub Actions
Workflows
Hello World
GitHub Actions: Continuous Integration
Learn how to create workflows that enable you to use Continuous Integration (CI) for your projects.
GitHub Actions
Workflows
CI
Continuous Integration
Integration
GitHub Actions: Publish to GitHub Packages
This course will walk you through using GitHub Actions to get your code in a deployable state once your CI workflows have completed.
GitHub Actions
GitHub Packages
Deployment
Workflows
Docker
Create two deployment workflows using AWS.
GitHub Actions
Workflows
CD
Amazon Web Services (AWS)
Deployment
GitHub Actions: Continuous Delivery with Azure
Create two deployment workflows using GitHub Actions and Microsoft Azure.
GitHub Actions
Microsoft Azure
Workflows
CD
Deployment
GitHub Actions: Writing JavaScript Actions
Learn how to write your own GitHub JavaScript Action! This course will empower you to begin automating customized tasks unique to your workflow.
JavaScript
API
Actions toolkit
GitHub Secrets
Workflows
GitHub Actions: Write Docker container actions
Learn how to write your own GitHub Docker container action! This course will empower you to begin automating customized tasks unique to your workflow.
Docker
Containers
Workflows
Application programming interface (API)
Publishing GitHub Actions
GitHub Actions: Using GitHub Script
This course covers how to use GitHub Script to quickly use octokit/rest in a GitHub Actions workflow.
GitHub Actions
Octokit
Workflow
Automation
Application programming interface (API)
Использование
Уровни и файлы git config
Прежде чем рассматривать использование , поговорим немного об уровнях конфигурации. Чтобы указать уровень конфигурации, на котором производится работа, к команде можно добавить аргументы. Доступны следующие уровни конфигурации:
—local
По умолчанию, если не были переданы опции конфигурации, команда будет вести запись на локальном уровне. Конфигурация локального уровня применяется к репозиторию, в котором вызывается команда . Значения локальной конфигурации хранятся в файле, который находится в каталоге .git репозитория: .
—global
Конфигурация глобального уровня зависит от пользователя, то есть применяется к пользователю операционной системы. Значения глобальной конфигурации хранятся в файле, который находится в домашнем каталоге пользователя. Это в Unix-системах и в системах Windows.
—system
Конфигурация уровня системы применяется ко всей машине. Она охватывает всех пользователей операционной системы и все репозитории. Конфигурация уровня системы указывается в файле в корневой папке системы. В Unix-системах это , в системах Windows файл находится в для Windows XP и в для Windows Vista и более новых версий.
Итак, порядок приоритета уровней конфигурации следующий: локальный, глобальный, системный. Это значит, что при поиске значения конфигурации система Git будет начинать с локального уровня и подниматься до уровня системы.
git init templates
Initializes a new Git repository and copies files from the into the repository.
Templates allow you to initialize a new repository with a predefined subdirectory. You can configure a template to have default directories and files that will get copied to a new repository’s subdirectory. The default Git templates usually reside in a directory but may be a different path on your machine.
The default templates are a good reference and example of how to utilize template features. A powerful feature of templates that’s exhibited in the default templates is Git Hook configuration. You can create a template with predefined Git hooks and initialize your new git repositories with common hooks ready to go. Learn more about Git Hooks at the Git Hook page.
GitHub
GitHub — это платформа, которая хранит Git-репозитории на своих множественных серверах. Как пользователь GitHub вы можете хранить свои удалённые репозитории на их серверах, а также вносить вклад в другие open-source репозитории. GitHub дополняет использование Git некоторыми новыми возможностями.
Например, вы можете сделать форк удалённого репозитория, то есть создать свою копию репозитория на севере GitHub. Это полезно в тех случаях, когда у вас нет прав на создание ветки в оригинальном репозитории. Когда вы воспользуетесь командой , ваш локальный репозиторий будет отслеживать удалённый форк как origin, а оригинальный репозиторий как upstream.
После этого вам может понадобиться слить тематическую ветку вашего удалённого репозитория в основную ветку оригинального. Для этого вы можете создать новый Pull Request — запрос на внесение изменений, где GitHub проверяет наличие конфликтов прежде чем повзолить вам провести слияние. Зачастую существуют и другие проверки перед слиянием, например просмотр и одобрение кода или даже запуск тестов. В запросе можно обсудить код, а все коммиты, которые вы отправляете в удалённую тематическую ветку, будут автоматически добавлены в запрос, даже если он был создан до этих коммитов.
Вариант 1. Я уже знаком с терминалом
Вот как начать работу с Git из терминала.
Если у вас есть директория проекта, то просто перейдите в терминал, а в самой директории проекта выполните команду
git init
Если хотите инициализировать проект со всеми файлами из директории проекта, то выполните команду
git init
Допустим, в вашем проекте есть папка . Вы можете перейти в нее из окна терминала и добавить локальный репозиторий. Это делается через следующую команду:
cd new_projectgit init
В вашем проекте появилась новая скрытая директория с названием. Именно здесь Git хранит все, что ему нужно для отслеживания проекта. Теперь вы можете последовательно добавлять файлы в область подготовки:
git add <имя_первого_файла>
или добавьте сразу все файлы через:
git add .
Создать коммит с этими изменениями можно через команду:
git commit -m “<сообщение_коммита>”
Если изменения вас устраивают, напишите:
git push
и отправьте эти изменения в репозиторий. Проверить, есть ли изменения для отправки, можно в любое время по команде:
git status
При внесении изменений следует обновить и сами файлы:
git add <имя_файла>
или
git add — all
Создайте коммит, добавьте нужное сообщение и отправьте этот коммит в репозиторий.
Вот и все! Теперь вы можете инициализировать репозиторий, создавать коммиты с файлами и сообщениями, а также отправлять коммиты в ветку .
Если с этим все понятно, то переходите к части 2: «Учимся работать с другими», в которой рассматривается градация веток и совместная работа над проектами.
Configuration & set up: git config
Once you have a remote repo setup, you will need to add a remote repo url to your local , and set an upstream branch for your local branches. The command offers such utility.
This command will map remote repository at to a ref in your local repo under . Once you have mapped the remote repo you can push local branches to it.
This command will push the local repo branch under to the remote repo at .
For more in-depth look at , see the .
Git stores configuration options in three separate files, which lets you scope options to individual repositories (local), user (Global), or the entire system (system):
- Local: – Repository-specific settings.
- Global: – User-specific settings. This is where options set with the —global flag are stored.
- System: – System-wide settings.
Define the author name to be used for all commits in the current repository. Typically, you’ll want to use the flag to set configuration options for the current user.
Define the author name to be used for all commits by the current user.
Adding the option or not passing a config level option at all, will set the for the current local repository.
Create a shortcut for a Git command. This is a powerful utility to create custom shortcuts for commonly used git commands. A simplistic example would be:
This creates a command that you can execute as a shortcut to . To learn more about git aliases visit the page.
Define the text editor used by commands like for all users on the current machine. The argument should be the command that launches the desired editor (e.g., vi). This example introduces the option. The option will set the configuration for the entire system, meaning all users and repos on a machine. For more detailed information on configuration levels visit the git config page.
Open the global configuration file in a text editor for manual editing. An in-depth guide on how to configure a text editor for git to use can be found on the Git config page.
Discussion
Git stores configuration options in three separate files, which lets you scope options to individual repositories, users, or the entire system:
- – Repository-specific settings.
- – User-specific settings. This is where options set with the —global flag are stored.
- – System-wide settings.
When options in these files conflict, local settings override user settings, which override system-wide. If you open any of these files, you’ll see something like the following:
You can manually edit these values to the exact same effect as .
Example
Tell Git who you are
Select your favorite text editor
Add some SVN-like aliases
This will produce the file from the previous section. Take a more in-depth look at git config on the git config page.
«Конституция» для разработчиков: как страничка на GitHub помогает нам не ругаться уже год
Год назад моя команда выросла: усложнялась бизнес-логика, по сути, мы делились на три подкоманды — в каждой были как новички, так и те, кто работал в компании годами. Подкоманды сфокусировались на своих направлениях, и хотя все пилили биллинг, перестал работать принцип общей зоны ответственности. Да и практики, которые работали у «старичков», не всегда подходили новому коллективу.
Обычно для сплочения команд мы практикуем выезды: ребята, в остальное время работающие на удаленке из своих городов, собираются в одной точке мира. Днем вместе проходят часть спринта, вечером вместе развлекаются. Но сроки поджимали, поэтому мы пошли другим путем. Вот что мы придумали — и кажется, такой подход может использовать любая команда, в которой нет авторитарного управления.
Our most popular courses
Introduction to GitHub
If you are looking for a quick and fun introduction to GitHub, you’ve found it. This class will get you started using GitHub in less than an hour.
Git
GitHub Pages
Branches
Commits
Pull Requests
Create a GitHub Action and use it in a workflow.
GitHub Actions
Workflows
Hello World
Communicating using Markdown
This course will walk you through everything you need to start organizing ideas and collaborating using Markdown, a lightweight language for text formatting.
GitHub
Markdown
Learning should be fun
There are no simulations or boring tutorials here, just hands-on lessons created with by the GitHub community and taught by the friendly Learning Lab bot.
Step 4. Open a Pull Request
Nice edits! Now that you have changes in a branch off of , you can open a pull request.
Pull Requests are the heart of collaboration on GitHub. When you open a pull request, you’re proposing your changes and requesting that someone review and pull in your contribution and merge them into their branch. Pull requests show diffs, or differences, of the content from both branches. The changes, additions, and subtractions are shown in green and red.
As soon as you make a commit, you can open a pull request and start a discussion, even before the code is finished.
By using GitHub’s in your pull request message, you can ask for feedback from specific people or teams, whether they’re down the hall or 10 time zones away.
You can even open pull requests in your own repository and merge them yourself. It’s a great way to learn the GitHub flow before working on larger projects.
Open a Pull Request for changes to the README
Click on the image for a larger version
Step | Screenshot |
---|---|
Click the Pull Request tab, then from the Pull Request page, click the green New pull request button. | ![]() |
In the Example Comparisons box, select the branch you made, , to compare with (the original). | ![]() |
Look over your changes in the diffs on the Compare page, make sure they’re what you want to submit. | ![]() |
When you’re satisfied that these are the changes you want to submit, click the big green Create Pull Request button. | ![]() |
Give your pull request a title and write a brief description of your changes. | ![]() |
When you’re done with your message, click Create pull request!
The git config editor — core.editor
When your identity is set up, Git uses your system’s default editor, which is Vi or Vim. The git config sets up which editor Git will use. Here is the list of most common editors with git config commands:
Editor | Config Command |
---|---|
Atom | git config --global core.editor "atom --wait" |
emacs | git config --global core.editor "emacs" |
nano | git config --global core.editor "nano -w" |
vim | git config --global core.editor "vim" |
Sublime Text (Mac) | git config --global core.editor "subl -n -w" |
Sublime Text (Win, 32-bit install) | git config --global core.editor "'c:/program files (x86)/sublime text 3/sublimetext.exe' -w" |
Sublime Text (Win, 64-bit install) | git config --global core.editor "'c:/program files/sublime text 3/sublimetext.exe' -w" |
Textmate | git config --global core.editor "mate -w" |
Bare repositories — git init —bare
Initialize an empty Git repository, but omit the working directory. Shared repositories should always be created with the flag (see discussion below). Conventionally, repositories initialized with the flag end in . For example, the bare version of a repository called should be stored in a directory called .
The flag creates a repository that doesn’t have a working directory, making it impossible to edit files and commit changes in that repository. You would create a bare repository to git push and git pull from, but never directly commit to it. Central repositories should always be created as bare repositories because pushing branches to a non-bare repository has the potential to overwrite changes. Think of as a way to mark a repository as a storage facility, as opposed to a development environment. This means that for virtually all Git workflows, the central repository is bare, and developers local repositories are non-bare.
The most common use case for is to create a remote central repository:
First, you SSH into the server that will contain your central repository. Then, you navigate to wherever you’d like to store the project. Finally, you use the flag to create a central storage repository. Developers would then clone to create a local copy on their development machine.