Initial commit

This commit is contained in:
chris
2025-03-07 15:21:52 +00:00
commit cb750faca6
982 changed files with 129235 additions and 0 deletions

View File

@@ -0,0 +1,329 @@
# Introduction to GitHub
This lesson covers the basics of GitHub, a platform to host and manage changes to your code.
![Intro to GitHub](../../sketchnotes/webdev101-github.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Pre-Lecture Quiz
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Introduction
In this lesson, we'll cover:
- tracking the work you do on your machine
- working on projects with others
- how to contribute to open source software
### Prerequisites
Before you begin, you'll need to check if Git is installed. In the terminal type:
`git --version`
If Git is not installed, [download Git](https://git-scm.com/downloads). Then, setup your local Git profile in the terminal:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
To check if Git is already configured you can type:
`git config --list`
You'll also need a GitHub account, a code editor (like Visual Studio Code), and you'll need to open your terminal (or: command prompt).
Navigate to [github.com](https://github.com/) and create an account if you haven't already, or log in and fill out your profile.
✅ GitHub isn't the only code repository in the world; there are others, but GitHub is the best known
### Preparation
You'll need both a folder with a code project on your local machine (laptop or PC), and a public repository on GitHub, which will serve as an example for how to contribute to the projects of others.
---
## Code management
Let's say you have a folder locally with some code project and you want to start tracking your progress using git - the version control system. Some people compare using git to writing a love letter to your future self. Reading your commit messages days or weeks or months later you'll be able to recall why you made a decision, or "rollback" a change - that is, when you write good "commit messages".
### Task: Make a repository and commit code
> Check out video
>
> [![Git and GitHub basics video](https://img.youtube.com/vi/9R31OUPpxU4/0.jpg)](https://www.youtube.com/watch?v=9R31OUPpxU4)
1. **Create repository on GitHub**. On GitHub.com, in the repositories tab, or from the navigation bar top-right, find the **new repo** button.
1. Give your repository (folder) a name
1. Select **create repository**.
1. **Navigate to your working folder**. In your terminal, switch to the folder (also known as the directory) you want to start tracking. Type:
```bash
cd [name of your folder]
```
1. **Initialize a git repository**. In your project type:
```bash
git init
```
1. **Check status**. To check the status of your repository type:
```bash
git status
```
the output can look something like this:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Typically a `git status` command tells you things like what files are ready to be _saved_ to the repo or has changes on it that you might want to persist.
1. **Add all files for tracking**
This also called as staging files/ adding files to the staging area.
```bash
git add .
```
The `git add` plus `.` argument indicates that all your files & changes for tracking.
1. **Add selected files for tracking**
```bash
git add [file or folder name]
```
This helps us to add only selected files to the staging area when we don't want to commit all files at once.
1. **Unstage all files**
```bash
git reset
```
This command helps us to unstage all files at once.
1. **Unstage a particular file**
```bash
git reset [file or folder name]
```
This command helps us to unstage only a particular file at once that we don't want to include for the next commit.
1. **Persisting your work**. At this point you've added the files to a so called _staging area_. A place where Git is tracking your files. To make the change permanent you need to _commit_ the files. To do so you create a _commit_ with the `git commit` command. A _commit_ represents a saving point in the history of your repo. Type the following to create a _commit_:
```bash
git commit -m "first commit"
```
This commits all of your files, adding the message "first commit". For future commit messages you will want to be more descriptive in your description to convey what type of change you've made.
1. **Connect your local Git repo with GitHub**. A Git repo is good on your machine but at some point you want to have backup of your files somewhere and also invite other people to work with you on your repo. One such great place to do so is GitHub. Remember we've already created a repo on GitHub so the only thing we need to do is to connect our local Git repo with GitHub. The command `git remote add` will do just that. Type the following command:
> Note, before you type the command go to your GitHub repo page to find the repository URL. You will use it in the below command. Replace ```https://github.com/username/repository_name.git``` with your GitHub URL.
```bash
git remote add origin https://github.com/username/repository_name.git
```
This creates a _remote_, or connection, named "origin" pointing at the GitHub repository you created earlier.
1. **Send local files to GitHub**. So far you've created a _connection_ between the local repo and the GitHub repo. Let's send these files to GitHub with the following command `git push`, like so:
> Note, your branch name may be different by default from ```main```.
```bash
git push -u origin main
```
This sends your commits in your "main" branch to GitHub.
2. **To add more changes**. If you want to continue making changes and pushing them to GitHub youll just need to use the following three commands:
```bash
git add .
git commit -m "type your commit message here"
git push
```
> Tip, You might also want to adopt a `.gitignore` file to prevent files you don't want to track from showing up on GitHub - like that notes file you store in the same folder but has no place on a public repository. You can find templates for `.gitignore` files at [.gitignore templates](https://github.com/github/gitignore).
#### Commit messages
A great Git commit subject line completes the following sentence:
If applied, this commit will <your subject line here>
For the subject use the imperative, present tense: "change" not "changed" nor "changes".
As in the subject, in the body (optional) also use the imperative, present tense. The body should include the motivation for the change and contrast this with previous behavior. You're explaining the `why`, not the `how`.
✅ Take a few minutes to surf around GitHub. Can you find a really great commit message? Can you find a really minimal one? What information do you think is the most important and useful to convey in a commit message?
### Task: Collaborate
The main reason for putting things on GitHub was to make it possible to collaborate with other developers.
## Working on projects with others
> Check out video
>
> [![Git and GitHub basics video](https://img.youtube.com/vi/bFCM-PC3cu8/0.jpg)](https://www.youtube.com/watch?v=bFCM-PC3cu8)
In your repository, navigate to `Insights > Community` to see how your project compares to recommended community standards.
Here are some things that can improve your GitHub repo:
- **Description**. Did you add a description for your project?
- **README**. Did you add a README? GitHub provides guidance for writing a [README](https://docs.github.com/articles/about-readmes/?WT.mc_id=academic-77807-sagibbon).
- **Contributing guideline**. Does your project have [contributing guidelines](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/?WT.mc_id=academic-77807-sagibbon),
- **Code of Conduct**. a [Code of Conduct](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **License**. Perhaps most importantly, a [license](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
All these resources will benefit onboarding new team members. And those are typically the kind of things new contributors look at before even looking at your code, to find out if your project is the right place for them to be spending their time.
✅ README files, although they take time to prepare, are often neglected by busy maintainers. Can you find an example of a particularly descriptive one? Note: there are some [tools to help create good READMEs](https://www.makeareadme.com/) that you might like to try.
### Task: Merge some code
Contributing docs help people contribute to the project. It explains what types of contributions you're looking for and how the process works. Contributors will need to go through a series of steps to be able to contribute to your repo on GitHub:
1. **Forking your repo** You will probably want people to _fork_ your project. Forking means creating a replica of your repository on their GitHub profile.
1. **Clone**. From there they will clone the project to their local machine.
1. **Create a branch**. You will want to ask them to create a _branch_ for their work.
1. **Focus their change on one area**. Ask contributors to concentrate their contributions on one thing at a time - that way the chances that you can _merge_ in their work is higher. Imagine they write a bug fix, add a new feature, and update several tests - what if you want to, or can only implement 2 out of 3, or 1 out of 3 changes?
✅ Imagine a situation where branches are particularly critical to writing and shipping good code. What use cases can you think of?
> Note, be the change you want to see in the world, and create branches for your own work as well. Any commits you make will be made on the branch youre currently “checked out” to. Use `git status` to see which branch that is.
Let's go through a contributor workflow. Assume the contributor has already _forked_ and _cloned_ the repo so they have a Git repo ready to be worked on, on their local machine:
1. **Create a branch**. Use the command `git branch` to create a branch that will contain the changes they mean to contribute:
```bash
git branch [branch-name]
```
1. **Switch to working branch**. Switch to the specified branch and update the working directory with `git switch`:
```bash
git switch [branch-name]
```
1. **Do work**. At this point you want to add your changes. Don't forget to tell Git about it with the following commands:
```bash
git add .
git commit -m "my changes"
```
Ensure you give your commit a good name, for your sake as well as the maintainer of the repo you are helping on.
1. **Combine your work with the `main` branch**. At some point you are done working and you want to combine your work with that of the `main` branch. The `main` branch might have changed meanwhile so make sure you first update it to the latest with the following commands:
```bash
git switch main
git pull
```
At this point you want to make sure that any _conflicts_, situations where Git can't easily _combine_ the changes happens in your working branch. Therefore run the following commands:
```bash
git switch [branch_name]
git merge main
```
This will bring in all changes from `main` into your branch and hopefully you can just continue. If not, VS Code will tell you where Git is _confused_ and you just alter the affected files to say which content is the most accurate.
1. **Send your work to GitHub**. Sending your work to GitHub means two things. Pushing your branch to your repo and then open up a PR, Pull Request.
```bash
git push --set-upstream origin [branch-name]
```
The above command creates the branch on your forked repo.
1. **Open a PR**. Next, you want to open up a PR. You do that by navigating to the forked repo on GitHub. You will see an indication on GitHub where it asks whether you want to create a new PR, you click that and you are taken to an interface where you can change commit message title, give it a more suitable description. Now the maintainer of the repo you forked will see this PR and _fingers crossed_ they will appreciate and _merge_ your PR. You are now a contributor, yay :)
1. **Clean up**. It's considered good practice to _clean up_ after you successfully merge a PR. You want to clean up both your local branch and the branch you pushed to GitHub. First let's delete it locally with the following command:
```bash
git branch -d [branch-name]
```
Ensure you go the GitHub page for the forked repo next and remove the remote branch you just pushed to it.
`Pull request` seems like a silly term because really you want to push your changes to the project. But the maintainer (project owner) or core team needs to consider your changes before merging it with the project's "main" branch, so you're really requesting a change decision from a maintainer.
A pull request is the place to compare and discuss the differences introduced on a branch with reviews, comments, integrated tests, and more. A good pull request follows roughly the same rules as a commit message. You can add a reference to an issue in the issue tracker, when your work for instance fixes an issue. This is done using a `#` followed by the number of your issue. For example `#97`.
🤞Fingers crossed that all checks pass and the project owner(s) merge your changes into the project🤞
Update your current local working branch with all new commits from the corresponding remote branch on GitHub:
`git pull`
## How to contribute to open source
First, let's find a repository (or **repo**) on GitHub of interest to you and to which you'd like to contribute a change. You will want to copy its contents to your machine.
✅ A good way to find 'beginner-friendly' repos is to [search by the tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copy a repo locally](images/clone_repo.png)
There are several ways of copying code. One way is to "clone" the contents of the repository, using HTTPS, SSH, or using the GitHub CLI (Command Line Interface).
Open your terminal and clone the repository like so:
`git clone https://github.com/ProjectURL`
To work on the project, switch to the right folder:
`cd ProjectURL`
You can also open the entire project using [Codespaces](https://github.com/features/codespaces), GitHub's embedded code editor / cloud development environment, or [GitHub Desktop](https://desktop.github.com/).
Lastly, you can download the code in a zipped folder.
### A few more interesting things about GitHub
You can star, watch and/or "fork" any public repository on GitHub. You can find your starred repositories in the top-right drop-down menu. It's like bookmarking, but for code.
Projects have an issue tracker, mostly on GitHub in the "Issues" tab unless indicated otherwise, where people discuss issues related to the project. And the Pull Requests tab is where people discuss and review changes that are in progress.
Projects might also have discussion in forums, mailing lists, or chat channels like Slack, Discord or IRC.
✅ Take a look around your new GitHub repo and try a few things, like editing settings, adding information to your repo, and creating a project (like a Kanban board). There's a lot you can do!
---
## 🚀 Challenge
Pair with a friend to work on each other's code. Create a project collaboratively, fork code, create branches, and merge changes.
## Post-Lecture Quiz
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Review & Self Study
Read more about [contributing to open source software](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Practice, practice, practice. GitHub has great learning paths available via [skills.github.com](https://skills.github.com):
- [First Week on GitHub](https://skills.github.com/#first-week-on-github)
You'll also find more advanced courses.
## Assignment
Complete [the First Week on GitHub course](https://skills.github.com/#first-week-on-github)

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View File

@@ -0,0 +1,332 @@
# Introducción a GitHub
Esta lección cubre los conceptos básicos de GitHub, una plataforma para alojar y administrar cambios en tu código.
![Introducción a GitHub](/sketchnotes/webdev101-github.png)
> Dibujo de [Tomomi Imura](https://twitter.com/girlie_mac)
## [Cuestionario previo a la clase](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
### Introducción
En esta lección, cubriremos:
- Seguimiento de trabajo que se realiza en su máquina.
- Trabajar en proyectos con otros.
- Cómo contribuir al software de código abierto (Open Source)
### Prerrequisitos
Antes de comenzar, debemos verificar si Git está instalado. Escribe en tu terminal:
`git --version`
Si Git no está instalado, [descargue Git desde aquí](https://git-scm.com/downloads). Luego, configure su perfil de Git local en la terminal:
`git config --global user.name "tu-nombre"`
`git config --global user.email "tu-email"`
Para comprobar si Git ya está configurado, escribe:
`git config --list`
También necesitarás una cuenta de GitHub, un editor de código (como Visual Studio Code) una terminal (también conocida como línea de comandos o símbolo del sistema).
Ve a [GitHub.com](https://github.com/) y crea una cuenta si aún no lo has hecho, o inicia sesión y completa tu perfil.
✅ GitHub no es el único lugar para almacenar código; hay otros, pero GitHub es el más conocido.
### Preparación
Necesitarás un directorio con un proyecto de código en tu máquina local (computadora portátil o PC) y un repositorio público en GitHub, que te servirá como ejemplo de cómo contribuir a los proyectos de otros.
---
## Gestión de código
Digamos que tienes una directorio local con algún proyecto de código y deseas rastrear tu progreso usando git (sistema de control de versiones). Algunas personas comparan el uso de git con escribir una carta de amor a tu futuro. Al leer tus mensajes de confirmación días, semanas o meses después, podrás recordar por qué tomaste una decisión o "revertiste" un cambio, siempre y cuando escribas buenos mensajes a la hora de enviar un commit.
### Tarea: Hacer un repositorio git y enviar código
> Revisa este video
>
> [![Video de los conceptos básicos de Git y GitHub](https://img.youtube.com/vi/9R31OUPpxU4/0.jpg)](https://www.youtube.com/watch?v=9R31OUPpxU4)
1. **Crear repositorio en GitHub**. En GitHub.com, en la pestaña de repositorios, o en la barra de navegación superior derecha, busca el botón **nuevo repositorio**.
1. Dale un nombre a tu repositorio (directorio)
1. Selecciona **Crear Repositorio**.
1. **Navegue a su directorio de trabajo**. En su terminal, navegue hasta el directorio donde tiene su proyecto que deseas comenzar a rastrear. Escribe:
```bash
cd [nombre de su directorio]
```
1. **Inicializar un repositorio de git**. En su proyecto escribe:
```bash
git init
```
1. **Comprobar estado**. Para comprobar el estado del proyecto escribe:
```bash
git status
```
La respuesta de la terminal (CLI) probablemente se verá así:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Por lo general, el comando `git status` nos avisa qué archivos están listos para ser guardados en el repositorio o cambios en tu codigo que puedes conservar.
1. **Agregar archivos al seguimiento**
```bash
git add .
```
El comando `git add` más `.` indica que todos tus archivos y cambios están listos para darles seguimiento.
1. **Agregar archivos puntuales**
```bash
git add [nombre de archivo o carpeta]
```
Esto nos ayuda a agregar solo los archivos seleccionados al área de preparación cuando no queremos confirmar todos los archivos a la vez.
1. **Eliminar archivos de la zona de staging**
```bash
git reset
```
Este comando nos ayuda a eliminar todos los archivos a la vez.
1. **Quitar un archivo en particular**
```bash
git reset [nombre del archivo o carpeta]
```
Este comando nos ayuda a eliminar un archivo/directorio puntual, para que éste no sea enviado en el próximo commit.
1. **Persistir en tu trabajo**. En este punto, has agregado los archivos a lo que se denomina _stagin area_. Un lugar donde Git rastrea tus archivos. Para que el cambio sea permanente, debes realizar un _commit_. Para hacerlo, utilizas el siguiente commando `git commit`. Un _commit_ representa un punto en el historial de tu repositorio que estás guardando, este viene acompañado de un mensaje, el cual nos sirve para saber que cambios se hicieron dentro de ese commit. Ejecuta el siguiente comando para realizar tu primer commit.
```bash
git commit -m "first commit"
```
Esto confirma todos tus archivos, agregando el mensaje "first commit". Para futuros mensajes de confirmación, querrás ser más descriptivo en tu descripción para transmitir qué tipo de cambio has realizado.
1. **Conecta tu repositorio de Git local con GitHub**. Es bueno tener un repositorio de Git en tu máquina, pero también tienes que guardar todos estos archivos en algún lugar e invitar a otras personas a trabajar contigo en tu repositorio. Un buen lugar para hacerlo es GitHub. Recuerda que ya hemos creado un repositorio en GitHub, por lo que lo único que debemos hacer es conectar nuestro repositorio de Git local con GitHub. El comando `git remote add` hará precisamente eso. Escribe el siguiente comando:
> Nota, antes de escribir el comando, ve a la página de tu repositorio de GitHub para encontrar el URL del repositorio. Lo usarás en el siguiente comando. Reemplaza `repository_name` con tu URL de GitHub.
```bash
git remote add origin https://github.com/USUARIO/NOMBRE_DEL_REPOSITORIO.git
```
Esto crea un _remote_, o conexión, llamado "origin" que apunta al repositorio de GitHub que creaste anteriormente.
Si tienes una conexión previa con algún "origin" y deseas cambiar la dirección puedes utilizar el siguiente comando:
```bash
git remote set-url https://github.com/USUARIO/NOMBRE DEL REPOSITORIO.git
```
1. **Envía archivos locales a GitHub**. Hasta ahora ha creado una _conexión_ entre el repositorio local y el repositorio de GitHub. Enviemos estos archivos a GitHub con el siguiente comando `git push`, así:
```bash
git push -u origin main
```
Esto envía una confirmación en tu rama "main" en GitHub.
1. **Para agregar más cambios**. Si deseas continuar haciendo cambios y enviarlos a GitHub, solo necesitas usar los siguientes tres comandos:
```bash
git add .
git commit -m "escribe tu mensaje de confirmación aquí"
git push
```
> Sugerencia: es posible que también desees adoptar un archivo `.gitignore` para evitar que los archivos que no deseas rastrear aparezcan en GitHub. Puedes encontrar plantillas para archivos `.gitignore` en [.gitignore templates](https://github.com/github/gitignore).
#### Confirmar mensajes
Una buena línea de asunto (subject line), completa la siguiente frase: "Si se aplica, este commit hará..."
Para el asunto use el imperativo, tiempo presente: "cambiar" no "cambió" ni "cambiará".
Como en el asunto, en el cuerpo (opcional) también use el presente imperativo. El cuerpo debe incluir el motivo del cambio y contrastarlo con el funcionamiento previo. Estás explicando el "por qué", no el "cómo".
✅ Tómate unos minutos para navegar por GitHub. ¿Puedes encontrar un mensaje de commit realmente bueno? ¿Puedes hallar uno aún más simple? ¿Qué información crees que es la más importante y útil de transmitir en un mensaje de commit?
### Tarea: Colaborar
La razón principal para poner cosas en GitHub fue hacer posible la colaboración con otros desarrolladores.
## Trabajando en proyectos con otros
> Revisa este video
>
> [![Video de los conceptos básicos de Git y GitHub](https://img.youtube.com/vi/bFCM-PC3cu8/0.jpg)](https://www.youtube.com/watch?v=bFCM-PC3cu8)
En tu repositorio, ve a `Insights > Community` para ver cómo se compara tu proyecto con los estándares comunitarios recomendados.
Aquí hay algunas cosas que pueden mejorar tu repositorio de GitHub:
- **Descripción**. ¿Agregaste una descripción para tu proyecto?
- **README**. ¿Agregaste un archivo README? GitHub proporciona una guía para escribir un [README](https://docs.github.com/articles/about-readmes/).
- **Guía de contribución**. ¿Tiene [guías de contribución](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/) tu proyecto?
- **Código de Conducta**. Crea un [Código de conducta](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/).
- **Licencia**. Quizás lo más importante, una [licencia](https://docs.github.com/articles/adding-a-license-to-a-repository/).
Todos estos recursos beneficiarán la incorporación de nuevos miembros del equipo. Y esos son típicamente el tipo de cosas que los nuevos colaboradores miran antes incluso de mirar tu código, para descubrir si tu proyecto es el lugar adecuado para que ellos pasen su tiempo.
✅ Los archivos README, aunque requieren tiempo para prepararse, a menudo son descuidados por los mantenedores. ¿Puedes encontrar un ejemplo de uno particularmente descriptivo? Nota: aquí hay algunas [herramientas para ayudar a crear buenos archivos READMEs](https://www.makeareadme.com/) que te puedes probar.
### Tarea: Fusionar (merging) código
Los documentos de contribución ayudan a las personas a contribuir al proyecto. Explica qué tipos de contribuciones estás buscando y cómo funciona el proceso. Los colaboradores deberán seguir una serie de pasos para poder contribuir a tu repositorio en GitHub:
1. **Bifurcando (forking) tu repositorio** Probablemente querrás que la gente _bifurque_ (fork) tu proyecto. Bifurcar significa crear una réplica de tu repositorio en su perfil de GitHub.
1. **Clonar**. Desde allí, clonarán el proyecto en su máquina local.
1. **Crear una rama**. Querrás pedirles que creen una _rama_ para su trabajo.
1. **Concentre su cambio en un área**. Pida a los colaboradores que concentren sus contribuciones en una cosa a la vez; de esa manera, las posibilidades de _fusionar_ su trabajo son mayores. Imagínate que escriben una corrección de errores, agregan una nueva función y actualizan varias pruebas; ¿qué sucede si quieres todos los cambios o solo puedes implementar 2 de 3 ó 1 de 3 cambios?
✅ Imagínate una situación en la que las ramas (branches) de git son particularmente críticas para escribir y enviar buen código. ¿Qué casos de uso se te ocurren?
> Sé el cambio que deseas ver en el mundo y crea también ramas para tu propio trabajo. Todos los commits que hagas se realizarán en la rama en la que estás actualmente "registrado". Usa `git status` para ver qué rama es.
Repasemos el flujo de trabajo de un colaborador. Supongamos que el colaborador ya ha _bifurcado_ y _clonado_ el repositorio para que tenga un repositorio de Git listo para trabajar en su máquina local:
1. **Crea una rama**. Usa el comando `git branch` para crear una rama que tendrá los cambios que quieres contribuir:
```bash
git branch [branch-name]
```
1. **Cambiar a rama de trabajo**. Cambia a la rama especificada y actualiza tu directorio de trabajo con `git switch`:
```bash
git switch [branch-name]
```
1. **Trabaja**. En este punto, deseas agregar tus cambios. No olvides informarle a Git con los siguientes comandos:
```bash
git add .
git commit -m "mis cambios"
```
Asegúrate de darle un buen nombre a tu commit, tanto por tu bien como por el del mantenedor del repositorio en el que estás ayudando.
1. **Combina tu trabajo con la rama `principal`**. En algún momento has terminado de trabajar y deseas combinar tu trabajo con el de la rama `principal`. La rama `main` podría haber cambiado mientras tanto, así que asegúrate de actualizarla con los siguientes comandos:
```bash
git switch main
git pull
```
En este punto, querrás asegurarte de que cualquier _conflicto_, situaciones en las que Git no pueda _combinarse_ fácilmente los cambios, ocurran en tu rama de trabajo. Por lo tanto, ejecuta los siguientes comandos:
```bash
git switch [branch_name]
git merge main
```
Esto traerá todos los cambios de `main` a su rama y es de esperar que pueda continuar. De lo contrario, VS Code le dirá dónde está _confundido_ Git y simplemente modificará los archivos afectados para decir qué contenido es el más preciso.
1. **Envía tu trabajo a GitHub**. Enviar tu trabajo a GitHub significa dos cosas. Empujar tu rama a tu repositorio y luego abrir un PR (Pull Request).
```bash
git push --set-upstream origin [branch-name]
```
El comando anterior crea la rama en tu repositorio bifurcado.
2. **Abre un Pull Request**. A continuación, abre un PR. Para hacerlo, navega al repositorio bifurcado en GitHub. Verás una indicación en GitHub donde te preguntarán si deseas crear un nuevo PR. Haz clic allí y te llevará a una interfaz donde puedes cambiar el título del mensaje de commit, asígnale una descripción más adecuada. Ahora, el mantenedor del repositorio que bifurcaste verá esta PR y _dedos cruzados_ valorarán y _fusionarán_ tu PR. Ahora eres un colaborador, ¡yay! :)
3. **Limpiar**. Se considera una buena práctica "_limpiar_" después de que tu Pull Request fue combinado a la rama principal exitosamente. Limpia tanto tu rama local como la rama que enviaste a GitHub. Primero eliminémoslo localmente con el siguiente comando:
```bash
git branch -d [branch-name]
```
Asegúrate de ir a la página de GitHub del repositorio bifurcado a continuación y elimina la rama remota que acabas de ingresar.
`Solicitud de extracción` (Pull request) parece un término tonto porque realmente deseas impulsar los cambios al proyecto. Pero el mantenedor (propietario del proyecto) o el equipo central debe considerar tus cambios antes de fusionarlo con la rama "principal" del proyecto, por lo que realmente estás solicitando una decisión de cambio a un mantenedor.
Una Pull request es el lugar para comparar y discutir las diferencias introducidas en una rama con revisiones, comentarios, pruebas integradas y más. Una buena Pull request sigue aproximadamente las mismas reglas que un mensaje de commit. Puedes agregar una referencia a un problema (issue) en el rastreador de problemas, cuando tu trabajo, por ejemplo, soluciona un problema. Esto se hace usando un '#' seguido del número de tu problema. Por ejemplo, `#97`.
🤞 Cruza los dedos para que todos los controles pasen y los propietarios del proyecto combinen tus cambios en el proyecto🤞
Actualiza tu rama de trabajo local actual con todas las nuevas confirmaciones de la rama remota correspondiente en GitHub:
`git pull`
## Cómo contribuir al código abierto
Primero, busquemos un repositorio en GitHub que te interese y al que te gustaría contribuir con un cambio. Querrás copiar el contenido a nuestra máquina.
✅ Una buena forma de encontrar repositorios 'aptos para principiantes' es [buscar por la etiqueta `good-first-issue`](https://github.blog/2020-01-22-browse-good-first-issues-para-empezar-a-contribuir-al-código-abierto/).
![Copia un repositorio localmente](../images/clone_repo.png)
Hay varias formas de copiar código. Una forma es "clonar" el contenido del repositorio, usando HTTPS, SSH o usando GitHub CLI (Interfaz de línea de comandos).
Abre tu terminal y clona el repositorio así:
`git clone https://github.com/ProjectURL`
Para trabajar en el proyecto, cambia al directorio correcto:
`cd ProjectURL`
También puedes abrir todo el proyecto utilizando [Codespaces](https://github.com/features/codespaces), el entorno de desarrollo en la nube / editor de código integrado de GitHub o [GitHub Desktop](https://desktop.github.com/).
Por último, puedes descargar el código en un directorio comprimido.
### Algunas cosas más interesantes sobre GitHub
Puedes destacar, ver y/o hacer "fork" cualquier repositorio público en GitHub. Asimismo, encontrar tus repositorios destacados en el menú desplegable de la parte superior derecha. Es como marcar como favorito, pero por código.
Los proyectos tienen un rastreador de problemas, principalmente en GitHub en la pestaña "Issues" a menos que se indique lo contrario, donde las personas debaten los problemas relacionados con el proyecto. Y la pestaña Pull requests es donde las personas debaten y revisan los cambios que están en curso.
Los proyectos también pueden tener discusiones en foros, listas de correo o canales de chat como Slack, Discord o IRC.
✅ Echa un vistazo a tu nuevo repositorio de GitHub y prueba algunas cosas, como editar la configuración, agregar información a tu repositorio y crear un proyecto (como un tablero Kanban). ¡Hay muchas cosas que puedes hacer!
---
## 🚀 Reto
Reúnete con un amigo para trabajar en el código del otro. Crea un proyecto en colaboración, haz fork del código, crea ramas y hagan merge a los cambios.
## [Cuestionario posterior a la clase](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Revisión y Autoestudio
Obtén más información sobre [contribución al software de código abierto](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Hoja de referencia de Git](https://training.github.com/downloads/github-git-cheat-sheet/).
Practica, practica, practica. GitHub tiene excelentes rutas de aprendizaje disponibles a través de [skills.github.com](https://skills.github.com/):
- [Primera semana en GitHub](https://skills.github.com/#first-week-on-github)
También encontrarás laboratorios más avanzados.
## Tarea
Completa [La Primera Semana en el Laboratorio de capacitación de GitHub](https://skills.github.com/#first-week-on-github)

View File

@@ -0,0 +1,318 @@
# Panimula sa GitHub
Sinasaklaw ng araling ito ang mga pangunahing kaalaman ng GitHub, isang platform para mag-host at mamahala ng mga pagbabago sa iyong code.
![Intro to GitHub](../sketchnotes/webdev101-github.png)
> Sketchnote ni [Tomomi Imura](https://twitter.com/girlie_mac)
## Pagsusulit bago ang lektura
[Pagsusulit bago ang lektura](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Panimula
Sa araling ito, tatalakayin natin ang:
- pagsubaybay sa gawaing ginagawa mo sa iyong makina
- nagtatrabaho sa mga proyekto kasama ang iba
- paano mag-ambag sa open source software
### Mga kinakailangan
Bago ka magsimula, kakailanganin mong suriin kung naka-install ang Git. Sa uri ng terminal:
`git --version`
Kung hindi naka-install ang Git, [download Git](https://git-scm.com/downloads). Pagkatapos, i-setup ang iyong lokal na profile sa Git sa terminal:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
Upang tingnan kung naka-configure na ang Git maaari kang mag-type:
`git config --list`
Kakailanganin mo rin ang isang GitHub account, isang code editor (tulad ng Visual Studio Code), at kakailanganin mong buksan ang iyong terminal (or: command prompt).
Mag-navigate sa [github.com](https://github.com/) at gumawa ng account kung hindi mo pa nagagawa, o mag-log in at punan ang iyong profile.
✅ Ang GitHub ay hindi lamang ang code repository sa mundo; may iba pa, ngunit ang GitHub ang pinakakilala
### Paghahanda
Kakailanganin mo ang parehong folder na may proyekto ng code sa iyong lokal na makina (laptop o PC), at isang pampublikong imbakan sa GitHub, na magsisilbing halimbawa kung paano mag-ambag sa mga proyekto ng iba.
---
## Pamamahala ng code
Sabihin nating mayroon kang lokal na folder na may ilang proyekto ng code at gusto mong simulan ang pagsubaybay sa iyong pag-unlad gamit ang git - ang version control system. Inihambing ng ilang tao ang paggamit ng git sa pagsulat ng love letter sa iyong sarili sa hinaharap. Ang pagbabasa ng iyong mga commit na mensahe mga araw o linggo o buwan mamaya, maaalala mo kung bakit ka gumawa ng desisyon, o "rollback" ng isang pagbabago - iyon ay, kapag sumulat ka ng magagandang "commit messages".
### Gawain: Gumawa ng repository at mag-commit ng code
1. **Create repository on GitHub**. Sa GitHub.com, sa tab na mga repositoryo, o mula sa kanang bahagi ng navigation bar, hanapin ang **new repo** pindutan.
1. Bigyan ng pangalan ang iyong repositoryo (folder).
1. Piliin **create repository**.
1. **Navigate to your working folder**. Sa iyong terminal, lumipat sa folder (kilala rin bilang direktoryo) na gusto mong simulan ang pagsubaybay. Uri:
```bash
cd [name of your folder]
```
1. **Initialize a git repository**. Sa uri ng iyong proyekto:
```bash
git init
```
1. **Check status**. Upang suriin ang katayuan ng iyong uri ng imbakan:
```bash
git status
```
ang output ay maaaring magmukhang ganito:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Karaniwang ang `git status` Ang command ay nagsasabi sa iyo ng mga bagay tulad ng kung anong mga file ang handa na _save_ sa repo o may mga pagbabago dito na maaaring gusto mong magpatuloy.
1. **Idagdag ang lahat ng mga file para sa pagsubaybay**
Tinatawag din itong staging file/pagdaragdag ng mga file sa staging area.
```bash
git add .
```
The `git add` plus `.` argument indicates that all your files & changes for tracking.
1. **Magdagdag ng mga napiling file para sa pagsubaybay**
```bash
git add [file or folder name]
```
Nakakatulong ito sa amin na magdagdag lamang ng mga napiling file sa staging area kapag ayaw naming i-commit ang lahat ng file nang sabay-sabay.
1. **Alisin ang lahat ng mga file**
```bash
git reset
```
Ang command na ito ay tumutulong sa amin na i-unstage ang lahat ng mga file nang sabay-sabay.
1. **Alisin ang isang partikular na file**
```bash
git reset [file or folder name]
```
Tinutulungan kami ng command na ito na i-unstage lang ang isang partikular na file nang sabay-sabay na hindi namin gustong isama para sa susunod na commit.
1. **Ipagpatuloy ang iyong trabaho**. Sa puntong ito naidagdag mo ang mga file sa isang tinatawag na _staging area_. Isang lugar kung saan sinusubaybayan ng Git ang iyong mga file. Upang gawing permanente ang pagbabago kailangan mong gawin _commit_ ang mga papeles. Upang gawin ito, lumikha ka ng isang _commit_ kasama ang `git commit` atas. A _commit_ kumakatawan sa isang punto ng pag-save sa kasaysayan ng iyong repo. I-type ang sumusunod upang lumikha ng a _commit_:
```bash
git commit -m "first commit"
```
Iko-commit nito ang lahat ng iyong file, idinaragdag ang mensaheng "first commit". Para sa mga commit na mensahe sa hinaharap, gugustuhin mong maging mas mapaglarawan sa iyong paglalarawan upang maihatid kung anong uri ng pagbabago ang iyong ginawa.
1. **Ikonekta ang iyong lokal na Git repo sa GitHub**. Ang isang Git repo ay mabuti sa iyong makina ngunit sa isang punto gusto mong magkaroon ng backup ng iyong mga file sa isang lugar at mag-imbita rin ng ibang mga tao na magtrabaho kasama mo sa iyong repo. Ang isang magandang lugar para gawin ito ay ang GitHub. Tandaan na nakagawa na kami ng repo sa GitHub kaya ang kailangan lang naming gawin ay ikonekta ang aming lokal na Git repo sa GitHub. Ang utos `git remote add` gagawin lang yan. I-type ang sumusunod na command:
> Tandaan, bago mo i-type ang command pumunta sa iyong GitHub repo page para mahanap ang repository URL. Gagamitin mo ito sa utos sa ibaba. Palitan `repository_name` gamit ang iyong GitHub URL.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Lumilikha ito ng isang _remote_, o koneksyon, pinangalanan "origin" na tumuturo sa GitHub repository na ginawa mo kanina.
1. **Magpadala ng mga lokal na file sa GitHub**. Sa ngayon ay nakagawa ka ng isang _connection_ sa pagitan ng lokal na repo at ng GitHub repo. Ipadala natin ang mga file na ito sa GitHub gamit ang sumusunod na command `git push`, tulad nito:
```bash
git push -u origin main
```
Ipinapadala nito ang iyong mga commit sa iyong "pangunahing" branch sa GitHub.
1. **Upang magdagdag ng higit pang mga pagbabago**. Kung gusto mong magpatuloy sa paggawa ng mga pagbabago at itulak ang mga ito sa GitHub kakailanganin mo lang gamitin ang sumusunod na tatlong utos:
```bash
git add .
git commit -m "type your commit message here"
git push
```
> Tip, Baka gusto mo ring magpatibay ng isang `.gitignore` file upang maiwasan ang mga file na hindi mo gustong subaybayan mula sa paglabas sa GitHub - tulad ng mga talang iyon na iniimbak mo sa parehong folder ngunit walang lugar sa isang pampublikong imbakan. Makakahanap ka ng mga template para sa `.gitignore` files at [.gitignore templates](https://github.com/github/gitignore).
#### Mag-commit ng mga mensahe
Ang isang mahusay na linya ng paksa ng Git commit ay kumukumpleto sa sumusunod na pangungusap:
Kung inilapat, gagawin ng commit na ito <your subject line here>
Para sa paksa gamitin ang pautos, kasalukuyang panahunan: "pagbabago" hindi "binago" o "pagbabago".
Tulad ng sa paksa, sa katawan (opsyonal) ay ginagamit din ang imperative, present tense. Dapat isama ng katawan ang motibasyon para sa pagbabago at ihambing ito sa nakaraang pag-uugali. Ipinapaliwanag mo ang `why`, hindi ang `how`.
✅ Maglaan ng ilang minuto upang mag-surf sa GitHub. Makakahanap ka ba ng talagang mahusay na commit message? Makakahanap ka ba ng talagang minimal? Anong impormasyon sa tingin mo ang pinakamahalaga at kapaki-pakinabang na ihatid sa isang commit message?
### Gawain: Magtulungan
Ang pangunahing dahilan ng paglalagay ng mga bagay sa GitHub ay upang gawing posible ang pakikipagtulungan sa ibang mga developer.
## Paggawa sa mga proyekto kasama ang iba
Sa iyong imbakan, mag-navigate sa `Insights > Community` upang makita kung paano inihahambing ang iyong proyekto sa mga inirerekomendang pamantayan ng komunidad.
Narito ang ilang bagay na maaaring mapabuti ang iyong GitHub repo:
- **Description**. Nagdagdag ka ba ng paglalarawan para sa iyong proyekto?
- **README**. Nagdagdag ka ba ng README? Nagbibigay ang GitHub ng gabay para sa pagsulat ng a [README](https://docs.github.com/articles/about-readmes/).
- **Contributing guideline**. Mayroon ba ang iyong proyekto [contributing guidelines](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Code of Conduct**. a [Code of Conduct](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **License**. Marahil ang pinakamahalaga, ang [license](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Makikinabang ang lahat ng mapagkukunang ito sa pag-onboard ng mga bagong miyembro ng team. At iyon ang karaniwang mga uri ng mga bagay na tinitingnan ng mga bagong kontribyutor bago man lang tingnan ang iyong code, upang malaman kung ang iyong proyekto ay ang tamang lugar para sa kanila na gugulin ang kanilang oras.
✅ Ang mga file ng README, bagama't nangangailangan sila ng oras upang maghanda, ay kadalasang napapabayaan ng mga abalang tagapangasiwa. Makakahanap ka ba ng isang halimbawa ng isang partikular na naglalarawan? Tandaan: may ilan [tools to help create good READMEs](https://www.makeareadme.com/) na baka gusto mong subukan.
### Gawain: Pagsamahin ang ilang code
Ang mga nag-aambag na doc ay tumutulong sa mga tao na mag-ambag sa proyekto. Ipinapaliwanag nito kung anong mga uri ng mga kontribusyon ang iyong hinahanap at kung paano gumagana ang proseso. Ang mga kontribyutor ay kailangang dumaan sa isang serye ng mga hakbang upang makapag-ambag sa iyong repo sa GitHub:
1. **Forking your repo** Malamang na gusto mo ang mga tao _fork_ your project. Ang ibig sabihin ng forking ay paggawa ng replica ng iyong repository sa kanilang profile sa GitHub.
1. **Clone**. Mula doon ay i-clone nila ang proyekto sa kanilang lokal na makina.
1. **Create a branch**. Gusto mong hilingin sa kanila na lumikha ng isang _branch_ para sa kanilang trabaho.
1. **Focus their change on one area**. Hilingin sa mga kontribyutor na ituon ang kanilang mga kontribusyon sa isang bagay sa isang pagkakataon - sa paraang iyon ang mga pagkakataong magagawa mo _merge_ sa kanilang trabaho ay mas mataas. Isipin na magsulat sila ng pag-aayos ng bug, magdagdag ng bagong feature, at mag-update ng ilang pagsubok - paano kung gusto mo, o maaari lang ipatupad ang 2 sa 3, o 1 sa 3 pagbabago?
✅ Isipin ang isang sitwasyon kung saan ang mga sangay ay partikular na kritikal sa pagsulat at pagpapadala ng magandang code. Anong mga use case ang maiisip mo?
> Tandaan, maging ang pagbabagong gusto mong makita sa mundo, at lumikha din ng mga sangay para sa iyong sariling gawain. Ang anumang commit na gagawin mo ay gagawin sa branch na kasalukuyan mong kinaroroonan “checked out” sa. Gamitin `git status` para makita kung saang branch yan.
Dumaan tayo sa isang daloy ng trabaho ng contributor. Ipagpalagay na ang nag-ambag ay mayroon na _forked_ at _cloned_ ang repo para magkaroon sila ng Git repo na handang gawin, sa kanilang lokal na makina:
1. **Create a branch**. Gamitin ang command `git branch` upang lumikha ng isang sangay na maglalaman ng mga pagbabagong ibig nilang i-ambag:
```bash
git branch [branch-name]
```
1. **Switch to working branch**. Lumipat sa tinukoy na sangay at i-update ang gumaganang direktoryo gamit ang `git switch`:
```bash
git switch [branch-name]
```
1. **Do work**. Sa puntong ito gusto mong idagdag ang iyong mga pagbabago. Huwag kalimutang sabihin kay Git ang tungkol dito gamit ang mga sumusunod na utos:
```bash
git add .
git commit -m "my changes"
```
Siguraduhing bibigyan mo ng magandang pangalan ang iyong commit, para sa iyong kapakanan pati na rin ang maintainer ng repo na tinutulungan mo.
1. **Combine your work with the `main` branch**. Sa ilang mga punto ay tapos ka nang magtrabaho at gusto mong pagsamahin ang iyong trabaho sa iyong trabaho `main` sangay. Ang `main` maaaring nagbago ang branch samantala kaya siguraduhing i-update mo muna ito sa pinakabago gamit ang mga sumusunod na command:
```bash
git switch main
git pull
```
Sa puntong ito gusto mong tiyakin na anuman _conflicts_, mga sitwasyon kung saan hindi madali ang Git _combine_ ang mga pagbabago ay nangyayari sa iyong nagtatrabaho na sangay. Samakatuwid, patakbuhin ang sumusunod na mga atas:
```bash
git switch [branch_name]
git merge main
```
Dadalhin nito ang lahat ng pagbabago mula sa `main` into your branch and sana matuloy mo na lang. Kung hindi, sasabihin sa iyo ng VS Code kung nasaan ang Git _confused_ at babaguhin mo lang ang mga apektadong file para masabi kung aling content ang pinakatumpak.
1. **Send your work to GitHub**. Ang pagpapadala ng iyong trabaho sa GitHub ay nangangahulugan ng dalawang bagay. Itulak ang iyong sangay sa iyong repo at pagkatapos ay magbukas ng isang PR, Hiling na Hilahin.
```bash
git push --set-upstream origin [branch-name]
```
Ang utos sa itaas ay lumilikha ng sangay sa iyong forked repo.
1. **Open a PR**. Susunod, gusto mong magbukas ng PR. Ginagawa mo iyon sa pamamagitan ng pag-navigate sa forked repo sa GitHub. Makakakita ka ng indikasyon sa GitHub kung saan itatanong nito kung gusto mong lumikha ng bagong PR, i-click mo iyon at dadalhin ka sa isang interface kung saan maaari mong baguhin ang pamagat ng commit message, bigyan ito ng mas angkop na paglalarawan. Ngayon ay makikita ng tagapangasiwa ng repo na iyong tinira ang PR na ito at _fingers crossed_ sila ay pahalagahan at _merge_ your PR. Isa ka na ngayong contributor, yay :)
1. **Clean up**. Ito ay itinuturing na mabuting kasanayan sa _clean up_ pagkatapos mong matagumpay na pagsamahin ang isang PR. Gusto mong linisin ang iyong lokal na sangay at ang sangay na itinulak mo sa GitHub. Una, tanggalin natin ito nang lokal gamit ang sumusunod na utos:
```bash
git branch -d [branch-name]
```
Tiyaking pupunta ka sa pahina ng GitHub para sa susunod na forked repo at alisin ang malayong sangay na itinulak mo lang dito.
`Pull request` parang silly term kasi gusto mo talagang i-push yung mga pagbabago mo sa project. Ngunit kailangang isaalang-alang ng maintainer (may-ari ng proyekto) o pangunahing koponan ang iyong mga pagbabago bago ito isama sa "pangunahing" sangay ng proyekto, kaya talagang humihiling ka ng desisyon sa pagbabago mula sa isang maintainer.
Ang pull request ay ang lugar upang paghambingin at pag-usapan ang mga pagkakaibang ipinakilala sa isang sangay na may mga review, komento, pinagsamang pagsubok, at higit pa. Ang isang mahusay na kahilingan sa paghila ay sumusunod sa halos kaparehong mga panuntunan gaya ng isang commit na mensahe. Maaari kang magdagdag ng reference sa isang isyu sa issue tracker, kapag ang iyong trabaho halimbawa ay nag-ayos ng isyu. Ginagawa ito gamit ang a `#` na sinusundan ng bilang ng iyong isyu. Halimbawa `#97`.
🤞Pinilit na ang lahat ng mga tseke ay pumasa at ang (mga) may-ari ng proyekto ay pinagsama ang iyong mga pagbabago sa proyekto🤞
I-update ang iyong kasalukuyang lokal na nagtatrabaho na sangay sa lahat ng mga bagong commit mula sa kaukulang remote na sangay sa GitHub:
`git pull`
## Paano mag-ambag sa open source
Una, maghanap tayo ng isang imbakan (o **repo**) sa GitHub ng interes sa iyo at kung saan mo gustong mag-ambag ng pagbabago. Gusto mong kopyahin ang mga nilalaman nito sa iyong makina.
✅ Ang isang mahusay na paraan upang makahanap ng 'beginner-friendly' repos ay ang [search by the tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copy a repo locally](images/clone_repo.png)
Mayroong ilang mga paraan ng pagkopya ng code. Ang isang paraan ay ang "i-clone" ang mga nilalaman ng repository, gamit ang HTTPS, SSH, o gamit ang GitHub CLI (Command Line Interface).
Buksan ang iyong terminal at i-clone ang repositoryo tulad nito:
`git clone https://github.com/ProjectURL`
Upang magtrabaho sa proyekto, lumipat sa kanang folder:
`cd ProjectURL`
Maaari mo ring buksan ang buong proyekto gamit ang [Codespaces](https://github.com/features/codespaces), Ang naka-embed na code editor / cloud development environment ng GitHub, o [GitHub Desktop](https://desktop.github.com/).
Panghuli, maaari mong i-download ang code sa isang naka-zip na folder.
### Ilang mas kawili-wiling bagay tungkol sa GitHub
Maaari mong lagyan ng star, panoorin at/o "i-fork" ang anumang pampublikong repository sa GitHub. Mahahanap mo ang iyong mga naka-star na repository sa kanang tuktok na drop-down na menu. Ito ay tulad ng pag-bookmark, ngunit para sa code.
Ang mga proyekto ay may tagasubaybay ng isyu, karamihan ay nasa GitHub sa tab na "Issues" maliban kung iba ang ipinahiwatig, kung saan tinatalakay ng mga tao ang mga isyung nauugnay sa proyekto. At ang tab na Pull Requests ay kung saan tinatalakay at sinusuri ng mga tao ang mga pagbabagong kasalukuyang isinasagawa.
Maaaring magkaroon din ng talakayan ang mga proyekto sa mga forum, mailing list, o mga channel ng chat tulad ng Slack, Discord o IRC.
✅ Tingnan ang iyong bagong GitHub repo at subukan ang ilang bagay, tulad ng pag-edit ng mga setting, pagdaragdag ng impormasyon sa iyong repo, at paggawa ng proyekto (tulad ng Kanban board). Marami kang magagawa!
---
## 🚀 Hamon
Ipares sa isang kaibigan para magtrabaho sa code ng isa't isa. Gumawa ng proyekto nang magkakasama, mag-fork ng code, gumawa ng mga sangay, at magsama ng mga pagbabago.
## Pagsusulit pagkatapos ng Lektura
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Pagsusuri at Sariling pag-aaral
Magbasa pa tungkol sa [contributing to open source software](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Magsanay, magsanay, magsanay. Ang GitHub ay may mahusay na mga landas sa pag-aaral na magagamit sa pamamagitan ng [lab.github.com](https://lab.github.com/):
- [First Week on GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Makakahanap ka rin ng mas advanced na mga lab.
## Takdang-aralin
Kumpletuhin [the First Week on GitHub training lab](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,318 @@
# Introduction à GitHub
Cette leçon couvre les principes de base de GitHub, une plateforme permettant dhéberger et de gérer les modifications apportées à votre code.
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote par [Tomomi Imura](https://twitter.com/girlie_mac)
## Quiz préalable
[Quiz préalable](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=fr)
## Introduction
Dans cette leçon, nous allons couvrir :
- suivre le travail que vous faites sur votre machine
- travailler sur des projets avec dautres personnes
- comment contribuer aux logiciels open source
### Prérequis
Avant de commencer, vous devrez vérifier si Git est installé. Dans le type de terminal :
`git --version`
Si Git nest pas installé, [télécharger Git](https://git-scm.com/downloads). Ensuite, configurez votre profil Git local dans le terminal:
* `git config --global user.name " votre-nom"`
* `git config --global user.email " your-email"`
Pour vérifier si Git est déjà configuré, vous pouvez taper :
`git config --list`
Vous aurez également besoin dun compte GitHub, dun éditeur de code (comme Visual Studio Code), et vous devrez ouvrir votre terminal (ou : invite de commandes).
Accédez à [github.com](https://github.com/) et créez un compte si vous ne lavez pas déjà fait, ou connectez-vous et remplissez votre profil.
✅ GitHub nest pas le seul référentiel de code au monde; il y en a dautres, mais GitHub est le plus connu
### Préparation
Vous aurez besoin à la fois dun dossier avec un projet de code sur votre ordinateur local (ordinateur portable ou PC) et dun référentiel public sur GitHub, qui servira dexemple pour contribuer aux projets dautres personnes.
---
## Gestion du code
Supposons que vous ayez un dossier localement avec un projet de code et que vous souhaitiez commencer à suivre votre progression à laide de git - le système de contrôle de version. Certaines personnes comparent lutilisation de git à lécriture dune lettre damour à votre futur moi. En lisant vos messages de validation des jours, des semaines ou des mois plus tard, vous pourrez vous rappeler pourquoi vous avez pris une décision, ou " annuler " une modification - cest-à-dire lorsque vous écrivez de bons " messages de validation ".
### Tâche : créer un référentiel et valider le code
1. **Créer un référentiel sur GitHub**. Sur GitHub.com, dans longlet Référentiels ou dans la barre de navigation en haut à droite, recherchez le bouton **nouveau référentiel**.
1. Donnez un nom à votre référentiel (dossier)
1. Sélectionnez **créer un référentiel**.
1. **Accédez à votre dossier de travail**. Dans votre terminal, basculez vers le dossier (également connu sous le nom de répertoire) que vous souhaitez démarrer le suivi. Tapez :
```bash
cd [nom de votre dossier]
```
1. **Initialiser un dépôt git**. Dans votre type de projet :
```bash
git init
```
1. **Vérifier létat**. Pour vérifier létat de votre type de référentiel :
```bash
git status
```
la sortie peut ressembler à ceci :
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
En règle générale, une commande `git status` vous indique des choses comme quels fichiers sont prêts à être _enregistrés_ dans le référentiel ou contient des modifications que vous voudrez peut-être conserver.
1. **Ajouter tous les fichiers pour le suivi**
Cela sappelle aussi fichiers intermédiaires/ ajout de fichiers à la zone de transit.
```bash
git add .
```
Largument `git add` plus `.` indique que tous vos fichiers &changes pour le suivi.
1. **Ajouter les fichiers sélectionnés pour le suivi**
```bash
git add [nom du fichier ou du dossier]
```
Cela nous aide à ajouter uniquement les fichiers sélectionnés à la zone de transit lorsque nous ne voulons pas valider tous les fichiers à la fois.
1. **Défaire la scène de tous les fichiers**
```bash
git reset
```
Cette commande nous aide à défaire tous les fichiers à la fois.
1. **Défaire un fichier particulier**
```bash
git reset [nom du fichier ou du dossier]
```
Cette commande nous aide à défaire un fichier particulier à la fois que nous ne voulons pas inclure pour le prochain commit.
1. **Persistance de votre travail**. À ce stade, vous avez ajouté les fichiers à un soi-disant _staging area_. Un endroit où Git suit vos fichiers. Pour rendre la modification permanente, vous devez _valider_ les fichiers. Pour ce faire, vous créez un _commit_ avec la commande `git commit`. Un _commit_ représente un point denregistrement dans lhistorique de votre référentiel. Tapez ce qui suit pour créer un _commit_ :
```bash
git commit -m " premier commit "
```
Cela valide tous vos fichiers, en ajoutant le message " premier commit ". Pour les futurs messages de validation, vous voudrez être plus descriptif dans votre description pour indiquer le type de modification que vous avez apportée.
1. **Connectez votre référentiel Git local avec GitHub**. Un référentiel Git est bon sur votre machine, mais à un moment donné, vous voulez avoir une sauvegarde de vos fichiers quelque part et également inviter dautres personnes à travailler avec vous sur votre dépôt. GitHub est un excellent endroit pour le faire. Noubliez pas que nous avons déjà créé un référentiel sur GitHub, donc la seule chose que nous devons faire est de connecter notre référentiel Git local à GitHub. La commande `git remote add` fera exactement cela. Tapez la commande suivante :
> Remarque, avant de taper la commande, accédez à votre page de référentiel GitHub pour trouver lURL du référentiel. Vous lutiliserez dans la commande ci-dessous. Remplacez `repository_name` par votre URL GitHub.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Cela crée un _remote_, ou une connexion, nommé " origin " pointant vers le référentiel GitHub que vous avez créé précédemment.
1. **Envoyer des fichiers locaux à GitHub**. Jusquà présent, vous avez créé une _connexion_ entre le référentiel local et le référentiel GitHub. Envoyons ces fichiers à GitHub avec la commande suivante `git push`, comme suit:
```bash
git push -u origin main
```
Cela envoie vos commits dans votre branche "main" à GitHub..
1. **Pour ajouter dautres modifications**. Si vous souhaitez continuer à apporter des modifications et à les pousser vers GitHub, il vous suffit dutiliser les trois commandes suivantes:
```bash
git add .
git commit -m " tapez votre message de validation ici "
git push
```
> Conseil, vous pouvez également adopter un fichier `.gitignore` pour empêcher les fichiers que vous ne souhaitez pas suivre dapparaître sur GitHub - comme ce fichier de notes que vous stockez dans le même dossier mais na pas sa place sur un référentiel public. Vous pouvez trouver des modèles pour les fichiers `.gitignore` dans [.gitignore templates](https://github.com/github/gitignore).
#### Valider les messages
Une grande ligne dobjet de commit Git complète la phrase suivante:
Sil est appliqué, ce commit le sera
Pour le sujet, utilisez limpératif, présent: "changement" pas "changé" ni "changements".
Comme dans le sujet, dans le corps (facultatif) utilisez également limpératif, le présent. Le corps doit inclure la motivation du changement et contraster cela avec le comportement précédent. Vous expliquez le `pourquoi`, pas le `comment`.
✅ Prenez quelques minutes pour surfer sur GitHub. Pouvez-vous trouver un très bon message dengagement? Pouvez-vous en trouver un vraiment minime? Quelles informations pensez-vous être les plus importantes et les plus utiles à transmettre dans un message de validation ?
### Tâche : Collaborer
La principale raison de mettre des choses sur GitHub était de permettre de collaborer avec dautres développeurs.
## Travailler sur des projets avec dautres
Dans votre référentiel, accédez à `Insights > Community ` pour voir comment votre projet se compare aux normes communautaires recommandées.
Voici quelques éléments qui peuvent améliorer votre référentiel GitHub :
- **Description**. Avez-vous ajouté une description pour votre projet ?
- **README**. Avez-vous ajouté un fichier README ? GitHub fournit des conseils pour lécriture dun [README](https://docs.github.com/articles/about-readmes/).
- **Guide de contribution**. Votre projet a-t-il des [directives de contribution](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Code de conduite**. Un [Code de conduite](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Licence**. Peut-être plus important encore, une [licence](https://docs.github.com/articles/adding-a-license-to-a-repository/) ?
Toutes ces ressources profiteront à lintégration des nouveaux membres de léquipe. Et ce sont généralement le genre de choses que les nouveaux contributeurs regardent avant même de regarder votre code, pour savoir si votre projet est le bon endroit pour quils passent leur temps.
✅ fichiers README, bien quils prennent du temps à préparer, sont souvent négligés par les mainteneurs occupés. Pouvez-vous trouver un exemple particulièrement descriptif? Remarque: il y a quelques [outils pour aider à créer de bons README](https://www.makeareadme.com/) que vous voudrez peut-être essayer.
### Tâche : fusionner du code
Les documents contributeurs aident les gens à contribuer au projet. Il explique les types de contributions que vous recherchez et comment le processus fonctionne. Les contributeurs devront passer par une série détapes pour pouvoir contribuer à votre référentiel sur GitHub :
1. **Forker votre repo** Vous voudrez probablement que les gens _fork_ votre projet. La duplication signifie la création dun réplica de votre référentiel sur leur profil GitHub.
1. **Cloner**. De là, ils cloneront le projet sur leur ordinateur local.
1. **Créer une branche**. Vous voudrez leur demander de créer une _branche_ pour leur travail.
1. **Concentrez leur changement sur un seul domaine**. Demandez aux contributeurs de concentrer leurs contributions sur une chose à la fois - de cette façon, les chances que vous puissiez _fusionner_ dans leur travail sont plus élevées. Imaginez quils écrivent un correctif de bogue, ajoutent une nouvelle fonctionnalité et mettent à jour plusieurs tests - que se passe-t-il si vous le souhaitez ou si vous ne pouvez implémenter que 2 modifications sur 3 ou 1 sur 3?
✅ Imaginez une situation où les branches sont particulièrement essentielles à lécriture et à lexpédition dun bon code. À quels cas dutilisation pouvez-vous penser ?
> Remarque, soyez le changement que vous voulez voir dans le monde et créez également des branches pour votre propre travail. Tous les commits que vous faites seront effectués sur la branche que vous avez actuellement "extraite". Utilisez `git status` pour voir de quelle branche il sagit.
Passons en revue un flux de travail de contributeur. Supposons que le contributeur a déjà _forked_ et _cloné_ le référentiel afin quil ait un référentiel Git prêt à être travaillé, sur sa machine locale :
1. **Créer une branche**. Utilisez la commande `git branch` pour créer une branche qui contiendra les modifications quils veulent contribuer:
```bash
git branch [nom_branche]
```
1. **Passer à la branche de travail**. Basculez vers la branche spécifiée et mettez à jour le répertoire de travail avec `git switch`:
```bash
git switch [nom_branche]
```
1. **Travailler**. À ce stade, vous souhaitez ajouter vos modifications. Noubliez pas den parler à Git avec les commandes suivantes:
```bash
git add .
git commit -m " mes modifications "
```
Assurez-vous de donner à votre engagement une bonne réputation, pour votre bien ainsi que pour le mainteneur du repo que vous aidez.
1. **Combinez votre travail avec la branche `main`**. À un moment donné, vous avez fini de travailler et vous voulez combiner votre travail avec celui de la branche `main`. La branche `main`" a peut-être changé entre-temps, alors assurez-vous de la mettre à jour au plus tard avec les commandes suivantes:
```bash
git switch principal
git pull
```
À ce stade, vous voulez vous assurer que tous les _conflits_, les situations où Git ne peut pas facilement _combiner_ les modifications se produisent dans votre branche de travail. Par conséquent, exécutez les commandes suivantes :
```bash
git switch [branch_name]
git merge main
```
Cela apportera tous les changements de `main` dans votre branche et jespère que vous pourrez simplement continuer. Sinon, VS Code vous dira où Git est _confus_ et vous modifiez simplement les fichiers affectés pour dire quel contenu est le plus précis.
1. **Envoyez votre travail à GitHub**. Lenvoi de votre travail à GitHub signifie deux choses. Pousser votre succursale à votre dépôt, puis ouvrir un PR, Pull Request.
```bash
git push --set-upstream origin [nom_branche]
```
La commande ci-dessus crée la branche sur votre référentiel duppliqué.
1. **Ouvrez une PR**. Ensuite, vous souhaitez ouvrir une PR. Pour ce faire, accédez au référentiel forké sur GitHub. Vous verrez une indication sur GitHub où il vous demande si vous souhaitez créer une nouvelle PR, vous cliquez dessus et vous êtes emmené vers une interface où vous pouvez changer le titre du message de validation, lui donner une description plus appropriée. Maintenant, le mainteneur du repo que vous avez forké verra ce PR et _croisons les doigts_ quil apprécieront et _fusionnera_ votre PR. Vous êtes maintenant un contributeur, yay :)
1. **Nettoyer**. Il est considéré comme une bonne pratique de _clean up_ après avoir fusionné avec succès un PR. Vous voulez nettoyer à la fois votre branche locale et la branche que vous avez poussée vers GitHub. Commençons par le supprimer localement avec la commande suivante:
```bash
git branch -d [nom_branche]
```
Assurez-vous daccéder à la page GitHub pour le référentiel duppliqué suivant et supprimez la branche distante que vous venez dy pousser.
`Pull request` semble être un terme stupide parce que vous voulez vraiment pousser vos modifications au projet. Mais le responsable (propriétaire du projet) ou léquipe principale doit prendre en compte vos modifications avant de la fusionner avec la branche " principale " du projet, vous demandez donc vraiment une décision de modification à un responsable.
Une pull request est lendroit idéal pour comparer et discuter des différences introduites sur une branche avec des révisions, des commentaires, des tests intégrés, etc. Une bonne pull request suit à peu près les mêmes règles quun message de validation. Vous pouvez ajouter une référence à un problème dans le suivi des problèmes, lorsque votre travail, par exemple, résout un problème. Cela se fait à laide dun `#` suivi du numéro de votre problème. Par exemple `#97`.
🤞croisons les doigts pour que toutes les vérifications réussissent et que le ou les propriétaires du projet fusionnent vos modifications dans le projet🤞
Mettez à jour votre branche de travail locale actuelle avec tous les nouveaux commits de la branche distante correspondante sur GitHub :
`git pull`
## Comment contribuer à lopen source
Tout dabord, trouvons un référentiel (ou **repo**) sur GitHub qui vous intéresse et auquel vous souhaitez apporter une modification. Vous voudrez copier son contenu sur votre machine.
✅ Un bon moyen de trouver des repos " conviviaux pour les débutants " est de [rechercher par la balise 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copy a repo locally](../images/clone_repo.png)
Il existe plusieurs façons de copier du code. Une façon consiste à " cloner " le contenu du référentiel, en utilisant HTTPS, SSH ou en utilisant linterface de ligne de commande GitHub CLI (Interface de ligne de commande).
Ouvrez votre terminal et clonez le référentiel comme suit:
`git clone https://github.com/ProjectURL`
Pour travailler sur le projet, basculez vers le dossier de droite :
`cd ProjectURL`
Vous pouvez également ouvrir lensemble du projet à laide de [Codespaces](https://github.com/features/codespaces), de léditeur de code intégré / environnement de développement cloud de GitHub ou de [GitHub Desktop](https://desktop.github.com/).
Enfin, vous pouvez télécharger le code dans un dossier compressé.
### Quelques choses plus intéressantes sur GitHub
Vous pouvez mettre en vedette, regarder et / ou " fork " nimporte quel référentiel public sur GitHub. Vous pouvez trouver vos référentiels étoilés dans le menu déroulant en haut à droite. Cest comme le bookmarking, mais pour le code.
Les projets ont un suivi des problèmes, principalement sur GitHub dans longlet " Problèmes ", sauf indication contraire, où les gens discutent des problèmes liés au projet. Et longlet Pull Requests est lendroit où les gens discutent et examinent les modifications en cours.
Les projets peuvent également avoir des discussions dans des forums, des listes de diffusion ou des canaux de chat tels que Slack, Discord ou IRC.
✅ Jetez un coup dœil à votre nouveau référentiel GitHub et essayez quelques éléments, comme la modification des paramètres, lajout dinformations à votre référentiel et la création dun projet (comme un tableau Kanban). Il y a beaucoup de choses que vous pouvez faire!
---
## 🚀 Challenge
Associez-vous à un ami pour travailler sur le code de lautre. Créez un projet en collaboration, bifurquez du code, créez des branches et fusionnez les modifications.
## Quiz de validation des connaissances
[Quiz de validation des connaissances](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=fr)
## Examen & Auto-apprentissage
En savoir plus sur [contribuer à un logiciel open source](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Pratique, pratique, pratique. GitHub a dexcellents chemins dapprentissage disponibles via [lab.github.com](https://lab.github.com/):
- [Première semaine sur GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Vous trouverez également des laboratoires plus avancés.
## Affectation
Complétez [la première semaine dans le laboratoire de formation GitHub](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,315 @@
# गिटहब का परिचय
इस पाठ में GitHub की मूल बातें शामिल हैं, जो आपके कोड में परिवर्तनों को होस्ट और प्रबंधित करने के लिए एक मंच है।
![GitHub का परिचय](/sketchnotes//webdev101-github.png)
> [टोमोमी इमुरा](https://twitter.com/girlie_mac) द्वारा स्केचनेट
## पूर्व व्याख्यान प्रश्नोत्तरी
[पूर्व व्याख्यान प्रश्नोत्तरी](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=hi)
## परिचय
इस पाठ में, हम कवर करेंगे:
- आपके द्वारा मशीन पर किए गए कार्य को ट्रैक करना
- दूसरों के साथ परियोजनाओं पर काम करना
- खुला स्त्रोत सॉफ़्टवेयर खोलने में योगदान कैसे करें
### आवश्यक शर्तें
शुरू करने से पहले, आपको जांचना होगा कि क्या Git स्थापित है। टर्मिनल में लिखे:
`git --version`
यदि गिट स्थापित नहीं है तो , [गिट डाउनलोड करे](https://git-scm.com/downloads). फिर, टर्मिनल में अपनी स्थानीय Git प्रोफ़ाइल सेट करें:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
यह जाँचने के लिए कि क्या Git पहले से कॉन्फ़िगर है आप टाइप कर सकते हैं:
`git config --list`
आपको एक GitHub खाते, एक कोड एडिटर (जैसे Visual Studio कोड) की आवश्यकता होगी, और आपको अपना टर्मिनल (या: कमांड प्रॉम्प्ट) खोलने की आवश्यकता होगी।
[Github.com](https://github.com/) पर नेविगेट करें और यदि आप पहले से नहीं हैं, तो एक खाता बनाएं या लॉग इन करें और अपना प्रोफ़ाइल भरें।
✅ GitHub दुनिया में एकमात्र कोड भंडार नहीं है; अन्य हैं, लेकिन GitHub सबसे अच्छा ज्ञात है
### तैयारी
आपको अपने स्थानीय मशीन (लैपटॉप या पीसी) पर एक कोड परियोजना के साथ एक फ़ोल्डर की आवश्यकता होगी, और GitHub पर एक सार्वजनिक भंडार, जो दूसरों की परियोजनाओं में योगदान करने के लिए एक उदाहरण के रूप में काम करेगा।
---
## कोड प्रबंधन
मान लें कि आपके पास कुछ कोड प्रोजेक्ट के साथ स्थानीय रूप से एक फ़ोल्डर है और आप संस्करण नियंत्रण प्रणाली - git का उपयोग करके अपनी प्रगति को ट्रैक करना शुरू करना चाहते हैं। कुछ लोग आपके भविष्य के लिए एक प्रेम पत्र लिखने के लिए git का उपयोग करने की तुलना करते हैं। अपने प्रतिबद्ध संदेशों को दिनों या हफ्तों या महीनों के बाद पढ़कर आप याद कर पाएंगे कि आपने निर्णय क्यों लिया, या "रोलबैक" में बदलाव किया - यानी जब आप अच्छा "कमिट मैसेज" लिखते हैं।
### कार्य: एक रीपाज़टॉरी और कमिट कोड बनाएं
1. **GitHub पर रीपाज़टॉरी बनाएँ**. GitHub.com पर, रिपॉजिटरी टैब में, या नेविगेशन बार टॉप-राइट से, **नया रेपो** बटन ढूंढें।
1. अपने रिपॉजिटरी (फ़ोल्डर) को एक नाम दें
1. **रिपॉजिटरी बनाएं** चुनें।
1. **अपने कार्यशील फ़ोल्डर में नेविगेट करें**. अपने टर्मिनल में, उस फ़ोल्डर पर स्विच करें (जिसे निर्देशिका के रूप में भी जाना जाता है) जिसे आप ट्रैक करना चाहते हैं, लिखे :
```bash
cd [फ़ोल्डरका नाम]
```
1. **एक गिट रिपॉजिटरी को प्रारंभ करें**. आपके प्रोजेक्ट मे लिखे:
```bash
git init
```
1. **अवस्था जांच**. अपने भंडार प्रकार की स्थिति की जांच करने के लिए लिखे:
```bash
git status
```
आउटपुट कुछ इस तरह दिख सकता है:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
आमतौर पर एक `git status` कमांड आपको ऐसी चीजें बताती है जैसे रेपो में _saved_ होने के लिए कौन सी फाइलें तैयार हैं या इस पर ऐसे बदलाव हैं जिन्हें आप जारी रखना चाहते हैं।
1. **ट्रैकिंग के लिए सभी फाइलें जोड़ें**
इसे स्टेजिंग फाइल / फाइल को स्टेजिंग एरिया में जोड़ना भी कहा जाता है।
```bash
git add .
```
`Git add` और `.` तर्क इंगित करता है कि आपकी सभी फाइलें और ट्रैकिंग के लिए परिवर्तन होगया है।
1. **ट्रैकिंग के लिए चयनित फ़ाइलें जोड़ें**
```bash
git add [फ़ाइल या फ़ोल्डर का नाम]
```
जब हम एक बार में सभी फ़ाइलों को कमिट नहीं करना चाहते हैं, तो यह हमें केवल स्टेजिंग क्षेत्र में चयनित फ़ाइलों को जोड़ने में मदद करता है।
1. **सभी फाइलों को अनस्टेज करें**
```bash
git reset
```
यह कमांड हमें एक ही बार में सभी फ़ाइलों को अस्थिर करने में मदद करता है।
1. **किसी विशेष फ़ाइल को अनस्टेज करें**
```bash
git reset [फ़ाइल या फ़ोल्डर का नाम]
```
यह कमांड हमें केवल एक विशेष फ़ाइल को एक बार में अनस्टेज करने में मदद करती है जिसे हम अगले कमिट के लिए शामिल नहीं करना चाहते हैं।
1. **अपना काम जारी रखना**. इस बिंदु पर आपने फ़ाइलों को तथाकथित _स्टैजिंग एरिया_ में जोड़ा है।एक जगह जहां Git आपकी फ़ाइलों को ट्रैक कर रही है। परिवर्तन को स्थायी करने के लिए आपको फ़ाइलों को _कॉमित_ की आवश्यकता होती है। ऐसा करने के लिए आप `git commit` कमांड के साथ एक _कमिट _ बनाते हैं। एक _कमिट_ आपके रेपो के इतिहास में एक बचत बिंदु का प्रतिनिधित्व करता है। _कमिट_ बनाने के लिए निम्नलिखित टाइप करें:
```bash
git commit -m "पहला कमिट"
```
यह आपकी सभी फ़ाइलों को "पहला कमिट" संदेश को जोड़ता है। भविष्य के कमिट संदेशों के लिए आप अपने विवरण में यह बताना चाहेंगे कि आपने किस प्रकार का परिवर्तन किया है।
1. **अपने स्थानीय Git रेपो को GitHub से कनेक्ट करें**. आपके मशीन पर एक Git रेपो अच्छा है, लेकिन कुछ बिंदु पर आप अपनी फ़ाइलों का बैकअप कहीं और रखना चाहते हैं और अन्य लोगों को भी अपने रेपो पर आपके साथ काम करने के लिए आमंत्रित करते हैं। ऐसा करने के लिए एक महान जगह GitHub है। याद रखें कि हमने पहले ही GitHub पर एक रेपो बना लिया है, इसलिए हमें केवल अपने Git रेपो को GitHub के साथ जोड़ना है। कमांड `git remote add` बस यही करेगा। निम्न कमांड टाइप करें:
> ध्यान दें, इससे पहले कि आप कमांड टाइप करें अपने रिपॉजिटरी URL को खोजने के लिए अपने GitHub रेपो पेज पर जाएं। आप इसे नीचे दिए गए कमांड में उपयोग करेंगे। अपने GitHub URL से `repository_name` बदलें।
```bash
git remote add origin https://github.com/username/repository_name.git
```
यह आपके द्वारा पहले बनाए गए GitHub रिपॉजिटरी को इंगित करते हुए "origin" नाम का एक _remote_, या कनेक्शन बनाता है।
1. **GitHub पर स्थानीय फ़ाइलें भेजें**. अब तक आपने स्थानीय रेपो और गिटहब रेपो के बीच एक _कनेक्शन_ बनाया है। चलो निम्न कमांड `git push` के साथ इन फाइलों को गिटहब को भेजें, जैसे:
```bash
git push -u origin main
```
यह आपकी "मैन" शाखा में GitHub को आपके कमिट भेजता है।
1. **अधिक परिवर्तन जोड़ने के लिए**. यदि आप परिवर्तन करना जारी रखना चाहते हैं और उन्हें GitHub पर धकेलना चाहते हैं, तो आपको निम्नलिखित तीन आदेशों का उपयोग करने की आवश्यकता होगी:
```bash
git add .
git commit -m "अपना संदेश यहाँ लिखें"
git push
```
> टिप, आप उन फ़ाइलों को रोकने के लिए एक `.gitignore` फ़ाइल भी अपनाना चाह सकते हैं जिन्हें आप GitHub पर दिखाने से रोकना चाहते हैं - जैसे नोट्स आप उसी फ़ोल्डर में संग्रहीत करते हैं, लेकिन सार्वजनिक रिपॉजिटरी में कोई स्थान नहीं है। आप `.gitignore` फाइल के लिए टेम्प्लेट में [.gitignore टेम्प्लेट](https://github.com/github/gitignore) पे पा सकते हैं
#### कमिट संदेश
एक महान Git कमिट विषय पंक्ति निम्नलिखित वाक्य को पूरा करती है:
यदि लागू किया जाता है, तो यह प्रतिबद्ध होगा <आपकी विषय पंक्ति यहां>
विषय के लिए अनिवार्य, वर्तमान काल का उपयोग करें: "परिवर्तन" न "बदला गया" और न ही "परिवर्तने"।
विषय के रूप में, शरीर में (वैकल्पिक) भी अनिवार्य, वर्तमान काल का उपयोग करते हैं। शरीर में परिवर्तन के लिए प्रेरणा शामिल होनी चाहिए और पिछले व्यवहार के साथ इसके विपरीत होना चाहिए। आप `क्यों` को समझा रहे हैं,` कैसे` को नहीं।
✅ GitHub के आसपास सर्फ करने के लिए कुछ मिनट लें। क्या आप वास्तव में महान कमिट संदेश पा सकते हैं? क्या आप वास्तव में न्यूनतम पा सकते हैं? आपको क्या संदेश लगता है कि एक कमिट संदेश देने के लिए सबसे महत्वपूर्ण और उपयोगी है?
### कार्य: सहयोग करें
गिटहब पर चीजें डालने का मुख्य कारण अन्य डेवलपर्स के साथ सहयोग करना संभव बनाना था।
## दूसरों के साथ परियोजनाओं पर काम करना
अपनी रिपॉजिटरी में, यह देखने के लिए कि आपकी परियोजना अनुशंसित सामुदायिक मानकों की तुलना कैसे करती है, `इनसाइट्स > कम्यूनिटी` पर जाएँ।
यहाँ कुछ चीजें हैं जो आपके GitHub रेपो में सुधार कर सकती हैं:
- **विवरण**. क्या आपने अपनी परियोजना के लिए एक विवरण जोड़ा?
- **README**. क्या आपने एक README जोड़ा? GitHub एक [README](https://docs.github.com/articles/about-readmes/) लिखने के लिए मार्गदर्शन प्रदान करता है।
- **योगदान दिशानिर्देश**. आपके प्रोजेक्टका [योगदान दिशानिर्देश](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/) है,
- **आचार संहिता**. एक [आचार संहिता](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **लाइसेंस**. शायद सबसे महत्वपूर्ण बात, एक [लाइसेंस](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
इन सभी संसाधनों से टीम के नए सदस्यों को लाभ मिलेगा। और वे आम तौर पर इस तरह की चीजें हैं जो आपके कोड को देखने से पहले भी नए योगदानकर्ताओं को देखते हैं, यह पता लगाने के लिए कि क्या आपका प्रोजेक्ट उनके लिए अपना समय बिताने के लिए सही जगह है।
✅ README फाइलें, हालांकि उन्हें तैयार करने में समय लगता है, अक्सर व्यस्त रखवाले द्वारा उपेक्षित कर दिए जाते हैं। क्या आप एक विशेष रूप से वर्णनात्मक का एक उदाहरण पा सकते हैं? नोट: कुछ अच्छे [READMEs बनाने में मदद करने के लिए कुछ उपकरण हैं](https://www.makeareadme.com/) जिन्हें आप आज़माना चाहते हैं।
### कार्य: कुछ कोड मर्ज करें
डॉक्स में योगदान करने से लोगों को परियोजना में योगदान करने में मदद मिलती है। यह बताता है कि आप किस प्रकार के योगदान की तलाश कर रहे हैं और प्रक्रिया कैसे काम करती है। योगदानकर्ताओं को GitHub पर आपके रेपो में योगदान करने में सक्षम होने के लिए कई चरणों से गुजरना होगा:
1. **अपने रेपो को फोर्क करना** आप शायद लोगों को अपनी परियोजना को _fork_ करना चाहेंगे। फोर्किंग का अर्थ है उनके GitHub प्रोफाइल पर अपनी रिपॉजिटरी की प्रतिकृति बनाना।
1. **क्लोन**.वहां से वे इस परियोजना को अपनी स्थानीय मशीन से जोड़ देंगे।
1. **एक शाखा बनाएँ**. आप उन्हें अपने काम के लिए एक _शाखा_ बनाने के लिए कहना चाहेंगे।
1. **एक क्षेत्र पर उनके परिवर्तन पर ध्यान दें**.योगदानकर्ताओं से एक समय में एक चीज़ पर उनके योगदान पर ध्यान केंद्रित करने के लिए कहें - इस तरह से संभावना है कि आप उनके काम में विलय कर सकते हैं। कल्पना कीजिए कि वे एक बग फिक्स लिखते हैं, एक नई सुविधा जोड़ते हैं, और कई परीक्षण अपडेट करते हैं - क्या होगा यदि आप चाहते हैं, या केवल 3 में से 2, या 3 में से 1 परिवर्तन लागू कर सकते हैं?
✅ ऐसी स्थिति की कल्पना करें जहां शाखाएं विशेष रूप से अच्छे कोड लिखने और शिपिंग करने के लिए महत्वपूर्ण हैं। आप किन मामलों का उपयोग कर सकते हैं?
> ध्यान दें, वह परिवर्तन हो जो आप दुनिया में देखना चाहते हैं, और अपने काम के लिए भी शाखाएँ बनाएँ। आपके द्वारा किया गया कोई भी शाखा उस शाखा पर बना दी जाएगी जिसे आप वर्तमान में "चेक आउट" कर रहे हैं। कौन सी शाखा है यह देखने के लिए `git status` का प्रयोग करें।
चलो एक योगदानकर्ता वर्कफ़्लो के माध्यम से चलते हैं। मान लें कि योगदानकर्ता पहले से ही रेपो को _फोर्क_ और _क्लोन_ कर चुका है, इसलिए उनके पास अपने स्थानीय मशीन पर काम करने के लिए तैयार गिट रेपो है:
1. **एक शाखा बनाएँ**.एक शाखा बनाने के लिए कमांड `git branch` का उपयोग करें जिसमें वे परिवर्तन होंगे जो उनके योगदान के लिए हैं:
```bash
git branch [शाखाका-नाम]
```
1. **कार्यशील शाखा पर स्विच करें**. निर्दिष्ट शाखा में स्विच करें और `git switch` के साथ कार्य निर्देशिका को अपडेट करें:
```bash
git switch [शाखाका-नाम]
```
1. **काम करो**. इस बिंदु पर आप अपने परिवर्तन जोड़ना चाहते हैं। निम्नलिखित आदेशों के बारे में Git को बताना न भूलें:
```bash
git add .
git commit -m "मेरे परिवर्तन"
```
यह सुनिश्चित करें कि आप अपनी खातिर एक अच्छा नाम दें, साथ ही साथ आप जिस रेपो में मदद कर रहे हैं उसका रखवालाका भी।
1. **`main` शाखा के साथ अपने काम को मिलाएं**. कुछ बिंदु पर आप काम कर रहे हैं और आप `main` शाखा के साथ अपने काम को जोड़ना चाहते हैं। `main` शाखा इस बीच बदल सकती है, इसलिए सुनिश्चित करें कि आपने इसे निम्न कमांड के साथ नवीनतम में अपडेट किया है:
```bash
git switch main
git pull
```
इस बिंदु पर आप यह सुनिश्चित करना चाहते हैं कि कोई भी _टकराव_, परिस्थितियां जहां Git आसानी से आपके कामकाजी शाखा में होने वाले परिवर्तनों को _संयोजित_ नहीं कर सकती है। इसलिए निम्न आदेश चलाएँ:
```bash
git switch [शाखाका-नाम]
git merge main
```
यह आपकी शाखा में `main` से सभी बदलाव लाएगा और उम्मीद है कि आप अभी भी जारी रख सकते हैं। यदि नहीं, तो VS कोड आपको बताएगा कि गिट कहां _उलझन_ में है और आप यह कहने के लिए प्रभावित फाइलों को बदल देते हैं कि कौन सी सामग्री सबसे सटीक है।
1. **अपना काम GitHub को भेजें**. अपने काम को GitHub में भेजने का मतलब है दो चीजें। अपनी शाखा को अपने रेपो में धकेलना और फिर एक पीआर, पुल अनुरोध को खोलें।
```bash
git push --set-upstream origin [शाखाका-नाम]
```
उपरोक्त कमांड आपके फोर्क्ड रेपो पर शाखा बनाता है।
1. **एक पीआर खोलें**. अगला, आप एक पीआर खोलना चाहते हैं। आप GitHub पर फोर्केड रेपो में नेविगेट करके ऐसा करते हैं। आपको GitHub पर एक संकेत दिखाई देगा जहां यह पूछता है कि क्या आप एक नया PR बनाना चाहते हैं, आप उस पर क्लिक करते हैं और आपको एक इंटरफ़ेस पर ले जाया जाता है जहाँ आप प्रतिबद्ध संदेश शीर्षक बदल सकते हैं, इसे अधिक उपयुक्त विवरण दे सकते हैं। अब रेपो के अनुरक्षक आप इस पीआर को देखेंगे और _उँगलियाँ पार_ कर जाएँगे जो आपके पीआर को सराहेंगे और _मर्ज_ करेंगे। अब आप एक योगदानकर्ता हैं, याय :)
1. **साफ - सफाई**. अपने को सफलतापूर्वक मर्ज करने के बाद _सफाई करना_ अच्छा माना जाता है। आप अपनी स्थानीय शाखा और उस शाखा को साफ़ करना चाहते हैं जिसे आपने GitHub में धकेल दिया है। पहले इसे निम्नलिखित कमांड के साथ स्थानीय रूप से हटा दें:
```bash
git branch -d [शाखाका-नाम]
```
सुनिश्चित करें कि आप अगले फोर्केड रेपो के लिए GitHub पृष्ठ पर जाएं और उस दूरस्थ शाखा को हटा दें जिसे आपने अभी पुश किया था।
`पुल अनुरोध` एक मूर्खतापूर्ण शब्द की तरह लगता है क्योंकि वास्तव में आप परियोजना में अपने परिवर्तनों को आगे बढ़ाना चाहते हैं। लेकिन अनुरक्षक (परियोजना स्वामी) या कोर टीम को परियोजना की "main" शाखा के साथ विलय करने से पहले आपके परिवर्तनों पर विचार करने की आवश्यकता है, इसलिए आप वास्तव में एक अनुचर से परिवर्तन के निर्णय का अनुरोध कर रहे हैं।
एक पुल अनुरोध समीक्षा, टिप्पणियों, एकीकृत परीक्षणों और अधिक के साथ एक शाखा पर पेश किए गए मतभेदों की तुलना और चर्चा करने का स्थान है। एक अच्छा पुल अनुरोध एक प्रतिबद्ध संदेश के समान नियमों का पालन करता है। आप समस्या ट्रैकर में किसी समस्या के संदर्भ को जोड़ सकते हैं, जब उदाहरण के लिए आपका कार्य किसी समस्या को हल करता है। यह आपके अंक की संख्या के बाद एक `#` का उपयोग करके किया जाता है। उदाहरण के लिए `# 97`।
🤞उंगलियों ने पार कर दिया कि सभी चेक पास हो गए और परियोजना के मालिकों ने परियोजना में आपके बदलावों को मर्ज कर दिया🤞
GitHub पर संबंधित दूरस्थ शाखा से सभी नए कमिट के साथ अपनी वर्तमान स्थानीय कार्य शाखा को अपडेट करें:
`git pull`
## कैसे खुला स्रोत में योगदान करे
सबसे पहले, आप के हित के GitHub पर एक रिपॉजिटरी (या **रेपो**) ढूंढें और जिसमें आप बदलाव में योगदान करना चाहते हैं। आप इसकी सामग्री को अपनी मशीन पर कॉपी करना चाहेंगे।
✅'शुरुआती-अनुकूल' रेपो को खोजने का एक अच्छा तरीका है, ['good-first-issue' द्वारा खोज करना](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![एक रेपो को स्थानीय रूप से कॉपी करें](../images/clone_repo.png)
कोड को कॉपी करने के कई तरीके हैं। एक तरीका है रिपॉजिटरी की सामग्री को "क्लोन" करना, HTTPS, SSH का उपयोग करना, या GitHub CLI (कमांड लाइन इंटरफ़ेस) का उपयोग करना।
अपना टर्मिनल खोलें और रिपॉजिटरी को क्लोन करें जैसे:
`git clone https://github.com/ProjectURL`
प्रोजेक्ट पर काम करने के लिए, सही फ़ोल्डर पर जाएँ:
`cd ProjectURL`
आप [Codespaces](https://github.com/features/codespaces), GitHub के एम्बेडेड कोड एडिटर / क्लाउड डेवलपमेंट एन्वायरमेंट, या [GitHub Desktop](https://desktop.github.com/) का उपयोग करके पूरी परियोजना भी खोल सकते हैं ) का है।
अंत में, आप ज़िप फ़ोल्डर में कोड डाउनलोड कर सकते हैं।
### GitHub के बारे में कुछ और दिलचस्प बातें
आप GitHub पर किसी भी पब्लिक रिपॉजिटरी को स्टार, पहरा और/या "फोर्क" कर सकते हैं। आप शीर्ष-दाएँ ड्रॉप-डाउन मेनू में अपने तारांकित रिपॉजिटरी पा सकते हैं। यह बुकमार्क करने जैसा है, लेकिन कोड के लिए।
परियोजनाओं में एक मुद्दा ट्रैकर है, ज्यादातर "इश्यू" टैब में गिटहब पर जब तक कि अन्यथा इंगित नहीं किया जाता है, जहां लोग परियोजना से संबंधित मुद्दों पर चर्चा करते हैं। और पुल अनुरोध टैब वह है जहां लोग उन परिवर्तनों की चर्चा और समीक्षा करते हैं जो प्रगति पर हैं।
परियोजनाओं की चर्चा फ़ोरम, मेलिंग सूचियों, या चैट चैनलों जैसे स्लैक, डिस्कोर्ड या आईआरसी में भी हो सकती है।
✅ अपने नए GitHub रेपो के चारों ओर एक नज़र डालें और कुछ चीजों को आज़माएं, जैसे कि सेटिंग्स को संपादित करना, अपने रेपो में जानकारी जोड़ना और एक प्रोजेक्ट बनाना (जैसे कंबन बोर्ड)। बहुत कुछ है जो आप कर सकते हैं!
---
## 🚀 चुनौती
एक दूसरे के कोड पर काम करने के लिए एक दोस्त के साथ जोडे। सहयोगी रूप से एक परियोजना बनाएँ, कोड बनाएँ, शाखाएँ बनाएँ, और परिवर्तनों को मर्ज करें।
## व्याख्यान उपरांत प्रश्नोत्तरी
[व्याख्यान उपरांत प्रश्नोत्तरी](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=hi)
## समीक्षा और स्व अध्ययन
[ओपन सोर्स सॉफ्टवेयर में योगदान](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution) के बारे में और पढ़ें।
[गिट चिटशीट](https://training.github.com/downloads/github-git-cheat-sheet/).
अभ्यास, अभ्यास, अभ्यास। GitHub में [lab.github.com](https://lab.github.com/) के माध्यम से सीखने के शानदार रास्ते उपलब्ध हैं:
- [GitHub पर पहला सप्ताह](https://lab.github.com/githubtraining/first-week-on-github)
आपको और भी उन्नत प्रयोगशालाएँ मिलेंगी।
## असाइनमेंट
[GitHub प्रशिक्षण प्रयोगशाला पर पहला सप्ताह](https://lab.github.com/githubtraining/first-week-on-github) पूरा करे

View File

@@ -0,0 +1,293 @@
# Dasar-dasar GitHub
Pelajaran ini mencakup dasar-dasar GitHub, platform untuk menghosting dan mengelola perubahan pada kode Anda.
![Dasar-dasar GitHub](/sketchnotes/webdev101-github.png)
> Catatan sketsa oleh [Tomomi Imura](https://twitter.com/girlie_mac)
## Kuis Pra-Kuliah
[Kuis pra-kuliah](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=id)
## Pengantar
Dalam pelajaran ini, kami akan membahas:
- melacak pekerjaan yang Anda lakukan di mesin Anda
- mengerjakan proyek dengan orang lain
- bagaimana berkontribusi pada perangkat lunak sumber terbuka
### Prasyarat
Sebelum memulai, Anda harus memeriksa apakah Git sudah diinstal. Di terminal ketik:
`git --version`
Jika Git tidak diinstal, [unduh Git](https://git-scm.com/downloads). Kemudian, atur profil Git lokal Anda di terminal:
`git config --global user.name "nama-anda"`
`git config --global user.email "email-anda"`
Untuk memeriksa apakah Git sudah dikonfigurasi, Anda dapat mengetik:
`git config --list`
Anda juga memerlukan akun GitHub, editor kode (seperti Visual Studio Code), dan Anda harus membuka terminal (atau: command prompt).
Buka [github.com](https://github.com/) dan buat akun jika Anda belum melakukannya, atau masuk dan isi profil Anda.
✅ GitHub bukan satu-satunya repositori kode di dunia; ada yang lain, tapi GitHub adalah yang paling terkenal
### Persiapan
Anda akan memerlukan folder dengan proyek kode di komputer lokal Anda (laptop atau PC), dan repositori publik di GitHub, yang akan berfungsi sebagai contoh cara berkontribusi pada proyek orang lain.
---
## Manajemen kode
Katakanlah Anda memiliki folder secara lokal dengan beberapa proyek kode dan Anda ingin mulai melacak kemajuan Anda menggunakan git - sistem kontrol versi. Beberapa orang membandingkan penggunaan git dengan menulis surat cinta untuk diri Anda di masa depan. Membaca pesan commit Anda beberapa hari atau minggu atau bulan kemudian, Anda akan dapat mengingat mengapa Anda membuat keputusan, atau "membatalkan" perubahan - yaitu, saat Anda menulis "pesan commit" yang baik.
### Tugas: Membuat repositori dan menyerahkan kode
1. **Buat repositori di GitHub**. Di GitHub.com, di tab repositories, atau dari kanan atas bilah navigasi, temukan tombol **repo baru (new repo)**.
1. Beri nama repositori (folder) Anda
1. Pilih **create repository**.
1. **Arahkan ke folder kerja Anda**. Di terminal Anda, beralihlah ke folder (juga dikenal sebagai direktori) yang ingin Anda mulai lacak. Ketik:
```bash
cd [nama folder anda]
```
1. **Inisialisasi repositori git**. Dalam proyek Anda ketik:
```bash
git init
```
1. **Periksa status**. Untuk memeriksa status repositori Anda ketik:
```bash
git status
```
hasilnya akan terlihat seperti ini:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Pada umunya perintah `git status` memberi tahu Anda hal-hal seperti file apa yang siap untuk _simpan_ ke repo atau ada perubahan di dalamnya yang mungkin ingin Anda pertahankan.
1. **Tambahkan file ke pelacakan**
```bash
git add .
```
`git add` ditambah argumen `.` menunjukkan bahwa semua file dan perubahan Anda untuk pelacakan.
1. **Mempertahankan pekerjaan Anda**. Pada titik ini Anda telah menambahkan file ke apa yang disebut _staging area_ (area pementasan). Tempat di mana Git melacak file Anda. Untuk membuat perubahan permanen Anda perlu _commit_ (menyerahkan) file. Untuk melakukannya, Anda membuat _commit_ dengan perintah `git commit`. Sebuah _commit_ mewakili titik penyimpanan dalam riwayat repo Anda. Ketik berikut ini untuk membuat _commit_:
```bash
git commit -m "first commit"
```
Ini menyerahkan (commit) semua file Anda, menambahkan pesan "first commit". Untuk pesan commit di masa mendatang, Anda akan ingin lebih deskriptif dalam deskripsi Anda untuk menyampaikan jenis perubahan apa yang telah Anda buat.
1. **Hubungkan repo Git lokal Anda dengan GitHub**. Sebuah Repo Git bagus di mesin Anda tetapi pada titik tertentu Anda ingin memiliki cadangan file Anda di suatu tempat dan juga mengundang orang lain untuk bekerja dengan Anda di repo Anda. Salah satu tempat yang bagus untuk melakukannya adalah GitHub. Ingat kita sudah membuat repo di GitHub jadi satu-satunya hal yang perlu kita lakukan adalah menghubungkan repo Git lokal kita dengan GitHub. Perintah `git remote add` akan melakukan hal itu. Ketik perintah berikut:
> Catatan, sebelum Anda mengetik perintah, buka halaman repo GitHub Anda untuk menemukan URL repositori. Anda akan menggunakannya di perintah di bawah ini. Ganti `nama_repository` dengan URL GitHub Anda.
```bash
git remote add origin https://github.com/username/nama_repository.git
```
Ini membuat _remote_, atau koneksi, bernama "origin" yang menunjuk ke repositori GitHub yang Anda buat sebelumnya.
1. **Kirim file lokal ke GitHub**. Sejauh ini Anda telah membuat _connection_ (koneksi) antara repo lokal dan repo GitHub. Ayo kirim file-file ini ke GitHub dengan perintah berikut `git push`, seperti itu:
```bash
git push -u origin main
```
Ini mengirimkan komit Anda di cabang "main" Anda ke GitHub.
1. **Untuk menambahkan lebih banyak perubahan**. Jika Anda ingin terus membuat perubahan dan menerapkannya ke GitHub, Anda hanya perlu menggunakan tiga perintah berikut:
```bash
git add .
git commit -m "ketik pesan komit Anda di sini"
git push
```
> Tip, Anda mungkin juga ingin mengadopsi file `.gitignore` untuk mencegah file yang tidak ingin Anda lacak muncul di GitHub - seperti file catatan yang Anda simpan di folder yang sama tetapi tidak memiliki tempat di repositori publik. Anda dapat menemukan template untuk file `.gitignore` di [.gitignore templates](github.com/github/gitignore).
#### Pesan commit
Baris subjek Git commit yang bagus melengkapi kalimat berikut:
Jika diterapkan, komit ini akan <baris subjek Anda di sini>
Untuk subjek gunakan imperatif, bentuk waktu sekarang (present tense): "merubah" bukan "perubahan" atau "mengubah".
Seperti pada subjek, dalam tubuh (opsional) juga gunakan imperatif, bentuk waktu sekarang. Tubuh harus memasukkan motivasi untuk perubahan dan membandingkannya dengan perilaku sebelumnya. Anda menjelaskan `mengapa`, bukan `bagaimana`.
✅ Luangkan beberapa menit untuk menjelajahi GitHub. Dapatkah Anda menemukan pesan commit yang sangat bagus? Dapatkah Anda menemukan yang sangat minim? Informasi apa yang menurut Anda paling penting dan berguna untuk disampaikan dalam pesan commit?
### Tugas: Berkolaborasi
Alasan utama menempatkan sesuatu di GitHub adalah untuk memungkinkan kolaborasi dengan pengembang lain.
## Mengerjakan proyek dengan orang lain
Di repositori Anda, buka `Insights > Community` untuk melihat bagaimana proyek Anda dibandingkan dengan standar komunitas yang direkomendasikan.
Berikut beberapa hal yang dapat meningkatkan repo GitHub Anda:
- **Deskripsi**. Apakah Anda menambahkan deskripsi untuk proyek Anda?
- **README**. Apakah Anda menambahkan README? GitHub memberikan panduan untuk menulis [README](https://docs.github.com/articles/about-readmes/).
- **Panduan berkontribusi**. Apakah project Anda memiliki [pedoman kontribusi](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Kode etik**. sebuah [Kode etik](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Lisensi**. Mungkin yang paling penting, sebuah [lisensi](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Semua sumber daya ini akan bermanfaat bagi anggota tim baru. Dan biasanya itu adalah jenis hal yang dilihat oleh kontributor baru bahkan sebelum melihat kode Anda, untuk mengetahui apakah proyek Anda adalah tempat yang tepat bagi mereka untuk menghabiskan waktu mereka..
✅ File README, meskipun membutuhkan waktu untuk mempersiapkannya, sering kali diabaikan oleh pengelola yang sibuk. Dapatkah Anda menemukan contoh yang sangat deskriptif? Catatan: ada beberapa [alat untuk membantu membuat README yang baik](https://www.makeareadme.com/) yang mungkin ingin Anda coba.
### Tugas: Menggabungkan beberapa kode
Dokumen kontribusi membantu orang berkontribusi pada proyek. Itu menjelaskan jenis kontribusi yang Anda cari dan bagaimana prosesnya bekerja. Kontributor harus melalui serangkaian langkah untuk dapat berkontribusi ke repo Anda di GitHub:
1. **Membagi (Forking) repo Anda** Anda mungkin ingin orang _fork_ proyek Anda. Forking berarti membuat replika repositori Anda di profil GitHub mereka.
1. **Clone**. Dari sana mereka akan mengkloning proyek tersebut ke mesin lokal mereka.
1. **Buat cabang**. Anda akan ingin meminta mereka untuk membuat _branch_ (cabang) untuk pekerjaan mereka.
1. **Fokuskan perubahan mereka pada satu area**. Minta kontributor untuk memusatkan kontribusinya pada satu hal pada satu waktu - dengan begitu, peluang Anda untuk _menggabungkan_ dalam pekerjaan mereka lebih tinggi. Bayangkan mereka menulis perbaikan bug, menambahkan fitur baru, dan memperbarui beberapa pengujian - bagaimana jika Anda ingin, atau hanya dapat mengimplementasikan 2 dari 3, atau 1 dari 3 perubahan?
✅ Bayangkan situasi di mana cabang sangat penting untuk menulis dan mengirimkan kode yang baik. Kasus penggunaan apa yang dapat Anda pikirkan?
> Perhatikan, jadilah perubahan yang ingin Anda lihat di dunia, dan buat cabang untuk pekerjaan Anda juga. Komit apa pun yang Anda buat akan dilakukan di cabang tempat Anda "check out" saat ini. Gunakan `git status` untuk melihat cabang mana itu.
Mari kita melalui alur kerja kontributor. Asumsikan kontributor sudah _forked (membagi)_ dan _cloned (mengkloning)_ repo sehingga mereka memiliki repo Git yang siap untuk dikerjakan, di mesin lokal mereka:
1. **Buat cabang**. Gunakan perintah `git branch` untuk membuat cabang yang akan berisi perubahan yang dimaksudkan untuk dikontribusikan:
```bash
git branch [nama-cabang]
```
1. **Beralih ke cabang kerja**. Beralih ke cabang yang ditentukan dan perbarui direktori kerja dengan `git switch`:
```bash
git switch [nama-cabang]
```
1. **Bekerja**. Pada titik ini Anda ingin menambahkan perubahan Anda. Jangan lupa untuk memberi tahu Git tentangnya dengan perintah berikut:
```bash
git add .
git commit -m "perubahan saya"
```
Pastikan Anda memberikan nama yang baik pada komitmen Anda, demi Anda dan juga pemelihara repo yang Anda bantu.
1. **Gabungkan pekerjaan Anda dengan cabang `main`**. Pada titik tertentu Anda telah selesai bekerja dan Anda ingin menggabungkan pekerjaan Anda dengan pekerjaan yang ada di cabang `main`. Cabang `main` mungkin telah berubah sementara itu jadi pastikan Anda terlebih dahulu memperbaruinya ke yang terbaru dengan perintah berikut:
```bash
git switch main
git pull
```
Pada titik ini Anda ingin memastikan bahwa setiap _conflicts (konflik)_, situasi di mana Git tidak dapat dengan mudah _combine (menggabugkan)_ perubahan terjadi di cabang kerja Anda. Oleh karena itu jalankan perintah berikut:
```bash
git switch [nama-cabang]
git merge main
```
Ini akan membawa semua perubahan dari `main` ke cabang Anda dan mudah-mudahan Anda bisa langsung melanjutkan. Jika tidak, VS Code akan memberi tahu Anda di mana Git _confused (bingung)_ dan Anda hanya mengubah file yang terpengaruh untuk mengatakan konten mana yang paling akurat.
1. **Kirim pekerjaan Anda ke GitHub**. Mengirim pekerjaan Anda ke GitHub berarti dua hal. Mendorong cabang Anda ke repo Anda dan kemudian membuka PR, Pull Request (Permintaan Tarik).
```bash
git push --set-upstream origin [nama-cabang]
```
Perintah di atas membuat cabang di repo bercabang Anda.
1. ****. Selanjutnya, Anda ingin membuka PR. Anda melakukannya dengan menavigasi ke repo bercabang di GitHub. Anda akan melihat indikasi di GitHub yang menanyakan apakah Anda ingin membuat PR baru, Anda mengkliknya dan Anda akan dibawa ke antarmuka di mana Anda dapat mengubah judul pesan commit, berikan deskripsi yang lebih sesuai. Sekarang pengelola repo Anda bercabang akan melihat PR ini dan _semoga_ mereka akan menghargai dan _merge (menggabungkan)_ PR Anda. Anda sekarang menjadi kontributor, hore :)
1. **Membersihkan**. Ini dianggap praktik yang baik untuk _membersihkan_ setelah Anda. Anda ingin membersihkan cabang lokal dan cabang yang Anda dorong ke GitHub. Pertama mari kita hapus secara lokal dengan perintah berikut:
```bash
git branch -d [nama-cabang]
```
Pastikan Anda membuka halaman GitHub untuk repo bercabang berikutnya dan hapus cabang jarak jauh yang baru saja Anda dorong ke sana.
`Pull request` sepertinya istilah yang konyol karena Anda benar-benar ingin mendorong perubahan Anda ke proyek. Namun pengelola (pemilik proyek) atau tim inti perlu mempertimbangkan perubahan Anda sebelum menggabungkannya dengan cabang "main" proyek, jadi Anda benar-benar meminta keputusan perubahan dari pengelola.
Pull request adalah tempat untuk membandingkan dan mendiskusikan perbedaan yang diperkenalkan pada cabang dengan ulasan, komentar, pengujian terintegrasi, dan banyak lagi. Pull request yang baik mengikuti aturan yang kira-kira sama dengan pesan komit. Anda dapat menambahkan referensi ke masalah di pelacak masalah, ketika pekerjaan Anda, misalnya, memperbaiki masalah (issue). Ini dilakukan dengan menggunakan `#` diikuti dengan nomor masalah (issue) Anda. Misalnya `#97`.
🤞Semoga semua pemeriksaan lulus dan pemilik proyek menggabungkan perubahan Anda ke dalam proyek🤞
Perbarui cabang lokal Anda saat ini dengan semua komit baru dari cabang jarak jauh yang sesuai di GitHub:
`git pull`
## Bagaimana berkontribusi pada open source
Pertama, mari temukan repositori - atau: repo - di GitHub yang Anda minati dan yang ingin Anda beri kontribusi perubahan. Anda akan ingin menyalin konten ke mesin kami.
✅ Cara yang baik untuk menemukan repositori 'ramah-pemula' adalah [menelusuri dengan tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-mulai-berkontribusi-ke-open-source/).
![Salin repo secara lokal](../images/clone_repo.png)
Ada beberapa cara untuk menyalin kode. Salah satu caranya adalah dengan "menggandakan" konten repositori, menggunakan HTTPS, SSH, atau menggunakan GitHub CLI (Command Line Interface).
Buka terminal Anda dan kloning repositori seperti ini:
`git clone https://github.com/ProjectURL`
Untuk mengerjakan proyek, alihkan ke folder yang benar:
`cd ProjectURL`
Anda juga dapat membuka seluruh proyek menggunakan [Codespaces](https://github.com/features/codespaces), editor kode / lingkungan pengembangan cloud GitHub yang disematkan, atau [GitHub Desktop](https://desktop.github.com/ ).
Terakhir, Anda dapat mengunduh kode dalam folder zip.
### Beberapa hal menarik lainnya tentang GitHub
Anda dapat membintangi, menonton, dan / atau "fork (membagi)" repositori publik apa pun di GitHub. Anda dapat menemukan repositori berbintang di menu tarik-turun kanan atas. Ini seperti mem-bookmark, tetapi untuk kode.
Proyek memiliki pelacak masalah, sebagian besar di GitHub di tab "Issues (Masalah)" kecuali dinyatakan lain, tempat orang-orang mendiskusikan masalah yang terkait dengan proyek. Dan tab Pull Requests (Permintaan Tarik) adalah tempat orang mendiskusikan dan meninjau perubahan yang sedang berlangsung.
Proyek mungkin juga memiliki diskusi di forum, milis, atau saluran obrolan seperti Slack, Discord atau IRC.
✅ Lihatlah repo GitHub baru Anda dan coba beberapa hal, seperti mengedit pengaturan, menambahkan informasi ke repo Anda, dan membuat proyek (seperti papan Kanban). Banyak yang bisa Anda lakukan!
---
## 🚀 Tantangan
Sandingkan dengan seorang teman untuk mengerjakan kode satu sama lain. Buat proyek secara kolaboratif, buat kode, buat cabang, dan gabungkan perubahan.
## Kuis Pasca Kuliah
[Kuis pasca kuliah](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=id)
## Review & Belajar Mandiri
Baca lebih lanjut tentang [berkontribusi pada software open source](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Latihan, latihan, latihan. GitHub memiliki jalur pembelajaran yang bagus yang tersedia melalui [lab.github.com](https://lab.github.com/):
- [Minggu Pertama di GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Anda juga akan menemukan lab yang lebih canggih.
## Tugas
Selesaikan [Minggu Pertama di lab pelatihan GitHub](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,315 @@
# Introduzione a GitHub
Questa lezione tratta delle basi di GitHub, una piattaforma per ospitare e gestire modifiche al proprio codice.
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Quiz Pre-lezione
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=it)
## Introduzione
In questa lezione tratteremo come:
- tracciare il lavoro che si fa sulla propria macchina
- lavorare con altri su progetti
- come contribuire a software open source
### Prerequisiti
Prima di iniziare, si dovrebbe verificare se Git è installato. Dal terminale digitare:
`git --version`
Se Git non è installato, [scaricare Git](https://git-scm.com/downloads). Poi impostare il proprio profilo locale Git dal terminale:
* `git config --global user.name "il-proprio-nominativo"`
* `git config --global user.email "la-propria-email"`
Per verificare se Git è già configurato si può digitare:
`git config --list`
E' anche necessario un account GitHub, un editor di codice (tipo Visual Studio Code), e sarà necessario aprire il proprio terminale (o prompt di comando).
Navigare su [github.com](https://github.com/) e creare un account se non se ne dispone già di uno, oppure accedere e compilare il proprio profilo.
✅ GitHub non è il solo deposito di codice nel mondo, ce ne sono altri, ma GitHub è il più conosciuto.
### Preparazione
Servirà sia una cartella con il codice di un progetto sulla propria macchina locale (laptop o PC), e un repository pubblico su GitHub, che servirà come esempio su come contribuire a progetti di altri.
---
## Gestione del codice
Diciamo che si ha una cartella in locale con del codice di un progetto e che si vuole iniziare a tracciarne lo sviluppo usando git - il sistema di controllo di versione. Alcuni paragonano l'uso di git alla scrittura di una lettera d'amore a se stessi nel futuro. Leggendo i messaggi di commit giorni, settimane o mesi più tardi si dovrà essere in grado di ricordare perchè è stata presa una certa decisione, o ripristinare ("rollback") una modifica - questo è, quando si scrivono dei buoni "messaggi di commit".
### Compito: Creare un repository e inserirvi codice via commit
1. **Creare un repository su GitHub**. Su GitHub.com, nella scheda repositories, o dalla barra di navigazione in alto a destra, trovare il bottone **new repository**.
1. Dare un nome al proprio repository (cartella)
1. Selezionare **create repository**.
1. **Navigare verso la propria cartella di lavoro**. Nel proprio terminale, portarsi nella cartella (detta anche directory) che si vuole iniziare a tracciare. Digitare:
```bash
cd [nome della cartella]
```
1. **Inizializzare un repository git**. Nel proprio progetto digitare:
```bash
git init
```
1. **Verifica stato**. Per verificare lo stato del proprio repository digitare:
```bash
git status
```
il risultato potrebbe essere qualcosa tipo:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
In genere un comando `git status` informa circa quali file sono pronti per essere _salvati_ nel repository o quali modifiche sono state effettuate che si vogliono persistere.
1. **Aggiungere tutti i file per la tracciatura**
Fase nota anche come aggiungere file nell'area di staging.
```bash
git add .
```
Gli argomenti `git add` più `.` indicano che tutti i propri file e modifiche sono selezionati per la tracciatura.
1. **Aggiungere file selezionati per la tracciatura**
```bash
git add [file o nome cartella]
```
Questo consente di aggiungere file nell'area di staging quando non si vogliono aggiungere tutti in una volta.
1. **Togliere dall'area di staging tutti i file**
```bash
git reset
```
Questo comando consente di togliere tutti i file dall'area di staging.
1. **Togliere dall'area di staging uno specifico file**
```bash
git reset [file o nome cartella]
```
Questo comando consente di togliere dall'area di staging uno specifico file che non si vuole includere nel commit successivo.
1. **Persistere il proprio lavoro**. A questo punto sono stati aggiunti tutti i file alla cosiddetta _area di staging_. Un posto nel quale Git sta tracciando i propri file. Per rendere permanenti le modifiche occorre eseguire un'azione di _commit_ dei file. Per farlo si crea un _commit_ con il comando `git commit`. Un _commit_ rappresenta un punto di salvataggio nella storia del proprio repository. Digitare questo per creare un _commit_:
```bash
git commit -m "primo commit"
```
Questo esegue il commit di tutti i file a suo tempo inclusi, aggiungendo il messaggio 'primo commit'. Per messaggi di commit successivi si vorrà essere più descrittivi nell'esposizione per identificare il tipo di modifiche effettuate.
1. **Connettere il repository Git locale a GitHub**. Un repository Git va bene sulla propria macchina ma a un certo punto si vuole avere una copia dei propri file da qualche altra parte e anche invitare altre persone a lavorare al proprio progetto. Un gran posto per fare questo è GitHub. Si ricorderà che è stato già creato un repository in GitHub quindi la sola cosa da fare è connettere il repository Git locale con GitHub. Il comando `git remote add` farà proprio questo. Digitare il comando:
> Nota, prima di digitare il comando portarsi sulla propria pagina del repository su GitHub per trovare l'URL del repository. Dovrà essere usato nel comando seguente. Sostituire `repository_name` con il proprio URL di GitHub e `username` con il proprio nome utente di github.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Questo crea un _remote_, o connessione, chiamata "origin" che punta al repository GitHub precedentemente creato.
1. **Inviare file locali a GitHub**. Fino ad ora è stata creata una _connessione_ tra il repository locale e quello GitHub. Ora si inviano i file locali a GitHub usando il comando `git push`, in questo modo:
```bash
git push -u origin main
```
Questo invia i propri commit nel ramo "main" di GitHub.
1. **Aggiungere ulteriori modifiche**. Se si vuole continuare a fare modifiche e inviarle a GitHub occorre usare uno dei tre comandi seguenti:
```bash
git add .
git commit -m "digitare qui il messaggio di commit"
git push
```
> Suggerimento, Si potrebbe anche utilizzare un file `.gitignore` per evitare che alcuni file che non si vogliono tracciare finiscano su GitHub - come le note che si salvano sulla cartella del progetto ma che non sono adatte in un repository pubblico. Si possono trovare modelli di file `.gitignore` a [modelli .gitignore](github.com/github/gitignore).
#### Messaggi di commit
Una grande riga di oggetto per un commit Git completa la seguente frase:
Se applicato, questo commit farà ... (qui la vostra riga oggetto)
Per l'oggetto utilizzare l'imperativo presente: "modifica" non "modificato" o "modifiche"- Come per l'oggetto nel corpo (opzionale) usar4 l'imperativo presente. Il corpo dovrebbe includere il motivo della modifica e il confronto con il precedente comportamento. Si sta spiegando il `perchè`, non il `come`.
✅ Si prenda qualche minuto per esplorare GitHub. E' possibile scovare un bel messaggio di commit? Se ne puà trovare uno assolutamente minimale? Quali informazioni si pensa che siano le più importanti e utili per un messaggio di commit?
### Compito: Collaborare
La ragione principale per inserire cose in GitHub è di fare in modo che si possa collaborare tra sviluppatori.
## Lavorare su progetti con altri
Nel proprio repository, portarsi a `Insights > Community` per vedere come il proprio progetto si confronta con gli standard della comunità.
Ecco alcune cose che possono migliorare il proprio repository GitHub:
- **Descrizione**. E' stata aggiunta una descrizione per il proprio progetto?
- **README**. E' stato aggiunto un README (leggimi)? GitHub fornisce una traccia per scrivere un [README](https://docs.github.com/articles/about-readmes/).
- **Linee guida per contribuire**. Il proprio progetto fornisce [linne guida per contribuire](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Codice di Condotta**. un [Codice di Condotta](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Licenza**. Forse la più imporatante, una [licenza](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Tutte queste risorse favoriranno la salita a bordo di nuovi elementi nella squadra. Queste sono in genere il tipo di cose che i nuovi contributori cercano anche prima di dare un'occhiata al codice, per scoprire se il progetto è il posto giusto per spendere il loro tempo.
✅ I file README, sebbene richiedono tempo per prepararli, sono spesso trascurati da manutentori troppo occupati. E' possibile trovare un esempio di uno particolarmente descrittivo? Nota: ci sono alcuni [strumenti per aiutare la creazione di buoni README](https://www.makeareadme.com/) che si potrebbero provare.
### Compito: Fondere del codice
La documentazione per la collaborazione aiuta a fare sì che la gente contribuisca al progetto. Spiega che tipo di collaborazione ci si deve attendere e come funziona il processo. I contributori dovranno compiere una serie di passi per poter contribuire a un repository su GitHub:
1. **Biforcare il repository** Probabilmente si vorrà che la gente possa _biforcare_ il proprio progetto (forking). Questa azione crea una replica di un repository al quale si vuole contribuire sul profilo del contributore su GitHub.
1. **Clonare**. Da qui verrà eseguita una azione di clonazione del progetto sulla macchina locale del contributore.
1. **Creare un ramo**. Sarà richiesto al contributore di creare un _ramo_ (branch) per il suo lavoro.
1. **Concentrare le modifiche del contributore su una area**. Richiedere ai contributori di concentrarsi su una cosa sola alla volta - in questo modo le possibilità che si possa _fondere_ (merge) il lavoro del contributore sono più alte. Se viene scritta la risoluzione di un bug, o viene aggiunta una nuova funzionalità o vengono aggiornati parecchi test - cosa succede se si vuole o si può, solo implementarne 2 su 3 o 1 su 3 di queste modifiche?
✅ Si immagini una situazione dove i rami sono particolarmente critici per la scrittura e lo sviluppo di buon codice. A quali casi d'uso sono stati individuati?
> Nota, siate il cambiamento che volete vedere nel mondo, e si creino rami anche per il proprio lavoro. Qualsiasi commit che verrà fatto sarà su rami che si sta attualmente *verificando* (check out). Usare `git status` per vedere su quale ramo ci si trova attualmente.
Si analizza il flusso di lavoro di un contributore. Si assume che egli abbia già eseguito il _fork_ e _clonato_ il repository in modo che lo stesso sia pronto per lavorarci, sulla sua macchina locale:
1. **Creare un ramo**. Usare il comando `git branch` per creare un ramo che conterrà le modifiche per le quali si è offerta la collaborazione:
```bash
git branch [branch-name]
```
1. **Passare al ramo di lavoro**. Passare al ramo specificato e aggiornare la directory di lavoro con `git switch`:
```bash
git switch [nome ramo]
```
1. **Eseguire il lavoro**. A questo punto si vorranno aggiungere i propri cambiamenti. Non dimenticarsi di dirlo a Git tramite questi comandi:
```bash
git add .
git commit -m "le mie modifiche"
```
Assicurarsi che il commit abbia un buon messaggio, a beneficio proprio e del manutentore del repository sul quale si sta collaborando.
1. **Combinare il proprio lavoro con il ramo `main`**. Una volta terminato il lavoro occorre combinarlo con quello del ramo principale (`main`). Il ramo principale potrebbe avere subito cambiamenti nel mentre quindi ci si deve assicurare di eseguire prima un aggiornamento all'ultima versione con i comandi:
```bash
git switch main
git pull
```
A questo punto occorre assicurarsi che qualsiasi eventuale _conflitto_ (conflict), situazioni dove Git non è in grado di determinare facilmente come _combinare_ le modifiche effettuate nel proprio ramo di lavoro. Eseguire i seguenti comandi:
```bash
git switch [branch_name]
git merge main
```
Questo porterà tutte le modifiche da `main` verso il proprio ramo, augurandosi che si possa poi continuare. In caso contrario VS Code vi può indicare dove Git si _confonde_ e si potranno modificare i file coinvolti per determinare quale contenuto sia il più accurato.
1. **Inviare il proprio lavoro a GitHub**. Questo significa due cose. Spingere il proprio ramo verso il proprio repository, quindi aprire una PR, Pull Request.
```bash
git push --set-upstream origin [nome-ramo]
```
Il comando qui sopra crea il ramo sulla propria biforcazione del repository.
1. **Aprire una PR**. Successivamente, si vorrà aprire una Pull Request. Si fa portandosi nel repository biforcato su GitHub. Si vedrà una indicazione su GitHub dove viene chiesto se si vuol creare una nuova PR, cliccando su questa si verrà portati su una interfaccia dove si potrà cambiare il titolo del messaggio di commit e fornire una descrizione più adatta. Ora il manutentore del repository che è stato biforcato vedrà questa PR e _incrociando le dita_ apprezzerà e _fonderà_ (merge) la PR. Ora si avrà contribuito, yay :)
1. **Pulire**. E' considerata buona pratica effettuare una _pulizia_ dopo il lavoro compiuto. Si vorrà pulire sia il ramo locale che quello spinto su GitHub. Per prima cosa cancellarlo localmente con il comando:
```bash
git branch -d [nome-ramo]
```
Successivamente assicurarsi di andare nella pagina GitHub per del repository biforcato per eliminare il ramo remoto che è stato appena spinto.
`Pull request` sembra un termine sciocco in quanto in realtà si vogliono portare le proprie modifiche al progetto. Ma il manutentore (proprietario del progetto) o la squadra base deve valutare i cambiamenti dei contributori prima di fonderli con il ramo principale del progetto, quindi in realtà il contributore sta chiedendo una decisione sulle modifiche al manutentore.
Una pull request è il posto dove confrontare e discutere le differenze introdotte su un ramo con valutazioni, commenti, verifiche integrate e altro. Una buona pull request segue grossolanmente le stesse regole di un messaggio di commit. Si può aggiungere un riferimento al problema nel tracciatore di problemi (issue tracker), quando il proprio lavoro risolve ad esempio un problema. Questo viene fatto usando un `#` seguito dal numero del vostro problema. Ad esempio `#97`.
🤞Incrociando le dita si spera che tutte le verifiche vengano superate e che il proprietario(i) del progetto voglia incorporare le modifiche all'interno del progetto🤞
Aggiornare il proprio ramo corrente locale con tutti i nuovi commit per il ramo remoto corrispondente su GitHub:
`git pull`
## Come contribuire a progetti open source
Per prima cosa, trovare un repository - o repo - che interessi su GitHub e per il quale si desideri contribuire con una modifica. Si vorrà copiare il contenuto sulla propria macchina.
✅ Un buon modo di trovare repository 'adatti per i principianti' è di [cercare il tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copiare un repository localmente](../images/clone_repo.png)
Ci sono parecchi modi di copiare il codice. Un modo è "clonare" il contenuto del repository, usando HTTPS, SSH, o usando l'interfaccia da riga di comando GitHub CLI.
Aprire il proprio terminale e clonare il repository così:
`git clone https://github.com/URLdelProgetto`
Per lavorare su un progetto, passare alla corretta cartella:
`cd URLdelProgetto`
Si può anche aprire l'intero progetto usando [Codespaces](https://github.com/features/codespaces), l'editor di codice incorporato di GitHub, oppure un ambiente di sviluppo nel cloud, oppure [GitHub Desktop](https://desktop.github.com/).
Infine si può scaricare il codice in una cartella compressa.
### Qualche altra cosa interessante riguardo a GitHub
E' possibile attribuire una stella, osservare, e/o "biforcare" un qualsiasi progetto pubblico su GitHub. Si possono trovare i propri repository che hanno stelle nel menù a tendina in alto a destra. E' come mettere un segnalibro, ma per il codice.
I progetti che hanno un tracciatore di problemi, per la maggior parte nella scheda "Issues" di GitHub a meno di indicazioni diverse, è dove la gente discute dei problemi relativi al progetto. E la scheda Pull Requests è dove la gente discute e verifica le modifiche in corso d'opera.
I progetti potrebbero anche essere discussi nei forum, liste di distribuzione, o canali chat come Slack, Discord o IRC.
✅ Dare una occhiata al proprio nuovo repository in GitHub e provare alcune cose, come modificare la configurazione, aggiungere informazioni al repository e creare un progetto come un tabellone Kanban. C'è tanto che si può fare!
---
## 🚀 Sfida
Fare coppia con un amico per lavorare al codice dei progetti l'uno dell'altro. Creare un progetto in modo collaborativo, biforcare il codice, craare rami e fondere modifiche.
## Quiz Post-lezione
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=it)
## Revisione e Auto Apprendimento
Leggene di più al riguardo: [contribuire a software open source](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Esercizio, esercizio, esercizio. GitHub ha ottimi percorsi di apprendimento disponibili via [lab.github.com](https://lab.github.com/):
- [Prima settimana su GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Si potranno trovare anche altri laboratori più avanzati.
## Compito
Completare [la prima settimana nel laboratorio di apprendimento di GitHub](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,294 @@
# GitHub 소개
이 강의에서는 코드 변경점을 호스팅하고 관리하는 플랫폼인 GitHub의 기본 사항을 다룹니다.
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## 강의 전 퀴즈
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=ko)
## 소개
이 강의에서는 다룹니다:
- 기계에서 수행하는 작업 추적
- 다른 사람들과 프로젝트 작업
- 오픈소스 소프트웨어에 기여하는 방법
### 작업 필요
시작하기 전에 Git이 설치되어 있는지 확인해야합니다. 터미널에서 작업:
`git --version`
만약 Git이 설치되어 있지 않다면, [Git 내려받습니다](https://git-scm.com/downloads). 그리고, 터미널에서 로컬 Git 프로필을 설정합니다:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
Git이 이미 구성되어 있는지 확인하려면 다음을 입력합니다:
`git config --list`
GitHub 계정, (Visual Studio Code와 같은) 코드 에디터가 필요하며, 터미널(혹은: command prompt)을 열어야 합니다.
아직 계정이 없는 경우에는 [github.com](https://github.com/)으로 이동하여 계정을 생성하거나, 로그인하여 프로필을 작성합니다.
✅ GitHub는 유일한 코드 저장소가 아닙니다. 다른 곳들도 있지만 GitHub가 가장 잘 알려져 있습니다.
### 준비
로컬 장치(노트북 또는 PC)에 코드 프로젝트 폴더와 다른 프로젝트에 기여하는 방법의 예시가 될 GitHub 공개 저장소가 모두 필요합니다.
---
## 코드 관리
일부 코드 프로젝트에 포함된 폴더가 로컬에 있고 버전 제어 시스템인 git을 사용하여 진행 상황을 추적하려고 한다고 가정해보겠습니다. 어떤 사람들은 git을 사용하여 미래의 자신에게 연애 편지를 쓰는 것과 비교합니다. 며칠, 몇 주 또는 몇 달 후에 커밋 메시지를 읽으면 그 때 결정을 한 이유를 기억하거나 변경점을 "롤백"할 수 있습니다. 즉, 좋은 "커밋 메시지"를 작성할 때입니다.
### 작업: 저장소 만들고 코드 커밋하기
1. **GitHub에 저장소 만들기**. GitHub.com에서 repositories 탭을 보거나, 우측 상단 네비케이션 바에서 **new repo** 버튼을 찾습니다.
1. 저장소(폴더)에 이름을 지정합니다
1. **create repository** 선택합니다.
1. **작업 폴더로 이동하기**. 터미널에서 추적을 시작할 폴더(디렉토리)로 이동하기 위해 입력합니다:
```bash
cd [name of your folder]
```
1. **git 저장소 초기화하기**. 프로젝트에서 입력합니다:
```bash
git init
```
1. **상태 확인하기**. 상태를 확인하려면 저장소에서 입력합니다:
```bash
git status
```
다음과 같이 출력될 수 있습니다:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
일반적으로 `git status` 명령은 어떤 파일이 저장소에 _저장_ 될 준비가 되었는 지 또는 유지하고 싶은 변경점이 있는 지 등을 알려줍니다.
1. **추적할 파일 추가하기**
```bash
git add .
```
`git add`와 같이 있는 `.` 인수는 모든 파일 및 변경점을 나타냅니다.
1. **작업 지속하기**. Git이 파일을 추적하는 곳에 _staging area_ 라는 파일을 추가했습니다. 영구적으로 변경하려면 파일을 _commit_ 해야합니다. 그렇게 하려면`git commit` 명령으로 _commit_ 을 생성합니다. _commit_ 은 저장소 기록의 저장 시점을 나타냅니다. 다음을 입력하여 _commit_ 을 생성합니다:
```bash
git commit -m "first commit"
```
이렇게하면 모든 파일이 커밋되고, "first commit" 메시지가 추가됩니다. 향후 커밋 메시지의 경우 변경점을 전달하기 위해 설명을 구체적으로 작성해야합니다.
1. **GitHub와 로컬 Git 저장소 연결하기**. Git 저장소는 장치에 존재하기에 좋지만, 어느 시점에서 파일을 어딘가에 백업하고 다른 사람이 저장소에서 함께 작업하도록 초대하고 싶습니다. 그렇게 하기에 좋은 곳 중 하나는 GitHub입니다. 이미 GitHub에 저장소를 만들었으므로 로컬 Git 저장소를 GitHub에 연결할 뿐입니다. `git remote add` 명령을 수행합니다. 다음 명령을 입력합니다:
> Note, 명령을 입력하기 전에 GitHub 저장소 페이지로 이동하여 저장소 URL을 찾아두십시오. 아래 명령에서 사용됩니다. `repository_name`을 GitHub URL로 바꿉니다.
```bash
git remote add origin https://github.com/username/repository_name.git
```
이렇게 이전에 만든 GitHub 저장소를 가리키는 "origin"이라는 _remote_ 또는 커넥션이 생성됩니다.
1. **GitHub로 로컬 파일 보내기**. 지금까지 로컬 저장소와 GitHub 저장소 사이에 _connection_ 을 생성했습니다. 다음과 같이 `git push` 명령을 사용하여 이러한 파일을 GitHub로 보냅니다:
```bash
git push -u origin main
```
"main" 브랜치는 GitHub로 커밋이 보내집니다.
1. **더 많은 변경점 추가하기**. 계속 작업하여 GitHub로 푸시하려면 다음 세 가지 명령을 사용하면됩니다:
```bash
git add .
git commit -m "type your commit message here"
git push
```
> Tip, 추적하고 싶지 않은 파일이 GitHub에 표시되는 것을 방지하기 위해 `.gitignore` 파일을 채용할 수 있습니다. 동일한 폴더에 저장하지만 공개 저장소에는 존재하지 않는 노트 파일과 같습니다. `.gitignore` 파일의 템플릿은 [.gitignore templates](https://github.com/github/gitignore)에서 찾을 수 있습니다.
#### 커밋 메시지
A great Git commit subject line completes the following sentence:
If applied, this commit will <your subject line here>
훌륭한 Git 커밋 제목 줄은 다음 문장을 완성합니다:
적용되면, 이 커밋은 <your subject line here>이 됩니다.
제목에 대해서는 명령문 또는 현재 시제를 사용하십시오 : "변경됨" 또는 "변경점"이 아닌 "변경".
제목과 마찬가지로 본문(선택 사항)에서도 명령문, 현재 시제를 사용합니다. 본문은 변화에 대한 동기를 포함하고 이를 이전 변경점과 대조해야 합니다. '어떻게'가 아니라 '왜'를 설명하고 있습니다.
✅ 몇 분 동안 GitHub를 둘러보세요. 정말 훌륭한 커밋 메시지를 찾을 수 있습니까? 정말 최소한의 것을 찾을 수 있습니까? 커밋 메시지에서 전달하는 데 가장 중요하고 유용한 정보는 무엇이라고 생각하십니까?
### 작업: 협업하기
GitHub에 코드를 올리는 주 이유는 다른 개발자와 협력할 수 있도록 하기 위함입니다.
## 다른 사람들과 함께 프로젝트 작업하기
저장소에서, `Insights> Community`로 이동하여 프로젝트에 권장되는 커뮤니티 표준과 어떻게 비교되는지 확인합니다.
다음은 GitHub 저장소를 개선 할 수있는 몇 가지 사항입니다:
- **설명**. 프로젝트에 설명을 추가했습니까?
- **README**. README를 추가했습니까? GitHub는 [README](https://docs.github.com/articles/about-readmes/) 작성에 대한 지침을 제공합니다.
- **기여 가이드**. [기여 가이드](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Code of Conduct**. [Code of Conduct](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **라이선스**. 아마도, 가장 중요한 [라이선스](https://docs.github.com/articles/adding-a-license-to-a-repository/)도 가지고 있습니까?
이러한 모든 리소스는 새로운 팀원을 온보딩하는 데 도움이 됩니다. 그리고 일반적으로 새로운 기여자들이 여러분의 프로젝트가 시간을 보내기에 적합한 장소인지 확인하기 위해 코드를 보기 전 살펴 보는 것입니다.
✅ README 파일은 준비하는 데 시간이 걸리지만 바쁜 관리자들은 종종 무시합니다. 특히 설명적인 예를 찾을 수 있습니까? Note: 몇 가지 [tools to help create good READMEs](https://www.makeareadme.com/)를 시도해 볼 수 있습니다.
### 작업: 코드 병합하기
문서를 제공하면 사람들이 프로젝트에 기여하는 데 도움이 됩니다. 찾고있는 기여 유형과 프로세스 작동 방식을 설명합니다. 기여자는 GitHub의 저장소에 기여할 수 있도록 일련의 단계를 거쳐야합니다:
1. **저장소 포크하기** 아마도 사람들이 당신의 프로젝트를 _fork_ 하기를 원할 것입니다. 포크는 자신의 GitHub 프로필에 저장소 복제본을 만드는 걸 의미합니다.
1. **복제하기**. 프로젝트를 로컬 컴퓨터에 복제합니다.
1. **브랜치 생성하기**. 작업을 위해 _branch_ 를 만들도록 요청하고 싶을 것입니다.
1. **한 영역에 변화를 집중하기**. 기여자에게 한 번에 한 가지만 집중하도록 요청하세요 - 그러면 작업에 _병합_ 할 수 있는 가능성이 더 높아집니다. 그들이 버그 수정을 작성하고, 새로운 기능을 추가하고, 여러 테스트를 추가한다고 상상해보십시오. 원한다면 3개 중 2개 또는 3개 중 1개만 구현할 수 있습니까?
✅ 좋은 코드를 작성하고 전달하는 데 branches가 중요한 상황을 상상해보십시오. 어떤 사용 사례를 생각할 수 있습니까?
> Note, 모두가 보고싶은 변경점이나, 자신의 작업만을 위한 브랜치를 만들 수도 있습니다. 모든 커밋은 현재 "체크 아웃"된 브랜치에서 이루어집니다. `git status`를 사용하여 어떤 브랜치인지 확인하십시오.
기여자 워크플로우를 살펴봅니다. 기여자가 이미 저장소를 _forked_ 하거나 _cloned_ 했기 때문에 로컬 머신에서 작업할 준비가 된 Git 저장소가 있다고 가정합니다.
1. **브랜치 생성하기**. `git branch` 명령을 사용하여 기여하려는 변경 사항을 포함하는 브랜치를 만듭니다:
```bash
git branch [branch-name]
```
1. **작업 브랜치 변경하기**. 지정된 브랜치로 전환하고 `git switch`으로 작업 디렉토리를 업데이트합니다:
```bash
git switch [branch-name]
```
1. **일하기**. 이 시점에서 변경 사항을 추가하려고 합니다. 다음 명령을 사용하여 Git에 알리는 것을 잊지 마시기 바랍니다:
```bash
git add .
git commit -m "my changes"
```
도와주고 있는 저장소의 관리자뿐만 아니라 당신을 위해서, 커밋에 좋은 이름을 부여해야 합니다.
1. **`main` 브랜치에서 작업하기**. 어느 시점에서 작업을 마치고 `main` 브랜치의 작업과 병합하려고 합니다. 그동안 `main` 브랜치가 변경되었을 수 있으므로, 먼저 다음 명령을 사용하여 최신 버전으로 업데이트해야합니다:
```bash
git switch main
git pull
```
이 시점에서 Git이 변경 사항을 쉽게 _결합_ 할 수 없는 _충돌_ 상황이 작업 브랜치에서 발생하는지 확인하려고합니다. 따라서 다음 명령을 실행합니다:
```bash
git switch [branch_name]
git merge main
```
이렇게하면 `main` 에서 브랜치로 모든 변경점을 가져올 수 있으며 계속 진행할 수 있습니다. 그렇지 않은 경우에는 VS Code는 Git이 _혼란스러운_ 위치를 알려주고 영향받는 파일을 변경하여 가장 정확한 곳을 알려주면 됩니다.
1. **GitHub로 작업 보내기**. 작업을 GitHub에 보내는 것은 두 가지를 의미합니다. 브랜치를 저장소로 푸시 한 다음 PR, Pull Request를 엽니다.
```bash
git push --set-upstream origin [branch-name]
```
위의 명령은 포크된 저장소에 브랜치를 만듭니다.
1. **PR 열기**. 다음으로, PR을 열고 싶습니다. GitHub의 포크된 저장소로 이동하면 됩니다. GitHub에서 새 PR을 만들 것인지 묻는 표시가 표시되고 이를 클릭하면 커밋 메시지 제목을 변경할 수 있는 인터페이스로 이동하게 되며 더 적절한 설명을 작성할 수 있습니다. 이제 포크한 저장소의 관리자는 이 PR을 보고 _행운을 빌며_ 감사하고 _병합_ PR을 수행합니다. 당신은 이제 기여자입니다, yay :)
1. **정라하기**. 나중에 _정리_ 하는 것은 좋은 습관으로 간주됩니다. 로컬 브랜치와 GitHub에 푸시한 브랜치를 모두 정리하려고 합니다. 먼저 다음 명령을 사용하여 로컬에서 삭제하겠습니다:
```bash
git branch -d [branch-name]
```
포크된 저장소의 GitHub 페이지로 이동하여 방금 푸시한 원격 브랜치를 제거합니다.
변경점을 프로젝트에 푸시하고 싶기 때문에 `Pull request`는 어리석은 용어처럼 보입니다. 그러나 관리자(프로젝트 소유자) 또는 핵심 팀은 변경점을 프로젝트의 "main" 브랜치와 병합하기 전에 고려해야 하므로 실제로 유지 관리자에게 결정을 요청하는 것입니다.
pull request는 리뷰, 코멘트, 통합 테스트 등을 통해 브랜치에 도입된 차이점을 비교하고 논의하는 곳입니다. 좋은 pull request는 커밋 메시지와 거의 동일한 규칙을 따릅니다. 예를 들어 작업에서 문제를 해결할 때 이슈 트래커에서 이슈에 대한 참조를 추가할 수 있습니다. 이 작업은 `#` 다음에 이슈 번호를 사용하여 수행됩니다. 예를 들어 `#97` 처럼 말입니다.
🤞 모든 검사가 통과되고 프로젝트 소유자가 변경 사항을 프로젝트에 병합한다는 손가락이 교차했습니다 🤞
현재 로컬 작업 브랜치를 GitHub의 원격 브랜치의 커밋으로 모두 업데이트합니다:
`git pull`
## 오픈소스에 기여하는 방법
먼저, GitHub에서 관심있고 변경 사항을 기여할 저장소를 찾아 보겠습니다. 그 곳의 내용을 자신의 장치에 복사하고 싶을 것입니다.
✅ '입문-친화적'인 저장소를 찾는 좋은 방법은 ['good-first-issue 태그로 검색하는 것입니다.'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copy a repo locally](../images/clone_repo.png)
코드를 복사하는 방법에는 여러 가지가 있습니다. 한 가지 방법은 HTTPS, SSH 또는 GitHub CLI (Command Line 인터페이스)를 사용하여 저장소의 내용을 "복제"하는 것입니다.
터미널을 열고 다음과 같이 저장소를 복제합니다:
`git clone https://github.com/ProjectURL`
프로젝트에서 작업하려면 올바른 폴더로 전환합니다:
`cd ProjectURL`
[Codespaces](https://github.com/features/codespaces), GitHub의 내장 코드 에디터 / 클라우드 개발 환경 또는 [GitHub Desktop](https://desktop.github.com/)을 사용하여 전체 프로젝트를 열 수 있습니다.
마지막으로 압축된 폴더로 코드를 내려받을 수 있습니다.
### GitHub에 대한 몇 가지 흥미로운 사항
GitHub의 모든 공개 저장소에 스타 표시, 워치 및/또는 "포크" 할 수 있습니다. 우측 상단 드롭다운 메뉴에서 스타 표시한 저장소를 찾을 수 있습니다. 북마크와 비슷하지만 코드를 위한 것 입니다.
프로젝트에는 달리 명시되지 않는 한 대부분 GitHub에 "이슈" 탭의 이슈 트레커가 있습니다. 그리고 Pull Requests 탭은 사람들이 진행중인 변경 사항을 논의하고 검토하는 곳입니다.
프로젝트는 포럼, 메일링 리스트 또는 Slack, Discord 또는 IRC와 같은 채팅 채널에서 토론 할 수도 있습니다.
✅ 새로운 GitHub 리포지토리를 둘러보고 설정 편집, 저장소 정보 추가, (Kanban 보드와 같은) 프로젝트 생성을 비롯한 몇 가지 작업을 시도해보시기 바랍니다. 할 수 있는 일이 많이 있습니다!
---
## 🚀 도전
친구와 페어링하여 서로의 코드를 작업하세요. 공동으로 프로젝트를 만들고, 코드를 포크하고, 브랜치를 만들고, 변경 사항을 병합합니다.
## 강의 후 퀴즈
[Post-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=ko)
## 리뷰 & 자기주도 학습
[contributing to open source software](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution)에 대해 읽습니다.
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Practice, practice, practice. GitHub에는 [lab.github.com](https://lab.github.com/)을 통해 사용할 수 있는 훌륭한 학습 경로가 있습니다:
- [First Week on GitHub](https://lab.github.com/githubtraining/first-week-on-github)
더 많은 고급 실습도 찾을 수 있습니다.
## 과제
[the First Week on GitHub training lab](https://lab.github.com/githubtraining/first-week-on-github) 완료하기

View File

@@ -0,0 +1,318 @@
# Pengenalan Tentang GitHub
Pelajaran ini merangkumi pengetahuan asas tentang GitHub, dan adalah salah satu platform untuk menjadi tuan rumah dan menguruskan perubahan pada kod anda.
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Kuiz Pra-Kuliah
[Pre-lecture quiz](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Pengenalan
Dalam pelajaran ini, kita akan belajar tentang:
- mengesan kerja yang anda lakukan di mesin anda
- membuat projek dengan orang lain
- bagaimanakah menyumbang kepada perisian sumber terbuka
### Prasyarat
Sebelum bermula, anda perlu memeriksa sama ada Git dipasang dalam komputer anda. Dalam terminal menaip:
`git --version`
Sekiranya Git tidak dipasang, [memuat turun Git](https://git-scm.com/downloads). Kemudian, siapkan profil Git anda di terminal:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
Untuk memeriksa sama ada Git sudah dikonfigurasi, anda boleh menaip:
`git config --list`
Anda juga memerlukan akaun GitHub, penyunting kod (seperti Visual Studio Code), dan anda perlu membuka terminal anda (atau: command prompt).
Navigasi ke [github.com] (https://github.com/) dan buat akaun jika anda belum melakukannya, atau log masuk dan isi profil anda.
✅ GitHub bukan satu-satunya repositori kod di dunia; ada yang lain, tetapi GitHub adalah yang paling terkenal.
### Persediaan
Anda memerlukan kedua-dua folder dengan projek kod pada mesin tempatan anda (komputer riba atau PC), dan repositori awam di GitHub, yang akan menjadi contoh bagaimana menyumbang kepada projek orang lain.
---
## Pengurusan Kod
Katakan anda mempunyai folder secara tempatan dengan beberapa projek kod dan anda ingin mula mengesan kemajuan anda menggunakan git - sistem kawalan versi. Sebilangan orang membandingkan menggunakan git dengan menulis surat cinta untuk diri masa depan anda. Membaca mesej komit anda beberapa hari atau minggu atau bulan kemudian anda akan dapat mengingat mengapa anda membuat keputusan, atau "memutar balik (rollback)" perubahan - iaitu ketika anda menulis "pesan komit (commit messages)" yang baik.
### Tugasan: Buat repositori dan kod komit
1. **Buat satu repository di GitHub**. Di GitHub.com, pada tab repositori, atau dari bar navigasi di sebelah kanan atas, cari butang **repo baru (new repo)**.
1. Beri nama repositori (folder) anda
1. Pilih **repositori kreat (create repository)**.
1. **Navigasi ke folder kerja anda**. Di terminal anda, beralih ke folder (juga dikenali sebagai direktori) yang ingin anda mulakan penjejakan. Jenis:
```bash
cd [name of your folder]
```
1. **Memulakan git repositori**. Dalam jenis projek anda:
```bash
git init
```
1. **Periksa status**. Untuk memeriksa status repositori anda:
```bash
git status
```
the output can look something like this:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Biasanya perintah `git status` memberitahu anda perkara seperti fail apa yang siap disimpan_ ke repo atau mempunyai perubahan di atasnya yang mungkin anda mahu berterusan.
1. **Tambahkan semua fail untuk penjejakan**
Ini juga disebut sebagai fail pementasan / menambahkan fail ke kawasan pementasan (staging area).
```bash
git add .
```
Argumen `git add` plus `.` menunjukkan bahawa semua fail & perubahan anda untuk dijejaki.
1. **Tambahkan fail terpilih untuk dijejaki**
```bash
git add [file or folder name]
```
Ini membantu kita untuk menambahkan fail yang dipilih hanya ke kawasan pementasan ketika kita tidak ingin melakukan semua fail sekaligus.
1. **Lepaskan semua fail**
```bash
git reset
```
Perintah ini membantu kita untuk melepaskan semua fail sekaligus.
1. **Lepaskan fail yang tertentu**
```bash
git reset [file or folder name]
```
Perintah ini membantu kita untuk melepaskan hanya fail yang tertentu sekaligus yang tidak ingin kita sertakan untuk komit berikutnya.
1. **Meneruskan kerja anda**. Pada masa ini anda telah menambahkan fail ke yang disebut _staging area_. Salah satu tempat di mana Git mengesan fail anda. Untuk melakukan perubahan itu kekal, anda perlu _commit_ fail itu. Untuk melakukannya anda perlu membuat _commit_ dengan perintah `git commit`. _commit_ mewakili titik simpanan dalam sejarah repo anda. Menaip perintah tersebut untuk membuat _commit_:
```bash
git commit -m "first commit"
```
Untuk komit semua fail anda, menaip mesej "komit pertama (first commit)". Untuk mesej komit pada masa kelak, anda ingin lebih terperinci dalam penerangan anda untuk menyampaikan jenis perubahan yang telah anda buat.
1. **Sambungkan repo Git tempatan anda dengan GitHub**. Repo Git adalah bagus dalam mesin anda tetapi pada satu ketika anda ingin mempunyai sandaran fail anda di suatu tempat dan juga mengundang orang lain untuk bekerja dengan anda di repo anda. Salah satu tempat yang bagus untuk melakukannya adalah di GitHub. Ingatlah bahawa kita sudah membuat repo di GitHub jadi satu-satunya perkara yang perlu kita lakukan ialah menghubungkan repo Git tempatan kita dengan GitHub. Perintah ini `git remote add` akan membuat tugasan tersebut. Menaip perintah tersebut:
> Perhatikan, sebelum anda mengetik perintah, pergi ke halaman repo GitHub anda untuk mencari URL repositori. Anda akan menggunakannya dalam arahan di bawah. Gantikan `repository_name` degan GitHub URL.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Ini membuat _remote_, atau sambungan, bernama "origin" yang menunjuk ke repositori GitHub yang anda buat sebelumnya.
1. **Hantar fail tempatan ke GitHub**. Setakat ini anda telah membuat _connection_ antara repo tempatan dan repo GitHub. Marilah hantarkan fail-fail ini ke GitHub dengan perintah berikut `git push`, seperti di bawah:
```bash
git push -u origin main
```
Perintah ini menghantar komit anda di cawangan "utama" (main branch) anda ke GitHub.
1. **Untuk menambahkan perubahan lain**. Sekiranya anda ingin terus membuat perubahan dan menghantar ke GitHub, anda hanya perlu menggunakan tiga arahan berikut:
```bash
git add .
git commit -m "type your commit message here"
git push
```
>Tip, Anda mungkin juga mahu mengadopsi fail `.gitignore` untuk mengelakkan fail yang tidak ingin anda lacak muncul di GitHub - seperti fail nota yang anda simpan di folder yang sama tetapi tidak mempunyai tempat di repositori awam. Anda boleh mencari templat untuk `.gitignore` fail pada [.gitignore templates](github.com/github/gitignore).
#### Mesej Komit
Baris subjek Git komit yang hebat melengkapkan ayat berikut:
Sekiranya berlaku, komit ini akan <baris subjek anda di sini>
Untuk subjek gunakan keharusan, ketegangan sekarang: "perubahan" tidak "berubah" atau "perubahan".
Seperti dalam subjek, dalam badan (pilihan) juga menggunakan keharusan, sekarang tegang. Tubuh harus merangkumi motivasi untuk perubahan dan membezakannya dengan tingkah laku sebelumnya. Anda menerangkan `mengapa`, bukan `bagaimana`.
✅ Luangkan masa beberapa minit untuk melayari GitHub. Bolehkah anda menemui mesej komit yang sangat hebat? Bolehkah anda mencari yang paling minimum? Maklumat apa yang anda fikir paling penting dan berguna untuk disampaikan dalam pesanan komited?
### Tugas: Kolaborasi
Sebab utama meletakkan perkara di GitHub adalah untuk memungkinkan untuk berkolaborasi dengan pemaju lain.
## Melakukan projek dengan orang lain
Dalam repositori anda, arahkan ke `Insights> Community` untuk melihat bagaimana projek anda dibandingkan dengan standard komuniti yang disyorkan.
Berikut adalah beberapa perkara yang dapat meningkatkan repo GitHub anda:
- **Penerangan**. Adakah anda menambah keterangan untuk projek anda?
- **README**. Adakah anda menambah README? GitHub memberikan panduan untuk menulis [README](https://docs.github.com/articles/about-readmes/).
- **Garis panduan penyumbang**. Adakah projek anda mempunyai [cGaris panduan penyumbang](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Tatakelakuan**. a [Tatakelakuan](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Lesen**. Yang paling penting, ialah [lesen](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Semua sumber ini akan memberi manfaat kepada ahli pasukan baru. Dan ini biasanya merupakan jenis perkara yang dilihat oleh penyumbang baru bahkan sebelum melihat kod anda, untuk mengetahui sama ada projek anda adalah tempat yang tepat untuk mereka menghabiskan masa.
✅ README fail, walaupun memerlukan masa untuk disiapkan, sering diabaikan oleh penyelenggara yang sibuk. Bolehkah anda mencari contoh yang sangat deskriptif? Catatan: ada beberapa [alat untuk membantu mencipta README yang baik](https://www.makeareadme.com/) yang anda boleh cuba.
### Tugas: Gabungkan beberapa kod
Menyumbang kepada dokumen membantu orang menyumbang dalam projek tersebut. Ini menerangkan jenis sumbangan yang anda cari dan bagaimana prosesnya berjalan. Penyumbang perlu melalui beberapa langkah untuk dapat menyumbang kepada repo anda di GitHub:
1. **Memalsukan repo anda** Anda mungkin mahu orang membuat projek anda. Memalsukan (_fork_) bermaksud membuat replika repositori anda di profil GitHub mereka.
1. **Klon**. Dari sana mereka akan mengklonkan projek ke mesin tempatan mereka.
1. **Buat branch**. Anda ingin meminta mereka membuat branch (_branch_) untuk kerja mereka.
1. **Fokus perubahan mereka pada satu kawasan**. Minta penyumbang memusatkan sumbangan mereka pada satu perkara pada satu masa - dengan cara itu peluang yang anda dapat _merge_ dalam pekerjaan mereka adalah lebih tinggi. Bayangkan mereka menulis perbaikan pepijat, menambah ciri baru, dan mengemas kini beberapa ujian - bagaimana jika anda mahu, atau hanya dapat melaksanakan 2 dari 3, atau 1 dari 3 perubahan?
✅ Bayangkan keadaan di mana branch sangat penting untuk menulis dan menghantar kod yang baik. Apa kes penggunaan yang boleh anda fikirkan?
> Perhatikan, jadikan perubahan yang ingin anda lihat di dunia, dan buatlah cawangan untuk karya anda sendiri juga. Segala komit yang anda buat akan dibuat di cabang tempat Anda sedang "check out" gunakan `git status` untuk melihat cabang mana.
Mari melalui aliran kerja penyumbang. Anggaplah penyumbang telah _forked_ dan _cloned_ repo sehingga mereka mempunyai repo Git yang siap diusahakan, di mesin tempatan mereka:
1. **Membuat branch**. Guna perintah `git branch` untuk membuat branch baharu seperti berikut:
```bash
git branch [branch-name]
```
1. **Tukar ke working branch**. Tukar ke branch yang ditentukan dan kemas kini direktori kerja dengan `git switch`:
```bash
git switch [branch-name]
```
1. **Membuat kerja**. Pada ketika ini anda ingin menambahkan perubahan anda. Jangan lupa memberitahu Git mengenainya dengan arahan berikut:
```bash
git add .
git commit -m "my changes"
```
Pastikan anda memberikan ayat dengan baik kepada komit anda, demi anda dan juga penjaga repo yang anda bantu.
1. **Gabungkan kerja anda dengan `main` branch**. Pada satu ketika anda selesai bekerja dan anda ingin menggabungkan kerja anda dengan `main` branch. `main` branch mungkin telah berubah sementara itu, pastikan anda mengemas kini terlebih dahulu kepada yang terbaru dengan arahan berikut:
```bash
git switch main
git pull
```
Pada ketika ini anda ingin memastikan bahawa apa-apa _conflicts_, keadaan di mana Git tidak dapat dengan mudah _combine_ perubahan berlaku di working branch anda. Oleh itu, jalankan arahan berikut:
```bash
git switch [branch_name]
git merge main
```
Ini akan membawa semua perubahan dari `main` ke branch anda dan semoga anda dapat meneruskannya. Sekiranya tidak, VS Code akan memberitahu anda di mana Git _confused_ dan anda hanya mengubah fail yang terjejas untuk mengatakan kandungan mana yang paling tepat.
1. **Hantar kerja anda ke GitHub**. Menghantar karya anda ke GitHub bermaksud dua perkara. Menolak branch anda ke repo anda dan kemudian membuka PR, Tarik Permintaan (Pull Request).
```bash
git push --set-upstream origin [branch-name]
```
Perintah di atas membuat branch untuk forked repo.
1. **Buka Tarik Permintaan (Pull Request)** Seterusnya, anda mahu membuka tarik permintaan (Pull Request). Anda melakukannya dengan menavigasi ke repo bercabang di GitHub. Anda akan melihat petunjuk di GitHub di mana ia bertanya sama ada anda mahu membuat tarik permintaan (Pull Request) baru, anda mengkliknya dan anda akan dibawa ke antara muka di mana anda boleh menukar tajuk mesej komit, berikan keterangan yang lebih sesuai. Sekarang penyelenggara repo yang anda garpu akan melihat PR ini dan _fingers crossed_ mereka akan menghargai dan _merge_ tarik permintaan (Pull Request) anda. Anda telah menjadi penyumbang, yay:)
1. **Bersihkan**. Menjadikan amalan baik untuk _cleanup_ selepas anda. Anda mahu membersihkan local branch dan branch yang anda dorong ke GitHub. Pertama marilah hapuskannya secara tempatan dengan arahan berikut:
```bash
git branch -d [branch-name]
```
Pastikan anda pergi ke halaman GitHub untuk forked repo seterusnya dan keluarkan branch terpencil yang baru anda tolak.
`Tarik Permintaan (Pull request)` nampaknya istilah yang tidak bermoral kerana anda benar-benar mahu mendorong perubahan anda ke projek. Tetapi penyelenggara (pemilik projek) atau pasukan inti perlu mempertimbangkan perubahan anda sebelum menggabungkannya dengan "main" branch projek, jadi anda benar-benar meminta keputusan perubahan dari penyelenggara.
Tarik permintaan (Pull Request) adalah tempat untuk membandingkan dan membincangkan perbezaan yang diperkenalkan di cabang dengan ulasan, komen, ujian bersepadu, dan banyak lagi. Tarik permintaan (Pull Request) yang baik mengikuti kira-kira peraturan yang sama dengan pesanan pesanan. Anda dapat menambahkan rujukan ke masalah dalam pelacak masalah, ketika pekerjaan Anda misalnya menyelesaikan masalah. Ini dilakukan dengan menggunakan `#` diikuti dengan jumlah masalah (issue) anda. Contohnya `# 97`.
🤞 Jari memintas bahawa semua cek lulus dan pemilik projek menggabungkan perubahan anda ke dalam projek🤞
Kemas kini working branch tempatan anda sekarang dengan semua komit baru dari branch terpencil yang sesuai di GitHub:
`git pull`
## Bagaimanakah menyumbang kepada sumber terbuka
Pertama, marilah kita cari repositori - atau: repo - di GitHub yang menarik bagi anda dan yang anda ingin menyumbang perubahan. Anda mahu menyalin kandungannya ke mesin kami.
✅ Kaedah yang baik untuk mencari repo 'mesra pemula (beginner-friendly)' adalah dengan [cari mengikut tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Salin repo secara tempatan](images/clone_repo.png)
Terdapat beberapa cara menyalin kod. Salah satu cara adalah dengan "mengklon" kandungan repositori, menggunakan HTTPS, SSH, atau menggunakan GitHub CLI (Command Line Interface).
Buka terminal dan klon repo seperti di bawah:
`git clone https://github.com/ProjectURL`
Untuk kerja dengan projek tersebut, tukar the fail kanan:
`cd ProjectURL`
And juga boleh membuka keseluruhan projek dengan [Codespaces](https://github.com/features/codespaces), Penyunting kod terbitan GitHub / persekitaran pengembangan awan, atau [GitHub Desktop](https://desktop.github.com/).
Akhirnya, anda boleh memuat turun kod dalam bentuk zip.
### Beberapa perkara menarik mengenai GitHub
Anda boleh membintangi, menonton, dan / atau "fork" mana-mana repositori awam di GitHub. Anda boleh mencari repositori berbintang anda di menu lungsur kanan atas. Ia seperti penanda buku, tetapi untuk kod.
Projek mempunyai pelacak masalah, kebanyakannya di GitHub di tab "Isu" kecuali dinyatakan sebaliknya, di mana orang membincangkan masalah yang berkaitan dengan projek. Dan tab Tarik Permintaan adalah tempat orang membincangkan dan mengkaji perubahan yang sedang berlangsung.
Projek mungkin juga ada perbincangan di forum, senarai surat, atau saluran sembang seperti Slack, Discord atau IRC.
✅ Lihatlah repo GitHub baru anda dan cuba beberapa perkara, seperti menyunting tetapan, menambahkan maklumat ke repo anda, dan membuat projek (seperti papan Kanban). Banyak yang boleh anda lakukan!
---
### 🚀 Cabaran
Berpasangan dengan rakan untuk mengerjakan kod masing-masing. Buat projek secara kolaboratif, fork kod, buat branch dan gabungkan perubahan.
## Kuiz Pasca Kuliah
[Kuiz Pasca Kuliah](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Mengkaji dan belajar sendiri
Membaca tentang [menyumbang kepada sumber terbuka](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git nota](https://training.github.com/downloads/github-git-cheat-sheet/).
Berlatih, berlatih, berlatih. GitHub mempunyai jalan pembelajaran yang hebat yang tersedia melalui [lab.github.com](https://lab.github.com/):
- [Minggu pertama di GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Anda juga akan menemui makmal yang lebih maju.
## Tugasan
Selesaikan [Minggu pertama di GitHub (training lab)](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,318 @@
# Inleiding van GitHub
Deze les behandelt de basisprincipes van GitHub, een platform voor het hosten en beheren van wijzigingen in uw code.
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac)
## Quiz voorafgaand aan de lezing
[Quiz voorafgaand aan de lezing](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Inleiding
In deze les behandelen we:
- het volgen van het werk dat u op uw machine doet
- samen met anderen aan projecten werken
- hoe u kunt bijdragen aan open source software
### Vereisten
Voordat u begint, moet u controleren of Git is geïnstalleerd. In het terminal typ:
`git --version`
Als Git niet is geïnstalleerd, [download Git](https://git-scm.com/downloads). Stel vervolgens uw lokale Git-profiel in de terminal in:
* `git config --global user.name "uw-naam"`
* `git config --global user.email "uw-email"`
Om te controleren of Git al is geconfigureerd, kunt u het volgende typen:
`git config --list`
U heeft ook een GitHub-account nodig, een code-editor (zoals Visual Studio Code) en u moet uw terminal openen (of: command prompt).
Navigeer naar [github.com](https://github.com/) en maak een account aan als u dat nog niet heeft gedaan, of log in en vul uw profiel in.
✅ GitHub is niet de enige coderepository ter wereld; er zijn anderen, maar GitHub is de bekendste
### Voorbereiding
U heeft zowel een map met een codeproject op uw lokale computer (laptop of pc) als een openbare repository op GitHub nodig, die als voorbeeld zal dienen voor hoe u kunt bijdragen aan de projecten van anderen.
---
## Code beheer
Laten we zeggen dat u lokaal een map hebt met een of ander codeproject en u wilt beginnen met het volgen van uw voortgang met git - het versiebeheersysteem. Sommige mensen vergelijken het gebruik van git met het schrijven van een liefdesbrief aan uw toekomstige zelf. Als u uw commitberichten dagen of weken of maanden later leest, zult u u kunnen herinneren waarom u een beslissing heeft genomen, of een wijziging "terugdraaien" - dat wil zeggen, wanneer u goede "commitberichten" schrijft.
### Taak: maak een repository en leg code vast
1. **Maak een repository op GitHub**. Zoek op GitHub.com, in het tabblad repositories, of in de navigatiebalk rechtsboven, de knop **new repo**.
1. Geef uw repository (map) een naam
1. Selecteer **create repository**.
1. **Navigeer naar uw werkmap**. Schakel in uw terminal naar de map (ook bekend als de directory) die u wilt beginnen met volgen. Typ:
```bash
cd [naam van uw map]
```
1. **Initialiseer een git-repository**. In uw project, typ:
```bash
git init
```
1. **Controleer de status**. Om de status van uw repository te controleren, typ:
```bash
git status
```
de output kan er ongeveer zo uitzien:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Typisch vertelt een `git status` commando u dingen zoals welke bestanden klaar zijn om _opgeslagen_ te worden naar de repo of bevat veranderingen die u misschien wilt behouden.
1. **Voeg alle bestanden toe voor tracking**
Dit wordt ook wel staging-bestanden/ bestanden toevoegen aan het staging-gebied genoemd.
```bash
git add .
```
Het `git add` plus `.` argument geeft aan dat al uw bestanden en wijzigingen voor tracking geselecteerd zijn.
1. **Voeg geselecteerde bestanden toe voor tracking**
```bash
git add [bestands- of mapnaam]
```
Dit helpt ons om alleen geselecteerde bestanden aan het staging-gebied toe te voegen als we niet alle bestanden tegelijk willen vastleggen.
1. **Unstage alle bestanden**
```bash
git reset
```
Dit commando helpt ons om alle bestanden tegelijk te unstagen.
1. **Unstage een bepaald bestand**
```bash
git reset [bestands- of mapnaam]
```
Dit commando helpt ons om alleen een bepaald bestand tegelijk te unstagen dat we niet willen opnemen voor de volgende commit.
1. **Uw werk voortzetten**. Op dit punt heeft u de bestanden toegevoegd aan een zogenaamd _staging-gebied_. Een plek waar Git uw bestanden bijhoudt. Om de wijziging permanent te maken, moet u de bestanden _commiten_. Om dit te doen maakt u een _commit_ aan met het `git commit` commando. Een _commit_ vertegenwoordigt een besparingspunt in de geschiedenis van uw repo. Typ het volgende om een _commit_ te maken:
```bash
git commit -m "eerste commit"
```
Dit commit al uw bestanden door het bericht "first commit" toe te voegen. Voor toekomstige commitberichten wilt u meer beschrijvend zijn in uw beschrijving om over te brengen wat voor soort wijziging u heeft aangebracht.
1. **Verbind uw lokale Git-repo met GitHub**. Een Git-repo is goed op uw computer, maar op een gegeven moment wilt u ergens een back-up van uw bestanden hebben en ook andere mensen uitnodigen om met u aan uw opslagplaats te werken. Een geweldige plek om dat te doen is GitHub. Onthoud dat we al een repo op GitHub hebben gemaakt, dus het enige dat we hoeven te doen, is onze lokale Git-repo verbinden met GitHub. Het commando `git remote add` zal precies dat doen. Typ de volgende commando:
> Let op: voordat u de opdracht typt, gaat u naar uw GitHub-repo-pagina om de repository-URL te vinden. U gebruikt het in het onderstaande commando. Vervang `repository_name` door uw GitHub-URL.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Dit creëert een _remote_, of verbinding, genaamd "origin", wijzend naar de GitHub-repository die u eerder heeft gemaakt.
1. **Stuur lokale bestanden naar GitHub**. Tot nu toe heeft u een _verbinding_ gemaakt tussen de lokale repo en de GitHub-repo. Laten we deze bestanden naar GitHub sturen met het volgende commando `git push`, zoals zo:
```bash
git push -u origin main
```
Dit stuurt uw commits in uw "main" tak naar GitHub.
1. **Om meer wijzigingen toe te voegen**. Als u door wilt gaan met het aanbrengen van wijzigingen en ze naar GitHub wilt pushen, hoeft u alleen maar de volgende drie commando's te gebruiken:
```bash
git add .
git commit -m "typ hier uw commitbericht"
git push
```
> Tip, misschien wilt u ook een `.gitignore`-bestand adopteren om te voorkomen dat bestanden die u niet wilt volgen, verschijnen op GitHub - zoals dat notitiesbestand dat u opslaat in dezelfde map maar geen plaats heeft op een openbare repository. U kunt sjablonen voor `.gitignore` bestanden vinden op [.gitignore templates](https://github.com/github/gitignore).
#### Commit berichten
Een geweldige onderwerpregel voor een commitbericht van Git maakt de volgende zin compleet:
Indien toegepast, zal deze commit <uw onderwerpregel hier>
Gebruik voor het onderwerp de gebiedende wijs, tegenwoordige tijd: "verander" niet "veranderd" noch "veranderingen".
Net als in het onderwerp, gebruik in het lichaam (optioneel) ook de imperatieve tegenwoordige tijd. Het lichaam moet de motivatie voor de verandering opnemen en dit contrasteren met eerder gedrag. U legt het `waarom` uit, niet het `hoe`.
✅ Neem een paar minuten de tijd om rond GitHub te surfen. Kunt u een echt geweldig commitbericht vinden? Kunt u een echt minimale vinden? Welke informatie is volgens u het belangrijkst en nuttigst om over te brengen in een commitbericht?
### Taak: Samenwerken
De belangrijkste reden om dingen op GitHub te zetten, was om het mogelijk te maken om samen te werken met andere ontwikkelaars.
## Samen met anderen aan projecten werken
Navigeer in uw repository naar `Insights > Community` om te zien hoe uw project zich verhoudt tot aanbevolen communitystandaarden.
Hier zijn enkele dingen die uw GitHub-repo kunnen verbeteren:
- **Omschrijving**. Heeft u een beschrijving voor uw project toegevoegd?
- **README**. Heeft u een README toegevoegd? GitHub biedt richtlijnen voor het schrijven van een [README](https://docs.github.com/articles/about-readmes/).
- **Richtlijn voor bijdragen**. Heeft uw project [richtlijnen voor bijdragen](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Gedragscode**. Een [Gedragscode](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Licentie**. Misschien nog belangrijker, een [licentie](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Al deze middelen zullen nieuwe teamleden helpen. En dat zijn typisch het soort dingen waar nieuwe bijdragers naar kijken voordat ze zelfs maar naar uw code kijken, om erachter te komen of uw project de juiste plek is om hun tijd door te brengen.
✅ README-bestanden, hoewel ze wat tijd nodig hebben om voor te bereiden, worden vaak genegeerd door drukke beheerders. Kunt u een voorbeeld vinden van een bijzonder beschrijvende? Opmerking: er zijn enkele [tools om goede README's te maken](https://www.makeareadme.com/) die u misschien zou willen proberen.
### Taak: voeg een code samen
Documenten voor bijdragen helpen mensen bij te dragen aan het project. Het legt uit wat voor soort bijdragen u zoekt en hoe het proces werkt. Bijdragers moeten een reeks stappen doorlopen om bij te dragen aan uw repo op GitHub:
1. **Uw repo forken** Waarschijnlijk wilt u dat mensen uw project _forken_. Forken betekent het maken van een replica van uw repository op hun GitHub-profiel.
1. **Kloon**. Van daaruit zullen ze het project naar hun lokale computer klonen (clone).
1. **Maak een tak**. U zult ze willen vragen om een _tak_ voor hun werk te creëren (branch).
1. **Richt hun verandering op één gebied**. Vraag bijdragers om hun bijdragen op één ding tegelijk te concentreren - op die manier is de kans groter dat u hun werk kan _samenvoegen_ (merge). Stelt u voor dat ze een bugfix schrijven, een nieuwe functie toevoegen en verschillende tests bijwerken - wat als u slechts 2 van de 3 of 1 van de 3 wijzigingen wilt of kunt implementeren?
✅ Stelt u een situatie voor waarin takken bijzonder cruciaal zijn voor het schrijven en verzenden van goede code. Welke use-cases kunt u bedenken?
> Let op: wees de verandering die u in de wereld wilt zien, en maak ook takken voor uw eigen werk. Alle commits die u maakt, worden gemaakt op de tak waar u momenteel naar "uitgecheckt" bent. Gebruik `git status` om te zien welke tak dat is.
Laten we een workflow voor bijdragers doorlopen. Veronderstel dat de bijdrager de repo al _geforkt_ en _gekloond_ heeft, zodat ze een Git-repo hebben klaar om aan te werken, op hun lokale computer:
1. **Maak een tak**. Gebruik het commando `git branch` om een branch te maken die de wijzigingen bevat die ze willen bijdragen:
```bash
git branch [taknaam]
```
1. **Overschakelen naar werkende tak**. Schakel over naar de gespecificeerde tak en update de werkdirectory met `git switch`:
```bash
git switch [taknaam]
```
1. **Werken**. Op dit punt wilt u uw wijzigingen toevoegen. Vergeet niet om Git erover te vertellen met de volgende commando's:
```bash
git add .
git commit -m "mijn veranderingen"
```
Zorg ervoor dat u uw commit een goede naam geeft, zowel voor u als voor de beheerder van de repo waarmee u helpt.
1. **Combineer uw werk met de `main` tak**. Op een gegeven moment bent u klaar met werken en wilt u uw werk combineren met dat van de `main` tak. De `main` tak kan ondertussen veranderd zijn, dus zorg ervoor dat u deze eerst bijwerkt naar de laatste versie met de volgende commando's:
```bash
git switch main
git pull
```
Op dit punt wilt u er zeker van zijn dat alle _conflicten_, situaties waarin Git niet gemakkelijk de veranderingen kan _combineren_ plaatsvinden in uw werkende tak. Voer daarom de volgende opdrachten uit:
```bash
git switch [taknaam]
git merge main
```
Dit brengt alle wijzigingen van `main` naar uw tak en hopelijk kunt u gewoon doorgaan. Als dit niet het geval is, zal VS Code u vertellen waar Git _in de war_ is en verandert u gewoon de betrokken bestanden om te zeggen welke inhoud het meest accuraat is.
1. **Stuur uw werk naar GitHub**. Het verzenden van uw werk naar GitHub betekent twee dingen. Uw tak naar uw repo pushen en vervolgens een PR, Pull Request openen.
```bash
git push --set-upstream origin [taknaam]
```
Het bovenstaande commando maakt de tak op uw geforkte repo.
1. **Open een PR**. Vervolgens wilt u een PR openen. U doet dat door naar de geforkte repo op GitHub te navigeren. U ziet een indicatie op GitHub waar het vraagt of u een nieuwe PR wilt maken, u klikt erop en u wordt naar een interface geleid waar u de titel van het commitbericht kunt wijzigen, geef het een meer geschikte beschrijving. Nu zal de beheerder van de repo die u heeft geforkt deze PR zien en, _vingers gekruist_, zullen ze uw PR waarderen en _samenvoegen_. U bent nu een bijdrager, yay :)
1. **Opruimen**. Het wordt als een goede gewoonte beschouwd om _op te ruimen_ nadat u met succes een PR hebt samengevoegd. U wilt zowel uw lokale tak opruimen als de tak die u naar GitHub hebt gepusht. Laten we het eerst lokaal verwijderen met het volgende commando:
```bash
git branch -d [taknaam]
```
Zorg ervoor dat u naar de GitHub-pagina gaat voor de geforkte repo en verwijder de externe tak die u er zojuist naartoe hebt gepusht.
`Pull request` lijkt een gekke term, omdat u uw wijzigingen echt in het project wilt pushen. Maar de onderhouder (projecteigenaar) of het kernteam moet rekening houden met uw wijzigingen voordat u deze samenvoegt met de "main" tak van het project, dus u vraagt echt om een wijzigingsbesluit van een onderhouder.
Een pull request is de plek om de verschillen die op een tak zijn geïntroduceerd te vergelijken en te bespreken met recensies, opmerkingen, geïntegreerde tests en meer. Een goed pull request volgt ongeveer dezelfde regels als een commitbericht. U kunt een verwijzing naar een probleem (issue) toevoegen in de issue tracker, bijvoorbeeld wanneer uw werk een probleem oplost. Dit doet u met een `#` gevolgd door het nummer van uw probleem. Bijvoorbeeld `# 97`.
🤞Duimen dat alle controles slagen en de projecteigenaar(s) uw wijzigingen in het project samenvoegen🤞
Update uw huidige lokale werkende tak met alle nieuwe commits van de corresponderende remote tak op GitHub:
`git pull`
## Hoe u kunt bijdragen aan open source
Laten we eerst een repository - of: repo - op GitHub zoeken die voor u interessant is en waaraan u een wijziging zou willen bijdragen. U zult de inhoud ervan naar uw machine kopiëren.
✅ Een goede manier om 'beginnersvriendelijke' repos te vinden, is door [te zoeken op de tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Kopieer lokaal een repo](../images/clone_repo.png)
Er zijn verschillende manieren om code te kopiëren. Een manier is om de inhoud van de repository te "klonen" door HTTPS, SSH of de GitHub CLI (Command Line Interface) te gebruiken.
Open uw terminal en kloon de repository op deze manier:
`git clone https://github.com/ProjectURL`
Schakel naar de juiste map om aan het project te werken:
`cd ProjectURL`
U kunt ook het hele project openen met [Codespaces](https://github.com/features/codespaces), GitHub's ingesloten code-editor /cloud-ontwikkelomgeving of [GitHub Desktop](https://desktop.github.com/).
Ten slotte kunt u de code downloaden in een gecomprimeerde map.
### Nog een paar interessante dingen over GitHub
U kunt elke openbare repository op GitHub een ster geven, bekijken en/of "forken". U kunt uw repositories met ster vinden in het vervolgkeuzemenu rechtsboven. Het is net als bladwijzers, maar dan voor code.
Projecten hebben een issue tracker, meestal op GitHub in de "Issues" tab, tenzij anders aangegeven, waar mensen problemen bespreken die verband houden met het project. En op het tabblad Pull Requests bespreken en beoordelen mensen lopende wijzigingen.
Projecten kunnen ook worden besproken in forums, mailinglijsten of chatkanalen zoals Slack, Discord of IRC.
✅ Kijk eens rond in uw nieuwe GitHub-repo en probeer een paar dingen, zoals het bewerken van instellingen, het toevoegen van informatie aan uw repo en het maken van een project (zoals een Kanban-bord). U kunt veel doen!
---
## 🚀 Uitdaging
Koppel met een vriend om aan elkaars code te werken. Creëer gezamenlijk een project, fork code, maak takken en voeg wijzigingen samen.
## Quiz na de lezing
[Quiz na de lezing](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Beoordeling en zelfstudie
Lees meer over [bijdragen aan open source software](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git-cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Oefenen, oefenen, oefenen. GitHub heeft geweldige leertrajecten beschikbaar via [lab.github.com](https://lab.github.com/):
- [Eerste week op GitHub](https://lab.github.com/githubtraining/first-week-on-github)
U zult ook meer geavanceerde labs vinden.
## Toewijzing
Voltooi [de eerste week op GitHub-trainingslaboratorium](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,317 @@
# Introdução ao GitHub
Esta lição cobre os fundamentos do GitHub, uma plataforma para hospedar e gerenciar alterações em seu código.
![Intro ao GitHub](/sketchnotes/webdev101-github.png)
> Sketchnote por [Tomomi Imura](https://twitter.com/girlie_mac)
## Quiz Pré-Aula
[Quiz Pré-Aula](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Introdução
Nesta lição vamos falar sobre:
- rastreando o trabalho que você faz em sua máquina
- trabalhando em projetos com outros
- como contribuir com software de código aberto
### Pré-requisitos
Antes de começar, você precisará verificar se o Git está instalado. No terminal, digite:
`git --version`
Se o Git não estiver instalado, [baixe o Git aqui](https://git-scm.com/downloads). Em seguida, configure seu perfil Git local no terminal:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
Para verificar se o Git já está configurado, você pode digitar:
`git config --list`
Você também precisará de uma conta do GitHub, um editor de código (como o Visual Studio Code) e abrir seu terminal (ou: prompt de comando).
Navegue para [github.com](https://github.com/) e crie uma conta, caso ainda não o tenha feito, ou faça login e preencha o seu perfil.
✅ O GitHub não é o único repositório de código do mundo; existem outros, mas o GitHub é o mais conhecido.
### Preparação
Você precisará de uma pasta com um projeto de código em sua máquina local (laptop ou PC) e de um repositório público no GitHub, que servirá como um exemplo de como contribuir com os projetos de outras pessoas.
---
## Gerenciamento de código
Digamos que você tenha uma pasta localmente com algum projeto de código e deseja começar a monitorar seu progresso usando git - o sistema de controle de versão. Algumas pessoas comparam o uso do git a escrever uma carta de amor para o seu futuro eu. Lendo suas mensagens de commit dias, semanas ou meses depois, você será capaz de se lembrar por que tomou uma decisão, ou "reverter" uma mudança - isto é, quando você escreve boas "mensagens de commit".
### Tarefa: Faça um repositório e conmmit o código
1. **Crie um repositório no GitHub**. No GitHub.com, na guia de repositórios ou na barra de navegação superior direita, encontre o botão **new repo** .
1. Dê um nome ao seu repositório (pasta)
1. Selecione **create repository**.
1. **Navegue até sua pasta de trabalho**. Em seu terminal, mude para a pasta (também conhecida como diretório) que deseja iniciar o rastreamento. Digite:
```bash
cd [nome da sua pasta]
```
1. **Inicialize um repositório git**. No seu projeto, digite:
```bash
git init
```
1. **Cheque status**. Para checar o status de seu repositório, digite:
```bash
git status
```
a saída pode ser parecida com esta:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Geralmente o comando `git status` diz a você coisas como quais arquivos estão prontos para serem _salvos_ para o repo ou tem alterações que você pode querer persistir.
1. **Adicionar todos os arquivos para rastreamento**
Isso também é chamado de arquivos de teste / adição de arquivos à área de teste.
```bash
git add .
```
O argumento `git add` plus `.` indiciona todos os seus arquivos e alterações para rastreamento.
1. **Adicionar arquivos selecionados para rastreamento**
```bash
git add [nome do arquivo ou pasta]
```
Isso nos ajuda a adicionar apenas os arquivos selecionados à área de teste quando não queremos enviar todos os arquivos de uma vez.
1. **Unstage todos os arquivos**
```bash
git reset
```
Este comando nos ajuda a unstage todos os arquivos de uma vez.
1. **Unstage um arquivo em particular**
```bash
git reset [nome do arquivo ou pasta]
```
Este comando nos ajuda a remover stage de apenas um arquivo específico de uma vez que não queremos incluir no próximo commit.
1. **Persistindo no seu trabalho**. Neste ponto, você adicionou os arquivos a um local chamado _staging area_. Um lugar onde o Git está rastreando seus arquivos. Para tornar a mudança permanente, você precisa _committar_ os arquivos. Para fazer isso, crie um _commit_ com o comando `git commit`. Um _commit_ representa um ponto na história do seu repo sendo salvo. Digite o seguinte para criar um _commit_:
```bash
git commit -m "first commit"
```
Isso confirma todos os seus arquivos, adicionando a mensagem "first commit" (primeiro commit). Para mensagens de commit futuras, você desejará ser mais descritiva em sua descrição para transmitir que tipo de mudança você fez.
1. **Conecte seu repositório Git local com GitHub**. Um repositório Git é bom em sua máquina, mas em algum momento você vai querer fazer backup de seus arquivos em algum lugar e também convidar outras pessoas para trabalhar com você em seu repositório. Um ótimo lugar para fazer isso é o GitHub. Lembre-se de que já criamos um repositório no GitHub, então a única coisa que precisamos fazer é conectar nosso repositório Git local ao GitHub. O comando `git remote add` fará exatamente isso. Digite o seguinte comando:
> Antes de digitar o comando, vá para a página do repositório GitHub para encontrar o URL do repositório. Você o usará no comando abaixo. Substitua `repository_name` pelo seu URL do GitHub.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Isso cria um _remote_, ou conexão, chamada "origin" apontando para o repositório GitHub que você criou anteriormente.
1. **Envie arquivos locais para GitHub**. Até agora, você criou uma _conexão_ entre o repositório local e o repositório GitHub. Vamos enviar esses arquivos para o GitHub com o seguinte comando `git push`, assim:
```bash
git push -u origin main
```
Isso envia seus commits em seu branch "principal" para o GitHub.
1. **Para adicionar mais mudanças**. Se quiser continuar fazendo alterações e enviando-as para o GitHub, você só precisará usar os três comandos a seguir:
```bash
git add .
git commit -m "digite sua mensagem de commit aqui"
git push
```
> Dica, você também pode adotar um arquivo `.gitignore` para evitar que arquivos que você não deseja rastrear apareçam no GitHub - como aquele arquivo de notas que você armazena na mesma pasta, mas não tem lugar em um repositório público. Você pode encontrar modelos para arquivos `.gitignore` em [modelos .gitignore](https://github.com/github/gitignore).
#### Mensagens de Commit
Uma ótima mensagem de Git commit completa a seguinte frase:
Se aplicado, este commit irá <sua mensagem de commit aqui>
Para o assunto use o tempo presente imperativo: "mudar" e não "mudou" nem "muda".
Assim como no sujeito, no corpo (opcional) também use o tempo presente imperativo. O corpo deve incluir a motivação para a mudança e contrastar isso com o comportamento anterior. Você está explicando o `porquê`, não o` como`.
✅ Reserve alguns minutos para navegar no GitHub. Você consegue encontrar uma mensagem de commit realmente ótima? Você pode encontrar uma ruim? Quais informações você acha que são as mais importantes e úteis para transmitir em uma mensagem de commit?
### Tarefa: Colabore
O principal motivo para colocar coisas no GitHub foi possibilitar a colaboração com outros desenvolvedores.
## Trabalhando em projetos com outras pessoas
Em seu repositório, navegue até `Insights> Community` para ver como seu projeto se compara aos padrões recomendados da comunidade.
Aqui estão algumas coisas que podem melhorar seu repositório GitHub:
- **Descrição**. Você adicionou uma descrição para o seu projeto?
- **README**. Você adicionou um README? O GitHub fornece orientação para escrever um [README](https://docs.github.com/articles/about-readmes/).
- **Guia de Contribuição**. Seu projeto tem um [guia para contribuição](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/),
- **Código de Conduta**. Um [Código de Conduta](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **Licença**. Talvez o mais importante, a [licença](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
Todos esses recursos irão beneficiar a integração de novos membros da equipe. E esses são normalmente o tipo de coisas que os novas pessoas colaboradoras olham antes mesmo de olhar para o seu código, para descobrir se o seu projeto é o lugar certo para elas passarem o tempo.
✅ Arquivos README, embora levem tempo para serem preparados, são freqüentemente negligenciados por pessoas mantenedores ocupadas. Você pode encontrar um exemplo particularmente descritivo? Nota: existem algumas [ferramentas para ajudar a criar bons READMEs](https://www.makeareadme.com/) que você pode querer experimentar.
### Tarefa: Dar merge em algum código
Documentos contribuintes ajudam as pessoas a contribuir para o projeto. Ele explica quais tipos de contribuições você está procurando e como funciona o processo. As pessoas colaboradoras precisarão seguir uma série de etapas para poder contribuir com seu repo no GitHub:
1. **Bifurcando seu repo** Você provavelmente vai querer que as pessoas _fork_ seu projeto. Bifurcação significa criar uma réplica de seu repositório em seu perfil GitHub.
1. **Clone**. A partir daí, elas clonarão o projeto em sua máquina local.
1. **Crie um branch**. Você vai querer pedir a elas que criem um _branch_ para seu trabalho.
1. **Concentre sua mudança em uma área**. Peça aos colaboradores para concentrarem suas contribuições em uma coisa de cada vez - dessa forma, as chances de você se _mergir_ no trabalho delas são maiores. Imagine que elas escrevam uma correção de bug, adicionem um novo recurso e atualizem vários testes - e se você quiser ou só puder implementar 2 de 3, ou 1 de 3 alterações?
✅ Imagine uma situação em que os branches são particularmente críticos para escrever e distribuir bons códigos. Em quais casos de uso você consegue pensar?
> Nota, seja a mudança que você deseja ver no mundo e crie ramificações para o seu próprio trabalho também. Todos os commits que você fizer serão feitos no branch em que você está atualmente “check-out”. Use `git status` para ver qual branch é.
Vamos analisar o fluxo de trabalho de uma pessoa colaboradora. Suponha que ela já _forked_ e _cloned_ o repo para que ela tenha um repositório Git pronto para ser trabalhado, em sua máquina local:
1. **Crie um brancj**. Use o comando `git branch` para criar um branch que conterá as mudanças que pretendem contribuir:
```bash
git branch [branch-name]
```
1. **Mudar para o branch de trabalho**. Mude para o branch especificado e atualize o diretório de trabalho com `git switch`:
```bash
git switch [branch-name]
```
1. **Trabalhe**. Neste ponto, você deseja adicionar suas alterações. Não se esqueça de contar ao Git sobre isso com os seguintes comandos:
```bash
git add .
git commit -m "minhas mudancas"
```
Certifique-se de dar ao seu commit um bom nome, para seu bem e também para os mantenedores do repo no qual você está ajudando.
1. **Combine seu trabalho com o branch `main`**. Em algum ponto, você concluiu o trabalho e deseja combinar seu trabalho com o do branch `principal`. O branch `main` pode ter mudado enquanto isso, certifique-se de primeiro atualizá-lo para o mais recente com os seguintes comandos:
```bash
git switch main
git pull
```
Neste ponto, você quer ter certeza de que quaisquer _conflitos_, situações em que o Git não pode _combinar_ facilmente as mudanças aconteçam em seu branch de trabalho. Portanto, execute os seguintes comandos:
```bash
git switch [branch_name]
git merge main
```
Isso trará todas as mudanças de `main` em seu branch e esperançosamente você pode simplesmente continuar. Caso contrário, o VS Code dirá onde o Git está _confundido_ e você apenas alterará os arquivos afetados para dizer qual conteúdo é o mais preciso.
1. **Envie seu trabalho para o GitHub**. Enviar seu trabalho para o GitHub significa duas coisas. Enviando seu branch para o repo e, em seguida, abra um PR, Pull Request.
```bash
git push --set-upstream origin [branch-name]
```
O comando acima cria o branch em seu repositório bifurcado.
1. **Abra um PR**. Em seguida, você deseja abrir um PR. Você faz isso navegando até o repositório bifurcado no GitHub. Você verá uma indicação no GitHub onde pergunta se você deseja criar um novo PR, você clica nele e é levado a uma interface onde pode alterar o título da mensagem de commit, dê-lhe uma descrição mais adequada. Agora, a mantenedora do repo que você bifurcou verá este PR e _dedos cruzados_, eles apreciarão e _mergirão_ seu PR. Agora você é uma pessoa contribuidora, eba :)
1. **Limpeza**. É considerado uma boa prática _limpar_ após mesclar com sucesso um PR. Você deseja limpar seu branch local e o branch que você enviou para o GitHub. Primeiro, vamos excluí-lo localmente com o seguinte comando:
```bash
git branch -d [branch-name]
```
Em seguida, vá para a página GitHub do repositório bifurcado e remova o branch remoto que você acabou de enviar para ele.
`Pull request` parece um termo bobo porque na verdade você deseja enviar suas alterações para o projeto. Mas a pessoa mantendo o repo ou equipe central precisa considerar suas mudanças antes de fundi-las com o branch "principal" do projeto, então você está realmente solicitando uma decisão de mudança de uma pessoa mantenedora.
Uma PR é o lugar para comparar e discutir as diferenças introduzidas em um branch com revisões, comentários, testes integrados e muito mais. Uma boa PR segue aproximadamente as mesmas regras de uma mensagem de commit. Você pode adicionar uma referência a um problema no rastreador de problemas, quando seu trabalho, por exemplo, corrige um problema. Isso é feito usando um `#` seguido pelo número do seu problema. Por exemplo `# 97`.
🤞 Dedos cruzados para que todas as verificações sejam aprovadas e as pessoas proprietárias do projeto deem merge nas suas alterações no projeto 🤞
Atualize seu branch de trabalho local atual com todos os novos commits do branch remoto correspondente no GitHub:
`git pull`
## Como contribuir com Open Source
Primeiramente, vamos encontrar um repositório (ou **repo**) no GitHub de interesse para você e para o qual você gostaria de contribuir. Você vai querer copiar o conteúdo desse repo para a sua máquina.
✅ Uma boa maneira de encontrar repos 'iniciantes' é [buscar usando a tag 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copiar um repo localmente](../images/clone_repo.png)
Existem várias maneiras de copiar códigos. Uma maneira é "clonar" o conteúdo do repositório, usando HTTPS, SSH ou usando o GitHub CLI (Command Line Interface).
Abra seu terminal e clone o repositório assim:
`git clone https://github.com/ProjectURL`
Para trabalhar no projeto, mude para a pasta certa:
`cd ProjectURL`
Você também pode abrir todo o projeto usando [Codespaces](https://github.com/features/codespaces), O editor de código incorporado do GitHub/ ambiente de desenvolvimento em nuvem, ou o [GitHub Desktop](https://desktop.github.com/).
Por último, você pode baixar o código em uma pasta como .zip.
### Mais algumas coisas interessantes sobre o GitHub
Você pode dar uma estrela, assistir e/ou "bifurcação" em qualquer repositório público no GitHub. Você pode encontrar seus repositórios estrelados no menu suspenso de cima para a direita. É como marcar, mas para código.
Os projetos têm um rastreador de problemas, no GitHub na aba "Problemas", a menos que indicado o contrário, onde as pessoas discutem questões relacionadas ao projeto. E a aba de Pull Requests é onde as pessoas discutem e analisam as mudanças que estão em andamento.
Os projetos também podem ter discussão em fóruns, listas de discussão ou canais de bate-papo como Slack, Discord ou IRC.
✅ Dê uma olhada no seu novo GitHub repo e experimente algumas coisas, como editar configurações, adicionar informações ao seu repo e criar um projeto (como uma placa Kanban). Há muita coisa que você pode fazer!
---
## 🚀 Desafio
Parear com uma amiga para trabalhar no código uma da outra. Crie um projeto de forma colaborativa, de fork no código, crie branches e de merge mudanças.
## Quiz pós-aula
[Quiz pós-aula](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Revisão & Auto estudo
Leia mais sobre [contribuindo para o software de código aberto](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/).
Pratique, pratique, pratique. GitHub tem ótimos caminhos de aprendizagem disponíveis via [lab.github.com](https://lab.github.com/):
- [Primeira semana no GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Você também encontrará laboratórios mais avançados.
## Lição de casa
Complete [o lab a Primeira Semana gitHub](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,321 @@
# Введение в GitHub
В этом уроке рассматриваются основы GitHub - платформы для хранения и управления изменениями вашего кода.
![Введение в GitHub](/sketchnotes/webdev101-github.png)
> Скетчноут [Tomomi Imura](https://twitter.com/girlie_mac)
## Предлекционный квиз
[Предлекционный квиз](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3)
## Введение
В этом уроке мы рассмотрим:
- отслеживание работы, которую вы делаете на своем устройстве
- совместная работа над проектами с другими людьми
- как внести свой вклад в программное обеспечение с открытым исходным кодом
### Требования
Прежде чем начать, вам нужно проверить, установлен ли Git. В терминале напечатайте:
`git --version`
Если Git не установлен, [установите Git](https://git-scm.com/downloads). Затем настройте свой локальный профиль Git в терминале:
- `git config --global user.name "ваше-имя"`
- `git config --global user.email "ваш-email"`
Чтобы проверить, настроен ли уже Git, вы можете ввести:
`git config --list`
Вам также понадобится аккаунт на GitHub, редактор кода (например, Visual Studio Code) и вам нужно будет открыть свой терминал (или командную строку).
Перейдите на [github.com](https://github.com/) и создайте аккаунт, если вы еще этого не сделали, или войдите в систему и заполните свой профиль.
✅ GitHub - не единственная платформа для хранения репозиториев кода в мире; есть и другие, но GitHub - самый известный.
### Подготовка
Вам понадобится как папка с проектом кода на вашем локальном компьютере (ноутбуке или ПК), так и общедоступный репозиторий на GitHub, который мы используем, чтобы показать, как внести свой вклад в другие проекты.
---
## Управление кодом
Допустим, у вас есть локальная папка с каким-то проектом и вы хотите начать отслеживать свой прогресс с помощью системы контроля версий Git. Некоторые люди сравнивают использование git с написанием любовного письма себе в будущем. Читая сообщения коммитов через несколько дней, недель или месяцев, вы сможете вспомнить, почему вы сделали так, а не иначе, или сможете «откатить» изменения.
### Задание: Сделать репозиторий и сделать коммит
1. **Создайте репозиторий на GitHub**. На GitHub.com на вкладке репозиториев или в правом верхнем углу панели навигации найдите кнопку **новый репозиторий**.
1. Дайте вашему репозиторию (папке) имя
1. Выберите **создать репозиторий**.
1. **Перейдите в свою рабочую папку**. В вашем терминале перейдите в папку (также известную как каталог), которую вы хотите начать отслеживать. Введите:
```bash
cd [имя вашей папки]
```
1. **Инициализируйте git репозиторий**. В вашем проекте напечатайте:
```bash
git init
```
1. **Проверьте статус**. Чтобы проверить статус вашего репозитория введите:
```bash
git status
```
вывод может выглядеть примерно так:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
Обычно команда `git status` сообщает вам, какие файлы готовы к _сохранению_ в репозиторий или в каких есть изменения, которые вы, возможно, захотите сохранить.
1. **Добавьте все файлы для отслеживания**.
Это также называется подготовленными файлами (staging files) / добавлением файлов в область подготовленных файлов (staging area).
```bash
git add .
```
Команда `git add` с аргументом `.` указывает, что все ваши файлы и изменения будут добавлены для отслеживания.
1. **Добавьте выбранные файлы для отслеживания**
```bash
git add [название файла или папки]
```
Это помогает нам добавлять только выбранные файлы в область подготовки, когда мы не хотим фиксировать все файлы сразу.
1. **Удаление всех файлов из области подготовки**
```bash
git reset
```
Эта команда помогает нам убрать все файлы сразу из staging area.
1. **Удаление определенного файла из области подготовки**
```bash
git reset [название файла или папки]
```
Эта команда помогает нам убрать определенный файл, который мы не хотим включать в следующий коммит.
1. **Сохраняйте свою работу**. На этом этапе вы добавили файлы в так называемую _staging area (область подготовки)_. Место, где Git отслеживает ваши файлы. Чтобы сделать изменение постоянным, вам необходимо _закоммитить (зафиксировать)_ файлы. Для этого вы создаете _коммит_ с помощью команды `git commit`. _Коммит_ представляет собой точку сохранения в истории вашего репозитория. Введите следующее, чтобы создать новый _коммит_:
```bash
git commit -m "первый коммит"
```
Эта команда сохраняет все ваши файлы, добавляя сообщение «первый коммит». Для будущих сообщений коммитов вам нужно будет быть более информативным в своем описании, чтобы передать, какой тип изменения вы внесли.
1. **Подключите локальный репозиторий Git к GitHub**. Репозиторий Git хорош на вашем компьютере, но в какой-то момент вы захотите сделать резервную копию ваших файлов, а также пригласить других людей поработать с вами над вашим проектом. Одно из таких прекрасных мест для этого - GitHub. Помните, что мы уже создали репозиторий на GitHub, поэтому единственное, что нам нужно сделать, это подключить наш локальный репозиторий Git к GitHub. Команда `git remote add` предназначена именно для этого. Введите следующую команду:
> Обратите внимание: прежде чем вводить команду, перейдите на страницу репозитория GitHub, чтобы найти URL-адрес репозитория. Вы будете использовать его в приведенной ниже команде. Замените `username/repository_name` своим URL-адресом репозитория на GitHub.
```bash
git remote add origin https://github.com/username/repository_name.git
```
Эта команда создает _удаленное соединение_ с именем «origin», указывающее на репозиторий GitHub, который вы создали ранее.
1. **Отправьте локальные файлы в GitHub**. Итак, вы создали _соединение_ между локальным репозиторием и репозиторием на GitHub. Давайте отправим эти файлы на GitHub с помощью следующей команды `git push`, вот так:
```bash
git push -u origin main
```
Эта команда отправляет коммиты из вашей локальной ветки "main" в одноименную ветку на GitHub.
1. **Добавление последующих изменений**. Если вы хотите продолжить вносить изменения и отправлять их на GitHub, вам просто нужно использовать следующие три команды:
```bash
git add .
git commit -m "напишите здесь свое сообщения для коммита"
git push
```
> Совет: вы также можете использовать файл `.gitignore`, чтобы файлы, которые вы не хотите отслеживать, не отправлялись на GitHub. Например, файл заметок, который вы храните в той же папке, но не хотите, чтобы он отображался в публичном репозитории. Вы можете найти шаблоны для файлов `.gitignore` по следующей ссылке [.gitignore templates](https://github.com/github/gitignore).
#### Сообщения коммитов
Хорошее сообщение к коммиту должно завершать следующее предложение:
_Если применить этот коммит, то он <ваше сообщение к коммиту>_
(_If applied, this commit will <your subject line here>_)
Для основного сообщения к коммиту используйте повелительное наклонение в настоящем времени: «change», а не «changed» или «changes». Также и в расширенном сообщении (которое необязательно) используйте повелительное наклонение в настоящем времени. Основное сообщение должно включать мотивацию к изменению и противопоставлять это предыдущему поведению. Вы объясняете `почему`, а не `как`.
✅ Потратьте несколько минут, чтобы немного исследовать GitHub. Сможете ли вы найти действительно отличное сообщение к коммиту? Можете ли вы найти минимальное сообщение к коммиту? Какую информацию вы считаете наиболее важной и полезной для передачи в сообщении к коммиту?
### Задание: Сотрудничество
Основная причина размещения проектов на GitHub заключается в том, чтобы дать возможность сотрудничать с другими разработчиками.
## Работа над проектами с другими разработчиками
В своем репозитории перейдите в `Insights > Community`, чтобы увидеть, как ваш проект сравнивается с рекомендованными стандартами сообщества.
Вот несколько вещей, которые могут улучшить ваш репозиторий на GitHub:
- **Описание**. Вы добавили описание для своего проекта?
- **README**. Вы добавили README? GitHub предлагает руководство по написанию [README](https://docs.github.com/articles/about-readmes/).
- **Рекомендации по внесению вклада**. У вашего проекта есть [рекомендации по внесению вклада (contributing guideline)](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/)?
- **Нормы поведения**. [Code of Conduct](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/).
- **Лицензия**. Возможно, самое важное - это [лицензия](https://docs.github.com/articles/adding-a-license-to-a-repository/).
Все эти ресурсы принесут пользу новым членам команды. И это, как правило, те вещи, на которые новые участники смотрят, прежде чем даже взглянуть на ваш код, чтобы узнать, является ли ваш проект подходящим местом для них, чтобы тратить свое время.
✅ Файлы README часто игнорируются занятыми разработчиками из-за нехватки времени на их подготовку. Можете ли вы найти пример README с хорошим описанием проекта? Примечание: есть несколько [инструментов для создания хороших README](https://www.makeareadme.com/), которые вы, возможно, захотите попробовать.
### Задание: Слияние кода
Правила соучастия (например, документ `CONTRIBUTING.md`) помогают людям разобраться, как вносить свой вклад в проект. В нем объясняется, какие типы вкладов вас интересуют и как работает этот процесс. Чтобы внести свой вклад в ваш репозиторий на GitHub, участникам потребуется выполнить ряд шагов:
1. **Сделать ответвление вашего репозитория (Forking)**. Вы, вероятно, захотите, чтобы люди сделали _ответвление (fork)_ вашего проекта. Ответвление означает создание копии вашего репозитория в их профиле GitHub.
1. **Клонировать**. Оттуда они будут клонировать проект на свой локальный компьютер.
1. **Создать ветку**. Вы можете попросить их создать _ветку_ для своей работы.
1. **Сосредоточить свои изменения на одной области**. Попросите участников концентрировать свой вклад на чем-то одном - так шансы, что вы сможете провести _слияние кода_ с их работой, будут выше. Представьте, что они написали исправление ошибки, добавили новую функцию и обновили несколько тестов - что, если вы хотите или можете принять только 2 из 3 или 1 из 3 изменений?
✅ Придумайте ситуацию, в которой ветки особенно важны для написания и распространения хорошего кода. Какие варианты использования приходят вам на ум?
> Примечание: будьте тем изменением, которое вы хотите увидеть в мире, и также создавайте ответвления для своей собственной работы. Любые совершаемые вами коммиты будут выполняться в той ветке, в которой вы в настоящее время находитесь. Используйте `git status`, чтобы узнать, какая это ветка.
Давайте рассмотрим рабочий процесс соавтора. Предположим, что соавтор уже _сделал ответвление_ и _склонировал_ ваш репозиторий, поэтому у него на локальном компьютере есть репозиторий Git, готовый к работе:
1. **Создание ветки**. Используйте команду `git branch` для создания ветки, которая будет содержать изменения, которые вы хотите внести:
```bash
git branch [название-ветки]
```
1. **Переход в рабочую ветку**. Переключитесь на указанную ветку и обновите рабочую папку с помощью команды `git switch`:
```bash
git switch [branch-name]
```
1. **Написание кода**. На этом этапе вы хотите добавить свои изменения. Не забудьте сообщить об этом Git с помощью следующих команд:
```bash
git add .
git commit -m "мои изменения"
```
Убедитесь, что вы написали хорошее сообщение для своего коммита, понятное как для себя, так и для владельца репозитория, которому вы помогаете.
1. **Совместите свою работу с веткой `main`**. В какой-то момент вы закончили работу и хотите совместить свою работу с работой над веткой `main`. Ветка `main` за это время могла измениться, поэтому убедитесь, что вы сначала обновили ее до последней версии с помощью следующих команд:
```bash
git switch main
git pull
```
На этом этапе вы хотите убедиться, что любые _конфликты_, ситуации, когда Git не может легко _комбинировать_ изменения, происходят в вашей рабочей ветке. Поэтому выполните следующие команды:
```bash
git switch [название-ветки]
git merge main
```
Это внесет все изменения из main в вашу ветку, и, надеюсь, вы сможете продолжить. Если нет, VS Code сообщит вам, где Git _не может самостоятельно решить конфликт_, и вы просто измените затронутые файлы, чтобы указать, какой контент является наиболее точным.
1. **Отправьте свою работу на GitHub**. Отправка вашей работы на GitHub означает две вещи. Отправьте свою ветку (push) в репозиторий, а затем откройте пул реквест (сокращенно PR).
```bash
git push --set-upstream origin [название-ветки]
```
Приведенная выше команда создает ветку в вашем, ответвленном от основного, репозитории.
1. **Открытие PR**. Далее, вы хотите открыть PR. Вы делаете это, перейдя к ответвленному репозиторию на GitHub. Вы увидите подсказку на GitHub, где вам предложат, хотите ли вы создать новый PR. Вы нажимаете на это указание, и попадаете в интерфейс, где вы можете изменить заголовок сообщения к пул реквесту, можете дать ему более подходящее описание. Теперь владелец репозитория, от которого вы сделали ответвление, увидит этот PR, и (_скрестим пальцы_) он одобрит и примет ваш PR в свой репозиторий. Теперь вы соавтор, ура :)
1. **Чистка (Clean up)**. Хорошей практикой считается _чистка_ после успешного слияния PR. Вы хотите очистить как локальную ветку, так и ветку, которую вы отправили на GitHub. Сначала удалим ее локально с помощью следующей команды:
```bash
git branch -d [название-ветки]
```
Убедитесь, что вы перешли на страницу GitHub для ответвленного репозитория и удалили удаленную ветку, которую вы только что отправили на GitHub.
`Pull request` (дословно: запрос на стягивание) кажется глупым термином, потому что на самом деле вы хотите отправить (push) свои изменения в проект. Но владелец проекта или основная команда должны рассмотреть ваши изменения перед слиянием их с основной ветвью проекта ("main"), поэтому вы действительно запрашиваете разрешение у владедьца о стягивании ваших изменений.
Pull request - это место, где можно сравнить и обсудить изменения, представленные в ветке, проверками, комментариями, интегрированными тестами и т.д. Хороший pull request следует примерно тем же правилам, что и сообщение к коммиту. Вы можете добавить ссылку на вопрос (issue) в систему отслеживания проблем, например, когда вы работаете над устранением проблемы/бага. Это делается с помощью символа `#`, за которым следует номер вашего issue. Например, `# 97`.
🤞Скрестив пальцы, все проверки проходят, и владелец (владельцы) проекта проводят слияние ваших изменений в проект🤞
Обновите текущую локальную рабочую ветку всеми новыми коммитами из соответствующей удаленной ветки на GitHub с помощью следующей команды:
`git pull`
## Как внести свой вклад в открытый исходный код
Во-первых, давайте найдем репозиторий на GitHub, который вас интересует и в который вы хотели бы внести изменения. Вам неоходимо скопировать его содержимое на свой компьютер.
✅ Хороший способ найти репозитории, удобные для новичков, - это [поиск по тегу 'good-first-issue'](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![Copy a repo locally](../images/clone_repo.png)
Есть несколько способов копирования кода. Один из способов - «клонировать» содержимое репозитория, используя HTTPS, SSH или используя GitHub CLI (интерфейс командной строки).
Откройте свой терминал и клонируйте репозиторий вот так:
`git clone https://github.com/ProjectURL`
Для работы над проектом перейдите в правильную папку:
`cd ProjectURL`
Вы также можете открыть весь проект, используя [Codespaces](https://github.com/features/codespaces), встроенный редактор кода / облачная среда разработки GitHub или [GitHub Desktop](https://desktop.github.com/).
Наконец, вы можете загрузить код в заархивированной папке.
### Еще несколько интересных вещей о GitHub
Вы можете отметить, посмотреть и / или «разветвить» любой публичный репозиторий на GitHub. Вы можете найти свои отмеченные репозитории в раскрывающемся меню в правом верхнем углу. Это как закладка, но для кода.
В проектах есть средство отслеживания проблем, в основном на GitHub на вкладке «Проблемы» (Issues), если не указано иное, где люди обсуждают проблемы, связанные с проектом. А на вкладке «Pull Requests» люди обсуждают и просматривают изменения, которые происходят.
Проекты также могут обсуждаться на форумах, в списках рассылки или в чатах, таких как Slack, Discord или IRC.
✅ Осмотрите свой новый репозиторий GitHub и попробуйте несколько вещей, например, отредактируйте настройки, добавьте информацию в репозиторий и создайте проект (например, доску Канбан). Вы можете многое сделать!
---
## 🚀 Челлендж
Объединитесь с другом, чтобы работать над кодом друг друга. Совместно создавайте проект, разветвляйте код, создавайте ветви и объединяйте изменения.
## Постлекционный квиз
[Постлекционный квиз](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4)
## Обзор и самообучение
Подробнее об [участие в разработке программного обеспечения с открытым исходным кодом](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[Шпаргалка по Git](https://training.github.com/downloads/github-git-cheat-sheet/).
Практика, практика, практика. GitHub предлагает отличные способы обучения, доступные через [lab.github.com](https://lab.github.com/):
- [Первая неделя на GitHub](https://lab.github.com/githubtraining/first-week-on-github)
Вы также можете найти более продвинутые лаборатории для практики.
## Задание
Завершите [первую неделю в учебной лаборатории GitHub](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,325 @@
# கிட்ஹப் அறிமுகம்
இந்த பாடம் கிட்ஹப் அடிப்படைகளை உள்ளடக்கியது, உங்கள் குறியீட்டில் மாற்றங்களை நடத்த மற்றும் நிர்வகிக்க ஒரு தளம்.
![Iகிட்ஹப் அறிமுகம்](/sketchnotes/webdev101-github.png)
> ஸ்கெட்ச்நோட் [டோமோமி இமுரா](https://twitter.com/girlie_mac)
## விரிவுரைக்கு முந்தைய வினாடி வினா
[ விரிவுரைக்கு முந்தைய வினாடி வினா](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=ta)
## அறிமுகம்
இந்த பாடத்தில், நாங்கள் உள்ளடக்குவோம்:
- உங்கள் இயந்திரத்தில் நீங்கள் செய்யும் வேலையைக் கண்காணித்தல்
- மற்றவர்களுடன் திட்டங்களில் வேலை செய்தல்
- திறந்த மூல மென்பொருள் பங்களிக்க எப்படி
### முன் நிபந்தனைகள்
நீங்கள் தொடங்குவதற்கு முன், கிட் நிறுவப்பட்டதா என்பதை நீங்கள் சரிபார்க்க வேண்டும். முனைய வகை:
`git --version`
கிட் நிறுவப்படவில்லை என்றால், [கிட் பதிவிறக்க](https://git-scm.com/downloads) . பின்னர், முனையத்தில் உங்கள் உள்ளூர் கிட் சுயவிவரத்தை அமை:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
கிட் ஏற்கனவே உள்ளமைக்கப்பட்டதா என்பதை சரிபார்க்க நீங்கள் தட்டச்சு செய்யலாம்:
`git config --list`
நீங்கள் ஒரு கிட்ஹப் கணக்கு, ஒரு குறியீட்டு ஆசிரியர் (விஷுவல் ஸ்டுடியோ குறியீடு போன்றவை) வேண்டும், மேலும் உங்கள் முனையத்தைத் திறக்க வேண்டும் (அல்லது: கட்டளை செயலழைப்பு).
நீங்கள் ஏற்கனவே இல்லை என்றால் [github.com](https://github.com/) செல்லவும் மற்றும் ஒரு கணக்கை உருவாக்கவும், அல்லது உள்நுழைந்து உங்கள் சுயவிவரத்தை நிரப்பவும்.
✅ கிட்ஹப் உலகின் ஒரே குறியீடு களஞ்சியம் அல்ல; மற்றவர்கள் இருக்கிறார்கள், ஆனால் கிட்ஹப் நன்கு அறியப்பட்டவர்
### முன்னேற்பாடு செய்தல்
உங்கள் உள்ளூர் இயந்திரத்தில் (மடிக்கணினி அல்லது பிசி) ஒரு குறியீட்டு திட்டத்துடன் ஒரு கோப்புறை மற்றும் கிட்ஹப்பில் ஒரு பொது களஞ்சியம் ஆகிய இரண்டும் உங்களுக்குத் தேவைப்படும், இது மற்றவர்களின் திட்டங்களுக்கு எவ்வாறு பங்களிக்க வேண்டும் என்பதற்கு ஒரு எடுத்துக்காட்டாக இருக்கும்.
---
## குறியீடு மேலாண்மை
சில குறியீட்டு திட்டத்துடன் உள்நாட்டில் ஒரு கோப்புறை உள்ளது என்று வைத்துக்கொள்வோம், மேலும் உங்கள் முன்னேற்றத்தை கிட் - பதிப்பு கட்டுப்பாட்டு அமைப்பு பயன்படுத்தி கண்காணிக்க த் தொடங்க வேண்டும். சிலர் கிட் பயன்படுத்தி உங்கள் எதிர்கால சுய ஒரு காதல் கடிதம் எழுத ஒப்பிட்டு. நாட்கள் அல்லது வாரங்கள் அல்லது மாதங்களுக்குப் பிறகு உங்கள் ஒப்புக்கொள்ளும் செய்திகளைப் படிக்கும்போது, நீங்கள் ஏன் ஒரு முடிவை எடுத்தீர்கள், அல்லது ஒரு மாற்றத்தை "திரும்பப் பெறுகிறீர்கள்" என்பதை நீங்கள் நினைவுகூர முடியும் - அதாவது, நீங்கள் நல்ல "செய்திகளைச் செய்யுங்கள்" என்று எழுதும்போது.
### பணி: ஒரு களஞ்சியத்தை உருவாக்கவும் மற்றும் குறியீட்டை செய்யவும்
1. **கிட்ஹப் இல் களஞ்சியத்தை உருவாக்கவும்** கிட்ஹப், களஞ்சியங்கள் தாவலை, அல்லது வழிசெலுத்தல் பட்டியில் மேல் வலது இருந்து, **புதிய ரெப்போ ** பொத்தானை கண்டுபிடிக்க.
1. உங்கள் களஞ்சியத்திற்கு (கோப்புறை) ஒரு பெயரைக் கொடுங்கள்
1. தேர்ந்தெடுக்கவும் **create repository**.
1. **உங்கள் பணி கோப்புறைக்கு செல்லவும்**. உங்கள் முனையத்தில், கோப்புறைக்கு மாறவும் (கோப்பகம் என்றும் அழைக்கப்படுகிறது) நீங்கள் கண்காணிக்கத் தொடங்க விரும்புகிறீர்கள். மாதிப் படிவம்:
```bash
cd [உங்கள் கோப்புறையின் பெயர்]
```
1. **ஒரு கிட் களஞ்சியத்தை துவக்கு**. உங்கள் திட்ட வகை:
```bash
git init
```
1. **நிலையை சரிபார்க்கவும்**. உங்கள் களஞ்சிய வகையின் நிலையை சரிபார்க்க:
```bash
git status
```
வெளியீடு இந்த மாதிரி ஏதாவது இருக்க முடியும்:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
பொதுவாக ஒரு `git status` கட்டளை, கோப்புகளில் _சேமிக்கதயாராக உள்ளது_ ரெப்போஅல்லது நீங்கள் தொடர்ந்து இருக்க விரும்பும் மாற்றங்களைக் கொண்டுள்ளது போன்ற விஷயங்களைஉங்களுக்குச் சொல்கிறது.
1. **கண்காணிப்பு அனைத்து கோப்புகளை சேர்க்க**
இது ஸ்டேஜிங் கோப்புகள் / ஸ்டேஜிங் பகுதியில் கோப்புகளைச் சேர்ப்பது என்றும் அழைக்கப்படுகிறது.
```bash
git add .
```
`git add` பிளஸ் `.` வாதம் உங்கள் கோப்புகள் அனைத்தும் கண்காணிக்க மாறும் என்பதைக் குறிக்கிறது.
1. **கண்காணிப்புக்காக தேர்ந்தெடுக்கப்பட்ட கோப்புகளைச் சேர்க்கவும்**
```bash
git add [கோப்பு அல்லது கோப்புறை பெயர்]
```
ஒரே நேரத்தில் அனைத்து கோப்புகளையும் செய்ய விரும்பாத போது, தேர்ந்தெடுக்கப்பட்ட கோப்புகளை மட்டுமே ஸ்டேஜிங் பகுதியில் சேர்க்க இது உதவுகிறது.
1. **அனைத்து கோப்புகளையும் நிலைநீக்கு**
```bash
git reset
```
இந்த கட்டளை அனைத்து கோப்புகளையும் ஒரே நேரத்தில் நிலைநீக்க உதவுகிறது.
1. **ஒரு குறிப்பிட்ட கோப்பை நிலைநீக்கு**
```bash
git reset [கோப்பு அல்லது கோப்புறை பெயர்]
```
அடுத்த கமிட் செய்ய விரும்பாத ஒரு குறிப்பிட்ட கோப்பை மட்டும் ஒரே நேரத்தில் கட்டமைக்க இந்த கட்டளை நமக்கு உதவுகிறது.
1. **உங்கள் வேலையை த் தொடருதல்**. இந்த கட்டத்தில் நீங்கள் _ஸ்டேஜிங் பகுதி_ என்று அழைக்கப்படும் கோப்புகளை சேர்த்துள்ளீர்கள். உங்கள் கோப்புகளை கிட் கண்காணிக்கும் இடம். மாற்றத்தை நிரந்தரமாக்க, கோப்புகளை _கமிட்_ செய்ய வேண்டும். அவ்வாறு செய்ய நீங்கள் `git commit` கட்டளையுடன் ஒரு _கமிட்_ உருவாக்குகிறீர்கள். ஒரு _கமிட்_ உங்கள் ரெப்போ வரலாற்றில் ஒரு சேமிப்பு புள்ளி யை குறிக்கிறது. _கமிட்_ உருவாக்க பின்வருவனவை தட்டச்சு செய்யவும்:
```bash
git commit -m "first commit"
```
இது உங்கள் கோப்புகள் அனைத்தையும் ஒப்புக்கொள்கிறது, "முதலில் ஒப்புக்கொள்ளுங்கள்" என்ற செய்தியைச் சேர்க்கிறது. எதிர்காலத்தில் செய்திகளைச் செய்ய நீங்கள் என்ன வகையான மாற்றத்தை செய்தீர்கள் என்பதை தெரிவிக்க உங்கள் விளக்கத்தில் இன்னும் விளக்கமாக இருக்க விரும்புகிறீர்கள்.
1. **உங்கள் உள்ளூர் கிட் ரெப்போவை கிட்ஹப் உடன் இணைக்கவும்**. ஒரு கிட் ரெப்போ உங்கள் இயந்திரத்தில் நல்லது, ஆனால் ஒரு கட்டத்தில் நீங்கள் எங்காவது உங்கள் கோப்புகளை காப்புப்பிரதி எடுக்க விரும்புகிறீர்கள், மேலும் உங்கள் ரெப்போவில் உங்களுடன் வேலை செய்ய மற்ற நபர்களை அழைக்கவும் விரும்புகிறீர்கள். அவ்வாறு செய்ய ஒரு பெரிய இடம் கிட்ஹப் ஆகும். நாம் ஏற்கனவே கிட்ஹப்பில் ஒரு ரெப்போவை உருவாக்கியுள்ளோம் என்பதை நினைவில் கொள்ளுங்கள், எனவே நாம் செய்ய வேண்டிய ஒரே விஷயம் கிட்ஹப் உடன் எங்கள் உள்ளூர் கிட் ரெப்போவை இணைக்க வேண்டும். `git remote add` என்ற கட்டளை அதைச் செய்யும். பின்வரும் கட்டளையை தட்டச்சு செய்யவும்:
> குறிப்பு, நீங்கள் கட்டளையை தட்டச்சு செய்வதற்கு முன், உங்கள் கிட்ஹப் ரெப்போ பக்கத்திற்கு சென்று களஞ்சியத்தை கண்டுபிடிக்கவும். நீங்கள் கீழே உள்ள கட்டளையில் பயன்படுத்துவீர்கள். ```https://github.com/username/repository_name.git``` என்பதை உங்கள் கிட்ஹப் யுஆர்எல் மூலம் மாற்றவும்.
```bash
git remote add origin https://github.com/username/repository_name.git
```
இது ஒரு _தொலை__ அல்லது இணைப்பை உருவாக்குகிறது, "தோற்றம்" என்று பெயரிடப்பட்டது, நீங்கள் முன்பு உருவாக்கிய கிட்ஹப் களஞ்சியத்தை சுட்டிக்காட்டுகிறது.
1. **கீதுப் க்கு உள்ளூர் கோப்புகளை அனுப்பவும்** இதுவரை நீங்கள் உள்ளூர் ரெப்போ மற்றும் கிட்ஹப் ரெப்போ இடையே ஒரு _இணைப்பு_ உருவாக்கியுள்ளீர்கள். பின்வரும் கட்டளை `git push`உடன் இந்த கோப்புகளை கிட்ஹப் க்கு அனுப்புவோம், இது போன்றது:
> குறிப்பு, உங்கள் கிளை பெயர் முன்னிருப்பாக வேறுபட்டிருக்கலாம் ```main```.
```bash
git push -u origin main
```
இது உங்கள் "main" கிளையில் உள்ள உங்கள் உறுதிகளை கிட்ஹப் க்கு அனுப்புகிறது.
2. **மேலும் மாற்றங்களைச் சேர்க்க**. நீங்கள் மாற்றங்களைதொடர்ந்து செய்ய விரும்பினால், அவற்றை கிட்ஹப் க்கு தள்ளவிரும்பினால், பின்வரும் மூன்று கட்டளைகளைப் பயன்படுத்த வேண்டும்:
```bash
git add .
git commit -m "உங்கள் ஒப்புக்கொள்ளும் செய்தியை இங்கே தட்டச்சு செய்யவும்"
git push
```
> உதவிக்குறிப்பு, நீங்கள் கிட்ஹப்பில் காண்பிக்க விரும்பாத கோப்புகளைத் தடுக்க ஒரு `.gitignore` கோப்பை நீங்கள் ஏற்றுக்கொள்ள விரும்பலாம் - அதே கோப்புறையில் நீங்கள் சேமித்து வைக்கும் குறிப்புகள் கோப்பு போல, ஆனால் ஒரு பொது களஞ்சியத்தில் இடமில்லை. [.gitignore templates](https://github.com/github/gitignore) இல் `.gitignore` கோப்புகளுக்கான வார்ப்புருக்களை நீங்கள் காணலாம்
#### செய்திகளை ஒப்புக்கொள்
ஒரு பெரிய கிட் கமிட் சப்ஜெக்ட் லைன் பின்வரும் வாக்கியத்தை நிறைவு செய்யும்:
பயன்படுத்தப்பட்டால், இந்த உறுதி <உங்கள் பொருள் வரி இங்கே>
பொருள் கட்டாயபயன்படுத்த, தற்போதைய: "மாற்றம்" "மாற்ற" அல்லது "மாற்றங்கள்".
பொருள் போன்ற, உடலில் (விரும்பினால்) மேலும் கட்டாய பயன்படுத்த, தற்போதைய பதற்றம். உடல் மாற்றம் உந்துதல் சேர்க்க வேண்டும் மற்றும் முந்தைய நடத்தை இந்த மாறாக வேண்டும். நீங்கள் `ஏன்` விளக்குகிறீர்கள், `எப்படி` அல்ல.
✅ கிட்ஹப் சுற்றி உலாவ சில நிமிடங்கள் எடுத்துக் கொள்ளுங்கள். நீங்கள் ஒரு பெரிய ஒப்புக்கொள்ளசெய்தி கண்டுபிடிக்க முடியும்? நீங்கள் ஒரு மிகவும் குறைந்த ஒரு கண்டுபிடிக்க முடியும்? ஒரு கமிட் செய்தியில் தெரிவிக்க மிகவும் முக்கியமான மற்றும் பயனுள்ள தகவல் என்று நீங்கள் நினைக்கிறீர்கள்?
### பணி: ஒத்துழைக்க
கிட்ஹப்பில் விஷயங்களை வைப்பதற்கான முக்கிய காரணம் மற்ற டெவலப்பர்களுடன் ஒத்துழைப்பதை சாத்தியமாக்குகிறது.
## மற்றவர்களுடன் திட்டங்களில் வேலை செய்தல்
உங்கள் களஞ்சியத்தில், பரிந்துரைக்கப்பட்ட சமூக தரங்களுடன் உங்கள் திட்டம் எவ்வாறு ஒப்பிடுகிறது என்பதைப் பார்க்க `நுண்ணறிவு > சமூகம்` செல்லவும்.
இங்கே உங்கள் கிட்ஹப் ரெப்போ மேம்படுத்த முடியும் என்று சில விஷயங்கள் உள்ளன:
- **விளக்கம்**. உங்கள் திட்டத்திற்கான விளக்கத்தைச் சேர்த்தீர்களா?
- **ரீட்மே**. நீங்கள் ஒரு ரீட்மேசேர்த்தீர்களா? கிட்ஹப் ஒரு [ரீட்மே](https://docs.github.com/articles/about-readmes/) எழுதுவதற்கான வழிகாட்டலை வழங்குகிறது
- **பங்களிப்பு வழிகாட்டுதல்**. உங்கள் திட்டத்தில் [பங்களிப்பு வழிகாட்டுதல்கள்](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/) உள்ளதா,
- **நடத்தை விதிகள்**. அ [நடத்தை விதிகள்](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/),
- **உரிமம்**. ஒருவேளை மிக முக்கியமாக, ஒரு [உரிமம்](https://docs.github.com/articles/adding-a-license-to-a-repository/)?
இந்த வளங்கள் அனைத்தும் புதிய குழு உறுப்பினர்களுக்கு பயனளிக்கும். உங்கள் குறியீட்டைப் பார்ப்பதற்கு முன்பு புதிய பங்களிப்பாளர்கள் பார்க்கும் விஷயங்கள் பொதுவாக உள்ளன, உங்கள் திட்டம் அவர்கள் தங்கள் நேரத்தை செலவழிக்க சரியான இடம் தானா என்பதைக் கண்டறிய.
✅ ரீட்மே கோப்புகள், அவை தயாரிக்க நேரம் எடுத்துக்கொண்டாலும், பெரும்பாலும் பிஸியான பராமரிப்பாளர்களால் புறக்கணிக்கப்படுகின்றன. குறிப்பாக விளக்கப்பட்ட ஒரு உதாரணத்தை நீங்கள் கண்டுபிடிக்க முடியுமா? குறிப்பு: நீங்கள் முயற்சி செய்ய விரும்பும் சில [நல்ல ரீ.ஈ.டி.எம்.இ.க்களை உருவாக்க உதவும் கருவிகள்](https://www.makeareadme.com/) உள்ளன.
### பணி: சில குறியீட்டை ஒன்றுசேர்
பங்களிப்பு ஆவணங்கள் மக்கள் திட்டத்திற்கு பங்களிக்க உதவுகின்றன. நீங்கள் என்ன வகையான பங்களிப்புகளைத் தேடுகிறீர்கள் மற்றும் செயல்முறை எவ்வாறு செயல்படுகிறது என்பதை இது விளக்குகிறது. பங்களிப்பாளர்கள் கீதுப் மீது உங்கள் ரெப்போபங்களிக்க முடியும் படிகள் ஒரு தொடர் மூலம் செல்ல வேண்டும்:
1. **உங்கள் ரெப்போவை ஃபோர்கிங்** ஒருவேளை நீங்கள் மக்கள் உங்கள் திட்டத்தை _ஃபோர்க்_ வேண்டும். ஃபோர்கிங் என்பது அவர்களின் கிட்ஹப் சுயவிவரத்தில் உங்கள் களஞ்சியத்தின் பிரதியை உருவாக்குவதாகும்.
1. **குளோன்**. அங்கிருந்து அவர்கள் தங்கள் உள்ளூர் இயந்திரத்திற்கு திட்டத்தை குளோன் செய்வார்கள்.
1. **ஒரு கிளை உருவாக்க**. நீங்கள் அவர்களின் வேலைக்கு ஒரு _கிளை_ உருவாக்க அவர்களை கேட்க வேண்டும்.
1. **ஒரு பகுதியில் தங்கள் மாற்றத்தை கவனம் செலுத்தவும்**. பங்களிப்பாளர்களை ஒரு நேரத்தில் ஒரு விஷயத்தில் தங்கள் பங்களிப்புகளை ஒருமுகப்படுத்தும்படி கேளுங்கள் - அந்த வழியில் நீங்கள் அவர்களின் வேலையில் _ஒன்றிணைக்க_ வாய்ப்புகளை அதிகமாக உள்ளது. அவர்கள் ஒரு பிழை சரி எழுத கற்பனை, ஒரு புதிய அம்சம் சேர்க்க, மற்றும் பல சோதனைகள் புதுப்பிக்க - நீங்கள் விரும்பினால் என்ன, அல்லது மட்டுமே 3 வெளியே 2 செயல்படுத்த முடியும், அல்லது 3 மாற்றங்கள் 1?
✅ நல்ல குறியீட்டை எழுதுவதற்கும் அனுப்புவதற்கும் கிளைகள் குறிப்பாக முக்கியமான ஒரு சூழ்நிலையை கற்பனை செய்து பாருங்கள். வழக்குகள் என்ன பயன் என்று நீங்கள் நினைக்கலாம்?
> குறிப்பு, நீங்கள் உலகில் பார்க்க விரும்பும் மாற்றமாக இருங்கள், உங்கள் சொந்த வேலைக்கும் கிளைகளை உருவாக்குங்கள். நீங்கள் செய்யும் எந்தவொரு உறுதிப்படமும் நீங்கள் தற்போது "சரிபார்க்கப்பட்ட" கிளையில் செய்யப்படும். எந்த கிளை என்று பார்க்க `git status` பயன்படுத்தவும்.
பங்களிப்பாளர் பணிப்பாய்வின் மூலம் செல்லலாம். பங்களிப்பாளர் ஏற்கனவே _ஃபோர்க்_ மற்றும் _குளோன்_ ரெப்போவை வைத்திருக்கிறார் என்று வைத்துக்கொள்ளுங்கள், எனவே அவர்கள் தங்கள் உள்ளூர் இயந்திரத்தில் வேலை செய்ய தயாராக ஒரு கிட் ரெப்போவை வைத்திருக்கிறார்கள்:
1. **ஒரு கிளை உருவாக்க**. `git branch` என்ற கட்டளையைப் பயன்படுத்தி, அவர்கள் பங்களிக்க வேண்டிய மாற்றங்களைக் கொண்ட ஒரு கிளையை உருவாக்கவும்:
```bash
git branch [கிளை பெயர்]
```
1. **வேலை செய்யும் கிளைக்கு மாறவும்**. குறிப்பிட்ட கிளைக்கு மாறி, பணி கோப்பகத்துடன் புதுப்பிக்கவும் `git switch`:
```bash
git switch [கிளை பெயர்]
```
1. **வேலை செய்யுங்கள்**. இந்த கட்டத்தில் நீங்கள் உங்கள் மாற்றங்களை சேர்க்க விரும்புகிறீர்கள். பின்வரும் கட்டளைகளுடன் அதைப் பற்றி கிட் சொல்ல மறக்க வேண்டாம்:
```bash
git add .
git commit -m "என் மாற்றங்கள்"
```
உங்கள் நலனுக்காகவும், நீங்கள் உதவி செய்யும் ரெப்போவின் பராமரிப்பாளராகவும், உங்கள் உறுதிக்கு ஒரு நல்ல பெயரைக் கொடுப்பதை உறுதி செய்யுங்கள்.
1.**உங்கள் வேலையை `main` கிளையுடன் இணைக்கவும்**. ஒரு கட்டத்தில் நீங்கள் வேலை செய்து விட்டீர்கள், உங்கள் வேலையை `main` கிளையுடன் இணைக்க விரும்புகிறீர்கள். `main` கிளை இதற்கிடையில் மாறியிருக்கலாம், எனவே பின்வரும் கட்டளைகளுடன் சமீபத்தியதை முதலில் புதுப்பிக்கவும்:
```bash
git switch main
git pull
```
இந்த கட்டத்தில், உங்கள் பணிக்கிளையில் மாற்றங்கள் எளிதாக _இணைவுகள்_ செய்ய முடியாத சூழ்நிலைகளில் ஏதேனும் _இணை_, இருப்பதை உறுதி செய்ய விரும்புகிறீர்கள். எனவே பின்வரும் கட்டளைகளை இயக்கவும்:
```bash
git switch [கிளை பெயர்]
git merge main
```
இது உங்கள் கிளையில் `main` இருந்து அனைத்து மாற்றங்களையும் கொண்டு வரும் மற்றும் வட்டம் நீங்கள் தொடர முடியும். இல்லையெனில்,கிட் _confused_ எங்கே என்று விஎஸ் குறியீடு உங்களுக்கு சொல்லும், மேலும் எந்த உள்ளடக்கம் மிகவும் துல்லியமானது என்று சொல்ல பாதிக்கப்பட்ட கோப்புகளை மாற்றவும்.
1. 1. **உங்கள் வேலையை கிட்ஹப்**க்கு அனுப்பவும். உங்கள் வேலையை கிட்ஹப் க்கு அனுப்புவது என்பது இரண்டு விஷயங்களைக் குறிக்கிறது. உங்கள் கிளையை உங்கள் ரெப்போவுக்குத் தள்ளி, பின்னர் ஒரு பேஆர், புல் கோரிக்கையைத் திறக்கவும்.
```bash
git push --set-upstream origin [கிளை பெயர்]
```
மேலே கட்டளை உங்கள் முட்கரண்டி ரெப்போ கிளை உருவாக்குகிறது.
1. **ஒரு பேஆர்** திறக்கவும். அடுத்து, நீங்கள் ஒரு பேஆர் ஐ திறக்க விரும்புகிறீர்கள். நீங்கள் கிட்ஹப் மீது ஃபோர்க்செய்யப்பட்ட ரெப்போவுக்கு வழிசெலுத்துவதன் மூலம் அதைச் செய்கிறீர்கள். நீங்கள் ஒரு புதிய பேஆர் ஐ உருவாக்க விரும்புகிறீர்களா என்று கேட்கும் கிட்ஹப்பில் ஒரு அறிகுறியைப் பார்ப்பீர்கள், அதை கிளிக் செய்து, செய்தி தலைப்பை மாற்றக்கூடிய ஒரு இடைமுகத்திற்கு நீங்கள் அழைத்துச் செல்லப்படுகிறீர்கள், அதற்கு மிகவும் பொருத்தமான விளக்கத்தை க்கொடுங்கள். இப்போது நீங்கள் ஃபோர்க் செய்த ரெப்போவின் பராமரிப்பாளர் இந்த பேஆர் ஐப் பார்ப்பார், _விரல்கள் கடந்து_ அவர்கள் பாராட்டுவார்கள் மற்றும் உங்கள் பேஆர் ஐ இணைப்பார்கள். நீங்கள் இப்போது ஒரு பங்களிப்பாளராக இருக்கிறீர்கள், நீங்கள் :)
1. **சுத்தம்**. நீங்கள் வெற்றிகரமாக ஒரு பேஆர் ஐ இணைத்த பிறகு _சுத்தம்_ நல்ல நடைமுறையாகக் கருதப்படுகிறது. உங்கள் உள்ளூர் கிளை மற்றும் நீங்கள் கிட்ஹப் க்கு தள்ளிய கிளை இரண்டையும் சுத்தம் செய்ய விரும்புகிறீர்கள். முதலில் பின்வரும் கட்டளையுடன் அதை உள்நாட்டில் நீக்குவோம்:
```bash
git branch -d [கிளை பெயர்]
```
நீங்கள் அடுத்த ஃபோர்க்செய்யப்பட்ட ரெப்போவிற்கு கிட்ஹப் பக்கம் செல்வதை உறுதி செய்து, நீங்கள் அதை தள்ளிய தொலைதூர கிளையை அகற்றவும்.
`புல் கோரிக்கை` ஒரு முட்டாள்தனமான சொல் போல் தெரிகிறது, ஏனென்றால் உண்மையில் நீங்கள் திட்டத்தில் உங்கள் மாற்றங்களை தள்ள விரும்புகிறீர்கள். ஆனால் பராமரிப்பாளர் (திட்ட உரிமையாளர்) அல்லது முக்கிய குழு திட்டத்தின் "முக்கிய" கிளையுடன் இணைப்பதற்கு முன் உங்கள் மாற்றங்களை கருத்தில் கொள்ள வேண்டும், எனவே நீங்கள் உண்மையில் ஒரு பராமரிப்பவரிடமிருந்து ஒரு மாற்ற முடிவைக் கோருகிறீர்கள்.
ஒரு இழு கோரிக்கை மதிப்புரைகள், கருத்துக்கள், ஒருங்கிணைந்த சோதனைகள் மற்றும் பலவற்றுடன் ஒரு கிளையில் அறிமுகப்படுத்தப்பட்ட வேறுபாடுகளை ஒப்பிட்டு விவாதிக்க ும் இடம். ஒரு நல்ல இழுப்பு கோரிக்கை ஒரு ஒப்புக்கொள்ளும் செய்தி போன்ற கிட்டத்தட்ட அதே விதிகளைப் பின்பற்றுகிறது. எடுத்துக்காட்டாக, உங்கள் வேலை ஒரு சிக்கலைத் சரிசெய்யும்போது, சிக்கல் டிராக்கரில் உள்ள ஒரு பிரச்சினைக்கு நீங்கள் ஒரு குறிப்பைச் சேர்க்கலாம். இது ஒரு `#` பயன்படுத்தி செய்யப்படுகிறது, அதைத் தொடர்ந்து உங்கள் பிரச்சினையின் எண்ணிக்கை. உதாரணமாக `#97`.
🤞அனைத்து காசோலைகளும் கடந்து, திட்ட உரிமையாளர்(கள்) உங்கள் மாற்றங்களை திட்டத்தில் இணைக்க வேண்டும் என்று விரல்கள் கடந்து விட்டன🤞
கிட்ஹப்பில் உள்ள தொடர்புடைய தொலைநிலை கிளையிலிருந்து அனைத்து புதிய ஒப்புக்களுடன் உங்கள் தற்போதைய உள்ளூர் பணிகிளையைப் புதுப்பிக்கவும்:
`git pull`
## திறந்த மூலத்திற்கு எவ்வாறு பங்களிக்க வேண்டும்
முதலில், உங்களுக்கு ஆர்வமுள்ள கிட்ஹப்பில் ஒரு களஞ்சியத்தை (அல்லது **ரெப்போ**) காணலாம், அதற்கு நீங்கள் ஒரு மாற்றத்தை பங்களிக்க விரும்புகிறீர்கள். அதன் உள்ளடக்கங்களை உங்கள் இயந்திரத்தில் நகலெடுக்க விரும்புகிறீர்கள்..
✅ 'தொடக்க நட்பு' ரெப்போஸைக் கண்டுபிடிக்க ஒரு நல்ல வழி ['நல்ல முதல் பிரச்சினை' என்ற குறிச்சொல்மூலம் தேடுவதாகும்](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/).
![உள்ளூரில் ஒரு ரெப்போவை நகலெடுக்கவும்](../images/clone_repo.png)
குறியீட்டை நகலெடுக்க பல வழிகள் உள்ளன. ஒரு வழி களஞ்சியத்தின் உள்ளடக்கங்களை "குளோன்" செய்வது, HTTPஎஸ், எஸ்எஸ்ஹெச், அல்லது கிட்ஹப் சிஎல்ஐ (கட்டளை வரி இடைமுகம்) பயன்படுத்தி.
உங்கள் முனையத்தைத் திறந்து களஞ்சியத்தை இவ்வாறு குளோன் செய்யுங்கள்:
`git clone https://github.com/புரொஜக்ட்யுஆர்எல்`
திட்டத்தில் வேலை செய்ய, சரியான கோப்புறைக்கு மாறவும்:
`cd புரொஜக்ட்யுஆர்எல்`
நீங்கள் [கோட்ஸ்பேஸ்](https://github.com/features/codespaces), கிட்ஹப்பின் உட்பொதிக்கப்பட்ட குறியீடு ஆசிரியர் / கிளவுட் மேம்பாட்டு சூழல் அல்லது [கிட்ஹப் டெஸ்க்டாப்](https://desktop.github.com/) பயன்படுத்தி முழு திட்டத்தையும் திறக்கலாம்
இறுதியாக, நீங்கள் ஒரு ஜிப் செய்யப்பட்ட கோப்புறையில் குறியீட்டைப் பதிவிறக்கலாம்.
### கிட்ஹப் பற்றி இன்னும் சில சுவாரஸ்யமான விஷயங்கள்
நீங்கள் கீதுப்-இல் உள்ள எந்தவொரு பொது களஞ்சியத்தையும் நட்சத்திர, பார்வை மற்றும் /அல்லது "முட்கரண்டி" செய்யலாம். மேல்-வலது கீழ்-கீழ் மெனுவில் உங்கள் நட்சத்திரகளஞ்சியங்களை நீங்கள் காணலாம். இது புக்மார்க்கிங் போன்றது, ஆனால் குறியீட்டுக்கு.
திட்டங்கள் ஒரு சிக்கல் டிராக்கர் வேண்டும், பெரும்பாலும் "சிக்கல்கள்" தாவலில் கிட்ஹப் இல்லையெனில் சுட்டிக்காட்டப்படாவிட்டால், அங்கு மக்கள் திட்டம் தொடர்பான சிக்கல்களைவிவாதிக்கிறார்கள். மற்றும் புல் கோரிக்கைகள் தாவல் மக்கள் விவாதிக்க மற்றும் முன்னேற்றத்தில் இருக்கும் மாற்றங்களை மதிப்பாய்வு எங்கே உள்ளது.
திட்டங்கள் மன்றங்கள், அஞ்சல் பட்டியல்கள் அல்லது ஸ்லாக், டிஸ்ட்டர் அல்லது ஐஆர்சி போன்ற அரட்டை சேனல்களிலும் விவாதம் நடத்தலாம்.
✅ உங்கள் புதிய கிட்ஹப் ரெப்போவைச் சுற்றி பாருங்கள் மற்றும் சில விஷயங்களை முயற்சிக்கவும், எடிட்டிங் அமைப்புகள், உங்கள் ரெப்போவில் தகவலைச் சேர்த்தல், மற்றும் ஒரு திட்டத்தை உருவாக்குதல் (ஒரு கன்பன் பலகை போன்றது). நீங்கள் செய்ய முடியும் நிறைய இருக்கிறது!
---
## 🚀 அறைகூவல்
ஒருவருக்கொருவர் குறியீட்டில் வேலை செய்ய ஒரு நண்பருடன் ஜோடி சேரவும். ஒரு திட்டத்தை கூட்டாக உருவாக்கவும், ஃபோர்க் குறியீடு, கிளைகளை உருவாக்கவும், மாற்றங்களை இணைக்கவும்.
## விரிவுரைக்குப் பிந்தைய வினாடி வினா
[விரிவுரைக்குப் பிந்தைய வினாடி வினா](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=ta)
## ஆய்வு & சுய ஆய்வு
மேலும் வாசிக்க [திறந்த மூல மென்பொருளுக்கு பங்களிப்பு](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution).
[கிட் ஏமாற்றுதாள்](https://training.github.com/downloads/github-git-cheat-sheet/).
பயிற்சி, பயிற்சி, பயிற்சி. கிட்ஹப் [lab.github.com](https://lab.github.com/) வழியாக கிடைக்கும் சிறந்த கற்றல் பாதைகளைக் கொண்டுள்ளது:
- [கிது முதல் வாரம்](https://lab.github.com/githubtraining/first-week-on-github)
நீங்கள் இன்னும் மேம்பட்ட ஆய்வகங்கள் காண்பீர்கள்.
## வகுத்தமைத்தல்
முழுமையான [கிட்ஹப் பயிற்சி ஆய்வகத்தில் முதல் வாரம்](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,318 @@
# GitHub 介绍
这节课涵盖了 GitHub 的基础知识,这是一个可以用来存放代码和管理代码变更的平台。
![Intro to GitHub](/sketchnotes/webdev101-github.png)
> 涂鸦笔记作者:[Tomomi Imura](https://twitter.com/girlie_mac)
## 课前小测
[课前小测](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=zh_cn)
## 大纲
这节课我们将会介绍:
- 在你的电脑上追踪你的工作
- 与他人协同开发项目
- 如何参与开源软件贡献
### 开始之前
开始之前,你需要确保安装了 Git在终端译注即上一节课中介绍的命令行中输入
`git --version`
如果没有安装 Git请先[下载并安装 Git](https://git-scm.com/downloads)。然后用如下命令设置你的本地 Git 使用者配置文件:
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
要检查 Git 使用者是否配置完成,可以输入:
`git config --list`
你还需要一个 GitHub 账户,一个代码编辑器(比如 Visual Studio Code并且要打开你的终端或者其他命令行
如果你没有现成的 Github 账号,去 [github.com](https://github.com/) 创建一个。如果已经有账号,就登录进去并且完成个人资料的配置。
✅ GitHub 并不是世界上唯一的代码仓库,但是最知名的。
### 课前准备
你需要在本地(你的笔记本或 PC创建一个项目文件夹还需要在 GitHub 上创建一个公开的仓库(译注:后文会有指引),作为本节课中向其他人的项目提贡献的示例。
---
## 代码管理
假如你在本地有一个代码项目的文件夹,你希望开始使用 Git (版本控制系统)来追踪你的进度。有的人将使用 Git 比作给未来的你自己写一封情书在数日、数周乃至数月后阅读你的提交信息commit messages你就可以想起你做出某个决定的原因或者回滚rollback一次变更 —— 前提是你写了不错的提交信息。
### 任务:创建仓库并提交代码
1. **在 GitHub 上创建仓库**。进入 GitHub.com在 “Repositories” 标签或者右上角导航栏找到 **New repository** 按钮。
1. 给你的仓库取个名字;
1. 点击 **Create repository**
1. **前往你的工作目录**。在你的终端中,通过输入下方命令切换到你希望开始追踪的文件夹(即目录):
```bash
cd [文件名称/目录路径]
```
1. **初始化一个 Git 仓库**。在你的项目下输入:
```bash
git init
```
1. **检查状态**。要检查你的仓库状态,输入:
```bash
git status
```
输出看起来将会像这样:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
一般来说 `git status` 命令会告诉你诸如什么文件已经 _被保存到_ 仓库内或者有一些你可能想要保留的变更之类的事。
1. **追踪所有文件**
这个操作也叫做暂存stage文件或者将文件添加到暂存区staging area
```bash
git add .
```
`git add` 命令加上 `.` 参数将会追踪你的所有文件和变更。
1. **只追踪选定的文件**
```bash
git add [文件或文件夹名]
```
如果你不想一次性将所有文件添加到暂存区,可以用这个命令仅仅添加选定的文件。
1. **取消所有文件的追踪**
```bash
git reset
```
这条命令可以帮我们取消暂存unstage所有文件。
1. **取消特定文件的追踪**
```bash
git reset [文件或文件夹名]
```
如果你在下次提交中不希望提交某个已经暂存的文件,可以用这条命令取消它的暂存。
1. **保存你的工作**。现在你应该已经将文件添加到了所谓 _暂存区_ 中,这是 Git 追踪你的文件的地方。为了永久地保存变更,你需要 _提交commit_ 这些文件。你可以用 `git commit` 命令创建一次 _提交_。一次 _提交_ 代表你的仓库历史中的一个存档点。输入下方命令来创建一次 _提交_
```bash
git commit -m "first commit"
```
这会提交你暂存区中的所有文件,并带上一条提交信息 —— “first commit”。在以后的提交信息中你会想要加入更加准确的描述比如一些表示你这次变更的类型的信息。
1. **将你的本地仓库连接到 GitHub**。现在 Git 仓库已经能在你的本地机器上正常运作但是有时候你会想要将你的文件备份到别处或者希望邀请其他人来一起参与这个仓库的协作。GitHub 就是一个可以满足你要求的好地方。我们此前已经在 GitHub 上创建了一个仓库,现在只需要将本地 Git 仓库连接到 GitHub 就可以了,用 `git remote add` 命令就可以做到。输入下面的命令:
> 注意,在你输入命令前,需要前往你的 GitHub 仓库而页面来找到仓库的地址URL用它来替换命令中 `username/repository_name` 这一部分。
```bash
git remote add origin https://github.com/username/repository_name.git
```
这会创建一个被命名为 “origin” 的 _远程仓库位置remote_也可以理解为一个连接指向你早先创建的 GitHub 仓库。
1. **将本地文件上传至 GitHub**。现在你已经创建了一个本地仓库和 GitHub 仓库间的 _连接_。让我们通过 `git push` 命令将这些文件上传至 GitHub就像这样
```bash
git push -u origin main
```
这样就会把你的提交上传到 GitHub 上你的 “main” 分支了。
1. **添加更多的变更**。如果你想继续搞点变更并且将它们传到 GitHub 上,你只需要使用下面的三行命令:
```bash
git add .
git commit -m "在这里填写你的提交信息"
git push
```
> 提示,你可能还需要建立一个 `.gitignore` 文件来防止 Git 追踪一些文件并且让它们不会被上传到 GitHub比如一些你写在本地仓库但并不想放到公开仓库的笔记文件。你可以在 [.gitignore templates](https://github.com/github/gitignore) 找到一些现成的 `.gitignore` 文件模板。
#### 提交信息Commit Messages
一条好的 Git 提交信息标题subject line可以理解为下方句子的填空
如果生效,这次提交将会 <你的提交信息标题>
在标题内,使用祈使语气和现在时态,即使用 “change” 而非 “changed” 或 “changes”。
同理在正文body可选中也要用祈使语气和现在时态。正文中需要包括更改的动机并对比与更改前后行为的变化。确保你说明的是`为什么`,而不是`怎么做`。
✅ 花几分钟逛逛 GitHub。你能找到感觉非常棒的提交信息吗你可以找到非常简洁的提交信息吗你认为在一条提交信息中传达什么信息是最重要和有用的
### 任务:协作
将项目放到 GitHub 的主要原因是让和其他开发者协作开发成为可能。
## 和其他人协作开发项目
在你的仓库中,前往 `Insights > Community` 来查看你的项目和推荐的社区规范的对比。
这里有一些你可以改进你的项目仓库的点:
- **项目描述Description**。你为你的项目添加了描述吗?
- **README**。你有添加 README 吗GitHub 提供了撰写 [README](https://docs.github.com/articles/about-readmes/) 的指南。
- **贡献指南Contributing guideline**。你的项目是否有[贡献指南](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/)
- **行为准则Code of Conduct**。添加一份 [行为准则](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/)
- **开源协议License**。或许是最重要的,添加一个[开源协议](https://docs.github.com/articles/adding-a-license-to-a-repository/)
所有这些资源对于新加入的团队成员都是很有好处的,这些一般是新的贡献者在看你的代码前会更先去看的东西,以确认你的项目是否值得他们在这上面花费时间。
✅ 尽管很多人都准备了 README 文件,但常常会因为太忙而疏于维护。你能找到一个这样的例子吗?注:这里有一些可以[用于创建优秀的 README 的工具](https://www.makeareadme.com/),你或许愿意试试。
### 任务合并Merge一些代码
贡献文档帮助人们对项目做贡献,其中说明了你正需要什么样的贡献以及贡献的过程该是怎样的。贡献者需要完成一系列步骤才能在 GitHub 上参与你项目的贡献:
1. **复刻Fork你的仓库**。你可能希望人们 _复刻_ 你的项目。复刻意味着在他们自己的 GitHub 账户下创建你的项目的一份副本。
1. **克隆Clone**。在这里他们将会将项目克隆到他们的本地机器上。
1. **创建一个分支Branch**。你可能希望他们能创建一个 _分支_ 来进行他们的工作。
1. **集中进行一个区域的修改**。要求贡献者每次贡献只专注做一件事,这样你才更可能 _合并_ 他们的工作。想象一下如果他们修了一个 BUG添加了一个新特性然后更新了几个测试而你其实只想要其中的一个或两个更改时该怎么办
✅ 想一想分支在什么情况下对于编写和发布优质的代码非常重要?你能想到哪些使用实例?
> 注意要以身作则对你自己的工作也要创建分支。任何提交都需要在当前“检出checked out”的分支上进行。使用 `git status` 来查看是哪一个分支。
让我们走一遍贡献者的工作流程。假设贡献者已经 _复刻_ 并 _克隆_ 了仓库,他们在本地机器已经有了一个可以工作的仓库:
1. **创建一个分支**。使用命令 `git branch` 来创建一个他们希望用来包含计划进行的变更的分支:
```bash
git branch [分支名]
```
1. **切换到工作分支**。使用 `git switch` 来切换到指定分支并且更新工作目录中的文件:
```bash
git switch [分支名]
```
1. **干活**。现在你可以添加你的变更了,别忘了用下面的命令告诉 Git 你所做的工作:
```bash
git add .
git commit -m "变更内容"
```
确保你的提交有一个好名字,不论是对你自己还是你正在帮助的仓库维护者来说都有好处。
1. **将你的工作合入 `main` 分支**。在完成工作后,你打算将你的工作和 `main` 分支上的合并。`main` 分支可能同时有了一些新的变更,所以要先用以下命令确保将其更新至最新版本:
```bash
git switch main
git pull
```
这时你想确认是否存在 _冲突conflicts_即 Git 没法简单地将这些变化 _合入_ 你的分支的情况。为此运行下面的命令:
```bash
git switch [分支名]
git merge main
```
这将会把所有 `main` 分支上的变更带入到你的分支上。运气好的话一切都会自动搞定,否则 VS Code 会告诉你哪些文件 Git _不确定_ 该如何合并,你只需要手动修改对应文件来解决冲突即可。
1. **将你的工作上传至 GitHub**。将你的工作上传至 GitHub 意味着两件事:把你的分支上传到你自己的仓库,然后开启一个 PRPull Request
```bash
git push --set-upstream origin [分支名]
```
上述命令在你复刻的仓库中创建了一个分支。
1. **开启一个 PR**。接下来,你打算开启一个 PR。前往 GitHub 上你打算贡献的仓库,你将会看到一个消息条询问你是否想要创建一个新的 PR点击后即可进入创建 PR 的界面。在这里你可以更改提交标题,给出更准确的描述。创建 PR 后,仓库维护者将会看到这个,如果 _一切顺利_ 的话他们会表示感谢并且 _合并_ 你的 PR。你现在就是一位贡献者啦 :)
1. **清理**。成功合入一个 PR 后,做做 _清理_ 是一个好习惯。你会想要清理本地和你上传到 GitHub 的分支。首先让我们通过下面的命令来删除本地的分支:
```bash
git branch -d [分支名]
```
接下来请确保前往 GitHub 中对应仓库的页面并删除你刚才上传的分支。
`Pull request` 这个术语看起来有些憨,因为你确实打算把你的变更提交到这个项目中。但是在将你的变更合入到项目的 `main` 分支前维护者项目拥有者或者核心团队需要考虑和检查你的变更这意味着你实际上是在请求request维护者的变更决定。
Pull Request 是一个可以用来比较和讨论一个分支引入的改动的地方,并有代码审查、评论、集成测试等功能。优质的 Pull Request 严格遵照与提交信息相同的规则。如果你的工作是为了修复一个 Issues 面板中的事项,你可以在 PR 中提及这个事项。具体做法是写一个 `#` 加上事项的编号,比如 `#97`。
🤞如果一切顺利,所有的检查都通过后项目拥有者就会将你的变更合入项目🤞
使用这个命令即可将 GitHub 上对应远程分支的所有新提交更新到当前本地的工作分支上:
`git pull`
## 如何参与开源贡献
首先,让我们在 GitHub 上找到一个你感兴趣且愿意参与贡献的仓库(**repo**),你会复制一份它的内容到你的机器上。
✅ 一个寻找对入门者友好的仓库的好办法是[搜索 “good-first-issue” 标签](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/)。
![Copy a repo locally](../images/clone_repo.png)
有很多种复制代码的方法,其中一种就是“克隆”仓库的内容,可以用 HTTPS、SSH 或者 GitHub CLICommand Line Interface来做到。
打开你的终端并且用类似下方的命令来克隆仓库:
`git clone https://github.com/ProjectURL`
切换到正确的工作目录:
`cd ProjectURL`
你也可以用 [Codespaces](https://github.com/features/codespaces) 来打开整个项目,这是 GitHub 内置的代码编辑器和云开发环境,或者用 [GitHub Desktop](https://desktop.github.com/)。
当然,你也可以直接下载代码的压缩包。
### 更多 GitHub 的有趣小知识
你可以收藏star、关注watch和复刻forkGitHub 上的任何公开仓库。可以在右上角的下拉菜单找到你收藏的仓库,这就像书签一样,但收藏的是代码。
项目都有一个事项面板issue tracker用于让人们讨论和这个项目相关的事项事项面板基本都在 GitHub 的 “Issues” 标签页中,偶尔也会指明在其他地方。而 “Pull Requests” 标签页则是人们讨论和检查正在进行的变更的地方。
项目也可能会在论坛、邮件列表或者如 Slack、Discord、IRC 这样的聊天频道进行讨论。
✅ 看看你新建立的 GitHub 仓库,尝试做一些其他事,比如编辑设置、为仓库增加信息、创建一个 Project类似看板有很多可以尝试的东西
---
## 🚀 挑战
找朋友一起编辑彼此的代码。协作创建一个项目、复刻代码、创建分支,然后合并变更。
## 课后小测
[课后小测](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=zh_cn)
## 复习 & 自学
了解更多 [如何提交贡献](https://opensource.guide/zh-hans/how-to-contribute/#%E5%A6%82%E4%BD%95%E6%8F%90%E4%BA%A4%E8%B4%A1%E7%8C%AE)。
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/)。
练习练习再练习。GitHub 在 [lab.github.com](https://lab.github.com/) 提供了很棒的学习路径:
- [在 GitHub 的第一周](https://lab.github.com/githubtraining/first-week-on-github)
你还可以在上面找到更多高阶的实验内容。
## 作业
完成 [在 GitHub 的第一周](https://lab.github.com/githubtraining/first-week-on-github)

View File

@@ -0,0 +1,319 @@
# GitHub 簡介
這堂課程講述一個提供加設與管理程式碼的平台 ── Github的基本功能。
![GitHub 簡介](/sketchnotes/webdev101-github.png)
> 由[Tomomi Imura](https://twitter.com/girlie_mac) 繪製
## 課前測驗
[課前測驗](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/3?loc=zh_tw)
## 大綱
在這堂課中,包含:
- 追蹤裝置上的工作專案
- 與其他人共同開發專案
- 如何貢獻網路上的開源軟體
### 開始之前
在你開始課程之前,你需要安裝 Git 這套套件。在你的終端機上輸入:
`git --version`
若你的裝置上沒有安裝 Git[請下載並安裝 Git](https://git-scm.com/downloads)。 安裝完之後,請設定裝置本地 Git 的使用者設定。
* `git config --global user.name "your-name"`
* `git config --global user.email "your-email"`
要確認 Git 使用者設定是否完成,你可以輸入:
`git config --list`
此外,你需要一組 GitHub 的帳戶、一款文字編輯器 (如Visual Studio Code) 與你的終端機 (或 command prompt)。
若你缺少 GitHub 帳戶,請前往 [github.com](https://github.com/)建立並登入一組帳戶,遵循指示完成資料的填寫。
✅ GitHub 不是唯一的程式碼數據庫,但 GitHub 是家喻戶曉的。
### 課前準備
你需要在裝置(筆電或電腦)上建立程式專案的資料夾,與 GitHub 公共的數據庫(Public Repository)。之後的例子會使用到此公共數據庫來與他人分享程式碼。
---
## 程式碼管理
假設你的本地端資料夾存放著一些程式專案,你想利用 Git 來作專案追蹤與版本控制,甚至是對未來的你寫一封情書。在一天、一週甚至是一個月後閱讀你的提交紀錄,了解當初你的決定,回想之前的更動。前提是當初你有寫一條完整的提交紀錄。
### 課題:建立數據庫並提交程式碼
1. **在 GitHub 上建立數據庫** 在 GitHub.com 上,在 "Repositories" 的標籤或導航欄的右上方,找到 **new repo** 的按鈕。
1. 為你的數據庫資料夾取個名字。
1. 選擇 **建立數據庫(create repository)**.
1. **調查本地的專案資料夾** 在終端機中開啟儲存程式碼的資料夾,在你想追蹤的目錄下輸入:
```bash
cd [資料夾名稱]
```
1. **初始化 git 數據庫(repo)** 在目錄下輸入:
```bash
git init
```
1. **檢查狀態** 若想檢查目前數據庫的狀態,輸入:
```bash
git status
```
它會輸出類似以下的訊息:
```output
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: file.txt
modified: file2.txt
```
指令 `git status` 會回報那些檔案已經準備 _被存到_ 數據庫或是被更動過但不想更新上去。
1. **開始追蹤所有檔案**
新增檔案到暫存區(staging area)。
```bash
git add .
```
`git add` 加上路徑 `.` 表示追蹤該路徑下所有的檔案。
1. **只追蹤選擇的檔案**
```bash
git add [檔案或資料夾路徑]
```
上述指令幫助你只追蹤被選取的檔案,允許使用者分批提交。
1. **取消追蹤所有檔案**
```bash
git reset
```
上述指令能取消追蹤(unstage)暫存區的檔案。
1. **取消追蹤特定的檔案**
```bash
git reset [檔案或資料夾路徑]
```
上述指令只取消追蹤單一檔案,在下一次提交時不被圈選在裡面。
1. **保存工作狀態** 現在,已經有一些檔案被標記在 _暫存區(staging area)_。 Git 會追蹤區域內的檔案。若要保存這些檔案的狀態,你需要 _提交(commit)_ 這些檔案。 _提交_ 會記錄當下數據庫中檔案的狀態到歷史紀錄中。 你需要指令`git commit` 完成這項工作。
```bash
git commit -m "first commit"
```
這會提交暫存區內的檔案,"first commit"即提交紀錄。提交紀錄最好能識別出這次的提交主要做了那些更動。
1. **連接本地數據庫到 GitHub 遠端數據庫** 現在 Git 數據庫已經成功運行在你的本地裝置上,但有時候你希望能將檔案備份到其他地方,或是邀請他人參與這項程式專案。 GitHub 便是一個好地方。先前我們已經建立遠端數據庫在 GitHub 上,現在我們只要連接本地數據庫到 GitHub上。指令 `git remote add` 能完成這項課題:
> 注意,在輸入指令前,你需要取得 GitHub 遠端數據庫的 URL 位置。請將下列的 `repository_name` 替換為你的遠端數據庫路徑。
```bash
git remote add origin https://github.com/username/repository_name.git
```
這會在 GitHub 遠端數據庫上建立一個名叫 "origin" 的 _遠端位置(remote)_ ,或稱 _連接(connection)_。
1. **上傳本地檔案到 GitHub** 現在已經建好了遠端與本地的 _連接_。 利用指令 `git push` 可以將本地檔案上傳到遠端數據庫當中:
```bash
git push -u origin main
```
所有的提交都會加到 GitHub 上 "main" 的分支當中。
1. **增加更多的更動** 若之後再對程式碼有所更動、提交並上傳到 GitHub 上,只要輸入:
```bash
git add .
git commit -m "type your commit message here"
git push
```
> 提示:建立 `.gitignore` 檔案可以讓你自動排除的特定檔案項目不被 GitHub 追蹤。好比是有一個在同一個目錄下的筆記檔不想被上傳到遠端數據庫。以下是 `.gitignore` 的參考版型: [.gitignore 參考版型](https://github.com/github/gitignore)。
#### 提交紀錄(Commit Messages)
一條好的 Git 提交標題行最好滿足下列條件:
提交完後,提交紀錄會顯示 <你的標題>
標題使用祈使語句,如使用 "change" 而非 "changed" 或 "changes"。
同理地,內文(選擇性)也使用祈使語句。內文須包含改動的動機與改動前後的差異。你需要解釋「為什麼改」而非「怎麼改」。
✅ 花點時間在 GitHub 上閒晃。你能找到很棒的提交紀錄嗎? 你能找到簡潔的提交紀錄嗎? 哪些資訊是你認為一個提交紀錄要有的重要資訊?
### 課題:多人合作
另一個將專案上傳到 GitHub 的主要原因是讓其他開發者能參與其中。
## 與其他人共同開發專案
在你的遠端資料庫中,前往 `Insights > Community` 來對比你的專案與其他推薦社群專案。
以下是一些你的 GitHub 數據庫需要精進的地方:
- **專案描述(Description)** 你有為你的專案新增描述嗎?
- **README** 你有新增 README 嗎? GitHub 提供編寫 README 的指引與參考: [README](https://docs.github.com/articles/about-readmes/)
- **開發指引(Contributing guideline)** 你的專案內有[開發指引](https://docs.github.com/articles/setting-guidelines-for-repository-contributors/)嗎?
- **行為準則(Code of Conduct)** [行為準則](https://docs.github.com/articles/adding-a-code-of-conduct-to-your-project/)
- **授權條款License** 這或許是最重要的:[授權條款](https://docs.github.com/articles/adding-a-license-to-a-repository/)
這些資源對剛加入到專案的新成員有所幫助。這些是新的合作夥伴比看程式碼還優先查詢的地方。完善它們能有效縮減他人消化的時間。
✅ README 檔,雖然多數人都會配置,但忙碌的開發者都會疏於管理。 你能在社群中找到相關的例子嗎? 這邊有[關於建立 READMEs 的有利工具](https://www.makeareadme.com/)可以嘗試。
### 課題:合併程式碼
開發指引文件幫助他人了解如何共同開發專案。它提供專案需要被貢獻的部分與該如何運作。共同開發者需要經過下列步驟來與他人在 GitHub 共同開發專案:
1. **分叉(Fork)專案** 你或許希望別人能 _分叉(fork)_ 你的專案。 分叉代表別人建立一份你的專案副本到他人的 GitHub 數據庫中。
1. **複製(Clone)** 複製專案到他人的本地裝置中。
1. **建立分支(branch)** 依照工作需求建立 _分支(branch)_。
1. **專注在他人投入的工作範圍** 要求他人只專注在單一課題上,這樣能提升他們工作 _合併(merge)_ 的機會。想像他們在修正錯誤,同時又新增新功能、更新測試機制......這時如果你只想合併其中的一個、或者是兩個功能呢?
✅ 想像一個情況:一個重要的分支是編輯與分享的主軸,它能被如何應用?
> 注意,在做更動前,記得建立新的分支。任何提交都會在你所在的分支上,指令 `git status` 可以檢查你現在所在的分支。
現在,我們以共同開發者的角度來看。假設開發者已經 _分支_ 且 _複製_ 了他人的數據庫到自己的 Git 數據庫上,準備開始編輯檔案:
1. **建立新的分支** 利用指令 `git branch` 來建立新的分支,只做相關的工作改動。
```bash
git branch [分支名稱]
```
1. **切換到該工作分支** 使用指令 `git switch` 來切換到特定分支,更新分支的檔案狀態:
```bash
git switch [分支名稱]
```
1. **程式設計** 記得追蹤你所更改的地方,利用下列的指令來告訴 Git
```bash
git add .
git commit -m "my changes"
```
請確保提交都有適當的名稱,對管理者與你自己都有好處。
1. **將工作分支與 `main` 分支進行合併** 當工作完成時,你會需要將工作分支與 `main` 分支進行合併。 `main` 分支可能會被他人更新,在合併之前記得更新主分支:
```bash
git switch main
git pull
```
這項步驟可能會面臨到 _衝突(conflicts)_代表 Git 無法將本地的更動作 _合併(combine)_ 。此時你需要執行下列的指令:
```bash
git switch [分支名稱]
git merge main
```
這會將所有 `main` 分支的改動加入到你的本地目錄中。若出現狀況VS Code會告訴你 Git 會對衝突的檔案感到 _困惑(confused)_ 你需要判斷哪一項檔案或程式碼才是最適當的選擇。
1. **將你的成果上傳到 GitHub** 這代表著兩件事:將分支推到你的遠端數據庫以及準備建立 Pull Request(PR)。
```bash
git push --set-upstream origin [分支名稱]
```
上述的指令會在分叉的數據庫中新增分支。
1. **建立 PR** 藉由造訪分叉的數據庫中建立 PRGitHub 會指示你是否要建立 PR之後要填寫提交紀錄以及編寫詳細的說明。讓管理者了解你做了哪些更動並進行 _交叉比對(fingers crossed)_。 他們會感激你的貢獻並 _合併(merge)_ 你的 PR。完成這步後你就成為了專案貢獻者恭喜
1. **清理專案** 在 PR 被成功合併後, _清除專案(clean up)_ 會是一個好習慣。 你需要清除你的本地分支以及你的遠端數據庫分支。首先,你可以利用下列的指令清除本地分支:
```bash
git branch -d [分支名稱]
```
之後,請確保在 GitHub 頁面上刪除遠端分支。
`Pull request` 要求更新更動到「自己」的專案數據庫,這看起來很蠢。但管理者與核心組員必須謹慎地考量你的更動才能合併到專案的主分支中。這便是向管理者請求上傳許可。
一個 PR 提供比對以及討論的地方,解釋分支的意義、確認程式的合理性、留言與測試……等等。一個好的 PR 必須參照前述所說的提交紀錄準則。若你的 PR 有解決特定的 issue記得標記在 PR 當中。使用 `#` 接在數字前面來標記 issue 編號,如 `#97`。
🤞 交叉比對每個程式環節都正確無誤後,專案管理者才合併你所作的更動 🤞
若要從 GitHub 遠端數據庫更新到目前的本地工作分支,使用:
`git pull`
## 如何貢獻網路上的開源軟體
首先,尋找一個你感興趣的數據庫,你會複製一份副本到自己的裝置上。
✅ 對新手而言,尋找「適合新手」的數據庫可以[搜尋 'good-first-issue' 標籤](https://github.blog/2020-01-22-browse-good-first-issues-to-start-contributing-to-open-source/)。
![複製數據庫到本地](../images/clone_repo.png)
有許多方式來複製數據庫。 一種是利用 "clone" 整個數據庫的內容。可以使用 HTTPS、SSH 或是 GitHub CLI (Command Line Interface)。
打開終端機並輸入下列指令來複製數據庫:
`git clone https://github.com/ProjectURL`
複製完後記得切換到正確的資料夾當中:
`cd ProjectURL`
你也可以利用[Codespaces](https://github.com/features/codespaces)來打開專案,一款嵌入在 GitHub 中的雲端開發環境,或是使用[GitHub Desktop](https://desktop.github.com/)。
最後,你也可以下載數據庫的壓縮檔。
### 有關 GitHub 的小知識
你可以為別人打星星(star)、追蹤(watch)或分叉(fork)任何一個 GitHub 上的共享數據庫。打上星星的數據庫會出現在右上方的導航欄中。就像是書籤,但是是給程式碼用的。
專案內會有 issue 追蹤器。大多數的 issue 會在 GitHub "Issue" 的標籤內(有些Issue會由作者另外說明),供大家進行討論。 Pull Requests 標籤內會有正在討論與審核的程式更動。
專案也會有討論區、寄信功能以及聊天室如 Slack、Discord 或 IRC。
✅ 花點時間觀察你的新專案,試著更新設定、新增描述、或架構成一個大型專案(像個大看板一樣!)。你可以創造出任何東西!
---
## 🚀 挑戰
找朋友一起編輯彼此的程式。共同建立一項專案、分叉程式、建立分支、合併更動。
## 課後測驗
[課後測驗](https://ashy-river-0debb7803.1.azurestaticapps.net/quiz/4?loc=zh_tw)
## 複習與自學
了解更多:
[貢獻開源軟體](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution)
[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/)
練習,練習,再練習! GitHub 有提供很好的學習管道:[lab.github.com](https://lab.github.com/)
- [第一週在 GitHub 上](https://lab.github.com/githubtraining/first-week-on-github)
你能找到更資深的實驗內容。
## 作業
完成[第一週在 GitHub 上](https://lab.github.com/githubtraining/first-week-on-github)