GithubHelp home page GithubHelp logo

oleksiyrudenko / dev-env-git Goto Github PK

View Code? Open in Web Editor NEW
10.0 1.0 4.0 89 KB

Basic git setup

Home Page: https://oleksiyrudenko.github.io/dev-env-git/

License: MIT License

Shell 100.00%
tweaking-git cli-enhancements git developer-tools environment-configuration

dev-env-git's Introduction

Entry level: beginner

Development Environment Helpers: git

This repo contains opinionated recommendations and suggestions as to the tools that many frontend developers (especially beginners) will find useful.

If you are a beginner frontend developer you may also find dev-env-frontend recommendations useful.

Table of Contents

Intro

This repo contains scripts that make git users' and project maintainers' life easier.

All scripts are optional. It is recommended that you look into the script of your choice before using it. Some scripts require you to patch e.g. file path before they can be efficiently invoked.

Some tools/scripts are specific to Windows OS (as denoted). Under Windows scripts are intended to get launched under e.g. Git Bash that comes bundled with git distribution. It would be available from file explorer context menu.

In terminal navigate to this project directory and execute chmod u=rwx *.sh to make shell scripts executable.

Remember to precede script with explicit path, e.g. ./script.sh

Basic setup

Get registered with github.com.

Install git.

Notes for Windows users

When prompted to choose an editor it is recommended that you opt for Notepad++ (a GUI enabled editor) or Nano (non-GUI, yet friendlier to beginners than vim). When prompted for extra options enable file system caching.

Open Terminal (Git Bash under Windows). The most of the instructions below are to be completed in Terminal.

A note for Windows users (click to expand) Did you you can open git bash from File Explorer? Locate your project (or just e.g. any directory in your file system) in File Explorer, right click within explorer window to open context menu and select "Git Bash Here" option.

Bash will get opened in context of your project.

git bash context menu

All OS

Execute following commands to have your git identity configured. Replace "John Doe" with your real name (obey quotes) and [email protected] with the email you used to register on GitHub.

git config --global user.name "John Doe"
git config --global user.email [email protected]

Note! Copy-paste + edit are your best friends at the most of times.

Navigate to the location you gonna have your development projects in. Your home directory is a good point to start at. You can get to your home directory by executing cd ~/ command in Terminal.

Next execute the following commands one-by-one to have all required files from this repository on your machine:

git clone https://github.com/OleksiyRudenko/dev-env-git.git
cd dev-env-git

Execute chmod u=rwx *.sh to make shell scripts executable.

You may close Terminal eventually. You can get back to this project at any time by executing the following command in terminal to catch up:

cd ~/dev-env-git

Credentials manager

Credential manager helps to avoid authorization phase at every operation on remote repo with git.

Windows: Install Git Credential Manager for Windows. For downloads unfold and check Assets subsection below latest release Change Log.

MacOS: OSX keychain store is used by default, no need to install anything. Just tell Git to use the KeyChain to store your credentials:

git config --global credential.helper osxkeychain

Linux Mint/Ubuntu

Execute ./credential-manager-linux.sh in Terminal:

If any command fails try googling the error message to fix the issue.

Alternatively, for Linux you may try Git Credential Manager from Microsoft.

Success criteria: when Credential Manager is installed properly git will ask for access credentials only once per each remote repos storage (e.g. GitHub), normally on first attempt to push your local repo to the remote.

If under Windows you are getting prompted for credentials repeatedly or presented with an error message

fatal: HttpRequestException encountered.
   An error occurred while sending the request.
fatal: HttpRequestException encountered.
   An error occurred while sending the request.
Username for 'https://github.com':

try the following command: git config --global credential.modalPrompt true. Check official docs for the fixes for other possible issues you may face. Keep this project among your bookmarks just for the case you face the authentication issue at some later time.

Friendly git editor

Many won't find vim or vi (that are used by default by git) friendly enough.

Alternatives are:

NB: Windows Notepad.exe is not a recommended option as it doesn't support Linux linefeed.

Windows: if you're opted for Notepad++ or Nano when when installed git and you're happy with your choice, you may skip this section completely.

You may opt for a different editor of your choice. There is a couple of basic requirements it should meet:

  • support Linux style linefeed
  • CLI friendly (normally offers an option like --wait to correctly handle files)
  • be lightweight enough to start quickly

Google for "your-editor-name as a git editor" to check how to use your favourite editor with git.

Install an editor of your choice (git-editor-linux.sh contains instructions to install nano or emacs).

Emacs under Windows: unpack distribution archive into C:/Program Files/emacs

MacOS: You may need to move downloaded installations to Applications.

Some editors come pre-bundled with OS, so try launching the editor of your choice from Terminal to know if you need installing it first.

Open corresponding git-editor-<platform>.sh to edit. <platform> is your OS: linux, macos, or windows.

Uncomment (remove leading # ) section that corresponds to your editor of choice and edit the path to the editor executable as the pre-defined may not match actual installation path.

Linux CLI commands command -v <executable_name> and which <executable_name> may help you to find proper path.

Then launch the script with ./git-editor-<platform>.sh.

If the editor of your choice opens and you see something like

[user]
	name = John Doe
	email = [email protected]
	username = JohnDoe
[core]
	editor = 'D:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin ''
	pager = cat
[credential]
	helper = wincred

then you have succeeded. Just close the editor.

What might go wrong?

You can see the file above but the editor is not the one you expected.

You might not have all lines relevant to your editor in ./git-editor-<platform>.sh uncommented. So, the default editor didn't change.

  1. Quit the editor.
    • If editor shows commands in a toolbar then press a relevant hot-key (normally ^X or ^Q)
    • If editor offers GUI then option to quit is located under File menu
    • You may find yourself in vim or vi. Press ESC, type :q! and hit Return key
  2. Uncomment relevant commands in ./git-editor-<platform>.sh by removing leading # .
  3. Launch ./git-editor-<platform>.sh

Editor didn't start. Some error reported

The path to the editor in ./git-editor-<platform>.sh is not correct.

  1. Fix path to your editor in ./git-editor-<platform>.sh. Try finding proper path to your editor. Optionally consult google for a proper path to the editor of your choice as described in this section above.
  2. Launch ./git-editor-<platform>.sh

If you do not succeed either then try setting different editor. Do not forget to comment back failing commands in ./git-editor-<platform>.sh before uncommenting commands for a different editor. Or yell for help in your student community.

Git Helpers

CLI Enhancements

Make your terminal shell prompt informative. Executing ./cli-tune.sh will copy .bash_profile, git-completion.bash and git-prompt.sh to your $HOME.

The above improves CLI by e.g. adding info about current git branch to the shell prompt and adding auto-completion feature to git commands (branch names, commands per se, etc.).

It may happen that either of file copying operation fails. Most likely either of files already exists at target directory (~/). There are chances you have already tuned your CLI for git any time before. As for the .bash_profile you may already have one, then just update ~/.bash_profile with contents of this project's .bash_profile.

You'll need to close and re-open Git Bash before any changes take effect.

Credits: Udacity

Learn more about Customizing Linux/Mac terminal prompt

Git Aliases

Executing ./git-helpers.sh will:

  • add global .gitignore to ignore most common file patterns

  • add a collection of aliases/shorthands

  • Study git-helper.sh, try commands assigned to aliases on some of your repos to see what those do. Some of aliases:

More on global .gitignore: Global .gitignore decreases a risk of tracking of the most common files to be ignored (IDE settings, temporary files, directories for app builds etc). Global .gitignore works even when the project doesn't contain its own .gitignore. You may add more rules or remove some by editing ~/.gitignore.

More on aliases: Adding those is not harmful, using can be. Study git-helper.sh, try commands assigned to aliases on some of your repos to see what those do.

Git Flow

Basic flow

Executing ./git-flow-basic.sh will add aliases to support some basic git flow:

  • sync-master-upstream - updates local master and origin/master with upstream/master
  • sync-branch-upstream-merge
    • calls sync-master-upstream
    • updates feature branch from master using simple merge strategy
  • sync-master - updates local master from origin/master when on a feature branch
  • sync-branch-rebase - rebases current branch onto (updated) master; conflicts may arise
  • sync-branch-continue - completes reabasing after conflict resolution

Add and use those when you clearly understand what is behind. This is also a rather source of inspiration to build your own git flow than a commonly recognized pattern.

Git Town

Git town is yet another opinionated git flow toolset.

Learn and use git-town when you feel it matches the git flow you'd use.

Executing ./git-town-set.sh offers some initial settings, and works when git town is installed.

More resources on tweaking git

Advanced

Subrepo

git-subrepo is a great replacement for git-submodule and git-subtree. Please, refer to:

IDE minimal tweak

Tune your editor/IDE so it ensures empty line at the end of file.

Find and check the relevant setting. Examples:

  • IntelliJ IDEA products: File > Settings (or ProductName > Preferences) > Editor > General -- Ensure line feed at file end on Save
  • VS Code
  • Sublime: Command Palette > Preferences -- change or add "ensure_newline_at_eof_on_save": true

This ensures that adding code/text at the end of file will not mark the fragment that actually had not been effectively changed (which takes place when a line doesn't end with LF character). This makes history of changes cleaner and diffs reflecting actual changes.

.editorconfig

Some editors and IDEs support .editorconfig out-of-the-box, others may require plugins. Check how your editor/IDE is supported.

Copy .editorconfig with basic settings from this project to the root directory of your own projects.

If your own projects are located somewhere under your home directory (the default case) cp ./.editorconfig ~/ will do.

Your editor/IDE may require to enable .editorconfig somewhere in its settings.

Issues?

If anything above contains errors, not quite clear or requires improvement or update, please, feel free adding an Issue.

Contributors

There are people that contributed to this project by testing instructions herein and providing their feedback. Support and willingness to help is much appreciated.

dev-env-git's People

Contributors

oleksiyrudenko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

dev-env-git's Issues

Add bash completion

Sources:

  1. https://askubuntu.com/questions/280327/how-to-make-terminal-autocomplete-when-there-are-several-files-directory
  2. https://unix.stackexchange.com/questions/55203/bash-autocomplete-first-list-files-then-cycle-through-them
  3. https://unix.stackexchange.com/questions/16921/make-bashs-tab-completion-fill-in-first-match/16926#16926

From [1]:

# ~/.inputrc
# mappings to have up and down arrow searching through history:
"\e[A": history-search-backward
"\e[B": history-search-forward
# mappings to have left and right arrow go left and right: 
"\e[C": forward-char
"\e[D": backward-char

# mapping to have [Tab] and [Shift]+[Tab] to cycle through all the possible completions:
"\t": menu-complete
"\e[Z": menu-complete-backward

Documentation tests tracking combined transcript

Спасибо, что согласился.
Какая у тебя OS?
Пытался ли настраивать гит, credentials manager, редактор для гита?

Windows 10
Вообще по моему как то пытался, но после последней переустановки ничего не менял
Git bash
credentials manager - не устанавливал

Гут, принято
Мы будем двигаться шаг за шагом по разделам инструкции https://github.com/OleksiyRudenko/dev-env-git . Из всей инструкции мы возьмём только 6 этапов настройки:

  • Basic setup
  • Basic setup > Credentials manager
  • Friendly git editor
  • Git Helpers > CLI Enhancements
  • Git Helpers > Git Aliases
  • IDE minimal tweak

Цель тестов - выявить с твоей помощью недостатки инструкции, устранить их и получить на выходе инструкцию, с которой может справиться новичёк.

Первое задание: ознакомиться с инструкцией в целом, глубоко не вникая. Цель: прочуствовать объём задачи.
По готовности, сообщи мне, какие разделы были понятны, какие непонятны совсем из одного только чтения - общее впечатление. Я скажу, что делать дальше. Постараюсь учесть твои индивидуальные особенности.
У нас будут паузы, иногда большие - я синхронно веду нескольких участников.

...

Выполни пожалуйста инструкции раздела Basic setup, включая Credentials manager - всё до Friendly git editor. Разумеется, то, что уже сделано (например, установить гит и/или настройка имени/почты для гита), повторно делать не нужно.
Если какая-то CLI команда вернёт ошибку или какие-то инструкции вызовут трудности, напиши. С копи-пейстом ошибки из консоли или цитатой текста инструкции - идеально.

Я правлю инструкцию по ходу работы с участниками. Вот свежайшая редакция: https://github.com/OleksiyRudenko/dev-env-git/tree/dev#basic-setup

...

Следующее задание - настройка редактора: https://github.com/OleksiyRudenko/dev-env-git/tree/dev#friendly-git-editor

Но пара вопросов перед тем.
Что у тебя выдаёт команда git config --global --get core.editor ?

...

Значит не настроен. Это хорошо для нашего случая.
Ты уже определился, как редактор будешь использовать для гита? Есть какие-то предпочтения не из списка в доке?

В некоторых случаях гит предлагает отредактировать сообщение для коммита или набор команд для interactive git rebase в редакторе. Это удобно делать в чём-то легковесном но с GUI и хорошим юзабилити, особенно, когда требуется перемещать строки текста.
Выбери что-то из списка - кросплатформенное или Notepad++. Моя рекомендация для винды - Notepad++, он взлетает гораздо быстрее, чем саблайм или vs code.

Когда будешь готов с выбром, приступай к реализации инструкций раздела

...

Мы уже прошли половину пути. Самые сложные настройки, на самом деле, позади.
Теперь выполни инструкции разделов CLI enhancements и Git Aliases
https://github.com/OleksiyRudenko/dev-env-git/tree/dev#git-helpers

...

Пару разделов инструкции мы пропустим. Осталось только минимально настроить IDE или редактор, который ты используешь для написания кода (или убедиться, что необходимые настройки уже сделаны).
Раздел IDE minimal tweak
https://github.com/OleksiyRudenko/dev-env-git/tree/dev#ide-minimal-tweak

...


Теперь твоё окружение для гита более-менее настроено. Мы пропустили несколько разделов (Git flow, More resources... и Advanced), но они не критичны. Возможно, когда-нибудь у тебя возникнет потребность ещё более тонко настроить гит для себя и тогда эти материалы окажутся полезными. Сохрани где-нибудь ссылку в закладках.


Ты очень помог с допиливанием инструкции. Она теперь стала гораздо лучше.
Я хотел бы, в качестве благодарности, добавить тебя в раздел Contributors
Если у тебя нет возражений, пришли мне пожалуйста ссылку на твой профиль на гитхабе. Также я б указал и ссылку на профиль в телеграме или другой способ связи, потому что через гитхаб нет возможности связаться. Но последнее - на твоё усмотрение.

...

Если ты вдруг посчитаешь это полезным, то можешь без колебаний упоминать своё участие в этом проекте для начинающих разработчиков. Например, можно написать в резюме что-то в духе "Contributed to an open source educational project" и ссылку на этот репозиторий, или просто говорить об этом на собеседовании. Ценность конкретно этого проекта в целом не прям уж супер-впечатляющая, но некоторые работодатели учитывают социальную активность, направленную на помощь коллегам.

Add aliases to delete branches

  1. Local only git checkout master && git branch --delete --force <branch-name>
  2. Remote only git push origin --delete test
  3. 1+2

Documentation tests tracking

Tests

Section Sub-section Windows Mac Linux
Basic OK TBD TBD
Basic CredManager OK TBD TBD
Git editor Emacs TBD TBD TBD
Git editor Sublime TBD TBD TBD
Git editor VS Code OK TBD TBD
Git editor Notepad++ TBD n/a n/a
Git editor nano TBD TBD TBD
Git helpers CLI OK TBD TBD
Git helpers aliases OK TBD TBD
IDE tweak ItelliJ TBD TBD TBD
IDE tweak VS Code OK TBD TBD
IDE tweak Sublime TBD TBD TBD
IDE tweak .editorconfig TBD TBD TBD

Alias: Annotated tags

  • git config --global alias.taga "tag -m" (expects "message" "tag" as arguments)
  • git config --global alias.tags "tag --format='%(tag) %(subject)"
  • git config --global alias.push-tags "push --tags"

Add config: big repos handling

Issue

Counting objects: 2649, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (1280/1280), done.
error: RPC failed; result=22, HTTP code = 413 | 116 KiB/s   
fatal: The remote end hung up unexpectedly
Writing objects: 100% (2504/2504), 449.61 MiB | 4.19 MiB/s, done.
Total 2504 (delta 1309), reused 2242 (delta 1216)
fatal: The remote end hung up unexpectedly
Everything up-to-date

Cause

The default file post size for Git has been exceeded.

Solution

git config http.postBuffer 524288000

Script: Bump version

On merge/rebase to master

  • Increment version
  • Update changelog
  • Update README (optional)

master vs main

  1. Get default branch name
    Option 1a. git remote show <remote_name> | grep 'HEAD branch' | cut -d' ' -f5
    Option 1b. git branch -r --points-at refs/remotes/origin/HEAD | grep '\->' | cut -d' ' -f5 | cut -d/ -f2
    Option 1c. git remote show <remote_name> | awk '/HEAD branch/ {print $NF}'
    Option 1d.
upstream-name = !git remote | egrep -o '(upstream|origin)' | tail -1
head-branch = !git remote show $(git upstream-name) | awk '/HEAD branch/ {print $NF}'

Option 1e. git rev-parse --abbrev-ref origin/HEAD will print origin/<default-branch-name>
Option 1f. git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'
Option 1g. git remote show <remote_name> | grep "HEAD branch" | cut -d ":" -f 2
Option 1i.

( set -- `git ls-remote --symref origin HEAD`
test $1 = ref:  && echo $2 )

NB. <remote_name> is normally origin)

  1. Assign an alias branch name and use it in scripts
    Option 2a. git symbolic-ref refs/heads/default refs/heads/<default-branch>
    Note: one can still checkout default as such and any operations with default branch will just update the bound branch pointer. Current branch will be the bound branch, however bash prompt still may show default

Add aliases for squashing

Soft squash:
git reset --soft HEAD~3 && git commit

Squash, merge, and terminate feature branch (check the command sequence below):
git checkout <target> && git merge --squash - && git branch -D - && git push origin --delete -

Interactively rebase/squash onto target branch
git rebase -i ....

Add alias pushb

git pushb == git push --set-upstream origin <current_branch_name>

alias: tagv, delete-tag

tagv

Creates annotated tag (e.g. denoting version, thus "v" in "tagv") and pushes it to the remote (taga && push-tags)
tagv = "!git taga \"$1\" \"$1\" && git push-tags #"

delete-tag

Deletes a tag on both local and remote
delete-tag = "!git tag -d \"$1\" && git push --delete origin \"$1\" #"

Multiple user accounts

WIP. Use with care

In a repo with a different user to use:
1 . git config user.name|email ...
2. Run commands below

Option A. Env var

(use set instead of export if under native Windows terminal, i.e. not in git bash)

export GCM_NAMESPACE=git-account2
git clone https://github.com/account/repo.git
cd repo
git config credential.namespace git-account2

SET has effect for current repo only.

Tested under Windows 10. May work different under *nix systems

ref

Possible issues:

  • env var won't survive
  • env var will survive

Option B. credential.username

git config credential.username 'Billy Everytee'

You may be required to use a PAT.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.