Posts Tagged ‘ Git

Git: warning: Not a git repository

When you try to update/pull or get a diff for the Git repository, you can get a warning:

warning: Not a git repository. Use --no-index to compare two paths outside a working tree
usage: git diff --no-index [<options>] <path> <path>

It is because the new version of Git forbidden to run git commands in a directory that is not owned by the current user ( CVE-2022-24765 )

To fix, you need to change permission for the directory or set security options to git when running commands in CI/CD

git config --global --add safe.directory $(pwd)

Добавить существующий Git репозиторий в Bitbucket

git clone --mirror https://bitbucket.org/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository
 
cd repository-to-mirror.git
git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror
 
git push --mirror

Git: запомнить пароль на день

Чтобы в течении рабочего дня не воодить постоянно пароль при доступе в Git в версии 1.7.9 и выше появилась возможность кеширования введенных данных

git config --global credential.helper cache

это заставит держать данные авторизации в памяти
По умолчанию 15минут.
Но можно выставить свое время
Read more

Продолжаем осваивать Git

Начало тут
После того как мы создали пустой репозиторий на сервере, нужно добавить туда наш проект

git add * && git commit -m "Initial commit" && git push origin master

где,
origin это сервер на котором у нас код… и добавляется он вот так

git remote add origin ssh://git@<hostname>/git/test.git
</hostname>

Возможны ошибки при первом комите:

root@client:app# git push
Password: 
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
fatal: The remote end hung up unexpectedly
error: failed to push some refs to 'ssh://root@giserver.com/git/app'

Указываем явно куда пушить

root@gitclient# git push origin master
Password: 
Counting objects: 3, done.
Writing objects: 100% (3/3), 203 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error: 
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error: 
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ssh://root@gitserver.com/git/app
 ! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to 'ssh://root@gitserver.com/git/app'

Все равно не поддается на провокацию. Сия ситуация хорошо описана тут http://pete.akeo.ie/2011/07/git-remote-repository.html
Git думает что раз репозиторий пустой, то есть не завершенный первый коммит и не дает простому смертному стать первым. Для этого мы на сервере создадим новую ветку:

root@gitserver : git checkout -b first-commit
Switched to a new branch 'first-commit'
root@gitserver $ git symbolic-ref HEAD refs/heads/first-commit

После этого можем внести изменения в код на клиенте и передать это на сервер

echo "new file" > README
git add README
git commit -m "Added file README"
git push origin master

Read more

Осваиваем Git

Никогда не пользовался системами контроля версий, так как мало что творю на языках программирования, а скрипты можно просто хранить в папочке.
Ну и вот решил попробовать хранить скрипты (и не только) в каком-то хранилище, но при этом упустить освоение SVN И CVS, а сразу приступить к Git’у , так как мы не исчем легких путей 🙂

Для начала создаем собственный репозиторий с проэктом, который будет находится не на локальной машине, а где-то в сети.
Пишу по мотивам статьи How to set up your own private Git server on Linux
Сервер и клиенты (в основном) работают под управлением Gentoo.
Итак приступим.
Для начала добавим свой публичный ключ на сервер

cd ~/.ssh
ssh-keygen -t rsa
scp ~/.ssh/id_rsa.pub 'user'@'server':.ssh/authorized_keys

Теперь мы можем зайти по SSH на наш сервер и установить Git:

ssh <server>
ACCEPT_KEYWORDS="~amd64" USE="bash-completion cvs subversion" emerge -av git
</server>

Теперь добавим пользователя

useradd -d /home/git -m -s /bin/bash git

Теперь вам нужно добавить свой публичный ключ для пользователя Git

mkdir /home/git/.ssh
cp ~/.ssh/authorized_keys /home/git/.ssh/
chown -R git:git /home/git/.ssh
chmod 700 !$
chmod 600 /home/git/.ssh/*

Read more