private void DynamicStartBeforeQueryStatus(object sender, EventArgs e)
        {
            var currentCommand = (sender as OleMenuCommand) ?? throw new InvalidCastException($"Unable to cast {nameof(sender)} to {typeof(OleMenuCommand)}");
            var mcs            = _package.GetServiceAsync(typeof(IMenuCommandService)).GetAwaiter().GetResult() as OleMenuCommandService
                                 ?? throw new InvalidCastException($"Unable to cast {nameof(IMenuCommandService)} to {typeof(OleMenuCommandService)}");

            foreach (var cmd in Commands)
            {
                mcs.RemoveCommand(cmd);
            }

            var history = _documentHistoryQueries.Get(Infrastructure.ConfigurationManager.Current.Config.MaxNumberOfHistoryItemsOnMenu);

            currentCommand.Visible = true;
            currentCommand.Text    = history.Any() ? "<History>" : "<No History>";

            var j = 1;

            foreach (var item in history)
            {
                var menuCommandId = new CommandID(CommandSet, CommandId + j);
                var command       = new OleMenuCommand(DynamicCommandCallback, menuCommandId);

                command.Properties.Add(HistoryItemKey, item);
                command.Text = $"{j++}: {PathFormatter.ShrinkPath(item.FullName, 50)}";
                command.BeforeQueryStatus += (x, y) =>
                {
                    (x as OleMenuCommand).Visible = true;
                };

                Commands.Add(command);
                mcs.AddCommand(command);
            }
        }
Ejemplo n.º 2
0
        public void ItShouldNotReachLimit(string path, int limit)
        {
            var ret = PathFormatter.ShrinkPath(path, limit);

            Assert.False(string.IsNullOrWhiteSpace(ret));
            Assert.True(ret.Length <= limit, $"Result: \"{ret}\" length of result: {ret.Length} but should not more than: {limit}.");
        }
Ejemplo n.º 3
0
        public void ItShouldContainSpacer(string path, int limit, string spacer)
        {
            var ret = PathFormatter.ShrinkPath(path, limit, spacer);

            Assert.False(string.IsNullOrWhiteSpace(ret));
            Assert.Contains(spacer, ret);
        }
Ejemplo n.º 4
0
        private static Task <int> ExecuteAsync(CancellationToken cancellationToken)
        {
            var includePattern = _includesOption.Values;
            var excludePattern = _excludesOption.Values;

            // When no include pattern is specified, we decide to include all recursive ('**')
            if (!includePattern.Any())
            {
                includePattern.Add("**");
            }

            var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);

            matcher.AddIncludePatterns(includePattern);
            matcher.AddExcludePatterns(excludePattern);

            var stopwatch = Stopwatch.StartNew();

            var      items           = matcher.Execute(_pathArgument.Value);
            int      totalItems      = items.Count;
            TimeSpan getItemsElapsed = stopwatch.Elapsed;

            void ExecuteWithProgressBar(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction)
            {
                var options = new ProgressBarOptions {
                    ProgressCharacter = '─', CollapseWhenFinished = false
                };

                using var progressBar = new ProgressBar(totalItems, "Start remove items...", options);
                var i = 0;

                foreach (string path in items.OrderByDescending(x => x.Length))
                {
                    string shrinkedPath = PathFormatter.ShrinkPath(path, Console.BufferWidth - 44);

                    progressBar.Message = $"Remove item {i + 1} of {totalItems}: {shrinkedPath}";

                    itemAction(path);

                    progressBar.Tick($"Removed item {i + 1} of {totalItems}: {shrinkedPath}");

                    ++i;
                }

                var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath);
                var rootPathCheck         = new Func <bool>(() => rootPathDirectoryInfo.Exists &&
                                                            rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0);

                if ((_skipPathOption.HasValue() || !rootPathCheck()) && (_skipPathOption.HasValue() || !_tryRunOption.HasValue()))
                {
                    return;
                }

                using ChildProgressBar childProgressBar = progressBar.Spawn(1, "child actions", options);
                {
                    string shrinkedPath = PathFormatter.ShrinkPath(matcher.RootPath, Console.BufferWidth - 44);

                    childProgressBar.Message = $"Remove empty root path: {shrinkedPath}";

                    rootPathAction(rootPathDirectoryInfo, rootPathCheck);

                    childProgressBar.Tick($"Removed empty root path: {shrinkedPath}");
                }
            }

            void ExecuteQuiet(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction)
            {
                foreach (string path in items.OrderByDescending(x => x.Length))
                {
                    itemAction(path);
                }

                var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath);
                var rootPathCheck         = new Func <bool>(() => rootPathDirectoryInfo.Exists &&
                                                            rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0);

                if (!_skipPathOption.HasValue() && rootPathCheck() || !_skipPathOption.HasValue() && _tryRunOption.HasValue())
                {
                    rootPathAction(rootPathDirectoryInfo, rootPathCheck);
                }
            }

            if (totalItems > 0)
            {
                var retryPolicy = Policy.Handle <Exception>().OrResult <bool>(r => r).WaitAndRetry(25, c => TimeSpan.FromMilliseconds(250));

                var itemAction = new Action <string>(path =>
                {
                    if (_tryRunOption.HasValue())
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        if (PathExtensions.IsDirectory(path))
                        {
                            var di = new DirectoryInfo(path);
                            retryPolicy.Execute(() =>
                            {
                                di.Refresh();
                                if (di.Exists)
                                {
                                    di.Attributes = FileAttributes.Normal;
                                    di.Delete(true);
                                }

                                di.Refresh();
                                return(di.Exists);
                            });
                        }
                        else
                        {
                            var fi = new FileInfo(path);
                            retryPolicy.Execute(() =>
                            {
                                fi.Refresh();
                                if (fi.Exists)
                                {
                                    fi.Attributes = FileAttributes.Normal;
                                    fi.Delete();
                                }

                                fi.Refresh();
                                return(fi.Exists);
                            });
                        }
                    }
                });
                var rootPathAction = new Action <DirectoryInfo, Func <bool> >((di, check) =>
                {
                    if (_tryRunOption.HasValue())
                    {
                        Thread.Sleep(1);
                    }
                    else
                    {
                        retryPolicy.Execute(() =>
                        {
                            di.Refresh();
                            if (check())
                            {
                                di.Attributes = FileAttributes.Normal;
                                di.Delete();
                            }

                            di.Refresh();
                            return(check());
                        });
                    }
                });

                if (!_listItemsOption.HasValue() && !_quietOption.HasValue())
                {
                    ExecuteWithProgressBar(itemAction, rootPathAction);
                }
                else if (_listItemsOption.HasValue() && !_quietOption.HasValue())
                {
                    foreach (string path in items.OrderByDescending(x => x.Length))
                    {
                        Console.WriteLine(path);
                    }

                    if (!_skipPathOption.HasValue())
                    {
                        Console.WriteLine(matcher.RootPath);
                    }
                }
                else if (!_listItemsOption.HasValue() && _quietOption.HasValue())
                {
                    ExecuteQuiet(itemAction, rootPathAction);
                }
            }

            stopwatch.Stop();
            TimeSpan completeElapsed = stopwatch.Elapsed;

            if (_listItemsOption.HasValue() || _quietOption.HasValue())
            {
                return(Task.FromResult(Ok));
            }

            PrintSummary(totalItems, completeElapsed, getItemsElapsed);

            return(Task.FromResult(Ok));
        }
Ejemplo n.º 5
0
        public void ItShouldHandleShorterPathThenTheLimit(string path, int limit)
        {
            var ret = PathFormatter.ShrinkPath(path, limit);

            Assert.Equal(path, ret);
        }
Ejemplo n.º 6
0
        public void ItShouldHandleInvalidInput(string path, int limit)
        {
            var ret = PathFormatter.ShrinkPath(path, limit);

            Assert.Equal(string.Empty, ret);
        }