Beispiel #1
0
 public void ReplaceTokens_Invalid(string[] tokens, string[] replacements)
 {
     Assert.Throws <ArgumentException>(() =>
     {
         var result = DWPSUtils.ReplaceTokens("this is a test", tokens, replacements);
     });
 }
Beispiel #2
0
        public RepoPaths GetRepoPaths(string currentPath, bool noCache)
        {
            if (string.IsNullOrWhiteSpace(currentPath))
            {
                throw new ArgumentException("Current path cannot be empty");
            }

            var       fixedCurPath = DWPSUtils.ForceTrailingSlash(currentPath);
            var       refCurPath   = "REF" + fixedCurPath;
            RepoPaths result       = null;

            if (!noCache)
            {
                result = RepoCache.Get <RepoPaths>(refCurPath);
            }

            if (result == null)
            {
                result = BuildRepoPaths(currentPath);
                RepoCache.Add(refCurPath, result, new TimeSpan(0, 10, 0), true);
            }

            result.IgnoreCache = noCache;

            return(result);
        }
Beispiel #3
0
        public void GetResourceNames_Tests()
        {
            var names = DWPSUtils.GetEmbeddedResourceNames(_assembly);

            _assembly.Received(1).GetManifestResourceNames();
            CollectionAssert.AreEqual(_resourceNames, names);
        }
Beispiel #4
0
        protected List <string> ResolveLinkedFiles(Dictionary <string, string> tokens)
        {
            var result = new List <string>();

            if (this.CacheLinkFiles != null && this.CacheLinkFiles.Length > 0)
            {
                foreach (var linkFile in this.CacheLinkFiles)
                {
                    var cacheLinkFile = linkFile.Replace("/", "\\");

                    foreach (var token in tokens)
                    {
                        if (cacheLinkFile.IndexOf(token.Key, StringComparison.InvariantCulture) >= 0)
                        {
                            cacheLinkFile = cacheLinkFile.Replace(token.Key, token.Value);
                        }
                        var linkFilePath = DWPSUtils.IsFullPath(cacheLinkFile)
                            ? cacheLinkFile
                            : _diskManager.Path.Combine(this.RepositoryDirectories.RepositoryFolder, cacheLinkFile);
                        result.Add(linkFilePath);
                    }
                }
            }

            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// replaces characters that git allows (i.e. double quotes) with Windows equivalents where possible.
        /// </summary>
        /// <param name="path">the path to check</param>
        /// <returns>a valid Windows-safe version of the file path</returns>
        public string FixInvalidFileNameCharsInPath(string path)
        {
            var findChars    = new string[] { "\"" }; // just double quotes for now but I suspect the list will grow over time
            var replaceChars = new string[] { "" };

            return(DWPSUtils.ReplaceTokens(path, findChars, replaceChars, false));
        }
Beispiel #6
0
        public void GetFullPath_Existing_matches(string testValue, string expectedValue)
        {
            string basePath = "J:\\junk\\path";
            var    result   = DWPSUtils.GetFullPath(basePath, testValue);

            Assert.AreEqual(expectedValue, result);
        }
Beispiel #7
0
 public void ForceTrailingSlash_Invalid(string compare)
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         var result = DWPSUtils.ForceTrailingSlash(compare);
     });
 }
Beispiel #8
0
 public void Bad_Command_Tests(string command)
 {
     Assert.Throws <ArgumentException>(() =>
     {
         DWPSUtils.ExecuteCommandSync(_diskManager, _processManager, command, "somePath");
     });
 }
Beispiel #9
0
        public string GetPathToRepository(string currentPath)
        {
            if (string.IsNullOrWhiteSpace(currentPath))
            {
                return(null);
            }
            var curDir = _diskManager.NewDirectoryInfo(currentPath);

            if (curDir == null)
            {
                return(null);
            }

            while (curDir != null)
            {
                var path = _diskManager.Path.Combine(curDir.FullName, ".git");
                if (_diskManager.Directory.Exists(path))
                {
                    return(DWPSUtils.ForceTrailingSlash(curDir.FullName));
                }
                curDir = curDir.Parent;
            }

            return(null);
        }
Beispiel #10
0
        internal RepoPaths BuildRepoPaths(string currentPath)
        {
            var fixedCurPath = DWPSUtils.ForceTrailingSlash(currentPath);
            var result       = new RepoPaths {
                CurrentPath = fixedCurPath
            };
            var repoPath = GetPathToRepository(currentPath);

            if (!String.IsNullOrWhiteSpace(repoPath))
            {
                result.RootFolder               = DWPSUtils.ForceTrailingSlash(repoPath);
                result.RepositoryFolder         = DWPSUtils.ForceTrailingSlash(_diskManager.Path.Combine(result.RootFolder, ".git"));
                result.RelativePathToRoot       = DWPSUtils.BuildRelativePath(currentPath, result.RootFolder);
                result.RelativePathToRepository = DWPSUtils.BuildRelativePath(currentPath, result.RepositoryFolder);
            }

            var refPath = result.RootFolder ?? result.CurrentPath;

            var cache = RepoCache.Get <ICommandCache>(refPath);

            if (cache == null)
            {
                cache = new CommandCache();
                RepoCache.Add(refPath, cache);
            }

            result.Cache = cache;

            return(result);
        }
Beispiel #11
0
        protected void Init(IStaticAbstraction diskManager, string defaultColorFile, string customColorFile)
        {
            _diskManager = diskManager ?? new StAbWrapper();

            var defColorFile  = string.IsNullOrWhiteSpace(defaultColorFile) ? _defaultColorFileName : defaultColorFile;
            var custColorFile = string.IsNullOrWhiteSpace(customColorFile) ? _defaultCustomColorFileName : customColorFile;

            var path     = _diskManager.NewFileInfo(_diskManager.Assembly.GetCallingAssembly().Location).DirectoryName;
            var testPath = DWPSUtils.IsFullPath(defColorFile) ? defColorFile : _diskManager.Path.Combine(path, defColorFile);

            if (_diskManager.File.Exists(testPath))
            {
                _defaultColorFilePath = testPath;
            }
            else
            {
                testPath = _diskManager.Path.Combine(path, "psscripts", defColorFile);
                if (_diskManager.File.Exists(testPath))
                {
                    _defaultColorFilePath = testPath;
                }
            }

            _customColorFilePath = DWPSUtils.IsFullPath(custColorFile) ? custColorFile : _diskManager.Path.Combine(path, custColorFile);

            RefreshColors();
        }
Beispiel #12
0
        public static void TagRepoDir(string name, string path)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(path))
            {
                return;
            }
            if (_gitDirs.ContainsKey(name) &&
                string.Compare(_gitDirs[name], path, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                return;
            }

            if (!_diskManager.Directory.Exists(_infoDir))
            {
                _diskManager.Directory.CreateDirectory(_infoDir);
            }

            var fileName = _diskManager.Path.Combine(_infoDir, DWPSUtils.MakeFileSystemSafe(name + ".repo"));

            if (_diskManager.File.Exists(fileName))
            {
                var touchInfo = _diskManager.NewFileInfo(fileName);
                touchInfo.LastAccessTimeUtc = DateTime.UtcNow;
                return;
            }

            _diskManager.File.WriteAllText(fileName, path);

            _gitDirs.Add(name, path);
        }
Beispiel #13
0
        public void Valid_Happy_Path_Tests()
        {
            var expectedCommand = "SomeAppName";

            DWPSUtils.ExecuteCommandSync(_diskManager, _processManager, expectedCommand, null);

            _processManager.Received(1).Execute(Arg.Any <string>(), "/c " + expectedCommand, Arg.Any <int>());
        }
Beispiel #14
0
 public void GetEmbeddedResource_valid_fullnames_Tests()
 {
     for (var i = 0; i < _resourceNames.Length; i++)
     {
         var res = DWPSUtils.GetEmbeddedResource(_assembly, _resourceNames[i]);
         Assert.AreEqual(_resourceData[i], res);
     }
 }
Beispiel #15
0
 public void GetEmbeddedResource_valid_partialnames_Tests(int lengthOfPartial)
 {
     for (var i = 0; i < _resourceNames.Length; i++)
     {
         var last5 = _resourceNames[i].Substring(_resourceNames[i].Length - lengthOfPartial);
         var res   = DWPSUtils.GetEmbeddedResource(_assembly, last5);
         Assert.AreEqual(_resourceData[i], res);
     }
 }
Beispiel #16
0
        public void Bad_Path_Tests()
        {
            var badPath = "f:\\bad\\path";

            _diskManager.Directory.Exists(badPath).Returns(false);

            Assert.Throws <DirectoryNotFoundException>(() =>
            {
                DWPSUtils.ExecuteCommandSync(_diskManager, _processManager, "filler", badPath);
            });
        }
Beispiel #17
0
 public void Bad_Parameter_Tests()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         DWPSUtils.ExecuteCommandSync(_diskManager, null, "filler", "somePath");
     });
     Assert.Throws <ArgumentNullException>(() =>
     {
         DWPSUtils.ExecuteCommandSync(null, _processManager, "filler", "somePath");
     });
 }
Beispiel #18
0
        public void ReplaceTokens_SingleCharacterKeepDuplicates()
        {
            var sourceText  = "||1|2|||3|";
            var tokens      = new string[] { "|" };
            var replaceWith = new string[] { "_" };
            var expected    = "__1_2___3_";

            var result = DWPSUtils.ReplaceTokens(sourceText, tokens, replaceWith, false);

            Assert.AreEqual(result, expected);
        }
Beispiel #19
0
        public void ReplaceTokens_RemovingCharacters()
        {
            var sourceText  = "The red fox swam through red water to paint the deck red";
            var tokens      = new string[] { " ", "i", "o" };
            var replaceWith = new string[] { "_", "", "" };
            var expected    = "The_red_fx_swam_thrugh_red_water_t_pant_the_deck_red";

            var result = DWPSUtils.ReplaceTokens(sourceText, tokens, replaceWith, true);

            Assert.AreEqual(result, expected);
        }
Beispiel #20
0
        public void ReplaceTokens_ReplaceContainsToken()
        {
            var sourceText  = "The red fox swam through red water to paint the deck red";
            var tokens      = new string[] { " ", "i", "o" };
            var replaceWith = new string[] { "\\ /", "dig", "OO" };
            var expected    = "The\\ /red\\ /fOOx\\ /swam\\ /thrOOugh\\ /red\\ /water\\ /tOO\\ /padignt\\ /the\\ /deck\\ /red";

            var result = DWPSUtils.ReplaceTokens(sourceText, tokens, replaceWith, true);

            Assert.AreEqual(result, expected);
        }
Beispiel #21
0
        public void ReplaceTokens_SingleCharacter()
        {
            var sourceText  = "PURpleThe pUrple fox swam through purplePURPLE water to paint the deck puRple";
            var tokens      = new string[] { "purple" };
            var replaceWith = new string[] { "red" };
            var expected    = "redThe red fox swam through red water to paint the deck red";

            var result = DWPSUtils.ReplaceTokens(sourceText, tokens, replaceWith, true);

            Assert.AreEqual(result, expected);
        }
Beispiel #22
0
        protected virtual string BuildCacheName()
        {
            var cacheName = this.CacheName;

            if (this.CommandExecFolder != null)
            {
                cacheName += $"_{DWPSUtils.MakeFileSystemSafe(this.CommandExecFolder)}";
            }

            return(cacheName);
        }
Beispiel #23
0
        public void ReplaceTokens_Basic()
        {
            var source    = " This    is      a Test! ";
            var tokens    = new string[] { " " };
            var reptokens = new string[] { "_" };

            var result = DWPSUtils.ReplaceTokens(source, tokens, reptokens);

            Assert.IsTrue(result == source.Replace(" ", "_"));

            result = DWPSUtils.ReplaceTokens(source, tokens, reptokens, true);
            Assert.AreEqual("_This_is_a_Test!_", result);
        }
Beispiel #24
0
        public void GetDirectoryPath_existingFolder(string folder, string expected)
        {
            _diskManager.File.Exists(Arg.Any <string>()).Returns(false);
            _diskManager.Directory.Exists(folder).Returns(true);
            var info = Substitute.For <IDirectoryInfo>();

            info.FullName.Returns(folder);

            _diskManager.NewDirectoryInfo(folder).Returns(info);

            var result = DWPSUtils.GetDirectoryPath(folder);

            Assert.AreEqual(result, expected);
        }
Beispiel #25
0
        public void GetDirectoryPath_existingFile(string folder, string fileName, string expected)
        {
            var filePath = folder.Trim('\\') + "\\" + fileName;

            _diskManager.File.Exists(filePath).Returns(true);
            var info = Substitute.For <IFileInfo>();

            info.DirectoryName.Returns(folder);
            _diskManager.NewFileInfo(filePath).Returns(info);

            var result = DWPSUtils.GetDirectoryPath(filePath);

            Assert.AreEqual(result, expected);
        }
Beispiel #26
0
        public virtual TResult GetCommandResults(bool skipCache = false)
        {
            if (RepositoryDirectories == null)
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(RepositoryDirectories.RootFolder))
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(this.Command))
            {
                return(null);
            }

            var cacheName = BuildCacheName();

            var useCache = this.UseCache;

            if (skipCache || RepositoryDirectories.IgnoreCache || string.IsNullOrWhiteSpace(this.CacheName))
            {
                useCache = false;
            }

            TResult resultOut = default(TResult);

            if (useCache)
            {
                resultOut = RepositoryDirectories.Cache.Get <TResult>(cacheName);
            }
            this.CommandOutput = null;

            if (resultOut == default(TResult) || !useCache)
            {
                var execFolder = this.CommandExecFolder ?? RepositoryDirectories.RootFolder;
                var writer     = new ConsoleWriter();
                var barColor   = _colorGroups.GetColor("commandExecBar");
                writer.WriteHeader(this.Command, barColor.Foreground, barColor.Background, ConsoleTextPosition.Center);
                var result = DWPSUtils.ExecuteCommandSync(_diskManager, _processManager, this.Command, execFolder);
                writer.ResetConsole();

                resultOut = this.Parser.Parse(result.Output);

                AddItemToCache(RepositoryDirectories, cacheName, resultOut);
                this.CommandOutput = result.Output;
            }

            return(resultOut);
        }
Beispiel #27
0
        public void Valid_Change_app_dir_Tests()
        {
            var currentFolder = "C:\\current\\folder\\here";
            var appFolder     = "C:\\app\\folder\\there";

            _diskManager.Directory.Exists(appFolder).Returns(true);
            _diskManager.Directory.GetCurrentDirectory().Returns(currentFolder);

            DWPSUtils.ExecuteCommandSync(_diskManager, _processManager, "filler", appFolder);

            _diskManager.Directory.Received(1).Exists(appFolder);
            _diskManager.Directory.Received(1).GetCurrentDirectory();
            _diskManager.Directory.Received(1).SetCurrentDirectory(appFolder);
            _diskManager.Directory.Received(1).SetCurrentDirectory(currentFolder);
        }
Beispiel #28
0
        public void GetAssemblyFolder_Path(string path, string expected)
        {
            var asm = Substitute.For <IAssemblyInstance>();

            asm.Location.Returns($"{path.Trim('\\')}\\Library.dll");

            var info = Substitute.For <IFileInfo>();

            info.DirectoryName.Returns(path);

            _diskManager.NewFileInfo(Arg.Any <string>()).Returns(info);

            var result = DWPSUtils.GetAssemblyFolder(asm);

            Assert.AreEqual(result, expected);
        }
Beispiel #29
0
        public void GetFullPath_whitespace_path_matches_basePath(string basePath, string fileName, string expectedValue)
        {
            var combined = string.IsNullOrWhiteSpace(fileName) ? basePath : new StAbWrapper().Path.Combine(basePath, fileName);

            _diskManager.Path.Combine(basePath, fileName).Returns(combined);
            var info = new MockFileInfo {
                FullName = combined
            };

            _diskManager.NewFileInfo(combined).Returns(info);
            var result = DWPSUtils.GetFullPath(basePath, fileName);

            Assert.AreEqual(expectedValue, result);
            _diskManager.Path.Received(0).Combine(Arg.Any <string>(), Arg.Any <string>());
            _diskManager.Received(0).NewFileInfo(Arg.Any <string>());
        }
Beispiel #30
0
        public void GetDirectoryPath_itemNotFound(string value)
        {
            _diskManager.File.Exists(Arg.Any <string>()).Returns(false);
            _diskManager.Directory.Exists(Arg.Any <string>()).Returns(false);

            var ex = Assert.Throws <ApplicationException>(() => { DWPSUtils.GetDirectoryPath(value); });

            Assert.IsNotNull(ex?.Message);
            if (value == "")
            {
                Assert.IsTrue(ex.Message.IndexOf("''") > 0);
            }
            else
            {
                Assert.IsTrue(ex.Message.IndexOf(value) > 0);
            }
        }