Source

Tfs2Hg / Tfs2Hg / TfsUtility.cs

Full commit
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace Tfs2Hg
{
    public class TfsUtility
    {
        private readonly string workspaceFolder;
        private readonly TfsTeamProjectCollection teamProjectCollection;
        private readonly VersionControlServer versionControlServer;
        private readonly Workspace workspace;

        public TfsUtility(string workspaceFolder, Uri tfsUri)
            : this(workspaceFolder, tfsUri, null)
        {
        }

        public TfsUtility(string workspaceFolder, Uri tfsUri, NetworkCredential credentials)
        {
            this.workspaceFolder = workspaceFolder;

            Uri tfsServerUri = GetServerUri(tfsUri);
            teamProjectCollection = (credentials == null) ? new TfsTeamProjectCollection(tfsServerUri) : new TfsTeamProjectCollection(tfsServerUri, credentials);

            teamProjectCollection.Authenticate();

            versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
            workspace = versionControlServer.TryGetWorkspace(workspaceFolder);
            if (workspace == null)
            {
                string workspaceName = String.Format("Tfs2Hg_{0:N}", Guid.NewGuid());
                string userName = (credentials != null) ? credentials.UserName : Environment.UserName;

                string serverItem = GetServerItem(tfsUri);

                workspace = versionControlServer.CreateWorkspace(workspaceName, userName, null, new[] { new WorkingFolder(serverItem, workspaceFolder) });
            }
        }

        private static string GetServerItem(Uri tfsUri)
        {
            string path = HttpUtility.UrlDecode(tfsUri.PathAndQuery);
            return String.Format("${0}", path);
        }

        private static Uri GetServerUri(Uri tfsUri)
        {
            return new Uri(tfsUri.GetLeftPart(UriPartial.Authority));
        }

        public IEnumerable<Changeset> GetChangesetHistory(VersionSpec fromVersionSpec, VersionSpec toVersionSpec)
        {
            return versionControlServer.QueryHistory(workspaceFolder, VersionSpec.Latest, 0, RecursionType.Full, null, fromVersionSpec, toVersionSpec, Int32.MaxValue, false, false)
                .OfType<Changeset>()
                .OrderBy(x => x.ChangesetId);
        }

        public void GetChangeset(Changeset changeset)
        {
            ChangesetVersionSpec changesetVersionSpec = new ChangesetVersionSpec(changeset.ChangesetId);
            workspace.Get(changesetVersionSpec, GetOptions.Overwrite);
        }
    }
}