Перейти к содержимому

Как переименовать папку в git

  • автор:

Переименование репозитория Git в проекте

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

Необходимые компоненты

  • Чтобы переименовать репозиторий, необходимо иметь разрешения на переименование репозитория в репозитории Git.
  • Если вы хотите использовать команду az repos update для переименования репозитория, обязательно выполните действия, описанные в статье «Начало работы с Azure DevOps CLI».

Переименование репозитория

  1. На веб-портале выберите «Репозиторий«, «Файлы«. View your files
  2. В раскрывающемся списке репозитория выберите «Управление репозиториями«. Manage repositories
  3. Выберите имя репозитория из списка репозиториев, выберите меню . , а затем выберите «Переименовать репозиторий«.Rename repository
  4. Переименуйте репозиторий, введя новое имя репозитория и выбрав «Переименовать«. Rename repository confirm
    1. На веб-портале откройте страницу администрирования проекта и выберите «Управление версиями«.

    Version control settings

    Rename a repository

    Выберите репозиторий, который вы хотите переименовать в репозиториях Git слева, и выберите . . Выберите «Переименовать репозиторий» в меню.

    Repositories pane

    Примечание. Если область репозиториев не развернута, выберите > ее, чтобы развернуть ее и отобразить список репозиториев.

    Rename repository confirm

  1. Введите новое имя репозитория в поле имени репозитория в диалоговом окне, а затем выберите «Переименовать«.

Можно использовать az repos update для обновления ветвь по умолчанию или переименования репозитория.

az repos show --repository [--default-branch] [--detect ] [--name] [--org] [--project] [--subscription] 

Параметры

Параметр Описание
repository Имя или идентификатор репозитория.
default-branch Укажите ветвь по умолчанию для репозитория. Пример: «refs/heads/live» или «live».
detect Автоматическое обнаружение организации. Допустимые значения: false , true .
name Новое имя репозитория.
org , organization URL-адрес организации Azure DevOps. Вы можете настроить организацию по умолчанию с помощью az devops configure -d organization= . Требуется, если не настроено как по умолчанию или выбрано с помощью конфигурации Git. Пример: https://dev.azure.com/MyOrganizationName/ .
project , p Имя или идентификатор проекта. Вы можете настроить проект по умолчанию с помощью az devops configure -d project= . Требуется, если не настроено как по умолчанию или выбрано с помощью конфигурации Git.
subscription Имя или идентификатор подписки Подписку по умолчанию можно настроить с помощью az account set -s .

Пример

Следующая команда переименовывает contosoREPO в contosoFabrikam для конфигурации az devops configure —defaults organization=https://dev.azure.com/fabrikamprime project=»Fabrikam Fiber» по умолчанию.

az repos show --repository contosoREPO --output table ID Name Default Branch Project ------------------------------------ ----------- ---------------- -------------- 30954ce5-417b-4930-b8d2-8b6cac934a34 contosoREPO main Fabrikam Fiber 

Дополнительные сведения см. в следующей команде:

az repos update --repository contosoREPO --name contosoFabrikam < "defaultBranch": "refs/heads/main", "id": "30954ce5-417b-4930-b8d2-8b6cac934a34", "isDisabled": false, "isFork": null, "name": "contosoFabrikam", "parentRepository": null, "project": < "abbreviation": null, "defaultTeamImageUrl": null, "description": "Guidance and source control to foster a vibrant ecosystem for Fabrikam Fiber applications and extensions.", "id": "56af920d-393b-4236-9a07-24439ccaa85c", "lastUpdateTime": "2021-05-24T21:52:14.95Z", "name": "Fabrikam Fiber", "revision": 438023732, "state": "wellFormed", "url": "https://dev.azure.com/fabrikamprime/_apis/projects/56af920d-393b-4236-9a07-24439ccaa85c", "visibility": "private" >, "remoteUrl": "https://fabrikamprime@dev.azure.com/fabrikamprime/Fabrikam%20Fiber/_git/contosoFabrikam", "size": 1627, "sshUrl": "git@ssh.dev.azure.com:v3/fabrikam/Fabrikam%20Fiber/contosoFabrikam", "url": "https://dev.azure.com/fabrikamprime/56af920d-393b-4236-9a07-24439ccaa85c/_apis/git/repositories/30954ce5-417b-4930-b8d2-8b6cac934a34", "validRemoteUrls": null, "webUrl": "https://dev.azure.com/fabrikamprime/Fabrikam%20Fiber/_git/contosoFabrikam" > 

Команды Интерфейса командной строки Azure DevOps не поддерживаются для локальной среды Azure DevOps Server.

Обновление удаленных устройств Git на компьютерах разработки

Git использует удаленные ссылки для получения и отправки изменений между локальной копией репозитория и удаленной версией, хранящейся на сервере. После переименования репозитория или проекта Git следует обновить удаленные ссылки. Обновите ссылки на то, что URL-адрес удаленный репозиторий содержит проект и имя репозитория.

Каждый член вашей команды должен обновить локальные репозитории Git, чтобы продолжить подключение с компьютеров разработки к репозиторию в проекте. В приведенных ниже инструкциях показано, как обновить удаленные устройства для репозитория Fabrikam Mobile , переименованного в Fabrikam.

Получение нового URL-адреса для репозитория

  1. Выберите Repos, Files. View your files
  2. Выберите «Клонировать » в правом верхнем углу окна «Файлы » и скопируйте URL-адрес клонирования. Retrieve the clone URL

Retrieve the clone URL

  • Выберите «Клонировать » в правом верхнем углу окна «Код» и скопируйте URL-адрес клонирования.

Обновление удаленного приложения в Visual Studio

Чтобы обновить удаленный сервер, выполните приведенные далее действия.

Screenshot shows the Options dialog with the option to edit remotes.

  1. В меню Git в строке меню выберите пункт «Управление удаленными«.
  2. В диалоговом окне «Параметры» выберите удаленный для редактирования, а затем нажмите кнопку «Изменить«.
  3. Замените получение и отправку удаленных ссылок URL-адресом, скопированным из удаленного репозитория.
  4. Нажмите кнопку «Сохранить» и «ОК«, чтобы закрыть диалоговое окно «Параметры«.

Visual Studio 2019 версии 16.8 и более поздних версий предоставляет интерфейс управления версиями Git, сохраняя пользовательский интерфейс Team Обозреватель Git. Чтобы использовать командную Обозреватель, un проверка Tools>Options>Preview Features>New Git user experience from the menu bar. Вы можете выполнять функции Git из любого интерфейса взаимозаменяемо.

Чтобы обновить удаленный из Visual Studio Team Обозреватель, выполните следующее:

  1. Подключение в репозиторий. Connect to the repository
  2. Откройте параметры проекта. Project settings
  3. Откройте параметры репозитория. Repository settings
  4. Измените получение и отправку удаленных ссылок и вставьте URL-адрес, скопированный из удаленного репозитория. Edit remote

Вопросы и ответы

Вопрос. Можно ли переименовать репозиторий еще раз? Можно ли повторно использовать старое имя репозитория?

Связанные статьи

Переименование файла

Любой файл в репозитории можно переименовать непосредственно в GitHub или с помощью командной строки.

Platform navigation

Renaming a file on GitHub

Renaming a file also gives you the opportunity to move the file to a new location

Tips:

  • If you try to rename a file in a repository that you don’t have access to, we will fork the project to your personal account and help you send a pull request to the original repository after you commit your change.
  • File names created via the web interface can only contain alphanumeric characters and hyphens ( — ). To use other characters, create and commit the files locally and then push them to the repository.
  • Some files, such as images, require that you rename them from the command line. For more information, see «Renaming a file.»
  1. In your repository, browse to the file you want to rename.
  2. In the upper right corner of the file view, click

Screenshot of a file. In the header, a button, labeled with a pencil icon, is outlined in dark orange.

to open the file editor.

Screenshot showing a repository file open for editing in the web browser. The file name field is active and highlighted with a dark orange outline.

In the filename field, change the name of the file to the new filename you want. You can also update the contents of your file at the same time.

Screenshot of a GitHub pull request showing a radio button to commit directly to the main branch or to create a new branch. New branch is selected.

  • Click Commit changes.
  • In the «Commit message» field, type a short, meaningful commit message that describes the change you made to the file. You can attribute the commit to more than one author in the commit message. For more information, see «Creating a commit with multiple authors.»
  • Below the commit message fields, decide whether to add your commit to the current branch or to a new branch. If your current branch is the default branch, you should choose to create a new branch for your commit and then create a pull request. For more information, see «Creating a pull request.»

    Renaming a file using the command line

    You can use the command line to rename any file in your repository.

    Many files can be renamed directly on GitHub, but some files, such as images, require that you rename them from the command line.

    This procedure assumes you’ve already:

    • Created a repository on GitHub, or have an existing repository owned by someone else you’d like to contribute to
    • Cloned the repository locally on your computer
    git mv OLD-FILENAME NEW-FILENAME 
    $ git status > # On branch YOUR-BRANCH > # Changes to be committed: > # (use "git reset HEAD . " to unstage) > # > # renamed: OLD-FILENAME -> NEW-FILENAME > # 
    $ git commit -m "Rename file" # Commits the tracked changes and prepares them to be pushed to a remote repository. # To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again. 
    $ git push origin YOUR_BRANCH # Pushes the changes in your local repository up to the remote repository you specified as the origin 

    Переименование репозитория

    Вы можете переименовать любой репозиторий, если вы являетесь владельцем организации или имеете права администратора для репозитория.

    When you rename a repository, all existing information, with the exception of project site URLs, is automatically redirected to the new name, including:

    For more information on project sites, see «About GitHub Pages.»

    In addition to redirecting web traffic, all git clone , git fetch , or git push operations targeting the previous location will continue to function as if made on the new location. However, to reduce confusion, we strongly recommend updating any existing local clones to point to the new repository URL. You can do this by using git remote on the command line:

    git remote set-url origin NEW_URL 

    If you plan to rename a repository that has a GitHub Pages site, we recommend using a custom domain for your site. This ensures that the site’s URL isn’t impacted by renaming the repository. For more information, see «About custom domains and GitHub Pages.»

    Note: GitHub will not redirect calls to an action hosted by a renamed repository. Any workflow that uses that action will fail with the error repository not found . Instead, create a new repository and action with the new name and archive the old repository. For more information, see «Archiving repositories.»

    Warning: If you create a new repository under your account in the future, do not reuse the original name of the renamed repository. If you do, redirects to the renamed repository will no longer work.

    1. On GitHub.com, navigate to the main page of the repository.
    2. Under your repository name, click

    Settings. If you cannot see the «Settings» tab, select the

    Screenshot of a repository header showing the tabs. The

    dropdown menu, then click Settings.

    Как мне изменить имена папок в гит? (с больших букв на маленькие)

    Недавно начал осваивать гит. Когда я делал первый пуш в репозиторий на гитхабе, случайно назвал директории с большой буквы. Хотел поменять регистр первых букв в папках, но команда git add * почему-то отказывается распознавать регистр и пушит всё как и раньше с большой буквы, либо же вообще говорит что изменений никаких не было. Как это исправить? Можно ли напрямую как-нибудь переименовать папки в репозитории? Регистр здесь важен т.к. все эти директории являются пакетами и при импорте интерпретатор может просто напросто их не увидеть.

    Отслеживать

    13.7k 12 12 золотых знаков 43 43 серебряных знака 75 75 бронзовых знаков

  • Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *