Ejemplo n.º 1
0
        /// <summary>
        /// Retrieves the latest changeset ID associated with a path
        /// </summary>
        /// <param name="localPath">A path on the local filesystem</param>
        /// <param name="credentials">Credentials used to authenticate against the serer</param>
        /// <returns></returns>
        public int GetLatestChangesetId(string localPath, ICredentials credentials)
        {
            int    latestChangesetId = 0;
            string server;

            Workstation   workstation   = new Workstation(versionControlClientAssembly);
            WorkspaceInfo workspaceInfo = workstation.GetLocalWorkspaceInfo(localPath);

            server = workspaceInfo.ServerUri.ToString();
            VersionControlServer sourceControl = new VersionControlServer(clientAssembly, versionControlClientAssembly, server, credentials);

            Workspace            workspace            = sourceControl.GetWorkspace(localPath);
            WorkspaceVersionSpec workspaceVersionSpec = new WorkspaceVersionSpec(versionControlClientAssembly, workspace);

            VersionSpec   versionSpec   = new VersionSpec(versionControlClientAssembly);
            RecursionType recursionType = new RecursionType(versionControlClientAssembly);

            IEnumerable history = sourceControl.QueryHistory(localPath, versionSpec.Latest, recursionType.Full, workspaceVersionSpec);

            IEnumerator historyEnumerator = history.GetEnumerator();
            Changeset   latestChangeset   = new Changeset(versionControlClientAssembly);

            if (historyEnumerator.MoveNext())
            {
                latestChangeset = new Changeset(versionControlClientAssembly, historyEnumerator.Current);
            }

            if (latestChangeset.Instance != null)
            {
                latestChangesetId = latestChangeset.ChangesetId;
            }
            return(latestChangesetId);
        }
Ejemplo n.º 2
0
        public override bool Execute()
        {
            Workspace            workspace;
            VersionControlServer versionControlServer;

            GetServices(out workspace, out versionControlServer);

            if (workspace == null || versionControlServer == null)
            {
                return(false);
            }

            VersionSpec spec              = new WorkspaceVersionSpec(workspace);
            IEnumerable history           = versionControlServer.QueryHistory(LocalPath, spec, 0, RecursionType.Full, null, null, null, 1, false, false);
            IEnumerator historyEnumerator = history.GetEnumerator();

            if (historyEnumerator.MoveNext())
            {
                Log.LogMessage(MessageImportance.Normal, "Found history entry");
                var cs = historyEnumerator.Current as Changeset;
                Log.LogMessage(MessageImportance.Normal, "changeset id: " + cs.ChangesetId);
                _changeset = cs.ChangesetId;
            }


            return(true);
        }
Ejemplo n.º 3
0
    public override void Run()
    {
        string path = Environment.CurrentDirectory;

        if (Arguments.Length > 0)
        {
            path = Path.GetFullPath(Arguments[0]);
        }

        char[] charsToTrim = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
        string fxdPath     = path.TrimEnd(charsToTrim);

        string    itemPath  = Path.Combine(path, "*");
        Workspace workspace = GetWorkspaceFromCache();

        workspace.RefreshMappings();
        string serverPath = workspace.GetServerItemForLocalItem(fxdPath);

        // pull item list based on WorkspaceVersion. otherwise might get
        // new items on server that haven't been pulled yet in the list returned
        WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspace);

        // process command options
        ItemSpec itemSpec = new ItemSpec(itemPath, RecursionType.Full);
        ItemSet  itemSet  = VersionControlServer.GetItems(itemSpec, version, DeletedState.NonDeleted, ItemType.Any, true);

        Item[] items = itemSet.Items;
        SortedList <string, bool> itemList = new SortedList <string, bool>(PathComparer);

        foreach (Item item in items)
        {
            string serverItem = item.ServerItem.Remove(0, serverPath.Length + 1);
            string fname      = Path.Combine(path, serverItem);
            //Console.WriteLine(serverItem + " : " + fname);
            itemList.Add(fname, true);
        }

        DirectoryInfo dir = new DirectoryInfo(path);

        foreach (FileInfo file in dir.GetFiles("*", SearchOption.AllDirectories))
        {
            if (!itemList.ContainsKey(file.FullName))
            {
                if (OptionPreview)
                {
                    Console.WriteLine(file.FullName);
                }
                else
                {
                    DeleteReadOnlyFile(file.FullName);
                }
            }
        }
    }
Ejemplo n.º 4
0
    private void ProcessFileList(SortedList <string, bool> files)
    {
        List <ItemSpec> itemSpecs = new List <ItemSpec>();

        foreach (string file in files.Keys)
        {
            itemSpecs.Add(new ItemSpec(file, RecursionType.None));
        }

        // pull item list based on WorkspaceVersion. otherwise might get
        // new items on server that haven't been pulled yet in the list returned
        WorkspaceVersionSpec        version  = new WorkspaceVersionSpec(workspace);
        SortedList <string, byte[]> itemList = new SortedList <string, byte[]>(PathComparer);

        // get item list from TFS server
        ItemSet[] itemSets = VersionControlServer.GetItems(itemSpecs.ToArray(), version, DeletedState.NonDeleted, ItemType.File, true);
        foreach (ItemSet itemSet in itemSets)
        {
            foreach (Item item in itemSet.Items)
            {
                string localItem = workspace.GetLocalItemForServerItem(item.ServerItem);
                itemList.Add(localItem, item.HashValue);
            }
        }

        // process adds and edits
        foreach (string file in files.Keys)
        {
            // skip files we're not interested in here
            if (IsExcludedFile(file))
            {
                continue;
            }

            if (!File.Exists(file))
            {
                if (OptionDeleted && itemList.ContainsKey(file))
                {
                    Console.WriteLine("Deleted: " + file);
                    deletedFiles.Add(file);
                }
                continue;
            }

            ProcessFile(itemList, file);
        }
    }
Ejemplo n.º 5
0
        // Fill in the workspace name if it is null.
        static VersionSpec ParseVersionSpec(String spec, Workspace workspace)
        {
            String user = workspace.VersionControlServer.TeamFoundationServer.AuthenticatedUserName;

            VersionSpec version = VersionSpec.ParseSingleSpec(spec, user);

            // If the user happened to specify only W for the workspace spec, we'll have to
            // fill in the workspace here (the parse method doesn't know it).
            WorkspaceVersionSpec wvs = version as WorkspaceVersionSpec;

            if (wvs != null && wvs.Name == null)
            {
                wvs.Name = workspace.Name;
            }

            return(version);
        }
Ejemplo n.º 6
0
        public void TestIncomingCommand()
        {
            TfsTask task = CreateTfsTaskFromLocalProjectPath(TFSServerAddress, this.testProjectPath);

            var history2 = task.VersionControlServer.QueryHistory(task.ProjectPath,
                                                                  new WorkspaceVersionSpec(task.Workspace), 0,
                                                                  RecursionType.Full, null, new WorkspaceVersionSpec(task.Workspace),
                                                                  null, 10, true, true).Cast <Changeset>().ToList();

            var w = new WorkspaceVersionSpec(task.Workspace);

            var history3 = task.VersionControlServer.QueryHistory(new QueryHistoryParameters(task.ProjectPath, RecursionType.Full)
            {
                VersionEnd = w,
                MaxResults = 1
            }).Cast <Changeset>().ToArray();

            var history5 = task.VersionControlServer.QueryHistory(new QueryHistoryParameters(task.ProjectPath, RecursionType.Full)
            {
                VersionStart = new ChangesetVersionSpec(history3[0].ChangesetId + 1),
                VersionEnd   = VersionSpec.Latest
            }).Cast <Changeset>().ToArray();
        }
Ejemplo n.º 7
0
        static int Main(string[] args)
        {
            try
            {
                Console.InputEncoding  = Encoding.UTF8;
                Console.OutputEncoding = Encoding.UTF8;

                if (args.Length != 0)
                {
                    Console.Error.WriteLine("This program is only expected to be called by the SonarQube TFS SCM plugin.");
                    return(1);
                }

                Console.WriteLine("Enter your credentials");
                Console.Out.Flush();
                var username = Console.ReadLine();
                var password = Console.ReadLine();
                var pat      = Console.ReadLine();

                TfsClientCredentials credentials;

                if (!String.IsNullOrEmpty(pat))
                {
                    credentials = new TfsClientCredentials(new BasicAuthCredential(new NetworkCredential("", pat)));
                }
                else if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(password))
                {
                    credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
                }
                else
                {
                    credentials = new TfsClientCredentials(true);
                }
                credentials.AllowInteractive = false;

                Console.WriteLine("Enter the Collection URI");
                Console.Out.Flush();
                var serverUriString = Console.ReadLine();

                if (!string.IsNullOrEmpty(serverUriString))
                {
                    if (!SetServerUri(serverUriString))
                    {
                        return(1);
                    }
                }

                using (var cache = new TfsCache(credentials))
                {
                    if (serverUri != null)
                    {
                        if (!UpdateCache(cache, serverUri))
                        {
                            return(1);
                        }
                    }

                    Console.Out.WriteLine("Enter the paths to annotate");
                    Console.Out.Flush();

                    string path;
                    while ((path = Console.ReadLine()) != null)
                    {
                        try
                        {
                            Console.Out.Flush();
                            Console.WriteLine(path);

                            if (!File.Exists(path))
                            {
                                FailOnFile("does not exist: " + path);
                                continue;
                            }

                            if (!Workstation.Current.IsMapped(path))
                            {
                                FailOnFile("is not in a mapped TFS workspace: " + path);
                                continue;
                            }

                            WorkspaceInfo        workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
                            WorkspaceVersionSpec version       = new WorkspaceVersionSpec(workspaceInfo);

                            if (serverUri == null || workspaceInfo.ServerUri.AbsoluteUri != serverUri.AbsoluteUri)
                            {
                                serverUri = workspaceInfo.ServerUri;
                                if (!UpdateCache(cache, serverUri))
                                {
                                    return(1);
                                }
                            }

                            var versionControlServer = cache.GetVersionControlServer(serverUri);

                            IAnnotatedFile annotatedFile = new FileAnnotator(versionControlServer).Annotate(path, version);
                            if (annotatedFile == null)
                            {
                                FailOnFile("is not yet checked-in: " + path);
                                continue;
                            }

                            if (annotatedFile.IsBinary())
                            {
                                FailOnFile("is a binary one: " + path);
                                continue;
                            }

                            bool failed = false;
                            for (int i = 0; !failed && i < annotatedFile.Lines(); i++)
                            {
                                var state = annotatedFile.State(i);
                                if (state != AnnotationState.COMMITTED)
                                {
                                    FailOnFile("line " + (i + 1) + " has not yet been checked-in (" + state + "): " + path);
                                    failed = true;
                                }
                            }
                            if (failed)
                            {
                                continue;
                            }

                            Console.WriteLine(annotatedFile.Lines());
                            for (int i = 0; i < annotatedFile.Lines(); i++)
                            {
                                Changeset changeset = annotatedFile.Changeset(i);
                                Console.Write(changeset.ChangesetId);
                                Console.Write('\t');
                                Console.Write(cache.GetEmailOrAccountName(serverUri, changeset.Owner));
                                Console.Write('\t');
                                Console.Write(ToUnixTimestampInMs(changeset.CreationDate));
                                Console.Write('\t');
                                Console.WriteLine(annotatedFile.Data(i));
                            }
                        }
                        catch (Exception e)
                        {
                            FailOnFile(e.Message);
                        }
                    }
                    Console.Out.Flush();
                }

                return(0);
            }
            catch (Exception e)
            {
                FailOnProject(e.Message);
                return(1);
            }
        }
        /// <summary>
        /// Retrieves the latest changeset ID associated with a path
        /// </summary>
        /// <param name="localPath">A path on the local filesystem</param>
        /// <param name="credentials">Credentials used to authenticate against the serer</param>
        /// <returns></returns>
        public int GetLatestChangesetId(string localPath, ICredentials credentials)
        {
            int latestChangesetId = 0;
            string server;

            Workstation workstation = new Workstation(versionControlClientAssembly);
            WorkspaceInfo workspaceInfo = workstation.GetLocalWorkspaceInfo(localPath);
            server = workspaceInfo.ServerUri.ToString();
            VersionControlServer sourceControl = new VersionControlServer(clientAssembly, versionControlClientAssembly, server, credentials);

            Workspace workspace = sourceControl.GetWorkspace(localPath);
            WorkspaceVersionSpec workspaceVersionSpec = new WorkspaceVersionSpec(versionControlClientAssembly, workspace);

            VersionSpec versionSpec = new VersionSpec(versionControlClientAssembly);
            RecursionType recursionType = new RecursionType(versionControlClientAssembly);

            IEnumerable history = sourceControl.QueryHistory(localPath, versionSpec.Latest, recursionType.Full, workspaceVersionSpec);

            IEnumerator historyEnumerator = history.GetEnumerator();
            Changeset latestChangeset = new Changeset(versionControlClientAssembly);
            if (historyEnumerator.MoveNext())
            {
                latestChangeset = new Changeset(versionControlClientAssembly, historyEnumerator.Current);
            }

            if (latestChangeset.Instance != null)
            {
                latestChangesetId = latestChangeset.ChangesetId;
            }
            return latestChangesetId;
        }
Ejemplo n.º 9
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.Error.WriteLine("Expected exactly one argument, the file to annotate. " + args.Length + " given.");
                return(1);
            }

            String path = args[args.Length - 1];

            if (!File.Exists(path))
            {
                Console.Error.WriteLine("The given file does not exist: " + path);
                return(2);
            }

            if (!Workstation.Current.IsMapped(path))
            {
                Console.Error.WriteLine("The given file is not in a mapped TFS workspace: " + path);
                return(3);
            }

            WorkspaceInfo        workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
            Uri                  serverUri     = workspaceInfo.ServerUri;
            WorkspaceVersionSpec version       = new WorkspaceVersionSpec(workspaceInfo);
            TfsClientCredentials credentials   = new TfsClientCredentials(true);

            using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(serverUri, credentials))
            {
                VersionControlServer server = collection.GetService <VersionControlServer>();

                IAnnotatedFile annotatedFile = new FileAnnotator(server).Annotate(path, version);
                if (annotatedFile == null)
                {
                    Console.Error.WriteLine("The given file has not yet been checked-in: " + path);
                    return(4);
                }

                if (annotatedFile.IsBinary())
                {
                    Console.Error.WriteLine("The given file is a binary one: " + path);
                    return(5);
                }

                for (int i = 0; i < annotatedFile.Lines(); i++)
                {
                    switch (annotatedFile.State(i))
                    {
                    case AnnotationState.UNKNOWN:
                        Console.Write("unknown ");
                        break;

                    case AnnotationState.LOCAL:
                        Console.Write("local ");
                        break;

                    case AnnotationState.COMMITTED:
                        Changeset changeset = annotatedFile.Changeset(i);
                        Console.Write(changeset.ChangesetId);
                        Console.Write(' ');
                        Console.Write(changeset.Owner);
                        Console.Write(' ');
                        Console.Write(changeset.CreationDate.ToString("MM\\/dd\\/yyyy"));
                        Console.Write(' ');
                        break;

                    default:
                        throw new InvalidOperationException("Unsupported annotation state: " + annotatedFile.State(i));
                    }

                    Console.WriteLine(annotatedFile.Data(i));
                }
            }

            return(0);
        }
Ejemplo n.º 10
0
    private void ProcessDirectory(string path)
    {
        char[] charsToTrim = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
        string itemPath    = path.TrimEnd(charsToTrim);
        string serverPath  = workspace.GetServerItemForLocalItem(itemPath);

        // pull item list based on WorkspaceVersion. otherwise might get
        // new items on server that haven't been pulled yet in the list returned
        WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspace);

        // process recursion settings
        RecursionType rtype            = OptionRecursive ? RecursionType.Full : RecursionType.OneLevel;
        bool          recursionSetting = Settings.Current.GetAsBool("Online.Recursive");

        if (recursionSetting)
        {
            rtype = RecursionType.Full;
        }
        SearchOption searchType = (rtype == RecursionType.Full) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;

        // process command options
        ItemSpec itemSpec = new ItemSpec(itemPath, rtype);
        ItemSet  itemSet  = VersionControlServer.GetItems(itemSpec, version, DeletedState.NonDeleted, ItemType.Any, true);

        // get item list from TFS server
        Item[] items = itemSet.Items;
        SortedList <string, byte[]> itemList = new SortedList <string, byte[]>(PathComparer);

        foreach (Item item in items)
        {
            if (item.ServerItem.Length == serverPath.Length)
            {
                continue;
            }
            string serverItem = item.ServerItem.Remove(0, serverPath.Length + 1);

            // server item paths are separated with '/', but on windows the file list below has '\' separated paths
            if (Path.DirectorySeparatorChar != '/')
            {
                serverItem = serverItem.Replace('/', Path.DirectorySeparatorChar);
            }

            string fname = Path.Combine(itemPath, serverItem);
            //Console.WriteLine(serverItem + " : " + fname);

            itemList.Add(fname, item.HashValue);
        }

        DirectoryInfo dir = new DirectoryInfo(path);

        FileInfo[] localFiles = dir.GetFiles("*", searchType);

        SortedList <string, bool> dirList = new SortedList <string, bool>();

        foreach (FileInfo file in localFiles)
        {
            // skip files we're not interested in
            if (IsExcludedFile(file.FullName))
            {
                continue;
            }

            dirList.Add(file.FullName, true);
            ProcessFile(itemList, file.FullName);
        }

        foreach (DirectoryInfo di in dir.GetDirectories("*", SearchOption.AllDirectories))
        {
            dirList.Add(di.FullName, true);
        }

        if (!OptionDeleted)
        {
            return;
        }

        foreach (string key in itemList.Keys)
        {
            // skip files that exist or we're not interested in
            if (dirList.ContainsKey(key))
            {
                continue;
            }
            if (IsExcludedFile(key))
            {
                continue;
            }

            Console.WriteLine("Deleted: " + key);
            deletedFiles.Add(key);
        }
    }
Ejemplo n.º 11
0
    public override void Run()
    {
        string path = Environment.CurrentDirectory;

        if (Arguments.Length > 0)
        {
            path = Path.GetFullPath(Arguments[0]);
        }

        if (File.Exists(path))
        {
            // would need to fixup dir.GetDirectories calls if we wanted to support filenames
            Console.WriteLine("Error: This command only takes paths as arguments, not file names.");
            Environment.Exit((int)ExitCode.Failure);
        }

        char[] charsToTrim = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
        string itemPath    = path.TrimEnd(charsToTrim);

        if (OptionWritable)
        {
            ShowWritableFiles(itemPath);
            Environment.Exit((int)ExitCode.Success);
        }

        Workspace workspace = GetWorkspaceFromCache();

        workspace.RefreshMappings();
        string serverPath = workspace.GetServerItemForLocalItem(itemPath);

        // process command options
        ItemSpec itemSpec = new ItemSpec(itemPath, RecursionType.Full);

        if (OptionOld)
        {
            ShowOldFiles(workspace, itemSpec);
            Environment.Exit((int)ExitCode.Success);
        }

        // pull item list based on WorkspaceVersion. otherwise might get
        // new items on server that haven't been pulled yet in the list returned
        WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspace);
        ItemSet itemSet = VersionControlServer.GetItems(itemSpec, version, DeletedState.NonDeleted, ItemType.Any, true);

        Item[] items = itemSet.Items;
        SortedList <string, string> itemList = new SortedList <string, string>(PathComparer);

        foreach (Item item in items)
        {
            if (item.ServerItem.Length == serverPath.Length)
            {
                continue;
            }
            string serverItem = item.ServerItem.Remove(0, serverPath.Length + 1);

            // server item paths are separated with '/', but on windows the file list below has '\' separated paths
            if (Path.DirectorySeparatorChar != '/')
            {
                serverItem = serverItem.Replace('/', Path.DirectorySeparatorChar);
            }

            string fname = Path.Combine(itemPath, serverItem);
            string hash  = "";

            if (item.ItemType == ItemType.File && item.HashValue != null)
            {
                hash = Convert.ToBase64String(item.HashValue);
            }

            itemList.Add(fname, hash);
        }

        if (OptionOthers)
        {
            ShowOtherFiles(itemPath, itemList);
        }
        else if (OptionDeleted)
        {
            ShowDeletedFiles(itemPath, itemList);
        }
        else if (OptionModified)
        {
            ShowModifiedFiles(itemPath, itemList);
        }
        else
        {
            foreach (string key in itemList.Keys)
            {
                Driver.WriteLine(key);
            }
        }
    }
Ejemplo n.º 12
0
    public void ShowModifiedFiles(Workspace workspace, string path)
    {
        char[] charsToTrim = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
        string itemPath    = path.TrimEnd(charsToTrim);

        workspace.RefreshMappings();
        string serverPath = workspace.GetServerItemForLocalItem(itemPath);

        // pull item list based on WorkspaceVersion. otherwise might get
        // new items on server that haven't been pulled yet in the list returned
        WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspace);

        // get item list from TFS server
        ItemSpec itemSpec = new ItemSpec(itemPath, RecursionType.Full);
        ItemSet  itemSet  = VersionControlServer.GetItems(itemSpec, version, DeletedState.NonDeleted, ItemType.Any, true);

        Item[] items = itemSet.Items;

        foreach (Item item in items)
        {
            if (item.ItemType != ItemType.File)
            {
                continue;
            }
            if (item.ServerItem.Length == serverPath.Length)
            {
                continue;
            }
            string serverItem = item.ServerItem.Remove(0, serverPath.Length + 1);

            // server item paths are separated with '/', but on windows the file list below has '\' separated paths
            if (Path.DirectorySeparatorChar != '/')
            {
                serverItem = serverItem.Replace('/', Path.DirectorySeparatorChar);
            }

            // only looking for modifications, not deletes or adds
            string fname = Path.Combine(itemPath, serverItem);
            if (!File.Exists(fname))
            {
                continue;
            }
            if (FileAttributes.ReadOnly == (File.GetAttributes(fname) & FileAttributes.ReadOnly))
            {
                continue;
            }

            using (FileStream fileStream = new FileStream(fname, FileMode.Open, FileAccess.Read))
            {
                string localHash = Convert.ToBase64String(md5.ComputeHash(fileStream));
                string itemHash  = Convert.ToBase64String(item.HashValue);
                if (itemHash == localHash)
                {
                    continue;
                }
            }

            string p = fname.Substring(path.Length + 1);
            if (OptionBrief)
            {
                Driver.WriteLine(CanonicalPath(p));
                continue;
            }

            string tnameA = Path.GetTempFileName();
            item.DownloadFile(tnameA);
            IDiffItem a = new DiffItemLocalFile(tnameA, item.Encoding, DateTime.Now, false);

            IDiffItem b = new DiffItemLocalFile(fname, item.Encoding, DateTime.Now, false);

            Difference.DiffFiles(VersionControlServer, a, b,
                                 GetDiffOptions(), p, true);

            if (!String.IsNullOrEmpty(tnameA))
            {
                File.Delete(tnameA);
            }
        }
    }