Как добавить локальное репо и обращаться с ним как с удаленным репо

Я пытаюсь заставить локальное репо действовать как удаленное с именем bak для другого локального репо на моем ПК, используя следующее:

git remote add /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git bak

который дает эту ошибку:

fatal: '/home/sas/dev/apps/smx/repo/bak/ontologybackend/.git' is not a valid remote name

Я пытаюсь синхронизировать два локальных репозитория, один из которых настроен как удаленный с именем bak для другого, а затем выдает git pull bak.

Как лучше всего это сделать?


Изменить:

Извините, глупый я, я только что понял, что удаленное добавление должно быть:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

имя пульта идет перед адресом.


person opensas    schedule 15.05.2012    source источник


Ответы (4)


Ваши аргументы для команды remote add перевернуты:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

См. git remote --help для получения дополнительной информации.

person larsks    schedule 15.05.2012
comment
Однако требуется ли .git в конце? - person Erik Aigner; 23.09.2016
comment
Это просто путь... Git не волнует, как он называется. - person larsks; 23.09.2016
comment
@ErikAigner традиционно голые репозитории заканчиваются суффиксом .git. Хотя обычно не как собственный каталог, а как: /path/to/projectname.git. - В остальном это мало что меняет. - person Atli; 08.04.2017
comment
Похоже, вам нужно использовать абсолютный путь, что для меня не очевидно. Когда я попытался использовать относительный путь, я получил fatal: '../dir' does not appear to be a git repository. - person Keith Layne; 30.10.2018
comment
Важно поставить file:// перед путем и использовать полный путь к локальному репозиторию, чтобы клиентское программное обеспечение могло получить к нему доступ по ожидаемому протоколу. И в ответ на вопрос Эрика выше, очевидно, необходим .git в конце пути. - person Scott Lahteine; 28.01.2020
comment
По крайней мере, в git 2.25+ (версия, которую я установил) вам не нужно указывать полный путь к каталогу, в котором находятся метаданные git (.git). Так что в примере достаточно с git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend - person Mariano Ruiz; 10.07.2020
comment
Однако клиенту необходим доступ на запись к локальной папке сервера. С настоящим удаленным доступом это легко сделать с помощью удаленного URL-адреса user@server, а пользователь является пользователем с разрешением, создавшим репозиторий сервера. - person Timo; 01.11.2020

Если ваша цель — сохранить локальную копию репозитория для удобного резервного копирования или хранения на внешнем диске или совместного использования через облачное хранилище (Dropbox и т. д.), вы можете использовать голый репозиторий. Это позволяет создать копию репозитория без рабочей директории, оптимизированную для совместного использования.

Например:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Точно так же вы можете клонировать, как если бы это было удаленное репо:

$ git clone ~/repos/myproject.git
person Matt Sanders    schedule 29.12.2015
comment
Это должен быть принятый ответ, потому что он идеально подходит для вопроса Как лучше всего это сделать? Локальное репо, рассматриваемое как удаленное репо, как его назвал @opensas, действительно является голым каталогом (точно так же, как настоящий удаленный репозиторий). - person Jack'; 23.11.2017
comment
Я предлагаю изменить: здесь указано, следует ли вам использовать git remot add.. + git push или просто git clone: ​​stackoverflow.com/a /31590993/5446285 (ответ Адельфуса) - person Jack'; 24.11.2017
comment
@ Джек, не могли бы вы уточнить, что вас смутило? Я рад внести поправку, но хочу, чтобы ответ был относительно кратким. - person Matt Sanders; 06.12.2017

Похоже, ваш формат неверен:

Если вы хотите поделиться локально созданным репозиторием или хотите получить вклад из чужого репозитория — если вы хотите каким-либо образом взаимодействовать с новым репозиторием, проще всего добавить его как удаленный. Вы делаете это, запуская git remote add [псевдоним] [url]. Это добавляет [url] под локальным удаленным именем [псевдоним].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

person Kristian    schedule 15.05.2012

Я публикую этот ответ, чтобы предоставить сценарий с пояснениями, которые охватывают три различных сценария создания локального репо с локальным пультом. Вы можете запустить весь скрипт, и он создаст тестовые репозитории в вашей домашней папке (проверено на Windows git bash). Объяснения находятся внутри сценария для более удобного сохранения в ваших личных заметках, его очень легко читать, например. Код Visual Studio.

Я также хотел бы поблагодарить Джека за ссылку на этот ответ, где adelphus содержит хорошие, подробные и практические объяснения по теме.

Это мой первый пост здесь, поэтому, пожалуйста, посоветуйте, что нужно улучшить.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

person Jarek    schedule 17.04.2020
comment
Добро пожаловать! и спасибо, что нашли время, чтобы собрать это вместе. Ваша готовность принять участие и внести свой вклад в наше сообщество является краеугольным камнем SO. - person cb4; 10.02.2021