#git checkout master
Explore tagged Tumblr posts
snarp · 1 year ago
Text
I'm allowed to cause terrible problems
11 notes · View notes
ashhaven · 7 months ago
Text
I know I don’t have a lot of programmers following me
But me and some friends a d colleagues just workshopped the git fucker 9000
git fetch && git checkout master && git branch —list -r | sort -R | xargs -L1 'git merge —strategy=ort —strategy-options=theirs -q —squash' && git reset $(git rev-list --max-parents=0 HEAD) --soft && git add -A && git commit --amend -m "lol, lmao even" && git branch --list | xargs -L1 'git branch -D' && git branch --list -r | xargs -L1 'git branch -D -r' && git push -u origin master -f
Do not run this
20 notes · View notes
yasirinsights · 12 days ago
Text
GitHub and Git Commands: From Beginner to Advanced Level
Tumblr media
Git and GitHub are essential tools for every developer, whether you're just starting or deep into professional software development. In this blog, we'll break down what Git and GitHub are, why they matter, and walk you through the most essential commands, from beginner to advanced. This guide is tailored for learners who want to master version control and collaborate more effectively on projects.
GitHub and Git Commands
What Is Git?
Git is a distributed version control system created by Linus Torvalds. It allows you to track changes in your code, collaborate with others, and manage your project history.
What Is GitHub?
GitHub is a cloud-based platform built on Git. It allows developers to host repositories online, share code, contribute to open-source projects, and manage collaboration through pull requests, issues, and branches
Why Learn Git and GitHub?
Manage and track code changes efficiently
Collaborate with teams
Roll back to the previous versions of the code
Host and contribute to open-source projects
Improve workflow through automation and branching
Git Installation (Quick Start)
Before using Git commands, install Git from git-scm.com.
Check if Git is installed:
bash
git --version
Beginner-Level Git Commands
These commands are essential for every new user of Git:
1. git init
Initialises a new Git repository.
bash
git init
2. git clone
Clones an existing repository from GitHub.
bash
git clone https://github.com/user/repo.git
3. git status
Checks the current status of files (modified, staged, untracked).
bash
git status
4. git add
Stage changes for commit.
bash
git add filename # stage a specific file git add . # stage all changes
5. git commit
Records changes to the repository.
bash
git commit -m "Your commit message"
6. git push
Pushes changes to the remote repository.
bash
git push origin main # pushes to the main branch
7. git pull
Fetches and merges changes from the remote repository.
bash
git pull origin main
Intermediate Git Commands
Once you’re comfortable with the basics, start using these:
1. git branch
Lists, creates, or deletes branches.
bash
git branch # list branches git branch new-branch # create a new branch
2. git checkout
Switches branches or restores files.
bash
git checkout new-branch
3. git merge
Merges a branch into the current one.
bash
git merge feature-branch
4. git log
Shows the commit history.
bash
git log
5. .gitignore
Used to ignore specific files or folders in your project.
Example .gitignore file:
bash
node_modules/ .env *.log
Advanced Git Commands
Level up your Git skills with these powerful commands:
1. git stash
Temporarily shelves changes not ready for commit.
bash
git stash git stash apply
2. git rebase
Reapplies commits on top of another base tip.
bash
git checkout feature-branch git rebase main
3. git cherry-pick
Apply the changes introduced by an existing commit.
bash
git cherry-pick <commit-hash>
4. git revert
Reverts a commit by creating a new one.
bash
git revert <commit-hash>
5. git reset
Unstages or removes commits.
bash
git reset --soft HEAD~1 # keep changes git reset --hard HEAD~1 # remove changes
GitHub Tips for Projects
Use Readme.md to document your project
Leverage issues and pull requests for collaboration
Add contributors for team-based work
Use GitHub Actions to automate workflows
Final Thoughts
Mastering Git and GitHub is an investment in your future as a developer. Whether you're working on solo projects or collaborating in a team, these tools will save you time and help you maintain cleaner, safer code. Practice regularly and try contributing to open-source projects to strengthen your skills.
Read MORE: https://yasirinsights.com/github-and-git-commands/
2 notes · View notes
technicallywrite · 2 years ago
Text
Progress update on Cosmosgate
I had promised myself I'd take a break from writing after reaching The Kiss (ie Chapter 30). The idea was that Cosmosgate would go on hiatus for a few weeks while I plotted out the next bunch of chapters, which only existed as rough outlines so far.
I'm happy to say I did that and the detailed plotting went faster than anticipated —in part because I figured out how to adapt some tricky bits of original Big Finish audio that I'd thought were going to be stumpers— so now I'm moving on to rough-drafting, with the goal of resuming posting chapters within the next couple of weeks.
Here are the working titles for chapters 31-37:
31- Power play
32- Back in the fold
33- A bridge too far
34- And yet, she persisted
35- Control-alt-delete
36- Git checkout master
37- Fianchetto
Feel free to speculate about the title references, I had a bit of fun with them 😆
12 notes · View notes
techsoundwave · 26 days ago
Text
Как управлять версиями кода с помощью Git?
Когда я только начал работать в стартапе, занимающемся созданием сайтов и мобильных приложений, я понял, как важно правильно управлять версиями кода. В особенно быстрых и динамичных проектах, как у нас, где разработка ведется параллельно и над несколькими функциями, использование системы контроля версий становится жизненно важным. Одним из самых популярных и мощных инструментов для этого является Git.
Git позволяет управлять версиями кода, отслеживать изменения, работать с разными ветками и эффективно координировать командную работу. Он также особенно полезен при разработке мобильных приложений, где требуется быстро вносить изменения и легко откатываться к предыдущим версиям. В этой статье я расскажу, как использовать Git для управления версиями и о базовых принципах работы с ним.
Что такое Git и зачем он нужен?
Git — это система контроля версий, которая позволяет разработчикам отслеживать изменения в коде, работать над проектами совместно и контролировать историю всех изменений. Git позволяет создавать локальные копии репозиториев, синхронизировать их с удалёнными серверами, создавать ветки и комбинировать их, а также откатывать изменения.
Когда вы занимаетесь созданием сайтов или мобильных приложений, очень важно не потерять важные изменения в коде, особенно если над проектом работают несколько человек. Git помогает вам не только избежать таких проблем, но и улучшить общую эффективность работы.
Основные команды Git
git init Эта команда инициализирует новый репозиторий Git в директории вашего проекта. Она позволяет начать использовать Git для отслеживания изменений.
git clone <url> Если вы хотите работать с уже существующим проектом, можно клонировать репозиторий с помощью команды git clone <url>, где URL — это ссылка на удалённый репозиторий.
git add <file> После того как вы внесли изменения в код, используйте команду git add <file> для добавления этих изменений в индекс, который будет сохранён в коммите.
git commit -m "message" Когда изменения готовы, выполните команду git commit -m "сообщение", чтобы зафиксировать их в ��стории проекта. Важно писать понятные и лаконичные сообщения, чтобы команда могла легко понять, что было изменено.
git push Для того чтобы отправить локальные изменения на удалённый репозиторий, используйте команду git push. Это позволяет синхронизировать вашу локальную работу с работой команды.
git pull Чтобы получить изменения с удалённого репозитория и синхронизировать их с вашим локальным проектом, используйте команду git pull.
Работа с ветками
Одна из сильных сторон Git — это возможность работать с ветками. Ветки позволяют изолировать различные изменения, тестировать новые функции, исправлять ошибки или разрабатывать новые идеи без вмешательства в основную кодовую базу. Это особенно полезно в мобильных приложениях, когда нужно внедрить новую фичу или интеграцию с внешним сервисом, не затрагивая текущую стабильную версию.
git branch Эта команда позволяет увидеть все ветки, которые существуют в проекте.
git checkout -b <branch-name> Команда git checkout -b <branch-name> используется для создания новой ветки и перехода на неё. Напр��мер, если вам нужно добавить новую фичу, можно создать ветку под названием feature-login.
git merge <branch-name> Когда работа над функцией завершена, вы можете объединить её изменения с основной веткой (обычно это main или master), используя команду git merge <branch-name>.
Рекомендации по использованию Git в команде
Частые коммиты. Делайте коммиты часто, чтобы легко отслеживать изменения и избегать потери данных. Также это облегчает процесс отката к предыдущим версиям кода.
Чистота истории. Важно, чтобы история коммитов была понятной и структурированной. Используйте осмысленные сообщения для коммитов и следуйте правилам кодирования, чтобы история оставалась читаемой.
Использование pull-request'ов. Когда работаете в команде, полезно использовать pull-request’ы для объединения веток. Это позволяет членам команды проверять код перед его слиянием с основной веткой, повышая качество и стабильность кода.
Tumblr media
Git — это незаменимый инструмент для любого разработчика, особенно когда вы работаете над проектами, такими как создание сайтов и мобильных приложений, где важна синхронизация командной работы и контроль версий. Git позволяет вам не только отслеживать изменения, но и работать более гибко, эффективно и безопасно. Правильное использование Git в проекте помогает избежать многих проблем и улучшить рабочий процесс.
Если у вас есть вопросы по Git или вы хотите узнать больше о том, как его применять в разработке мобильных приложений, пишите в комментариях — буду рад помочь!
0 notes
msrlunatj · 9 months ago
Text
Cómo Usar Git y GitHub para Control de Versiones: Guía Básica para Gestionar Proyectos y Colaborar con Otros
Introducción
El control de versiones es una herramienta esencial en el desarrollo de software. Git y GitHub son dos herramientas poderosas que te permiten gestionar cambios en tu código, colaborar con otros desarrolladores y mantener un historial de versiones de tus proyectos. En esta guía, te ofreceremos una introducción básica sobre cómo usar Git y GitHub para comenzar a gestionar tus proyectos de manera efectiva.
1. ¿Qué es Git y GitHub?
Git:
Git es un sistema de control de versiones distribuido que te permite rastrear los cambios en tu código fuente a lo largo del tiempo. Con Git, puedes gestionar versiones, deshacer cambios, y colaborar con otros sin perder el historial de tu proyecto.
GitHub:
GitHub es una plataforma en línea que utiliza Git para ofrecer servicios de alojamiento de repositorios. Permite colaborar en proyectos de manera más fácil al proporcionar una interfaz web para Git, junto con herramientas adicionales para la colaboración y la gestión de proyectos.
2. Instalación de Git
Paso 1: Descargar Git
Visita el sitio web oficial de Git (git-scm.com) y descarga la versión adecuada para tu sistema operativo.
Paso 2: Instalación
Sigue las instrucciones del instalador. Para la mayoría de los usuarios, las opciones predeterminadas funcionarán bien.
Paso 3: Configuración Inicial
Después de instalar Git, abre la terminal (o línea de comandos) y configura tu nombre de usuario y correo electrónico:
git config --global user.name "Tu Nombre" git config --global user.email "[email protected]"
3. Creación y Gestión de Repositorios Locales
Inicializar un Repositorio
Para comenzar a usar Git en un proyecto existente, navega a la carpeta del proyecto en la terminal y ejecuta:
git init
Esto creará un nuevo repositorio Git en tu proyecto.
Agregar Archivos al Repositorio
Añade archivos a tu repositorio usando:
git add nombre-del-archivo
Para agregar todos los archivos modificados, usa:
git add .
Confirmar Cambios
Realiza un commit para guardar los cambios en el repositorio:
git commit -m "Mensaje descriptivo sobre el cambio"
4. Uso Básico de GitHub
Crear un Repositorio en GitHub
Inicia sesión en tu cuenta de GitHub (github.com).
Haz clic en el botón "New" para crear un nuevo repositorio.
Completa los detalles del repositorio y haz clic en "Create repository".
Conectar un Repositorio Local con GitHub
Copia la URL del repositorio desde GitHub.
En la terminal, navega a tu repositorio local y agrega el repositorio remoto:
git remote add origin URL-del-repositorio
Envía tus cambios al repositorio remoto:
git push -u origin master
Actualizar tu Repositorio Local con Cambios desde GitHub
Para obtener los cambios realizados por otros en el repositorio remoto:
git pull origin master
5. Colaboración y Gestión de Proyectos
Ramas (Branches)
Las ramas permiten trabajar en diferentes versiones de tu proyecto al mismo tiempo. Para crear una nueva rama:
git branch nombre-de-la-rama
Para cambiar a la nueva rama:
git checkout nombre-de-la-rama
Combina cambios de una rama a otra con:
git merge nombre-de-la-rama
Solicitudes de Extracción (Pull Requests)
Las pull requests en GitHub permiten revisar y discutir cambios antes de fusionarlos en la rama principal del proyecto. Para crear una pull request:
Realiza cambios en una rama y haz un push a GitHub.
Ve a la página del repositorio en GitHub y crea una nueva pull request desde la rama modificada.
Issues y Gestión de Proyectos
GitHub ofrece herramientas para gestionar proyectos mediante issues (problemas). Puedes crear issues para reportar errores, solicitar mejoras o realizar un seguimiento de tareas.
6. Buenas Prácticas en el Uso de Git y GitHub
Hacer Commits Frecuentes: Realiza commits regularmente para capturar cambios pequeños y significativos.
Escribir Mensajes de Commit Claros: Asegúrate de que tus mensajes de commit describan claramente los cambios realizados.
Usar Ramas para Nuevas Funcionalidades: Desarrolla nuevas características en ramas separadas para mantener la rama principal estable.
Revisar Pull Requests Cuidadosamente: Antes de fusionar cambios, revisa y prueba el código para asegurar su calidad.
Conclusión
Git y GitHub son herramientas esenciales para la gestión de proyectos y la colaboración en el desarrollo de software. Con esta guía básica, estás listo para comenzar a utilizar estas herramientas para mejorar tu flujo de trabajo y colaborar efectivamente con otros desarrolladores. Recuerda que la práctica y la experimentación son clave para dominar estas herramientas, así que no dudes en empezar a usarlas en tus proyectos.
Recursos Adicionales
Documentación Oficial de Git: Git Documentation
Guía de GitHub: GitHub Docs
Tutoriales y Cursos:
Codecademy: Learn Git
Udemy: Git y GitHub para Principiantes
0 notes
webdevrahul007 · 1 year ago
Link
0 notes
nextonesolutions · 2 years ago
Text
Git: Mastering Version Control for Efficient Collaboration
Tumblr media
Introduction
In the world of software development and collaborative projects, efficient version control is paramount. Enter Git, a revolutionary tool that has transformed the way developers manage code and collaborate on projects. In this article, we will delve deep into Git, from its fundamental concepts to its most advanced features, empowering you to harness the full potential of this essential tool.
Git: A Brief Overview
Git is a distributed version control system designed to track changes in source code during software development. Created by Linus Torvalds in 2005, Git has become the cornerstone of modern development workflows. Its decentralized architecture and robust features make it a preferred choice for both individual developers and large-scale teams.
Understanding Version Control
Version control allows developers to keep track of changes made to their codebase over time. It ensures a structured and organized approach to collaboration, making it easier to manage and merge code from multiple contributors. Git's distributed nature empowers developers to work on their own copies of the repository, contributing to a more seamless and efficient development process.
The Power of Git
Git brings several key benefits to the table: Efficient Collaboration: Git enables developers to work on the same project simultaneously without interfering with each other's code. History Tracking: It maintains a detailed history of changes, allowing developers to revisit previous versions and understand the evolution of the codebase. Branching and Merging: Git's branching mechanism allows for parallel development, and merging simplifies the integration of different branches. Code Review: Git's pull request feature facilitates code review, ensuring code quality before merging changes. Open Source Community: Git's open-source nature has led to a vibrant community that contributes to its continuous improvement. Git Basics: Setting Up To get started with Git, follow these steps: Installation Install Git on your system by downloading it from the official Git website or using package managers like apt or Homebrew. Configuration Configure your Git username and email using the following commands: bash Copy code git config --global user.name "Your Name" git config --global user.email "[email protected]"
Git Workflow A typical Git workflow involves the following stages:
1. Working Directory This is where you make changes to your files.
2. Staging Area Use git add to stage changes for commit. This allows you to selectively choose which changes to include in the next commit.
3. Commit Create a snapshot of the staged changes using git commit. This creates a new version in the repository's history.
4. Branching Branching is at the core of Git. Create a new branch using git branch <branch-name>. Switch to a branch using git checkout <branch-name>.
5. Merging Merge changes from one branch into another using git merge <branch-to-merge>.
Git Commands You Need to Know
Here are some essential Git commands every developer should be familiar with: git clone <repository-url> Clone a remote repository to your local machine. git status Check the status of your working directory and staged changes. git pull Fetch and merge changes from a remote repository to your local branch. git push Push your local changes to a remote repository. git log View the commit history of the current branch. git diff Compare the differences between files and commits. Advanced Git Features Git offers a range of advanced features to streamline your workflow: Git Hooks Hooks are scripts that Git can run before or after certain events. They allow you to automate tasks like running tests before a commit. Git Submodules Submodules allow you to include other repositories within your own. This is useful for managing dependencies. Git Rebase Rebasing allows you to modify the commit history by moving, combining, or deleting commits.
FAQs
How is Git different from other version control systems? Git is distributed, meaning every developer has their own local copy of the entire repository. This leads to greater flexibility and robustness compared to centralized systems.
Can Git be used for non-code files? Absolutely! While Git is popular in the software development realm, it can be used to version control any type of file, including documents, images, and configuration files.
Is Git suitable for large projects? Yes, Git's performance scales effectively with project size. However, Git's branching and merging strategies need to be well-defined for large projects to avoid confusion.
How do I resolve merge conflicts? Merge conflicts occur when Git can't automatically reconcile differences between commits. You'll need to manually edit the conflicting files, then commit the resolved changes.
Are there graphical interfaces for Git? Yes, several graphical user interfaces (GUIs) are available for Git, such as GitHub Desktop, Sourcetree, and GitKraken. These GUIs simplify Git's commands through visual interfaces.
How do I contribute to open-source projects using Git? Fork the project repository, create a new branch for your changes, make the necessary changes, commit them, push to your fork, and then create a pull request to the original repository.
Conclusion
Git has revolutionized the world of version control, empowering developers to collaborate seamlessly and manage projects with unprecedented efficiency. By mastering Git's commands and understanding its principles, you're equipped to excel in modern software development. Whether you're a solo developer or part of a large team, Git is an indispensable tool in your toolkit. If you'd like to explore more about Git and its advanced features, you can check out the official Git documentation for in-depth information. Remember, version control isn't just about managing code; it's about fostering collaboration and driving innovation. Embrace Git, and embark on a journey of code mastery and productive collaboration.
0 notes
susidestroyerofworlds · 1 year ago
Text
git is a version control program (with lots of other programs wrapping around it, but not reimplementing it), it manages your text (usually code but really any structured text) using the concepts "repository" (repo for short), "branch", and "commit". A repo is a set of commits organized into branches. A commit is a set of changes among files, multiple commits are a "[commit] history". The way the version control works is that while youre working in a repo, you can switch between branches and commits. Moving between branches is spatial while moving between commits is temporal. Usually there is a branch called "master" or "main", which contains the canonical version of the program, usually one that at least works. To use git you generally use it as a commandline tool, get it from your OS' package manager.
A typical workflow in an existing git repo (created with the command "git init") is as follows (note: all these commands have little manuals embedded into git or provided as manpages, i recommend at least skimming those):
use "git checkout" to switch to the branch you want to work on, or create a new branch if you work on a new thing (like a feature or such)
edit your code
use "git add" to add all the files you want to commit
use "git commit" to create a commit with all the changes made to those files since the last commit, generally do this whenever you are done with some large changes that are usable, if incomplete (i.e. dont commit code with syntax errors or compile time errors unless you are about to clock out)
if your feature is done and the branch passed testing, you can merge it into master, which you use the "git merge" command for
if you are working with a "remote" (a thing that hosts your repo offsite, usually for multiple developers cooperating accross devices) you use "git push" to upload your changes and "git pull" to download changes (note: pull with the --rebase option to keep the commit history clean). If you want to use a remote youll have to set up ssh access, check the guide provided by your specific host
when you run into issues, git usually gives good error messages telling you exactly whats wrong and giving hints for fixing it, if you dont understand them people on the internet will understand them for you.
Further topics you can read up on that are out of the scope of a basic explanation: "pull requests" (changes that are requested to be put into a repo), "merge conflicts" (sometimes branches are incompatible and cant be automatically merged), "cherrypicking" (tbh i dont really get this), "squashing" (turning multiple commits into a single commit)
ask questions if anything remains unclear
Can someone explain to me in like five seconds how to use git, assuming that I know basic shit about coding/command line/whatever but don't know any of the specific terminology related to git. Like every tutorial online is at the same time both over my head and also vastly too basic. Just like. Tell me what it is.
Uh. First tell me its ontology. Is it a program, a standard, a language...? I know that it's for version control. Suppose I wanted to do version control at a piece of code. What do I do. What buttons do I press, on my computer? Tell me these things.
476 notes · View notes
criesindotangular · 2 years ago
Text
Deploy an Angular App to GitHub Pages With Angular CLI
Launch an Angular app in no time at all by hosting it for free on GitHub Pages.
Before deploying, finalize the code. Since any changes later leads to complications.
1. Create a GH-pages Branch
This is a hack that will help you get the GH-pages link to help to set the base-href.
First, create GH-pages in your local repository with the following command:
git branch gh-pages
Next, check out from the main branch to GH-pages to transfer all code:
git checkout gh-pages
Then, push GH-pages to GitHub to create a remote GH-pages branch:
git push origin gh-pages
2. Get the Repo Link
On the toolbar under the repo name, click Settings > Pages.
Under Build and deployment, select Deploy from a branch. Next, select gh-pages as the name of the branch, then click Save. This will create a GH-pages link at the top right under the GH-pages label.
Next, copy this link to the published site as illustrated below. You will use the link to set up the base-ref during deployment.
Tumblr media
3. Install Angular-CLI-GHpages
The angular-cli-ghpages package is a tool that the Angular CLI uses for deployment purposes.
Navigate back to your local project repository. Then install and run angular-cli-ghpages with this command:
ng add angular-cli-ghpages
4. Deploy the App
To build the app in production, you must connect it to a remote server on GitHub.
Configure your app to a remote server by running the following command:
ng deploy --base-href https://GithubUserName.github.io/GithubRepoName/
NOTE: Remember to replace the above link with the live link from GH pages
A successful build will look like the illustration below:
Tumblr media
Next, navigate to GitHub and click on the GH-pages link to see your deployed project.
Congratulations, you have deployed your Angular App!
If the link displays only the README file, please go back to GitHub GH-pages settings. Ensure the selected branch is gh-pages and not the main or master branch. Then give it five minutes and reload. Sometimes GitHub takes time to reflect changes.
0 notes
shieldfoss · 2 years ago
Text
You don't have to -
(17 notes... wait let me check)
Ok yeah nobody has said this yet.
"Github" uses the term "fork" in a non-standard sense unfortunately and I don't know which one you meant in your post, given that you are used to not-github but currently working on a github-based project but!
You don't have to - fork the repo (github sense) if github knows you are a contributor to this repo.
Instead of doing
$ git send-email ...args
you can just
$ gh pr create
- - - - Assuming you have installed the gh cli tool and authenticated yourself to github (which is really the way to go) the workflow is like
$ gh repo clone [org]/[project] $ cd [project] $ git checkout -b [myfeature] $ git push --set-upstream origin [myfeature]
That first push is to "claim the namespace" so to speak - you might get a conflict if two people work on features that sound the same so you might as well start out making sure you're not doing that on two branches with the same name but different commits.
Then you commit as you go along, push every so often if you want your changes backed up on github - they'll be on the feature branch you created so they won't interfere with anybody, and this way other people can pull your changes to themself without having to coordinate with you about it, which is a feature-not-bug in a collaborative github repo.
And when you're ready for primetime you do what you would normally do anyway - you pull master, merge master into your branch, push that merge commit, and then, last step, rather than doing git send-email, you do:
$ gh pr create
... Except on re-reading it looks like you're doing master/develop/feature rather than master/feature - which is totally valid, it just means you need to fork your branch off develop rather than off master, and the step before PR is to pull and merge develop into your branch, rather than master.
now we have these three repos that all have to stay in sync
So the thing about github is that you don't.
Git is decentralized? Yeah not so, not when using github.
You don't need to do anything you didn't already need to do with send-email (Unless you were bad at send-email but I'm thinking "not so").
With send-email, I hope the thing you did for PR was like
"get their state"
"merge into yours, solving conflicts"
"send back to them"
And github is the same, it's just that "their state" is now a centralized source of truth.
You can, separately, as a courtesy, keep track of the local repos of other contributors to make sure you don't pull into develop just before them, forcing them to re-do the work they did to match the develop branch. But, I mean. That's no different than before, yeah?
bah, the hack week project I was working on was supposed to happen on SourceHut which is a git-send-email based forge, but one of the other contributors wanted to move to github and I admit one does not sound reasonable asking people to do git-send-email in 2023.
I learned git independently of GitHub and web-based git in general, and even at my old job we tracked our system image with normal branch-based development, with merging and maintenance mostly handled user-side, so I really haven't ever internalized pull requests.
It's such a messy way to handle contribution! Having to generate my own fork and look after it just so I can fire off a ten line patch feels way worse than just cloning the main repo, making some changes, and running
git send-email --to="[email protected]" HEAD~
Fortunately it looks like someone handled migrating my work for me but like, now we have these three repos that all have to stay in sync and we each have a devel and master branch and gah. So many moving parts. I am very stupid, do not make me do this.
38 notes · View notes
kata4a · 2 years ago
Text
git checkout kat/master
41 notes · View notes
techsoundwave · 1 month ago
Text
Как научиться работать с Git и GitHub: базовые советы для начинающих
Как разработчик программного обеспечения в стартапе, я сталкиваюсь с необходимостью использовать системы контроля версий каждый день. Если вы новичок в программировании, вам обязательно стоит освоить Git и GitHub. Эти инструменты становятся неотъемлемой частью рабочего процесса, независимо от того, занимаетесь ли вы созданием сайтов, разработкой мобильных приложений или чем-то еще. В этой статье я поделюсь базовыми советами по работе с Git и GitHub, которые помогут вам начать и избежать распространенных ошибок.
Что такое Git и GitHub?
Git — это распределенная система контроля версий, которая позволяет отслеживать изменения в коде, работать с несколькими версиями проекта и возвращаться к предыдущим состояниям, если что-то пошло не так.
GitHub — это веб-сервис, который использует Git для хранения репозиториев в облаке и позволяет разработчикам работать над проектами совместно. Он предоставляет удобные инструменты для управления репозиториями, ревью кода, а также для совместной работы над проектами.
1. Установите Git
Первый шаг — установить Git на ваш компьютер. Это можно сделать, скачав установщик с официального сайта Git. После установки откройте терминал и выполните команду:git --version
Если все сделано правильно, терминал выведет установленную версию Git.
2. Настройка Git
После установки Git нужно настроить имя пользователя и электронную почту, которые будут отображаться в каждом коммите. Используйте команды:git config --global user.name "Ваше Имя" git config --global user.email "ваша@почта.com"
Это позволит Git связывать ваши изменения с вашим аккаунтом.
3. Создание репозитория
Для начала работы с Git создайте новый репозиторий. В терминале перейдите в директорию вашего проекта и выполните команду:git init
Эта команда инициализирует новый репозиторий, который теперь отслеживает изменения в вашем проекте.
4. Добавление файлов в репозиторий
Чтобы начать отслеживать файлы, используйте команду git add. Например, чтобы добавить все файлы:git add .
Эта команда добавляет все изменения в индекс (стадию, где Git готовит файлы для коммита).
5. Сохранение изменений
После того как вы добавили файлы, пора сохранить изменения в истории с помощью команды git commit:git commit -m "Первоначальный коммит"
Эта команда создаст коммит с сообщением, которое поможет вам и другим разработчикам понять, что было изменено.
6. Подключение к GitHub
Для работы с GitHub вам нужно создать репозиторий на этом сервисе. После создания репозитория на сайте GitHub, скопируйте URL репозитория, который будет выглядеть как https://github.com/ваше-имя/репозиторий.git.
Теперь свяжите ваш локальный репозиторий с удаленным на GitHub:git remote add origin https://github.com/ваше-имя/репозиторий.git
7. Отправка изменений на GitHub
После того как вы сделали коммит, отправьте изменения на GitHub с помощью команды:git push -u origin master
Эта команда отправит ваши изменения в основной (master) ветке на GitHub.
8. Получение изменений с GitHub
Когда несколько человек работают над проектом, важно получать актуальные изменения из репозитория. Для этого используйте команду:git pull origin master
Эта команда скачает последние изменения из репозитория на GitHub и объединит их с вашим локальным проектом.
9. Работа с ветками
Git позволяет работать с несколькими ветками, что особенно важно при разработке новых функций или исправлений. Чтобы создать новую ветку, выполните команду:git branch новая-ветка git checkout новая-ветка
Это создаст новую ветку и переключит вас на нее. Когда изменения в новой ветке будут готовы, их можно будет слить обратно в основную ветку с помощью команды git merge.
10. Советы для эффективной работы с Git
Коммитьте часто: Лучше делать маленькие и частые коммиты, чем один большой, потому что так легче отслеживать изменения.
Пишите понятные сообщения к коммитам: Каждое сообщение должно ясно объяснять, что изменено и почему.
Используйте ��етки для новых функций: Это помогает изолировать экспериментальные изменения и не нарушать основную работу проекта.
Tumblr media
Освоение Git и GitHub — это ключевая часть профессионального роста разработчика. Независимо от того, занимаетесь ли вы созданием сайтов, мобильными приложениями или другими проектами, эти инструменты помогут вам не только отслеживать изменения, но и работать над проектами в команде. Постепенно улучшая навыки работы с Git, вы будете уверенно справляться с любыми задачами, и это сделает вашу работу более продуктивной и организованной.
0 notes
albumhunter358-blog · 4 years ago
Text
Sourcetree Merge Branches
Tumblr media
That directly references reversing the merge commit, which sourcetree does not handle correctly (with the -m flag). If you have a branch that had a hypothetical 10,000 commits on it, you then merged (badly) into a branch that 20 other people then began working on immediately afterwards. For merge branch in Sourcetree you just need right click in the branch commit that you want and choose the option Merge. If you have some conflict you can also fix it by right clicking in the conflicted file, select the Resolve Conflicts and pick the desired option. You have to configure SourceTree to use your merge software. In the Diff tab of the Options dialog, look for the Merge tool dropdown for a list of programs that SourceTree knows how to use out of the box. Daniel Russell Sep 18, 2019 I don't understand where to see conflicts and what files need resolution etc.
Merge Branches In Sourcetree
Sourcetree Reverse Merge
Sourcetree Merge Two Branches
Sourcetree Merge Branches
Let's merge 'issue1' with 'master'
Merge Branches In Sourcetree
Use the merge command to merge branches.
$ git merge
By running the command above, the specified commit will be merged to the current active branch. Most of the time, you will want to merge a branch with the current active branch and you can do so by passing in the branch name in .
To merge commits into the master branch, let's now switch over to the master branch.
$ git checkout master Switched to branch 'master'
Sourcetree Reverse Merge
Tumblr media
Sourcetree Merge Two Branches
Before merging, open myfile.txt and check the content of the file.
Sourcetree Merge Branches
Git commands even a monkey can understand
As shown above, the change added on 'issue1' described in the previous page isn't included in myfile.txt on master branch.
$ git merge issue1 Updating 1257027..b2b23c4 Fast-forward myfile.txt | 1 + 1 files changed, 1 insertions(+), 0 deletions(-)
Tumblr media
The position of the master branch will now move over to that of 'issue1'. A fast-forward merge has been executed here.
Now, let's confirm myfile.txt.
Git commands even a monkey can understand add: Register a change in an index
Open myfile.txt and you will notice that the new line that we have committed to the 'issue1' branch is now here on the master branch.
Tumblr media
1 note · View note
transienturl · 1 year ago
Text
adding a different repo (like a template) as a remote to cherry pick from it frequently
git remote add [source-repo] https://github.com/[some-user]/[source-repo] git fetch [source-repo] git checkout -b [source-repo]-main [source-repo]/main
(replace main with master when necessary)
quickly copying a commit from another repo
git remote add temp-cherry-pick https://github.com/[some-user]/[source-repo] git fetch temp-cherry-pick git cherry-pick [long-commit-sha] git remote remove temp-cherry-pick
2 notes · View notes
mentalisttraceur-software · 5 years ago
Text
git checkout -b my-new-branch
git checkout -
git branch -d my-new-branch
git checkout -b my-new-branch master
Twice today now.
4 notes · View notes