CreateChangesetAsync - Как зарегистрировать существующий файл, не зная enconding или типа файла (просто путь к файлу) - PullRequest
0 голосов
/ 15 октября 2018

Я попытался последовать примеру создания набора изменений с несколькими файлами: [См. Ссылку] [1]

Хотя я немного застрял на этапах TFVCItem и ItemContent, где я не знаюКак извлечь содержимое и завершение моего файла.

Я пытаюсь написать некоторый код, чтобы проверить файл, данный мне filePath, и зарегистрировать его в указанном месте.

Кто-нибудь захочет помочь мне с тем, как это сделать?

Это то, что я дошел до сих пор:

  Public Function CreateChangeset(ByVal projectName As String,
                                      ByVal files As Dictionary(Of String, String),
                                      ByVal comment As String) As TfvcChangesetRef

    Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
    Dim newChangetset = New TfvcChangeset

    Dim changes = New List(Of TfvcChange)

    For Each fKP In files
        Dim fileSource = fKP.Key
        Dim fileTarget = fKP.Value

        Dim newChange = New TfvcChange

        newChange.ChangeType = VersionControlChangeType.Add

        Dim newItem = New TfvcItem
        newItem.Path = $"&/{projectName}/{fileTarget}"
        newItem.ContentMetadata = New FileContentMetadata

        '' TODO: How to extract the correct encoding, and type?...
        'newItem.ContentMetadata.Encoding = GetFileEncoding(fileSource)
        'newItem.ContentMetadata.ContentType = "text/plain"
        'newChange.Item = newItem

        '' TODO: How to extract the correct content, and type?...
        'Dim newContent = New ItemContent
        'newContent.Content = "Blabla"
        'newContent.ContentType = ItemContentType.RawText
        'newChange.NewContent = newContent

        changes.Add(newChange)
    Next
    newChangetset.Changes = changes
    newChangetset.Comment = comment

    Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result

    Return changesetRef
End Function

ОБНОВЛЕНИЕ: Хорошо, так что мне удалосьзаставить его работать, но я все еще не уверен, как правильно установить ContentType.

У меня есть выбор между ItemContentType.RawText и ItemContentType.Base64Encoded, но я не уверен, когда использовать один или другой.

Вот новый код, который работает:

    Public Function CreateChangeset(ByVal projectName As String,
                                ByVal files As Dictionary(Of String, String),
                                ByVal comment As String) As TfvcChangesetRef

    Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
    Dim newChangetset = New TfvcChangeset

    Dim changes = New List(Of TfvcChange)

    For Each fKP In files

        ' Extract and build our target and source paths.
        Dim fileSource = fKP.Key
        Dim fileTarget = fKP.Value
        Dim fileName = IO.Path.GetFileName(fileSource)

        Dim newChange = New TfvcChange

        ' Create the new TFVC item which will be checked-in.
        Dim newItem = New TfvcItem
        newItem.Path = $"$/{projectName}/{fileTarget}/{fileName}"
        newItem.ContentMetadata = New FileContentMetadata

        ' Try to extract the item from the server.
        Dim serverItem = c.GetItemAsync(newItem.Path).Result

        If serverItem Is Nothing Then
            ' If the file is not on the server, then its a new file.
            newChange.ChangeType = VersionControlChangeType.Add
        Else
            ' Indicate that we are dealing with a file modification 
            ' and specify which version we are editing.
            newChange.ChangeType = VersionControlChangeType.Edit
            newItem.ChangesetVersion = serverItem.ChangesetVersion
        End If

        ' Read the file content to a stream.
        Using reader = New StreamReader(fileSource,
                                        Text.Encoding.Default,
                                        True) ' This last parameter allows to extract the correct encoding.
            Dim fileContent As String = String.Empty

            ' Read all the file content to a string so that we can store 
            ' it in the itemcontent.
            ' NOTE: reading it also allows to retrieve the correct file enconding.
            If reader.Peek() >= 0 Then
                fileContent = reader.ReadToEnd
            End If

            ' Set the file enconding and MIME Type.
            newItem.ContentMetadata.Encoding = reader.CurrentEncoding.WindowsCodePage
            newItem.ContentMetadata.ContentType = System.Web.MimeMapping.GetMimeMapping(fileSource)
            newChange.Item = newItem

            ' Set the file content.
            Dim newContent = New ItemContent
            newContent.Content = fileContent

            ' TODO: What should be the logic to set the Content Type? Not too sure...
            ' If newItem.ContentMetadata.ContentType.StartsWith("text/") Then
            newContent.ContentType = ItemContentType.RawText
            '  Else
            '  newContent.ContentType = ItemContentType.Base64Encoded
            '  End If

            ' Store the content to the change.
            newChange.NewContent = newContent
        End Using

        changes.Add(newChange)
    Next

    newChangetset.Changes = changes
    newChangetset.Comment = comment

    Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result

    Return changesetRef
End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...