- Using Version Control in VS Code
- SCM Providers
- SCM Provider extensions
- Git support
- Commit
- Cloning a repository
- Branches and Tags
- Remotes
- Git Status Bar actions
- Gutter indicators
- Merge conflicts
- Viewing diffs
- Diff editor review pane
- Timeline view
- Git output window
- Initialize a repository
- VS Code as Git editor
- VS Code as Git diff tool
- Working with pull requests
- Next steps
- Common questions
- My team is using Team Foundation Version Control (TFVC) instead of Git. What should I do?
- Why do the Pull, Push and Sync actions never finish?
- How can I sign in to Git with my Azure DevOps organization that requires multi-factor authentication?
- I have GitHub Desktop installed on my computer but VS Code ignores it
- I keep getting Git authentication dialogs whenever VS Code is running
- Can I use SSH Git authentication with VS Code?
- Национальная библиотека им. Н. Э. Баумана Bauman National Library
- Персональные инструменты
- Microsoft SCC
- Содержание
- Провайдеры Microsoft SCC для SVN
- AgentSVN
- TamTamSVN
- PushOK SVN SCC Proxy
- Изменение SCC провайдера, если установлены два или более MSSCCI провайдеров в OS Windows
- Microsoft Team Foundation Server
- SCC в Platform Builder на базе Windows CE.NET
- SCC на базе Windows Embedded CE 6.0
- Управление исходным кодом веб-узлов
- Управление конфигурацией программного обеспечения с позиции управления исходным кодом (SharePoint 2007)
- SCC в Visual Studio 2015
- Основные функции SCC в Visual Studio 2015
- Инициализация и вспомогательные функции
- Основные функции управления источником
- Макросы для быстрой проверки на наличие ошибок
- MSSCCPRJ.SCC файл
- Иллюстрация формата файла MSSCCPRJ.SCC
- Управление хранилищем файлов в Visual Studio при помощи SCC
- Поддержка SCC в IBM Rational Team Concert
- Изучаем дерево исходников Windows 10: от телеметрии до open source
- Фильтрация данных из символьных файлов
- Фильтрация данных из исполняемых файлов
- Изучаем полученные данные
- Телеметрия
- Kernel Patch Protection
- Сомнительные файлы
- Open source?
Using Version Control in VS Code
Visual Studio Code has integrated source control management (SCM) and includes Git support in-the-box. Many other source control providers are available through extensions on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
SCM Providers
VS Code has support for handling multiple Source Control providers simultaneously. For example, you can open multiple Git repositories alongside your Azure DevOps Server local workspace and seamlessly work across your projects. To turn on the Source Control Providers view, select the overflow menu in the Source Control view ( ⌃⇧G (Windows, Linux Ctrl+Shift+G ) ), hover over Views, and make sure that Source Control Repositories is marked with a check. The Source Control Providers view shows the detected providers and repositories, and you can scope the display of your changes by selecting a specific provider.
SCM Provider extensions
If you would like to install another SCM provider, you can search on the scm providers extension category in the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ). Start typing ‘@ca’ and you will see suggestions for extension categories like debuggers and linters. Select @category:»scm providers» to see available SCM providers.
Git support
VS Code ships with a Git source control manager (SCM) extension. Most of the source control UI and work flows are common across other SCM extensions, so reading about the general Git support in VS Code will help you understand how to use another provider.
Note: If you are new to Git, the git-scm website is a good place to start, with a popular online book, Getting Started videos and cheat sheets. The VS Code documentation assumes you are already familiar with Git.
👉 When you commit, be aware that if your username and/or email is not set in your Git configuration, Git will fall back to using information from your local machine. You can find the details in Git commit information.
The Source Control icon in the Activity Bar on the left will always indicate an overview of how many changes you currently have in your repository. Selecting the icon will show you the details of your current repository changes: CHANGES, STAGED CHANGES and MERGE CHANGES.
Clicking each item will show you in detail the textual changes within each file. Note that for unstaged changes, the editor on the right still lets you edit the file: feel free to use it!
You can also find indicators of the status of your repository in the bottom-left corner of VS Code: the current branch, dirty indicators, and the number of incoming and outgoing commits of the current branch. You can checkout any branch in your repository by clicking that status indicator and selecting the Git reference from the list.
Tip: You can open VS Code in a sub-directory of a Git repository. VS Code’s Git services will still work as usual, showing all changes within the repository, but file changes outside of the scoped directory are shaded with a tool tip indicating they are located outside the current workspace.
Commit
Staging (git add) and unstaging (git reset) can be done via contextual actions in the files or by drag-and-drop.
You can type a commit message above the changes and press Ctrl+Enter (macOS: ⌘+Enter ) to commit them. If there are any staged changes, only changes will be committed. Otherwise, you’ll get a prompt asking you to select what changes you’d like to commit and get the option to change your commit settings.
Tip: If you commit your change to the wrong branch, undo your commit using the Git: Undo Last Commit command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
Cloning a repository
If you haven’t opened a folder yet, the Source Control view will give you the options to Open Folder from your local machine or Clone Repository.
If you select Clone Repository, you will be asked for the URL of the remote repository (for example on GitHub) and the parent directory under which to put the local repository.
For a GitHub repository, you would find the URL from the GitHub Code dialog.
You would then paste that URL into the Git: Clone prompt.
You’ll also see the option to Clone from GitHub. Once you authenticate with your GitHub account in VS Code, you’ll be able to search through repositories by name, and select any repo to clone it. You can also start the flow to clone a Git repository with the Git: Clone command in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). To see a step-by-step walkthrough, check out our Clone repos from VS Code video.
Branches and Tags
You can create and checkout branches directly within VS code through the Git: Create Branch and Git: Checkout to commands in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ).
If you run Git: Checkout to, you will see a dropdown list containing all of the branches or tags in the current repository. It will also give you the option to create a new branch if you decide that’s a better option, or checkout a branch in detached mode.
Remotes
VS Code is able to periodically fetch changes from your remotes. This enables VS Code to show how many changes your local repository is ahead or behind the remote. Starting with VS Code 1.19, this feature is disabled by default and you can use the git.autofetch setting to enable it.
Tip: You should set up a credential helper to avoid getting asked for credentials every time VS Code talks to your Git remotes. If you don’t do this, you may want to consider disabling automatic fetching via the git.autofetch setting to reduce the number of prompts you get.
Git Status Bar actions
There is a Synchronize Changes action in the Status Bar, next to the branch indicator, when the current checked out branch has an upstream branch configured. Synchronize Changes will pull remote changes down to your local repository and then push local commits to the upstream branch.
If there is no upstream branch configured and the Git repository has remotes set up, the Publish action is enabled. This will let you publish the current branch to a remote.
Gutter indicators
If you open a folder that is a Git repository and begin making changes, VS Code will add useful annotations to the gutter and to the overview ruler.
Merge conflicts
Merge conflicts are recognized by VS Code. Differences are highlighted and there are inline actions to accept either one or both changes. Once the conflicts are resolved, stage the conflicting file so you can commit those changes.
Viewing diffs
Our Git tooling supports viewing of diffs within VS Code.
Tip: You can diff any two files by first right clicking on a file in the Explorer or OPEN EDITORS list and selecting Select for Compare and then right-click on the second file to compare with and select Compare with ‘file_name_you_chose’. Alternatively from the keyboard hit ⇧⌘P (Windows, Linux Ctrl+Shift+P ) and select File: Compare Active File With and you will be presented with a list of recent files.
Diff editor review pane
There is a review pane in the Diff editor that presents changes in a unified patch format. You can navigate between changes with Go to Next Difference ( F7 ) and Go to Previous Difference ( ⇧F7 (Windows, Linux Shift+F7 ) ). Lines can be navigated with arrow keys and pressing Enter will jump back in the Diff editor and the selected line.
Note: This experience is especially helpful for screen reader users.
Timeline view
The Timeline view, accessible at the bottom of the File Explorer by default, is a unified view for visualizing time-series events (for example, Git commits) for a file.
VS Code’s built-in Git support provides the Git commit history of the specified file. Selecting a commit will open a diff view of the changes introduced by that commit. When you right-click on a commit, you’ll get options to Copy Commit ID and Copy Commit Message.
Visual Studio Code supports more Git history workflows through extensions available on the VS Code Marketplace.
Tip: Click on an extension tile to read the description and reviews in the Marketplace.
Git output window
You can always peek under the hood to see the Git commands we are using. This is helpful if something strange is happening or if you are just curious. 🙂
To open the Git output window, run View > Output and select Git from the dropdown list.
Initialize a repository
If your workspace is on your local machine, you can enable Git source control by creating a Git repository with the Initialize Repository command. When VS Code doesn’t detect an existing Git repository, the Source Control view will give you the options to Initialize Repository or Publish to GitHub.
You can also run the Git: Initialize Repository and Publish to GitHub commands from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ). Running Initialize Repository will create the necessary Git repository metadata files and show your workspace files as untracked changes ready to be staged. Publish to GitHub will directly publish your workspace folder to a GitHub repository, allowing you to choose between a private and public repositories. Check out our publishing repos video for more information about publishing to GitHub.
VS Code as Git editor
Here are the steps to do so:
VS Code as Git diff tool
Add the following to your Git configurations to use VS Code as the diff tool:
To summarize, here are some examples of where you can use VS Code as the editor:
Working with pull requests
Visual Studio Code also supports pull request workflows through the GitHub Pull Requests and Issues extension available on the VS Code Marketplace. Pull request extensions let you review, comment, and verify source code contributions directly within VS Code.
Next steps
Common questions
To push, pull, and sync you need to have a Git origin set up. You can get the required URL from the repository host. Once you have that URL, you need to add it to the Git settings by running a couple of command-line actions. For example:
My team is using Team Foundation Version Control (TFVC) instead of Git. What should I do?
Use the Azure Repos extension and this will light up TFVC support.
Why do the Pull, Push and Sync actions never finish?
This usually means there is no credential management configured in Git and you’re not getting credential prompts for some reason.
You can always set up a credential helper in order to pull and push from a remote server without having VS Code prompt for your credentials each time.
How can I sign in to Git with my Azure DevOps organization that requires multi-factor authentication?
There are now Git credential helpers that assist with multi-factor authentication. You can download these from Git Credential Manager for Mac and Linux and Git Credential Manager for Windows.
I have GitHub Desktop installed on my computer but VS Code ignores it
VS Code only supports the official Git distribution for its Git integration.
I keep getting Git authentication dialogs whenever VS Code is running
VS Code automatically fetches changes from the server in order to present you with a summary of incoming changes. The Git authentication dialog is independent from VS Code itself and is a part of your current Git credential helper.
One way to avoid these prompts is to set up a credential helper that remembers your credentials.
Can I use SSH Git authentication with VS Code?
Yes, though VS Code works most easily with SSH keys without a passphrase. If you have an SSH key with a passphrase, you’ll need to launch VS Code from a Git Bash prompt to inherit its SSH environment.
Национальная библиотека им. Н. Э. Баумана
Bauman National Library
Персональные инструменты
Microsoft SCC
SCC (англ. Source Code Control — управление исходным кодом ) — API, разработанный Microsoft и предназначенный для взаимодействия прикладных программ с системами управления версиями.
SCC предоставляет разработчикам прикладных программ стандартный интерфейс для выполнения типичных операций управления версиями, таких как получение нужной версии (check-out), публикация новой версии (check-in) и др. Прикладная программа взаимодействует с основными компонентами SCC, входящими в состав Windows, которые, в свою очередь, вызывают функции из библиотеки, предоставленной системой управления версиями. Таким образом, программа, использующая SCC, может взаимодействовать стандартным способом с любой системой управления версиями, которая зарегистрировала в системе свой SCC-провайдер.
Содержание
Провайдеры Microsoft SCC для SVN
AgentSVN
Agent SVN работает с разными интегрируемыми средами разработки, которые поддерживают:
TamTamSVN
Совместимая реализация, которая эффективно интегрирует SVN-клиент с такими продуктами как Microsoft Visual Studio / Visual Studio.NET, MatLab, FoxPro, 3D Studio Max и другие приложения, совместимые с MSSCCI.
PushOK SVN SCC Proxy
Изменение SCC провайдера, если установлены два или более MSSCCI провайдеров в OS Windows
Чтобы изменить провайдера управления версиями, выполните следующие действия:
Microsoft Team Foundation Server
Microsoft выпустила несколько MSSCCI-провайдеров для разных версий Team Foundation Server:
SCC в Platform Builder на базе Windows CE.NET
Системы управления исходного кода позволяют вам отследить изменения файлов исходного кода во время разработки программного обеспечения. С помощью Microsoft Platform Builder вы можете интегрировать систему управления исходного кода в свою среду проектирования. Если вы устанавливаете систему управления исходного кода, которая соответствует системе управления исходного кода Microsoft Source Code Control Interface, то вы сможете получить доступ к функциям контроля непосредственно из меню Platform Builder.
Если ваша установленная система управления исходного кода поддерживает операции в дополнение к тем, которые использует Microsoft Source Code Control Interface, то Platform Builder обеспечивает доступ к этим опциям с помощью кнопок Advanced. Кнопки Advanced могут быть найдены в нескольких диалоговых окнах, включая вкладку Source Control, команды Options из меню Tools, диалогового окна Add to Source Control и диалогового окна Check In File из меню Project. Если никакие другие операции не доступны, то кнопка Advanced будет затемнена или не появится.
SCC на базе Windows Embedded CE 6.0
Системы управления исходного кода позволяют вам отследить изменения файлов исходного кода во время разработки программного обеспечения. С помощью Windows Embedded CE 6.0 вы можете использовать систему управления исходного кода со своей средой разработки
Управление исходным кодом веб-узлов
Управление конфигурацией программного обеспечения с позиции управления исходным кодом (SharePoint 2007)
Эффективное управление исходным кодом — один из важнейших элементов любого проекта разработки. Управление исходным кодом позволит гарантировать успешность совместной работы в проектах разработки программного обеспечения следующим образом:
SCC в Visual Studio 2015
Основные функции SCC в Visual Studio 2015
Заголовочный файл: scc.h
Инициализация и вспомогательные функции
[Источник 11] Основные функции управления источникомМакросы для быстрой проверки на наличие ошибокMSSCCPRJ.SCC файлПри подключении модуля управления источником, поддерживающий MSSCCPRJ.SCC файл, необходимо придерживаться следующих рекомендаций: Иллюстрация формата файла MSSCCPRJ.SCCУправление хранилищем файлов в Visual Studio при помощи SCCУправление исходным кодом, предоставляемое Visual SourceSafe, позволяет управлять версиями файлов путем их сохранения в базе данных. Когда добавляется файл, его резервная копия сохраняется в базе данных, доступной для других пользователей, и изменения, которые были внесены в файл, сохраняются так, что в любое время можно восстановить предыдущую версию. Члены группы могут видеть последнюю версию любого файла, извлекать его из базы данных для внесения изменений и сохранять новую версию в базе данных, возвращая файл обратно. Поддержка SCC в IBM Rational Team ConcertВ версии 4.0 клиента IBM Rational Team Concert появляется поддержка MS-SCCI. Изучаем дерево исходников Windows 10: от телеметрии до open sourceНасколько бы закрытым ни было программное обеспечение Microsoft, информации о своем внутреннем устройстве оно выдает предостаточно. К примеру, экспорт функций из библиотеки по именам дает представление о ее интерфейсах. В свободном доступе есть и отладочные символы, которые повсеместно используются для диагностики ошибок в ОС. Однако на руках у нас все равно имеются только скомпилированные бинарные модули. Становится интересно: а какими они были до компиляции? Давайте попробуем разобраться, как вытащить побольше информации об исходных кодах, не делая ничего незаконного. Идея, конечно, не нова. В свое время подобное делали и Марк Руссинович, и Алекс Ионеску. Мне лишь было интересно получить свежие данные, немного дополнив и уточнив уже проделанную другими работу. Для эксперимента нам понадобятся пакеты отладочных символов, которые есть в свободном доступе. Я взял пакеты для последней релизной версии «десятки» (64 бита), причем решил исследовать и релизный пакет (free build), и отладочный (checked build). Отладочные символы — это набор файлов с расширением pdb (program database, база данных программы), в которых хранится различная информация для расширения возможностей отладки бинарных модулей в ОС, включая имена глобалов, функций и структур данных, иногда вместе с их содержимым. Помимо символов можно взять условно доступную отладочную сборку «десятки». Такая сборка богата на ассерты, в которых бывают описаны не только недокументированые и отсуствующие в символьных файлах имена переменных, но и номер строки в файле, в котором сработал ассерт. В примере видно не только имя файла и его расширение, но и структура каталогов до него, очень полезная даже без корня. Натравливаем на файлы символов утилиту strings от sysinternals и получаем около 13 ГБ сырых данных. А вот кормить все файлы из дистрибутива отладочной сборки подряд — так себе идея, ненужных данных будет слишком много. Ограничимся набором расширений: exe — исполняемые файлы, sys — драйвера, dll — билиотеки, ocx — ActiveX-компоненты, cpl — компоненты панели управления, efi — EFI-приложения, в частности загрузчик. Сырых данных от дистрибутива набралось 5,3 ГБ. К своему удивлению я обнаружил, что не так много программ способны хотя бы открыть файлы размером в десяток гигабайт, и уж тем более единицы смогли поддержать функцию поиска внутри таких файлов. В данном эксперименте для ручного просмотра сырых и промежуточных данных использовался 010 Editor. Фильтрация данных дешево и сердито осуществлялась скриптами на питоне. Фильтрация данных из символьных файловВ символьных файлах помимо прочего содержится информация компоновщика. То есть, в символьном файле присутствует список объектных файлов, которые использовались для компоновки соответствующего бинарника, причем в компоновщике используется полный путь до объектного файла. Получаем абсолютные пути, сортируем, удаляем дубликаты. К слову, мусора получилось не так много, и он был удален вручную. При осмотре полученных данных стала понятна примерная структура дерева исходных кодов. Корень — «d:\th», что по всей видимости означает threshold, в соответствии с названием ноябрьской версии Windows 10 — Threshold 1. Однако файлов с корнем «d:\th» оказалось мало. Это объясняется тем, что компоновщик принимает уже собранные файлы. А сборка объектников осуществляется в папки «d:\th.obj.amd64fre» для релизной сборки и «d:\th.obj.amd64chk» для отладочной. Для примера: По поводу расширения файлов: объектный файл получается из кучи разных типов исходного файла: «c», «cpp», «cxx», «asm» и т. д. На данном этапе неясно, какой именно тип исходного файла использовался, поэтому оставим расширение «c??». Помимо папки «d:\th» наблюдается множество других корней. Например, «d:\th.public.chk» и «d:\th.public.fre». Данную папку мы опустим ввиду того, что в ней хранится публичная часть sdk, то есть она нам не очень интересна. Также стоит отметить различные пути проектов для драйверов, которые, судя по всему, собираются где-то на рабочих местах разработчиков: c:\users\joseph-liu\desktop\sources\rtl819xp_src\common\objfre_win7_amd64\amd64\eeprom.obj Другими словами, существует набор драйверов устройств, отвечающих стандартам, например, USB XHCI, которые входят в дерево исходных кодов ОС. А все специфичные драйвера собираются где-то в другом месте. Выходные данные становятся все красивее! Однако на этом этапе дополнительные данные получить уже практически невозможно. Переходим к следующему набору сырых данных. Фильтрация данных из исполняемых файловНа этом этапе есть несколько проблем с данными, полученными из символов. Первая проблема: мы не уверены, что правильно откатили путь сборки исходного файла в объектный файл. И они действительно есть! То есть, для большинства каталогов можно утверждать, что их структура восстановлена правильно. Конечно, все еще остаются сомнительные каталоги, но думаю, эта погрешность вполне приемлема. Попутно можно смело заменять расширение «c??» на расширение совпавшего по пути исходника. Вторая проблема — заголовочные файлы. Дело в том, что это важная часть исходных файлов, однако из заголовочника не получается объектный файл, а это значит, что из информации об объектных файлах нельзя восстановить заголовочники. Приходится довольствоваться малым, а именно теми заголовочниками, которые мы нашли в сырых данных бинарных файлов. Третья проблема: мы все еще не знаем большинство расширений исходных файлов. Ну а как же исходники на ассемблере? За последним штрихом можно обратиться к Windows Research Kernel — исходным кодам Windows XP — и часть исходников на ассемблере переименовать вручную. Изучаем полученные данныеТелеметрияКакое-то время я изучал вопрос об устройстве телеметрии в Windows 10. К сожалению, анализ на скорую руку не выявил ничего стоящего. Я не нашел никаких кейлоггеров, никакой утечки чувствительных данных, ничего, к чему можно было бы прикопаться. И первым ключевым словом для поиска среди исходных файлов было «telemetry». Результат превзошел мои ожидания: 424 совпадения. Самые интересные приведу ниже. Комментировать, пожалуй, не стоит, поскольку все равно достоверно ничего не известно. Однако эти данные могут послужить хорошей отправной точкой для более детального исследования. Kernel Patch ProtectionСледующая находка — всеми любимый PatchGuard. Правда, в дереве исходников ОС присутствует только один файл непонятного, скорее всего бинарного типа. Сомнительные файлыНе придумав больше ничего меня интересующего, я начал искать все подряд — и остался доволен! d:\th\windows\core\ntgdi\fondrv\otfd\atmdrvr\umlib\backdoor.c?? d:\th\inetcore\edgehtml\src\site\webaudio\opensource\wtf\wtfvector.h Open source?d:\th\printscan\print\drivers\renderfilters\msxpsfilters\util\opensource\libjpeg\jaricom.c?? Архив с текстовым файлом со списком исходников приведен по ссылке. Делитесь своими находками в комментариях! Adblockdetector |