Esempio n. 1
0
        /// <summary>
        /// Updates .net core projects using the specified command line arguments. The first argument is the project list glob expression.
        /// </summary>
        /// <param name="args">The arguments used to update project with.</param>
        /// <param name="rootDirectory">The root directory to search for projects.</param>
        public void Update(string[] args, string rootDirectory = null)
        {
            Projects   = args[0];
            Properties = ParseArguments(args, 1);

            WriteLog($"Matching projects: {Projects}");
            var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);

            matcher.AddInclude(Projects);

            if (string.IsNullOrEmpty(rootDirectory))
            {
                rootDirectory = Environment.CurrentDirectory;
            }

            var currentDirectory  = new DirectoryInfo(rootDirectory);
            var startingDirectory = new DirectoryInfoWrapper(currentDirectory);
            var matchingResult    = matcher.Execute(startingDirectory);

            if (!matchingResult.HasMatches)
            {
                WriteLog($"Error: No Projects found: {Projects}");
                return;
            }

            foreach (var fileMatch in matchingResult.Files)
            {
                var filePath = Path.GetFullPath(fileMatch.Path);
                UpdateProject(filePath);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the files to move based on the given configuration
        /// </summary>
        /// <param name="sourceDirectory">The directory to search for files to move</param>
        /// <param name="config">The <see cref="TemplateConfig"/></param>
        /// <param name="promptResults">A <see cref="IDictionary{TKey, TValue}"/> of values from the prompts, where the key is the <see cref="AbstractPrompt.Id"/> and Value is the prompt result</param>
        /// <returns>A <see cref="FileGroup"/> of all files and the required template variables</returns>
        /// <exception cref="ArgumentException"></exception>
        public static IEnumerable <FileGroup> GetFilesToMove(string sourceDirectory, TemplateConfig config, IDictionary <string, object> promptResults)
        {
            if (string.IsNullOrWhiteSpace(sourceDirectory))
            {
                throw new ArgumentException("Source directory cannot be null or empty string", nameof(sourceDirectory));
            }

            var filesToMove = new List <FileGroup>();
            var info        = new DirectoryInfoWrapper(new DirectoryInfo(sourceDirectory));

            foreach (var file in config.Files)
            {
                var matcher = new Matcher();
                matcher.AddInclude(file.Glob);
                var result = matcher.Execute(info);

                filesToMove.Add(
                    new FileGroup
                {
                    Files            = result.Files,
                    VariablesToApply =
                        promptResults
                        .Where(v => file.Variables.Contains(v.Key))
                        .ToDictionary(p => p.Key, p => p.Value)
                });
            }

            return(filesToMove);
        }
Esempio n. 3
0
        public static IEnumerable <(string Path, string Stem)> GetFileList(string basedir, string[] includes, string[] excludes, bool ignoreCase)
        {
            var matcher = new Microsoft.Extensions.FileSystemGlobbing.Matcher(ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture);

            if (excludes != null)
            {
                foreach (var exclude in excludes)
                {
                    matcher.AddExclude(exclude);
                }
            }
            if (includes != null && includes.Length != 0)
            {
                foreach (var include in includes)
                {
                    matcher.AddInclude(include);
                }
            }
            else
            {
                matcher.AddInclude("**/*");
            }
            var di        = new DirectoryInfo(basedir);
            var diwrapper = new DirectoryInfoWrapper(di);
            var result    = matcher.Execute(diwrapper);

            if (!result.HasMatches)
            {
                return(Array.Empty <(string, string)>());
            }
            else
            {
                return(result.Files.Select(x => (x.Path, x.Stem)));
            }
        }
Esempio n. 4
0
        private static string CreateUnityPackage(IPackage meta, IPackageVariation variation)
        {
            var matcher = new Matcher();

            matcher.AddIncludePatterns(variation.UnityPackage.Includes);
            matcher.AddExclude("**/*.meta");
            if (variation.UnityPackage.Excludes != null)
            {
                matcher.AddExcludePatterns(variation.UnityPackage.Excludes);
            }

            var rootDirectory = new DirectoryInfoWrapper(new DirectoryInfo(Application.dataPath));
            var assets        = matcher.Execute(rootDirectory).Files.Select(w => $"Assets/{w.Path}");

            var destDirectory = Path.Combine(Application.dataPath, meta.Describe.Output);

            if (!Directory.Exists(destDirectory))
            {
                Directory.CreateDirectory(destDirectory);
            }

            var destName  = string.IsNullOrWhiteSpace(variation.UnityPackage.Name) ? $"{meta.Name}.unitypackage" : $"{variation.UnityPackage.Name}.unitypackage";
            var publishTo = Path.Combine(destDirectory, destName);

            if (File.Exists(publishTo))
            {
                File.Delete(publishTo);
            }

            AssetDatabase.ExportPackage(assets.ToArray(), publishTo, ExportPackageOptions.Default);

            return(publishTo);
        }
Esempio n. 5
0
        private Task LoadDirectoryFiles()
        {
            string rootDir = null;

            if (_initParams.rootUri != null)
            {
                rootDir = _initParams.rootUri.ToAbsolutePath();
            }
            else if (!string.IsNullOrEmpty(_initParams.rootPath))
            {
                rootDir = PathUtils.NormalizePath(_initParams.rootPath);
            }

            if (string.IsNullOrEmpty(rootDir))
            {
                return(Task.CompletedTask);
            }

            var matcher  = new Matcher();
            var included = _initParams.initializationOptions.includeFiles;

            matcher.AddIncludePatterns(included != null && included.Length > 0 ? included : new[] { "**/*" });
            matcher.AddExcludePatterns(_initParams.initializationOptions.excludeFiles ?? Enumerable.Empty <string>());

            var dib         = new DirectoryInfoWrapper(new DirectoryInfo(rootDir));
            var matchResult = matcher.Execute(dib);

            _server.LogMessage(MessageType.Log, $"Loading files from {rootDir}");
            return(LoadFromDirectoryAsync(rootDir, matchResult));
        }
Esempio n. 6
0
        /// <summary>
        /// Gets a fileset by FileSetSettings
        /// </summary>
        /// <example>
        /// <code>
        /// IEnumerable&gt;FilePath&lt; filePaths = FileSet.Find("D:\code\git\Cake.FileSet", new string[] { "/src/**/*.csproj" } , new string[] { "/src/**/*.Test.csproj" }, false);
        /// </code>
        /// </example>
        /// <returns>Returns an IEnumberable of <c>FilePath</c> that match the input patterns.</returns>
        /// <param name="includes">Patterns to include.</param>
        /// <param name="excludes">Patterns to exclude.</param>
        /// <param name="caseSensitive">Whether the pattern match is case senstive. Defaults to false.</param>
        /// <param name="basePath">Base directory to use for the fileset. The working directory is used if null.</param>
        public static IEnumerable <FilePath> Find(string basePath, IEnumerable <string> includes, IEnumerable <string> excludes = null, bool caseSensitive = false)
        {
            var directoryInfoWrapper = new DirectoryInfoWrapper(new DirectoryInfo(basePath));

            return(new FileSet(directoryInfoWrapper, includes ?? new string[0], excludes ?? new string[0], caseSensitive)
                   .GetFiles());
        }
Esempio n. 7
0
        private static string[] GetFiles(CommandOption includeOption, CommandOption excludeOption, string defaultInclude)
        {
            var matcher = new Microsoft.Extensions.FileSystemGlobbing.Matcher();

            if (includeOption.HasValue())
            {
                foreach (var include in includeOption.Values)
                {
                    matcher.AddInclude(include);
                }
            }
            else if (!string.IsNullOrEmpty(defaultInclude))
            {
                matcher.AddInclude(defaultInclude);
            }

            foreach (var exclude in excludeOption.Values)
            {
                matcher.AddExclude(exclude);
            }

            var currentDirectoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
            var directoryInfoWrapper = new DirectoryInfoWrapper(currentDirectoryInfo);

            var fileMatchResult = matcher.Execute(directoryInfoWrapper);

            return(fileMatchResult.Files.Select(f => Path.GetFullPath(f.Path)).ToArray());
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the IDirectory from the directory path
        /// </summary>
        /// <param name="directoryName">None encrypted path</param>
        /// <returns></returns>
        public override IDirectoryInfo FromDirectoryName(string directoryName)
        {
            var pathEnc = _fileSystem.Path.GetEncryptedPath(directoryName, true);
            var x       = new DirectoryInfoWrapper(_fileSystem, new System.IO.DirectoryInfo(pathEnc.GetPath(_source)));

            return(new LinuxEncDirectoryInfo(_fileSystem, _source, _destination, x, _encryption));
        }
        /// <summary>
        /// Get all files from a path and mask
        /// </summary>
        /// <param name="pathAndMask">Path and mask, this uses glob syntax. This should use forward slash only for dir separators</param>
        /// <returns>Found files</returns>
        public static IReadOnlyCollection <WatchedFile> GetFiles(string pathAndMask)
        {
            List <WatchedFile> files = new List <WatchedFile>();

            // pull out the directory portion of the path/mask, accounting for * syntax in the folder name
            string replacedPathAndMask = ReplacePathVars(pathAndMask);

            NormalizeGlob(replacedPathAndMask, out string dirPortion, out string globPortion);

            // create a matcher to match glob or regular file syntax
            Matcher fileMatcher = new Matcher(StringComparison.OrdinalIgnoreCase).AddInclude(globPortion);

            // get the base directory that does not have glob syntax
            DirectoryInfoWrapper baseDir = new DirectoryInfoWrapper(new DirectoryInfo(dirPortion));

            // read in existing files that match the mask in the directory being watched
            foreach (var file in fileMatcher.Execute(baseDir).Files)
            {
                try
                {
                    string fullPath   = dirPortion + file.Path;
                    long   fileLength = new FileInfo(fullPath).Length;
                    files.Add(new WatchedFile(fullPath, fileLength));
                }
                catch (Exception ex)
                {
                    if (!(ex is FileNotFoundException || ex is IOException))
                    {
                        throw;
                    }
                    // ignore, maybe the file got deleted...
                }
            }
            return(files);
        }
Esempio n. 10
0
        public void Run()
        {
            var matcher = new Matcher();

            matcher.AddInclude(args.FileFilter);

            var root = new DirectoryInfoWrapper(new DirectoryInfo(this.args.WorkingDirectory ?? Environment.CurrentDirectory));

            Console.WriteLine($"Looking for files matching '{args.FileFilter}' in '{root.FullName}'");

            var results = matcher.Execute(root);

            if (results.HasMatches == false)
            {
                Console.WriteLine("No matching files found");
                return;
            }

            if (this.args.OutputDirectory != null)
            {
                Directory.CreateDirectory(this.args.OutputDirectory);
            }

            foreach (var result in results.Files)
            {
                Console.WriteLine($"Found '{result.Path}', unpacking...");

                Unpack(Path.Combine(root.FullName, result.Path));
            }
        }
Esempio n. 11
0
        public static IEnumerable <string> ExpandGlobs(IAsset asset, IHostingEnvironment env)
        {
            string root  = asset.GetFileProvider(env).GetFileInfo("/").PhysicalPath;
            var    dir   = new DirectoryInfoWrapper(new DirectoryInfo(root));
            var    files = new List <string>();

            foreach (string sourceFile in asset.SourceFiles)
            {
                var matcher = new Matcher();
                matcher.AddInclude(sourceFile);
                PatternMatchingResult globbingResult = matcher.Execute(dir);
                IEnumerable <string>  fileMatches    = globbingResult.Files.Select(f => f.Path.Replace(root, string.Empty));

                if (!fileMatches.Any())
                {
                    throw new FileNotFoundException($"No files found matching \"{sourceFile}\" exist in \"{dir.FullName}\"");
                }

                files.AddRange(fileMatches.Where(f => !files.Contains(f)));
            }

            asset.Items[_physicalFilesKey] = files;

            return(files);
        }
        public void Length_TestWithFile()
        {
            File.WriteAllBytes(testFolder + "\\first.txt", new byte[] { 1, 2, 3 });
            wrapper = new DirectoryInfoWrapper(testFolder);

            Assert.AreEqual(3, wrapper.Length);
        }
        public void GetDirectories_DirectoryDoesntExist()
        {
            var info   = new DirectoryInfoWrapper(testFolder);
            var entity = new DirectoryEntity(info);

            Directory.Delete(testFolder, true);
            Assert.Throws(typeof(FileEntityNotFoundException), () => entity.GetDirectories());
        }
Esempio n. 14
0
        public static void Main(string[] args)
        {
            string        fileDirectory = @"D:\English";
            DirectoryInfo directoryInfo = new DirectoryInfo(fileDirectory);

            FileSystemVisitor filesv = new FileSystemVisitor((item) =>
            {
                return(!item.Name.Contains(".jpg"));
            });

            filesv.OnStart += (e, s) =>
            {
                Console.WriteLine("Search starts!");
            };

            filesv.OnFinish += (e, s) =>
            {
                Console.WriteLine("Search ends!");
            };

            filesv.OnFileFinded += (e, s) =>
            {
                Console.WriteLine($"File {s.Item.Name} finded");
            };

            filesv.OnDirectoryFinded += (e, s) =>
            {
                Console.WriteLine($"Directory {s.Item.Name} finded");
            };

            filesv.OnFileFiltered += (e, s) =>
            {
                if (s.Item.Name.Contains("cat"))
                {
                    s.Action = ActionType.Skip;
                }
                Console.WriteLine($"File {s.Item.Name} filtered");
            };

            filesv.OnDirectoryFiltered += (e, s) =>
            {
                if (s.Item.Name.Length <= 8)
                {
                    s.Action = ActionType.Stop;
                }
                Console.WriteLine($"Directory {s.Item.Name} filtered");
            };

            var wrapper = new DirectoryInfoWrapper(directoryInfo);

            foreach (IFileSystemInfoWrapper fileSysInfo in filesv.StartProcess(wrapper))
            {
                Console.WriteLine(fileSysInfo);
            }

            Console.ReadKey();
        }
Esempio n. 15
0
        private void AddPackageFiles(string projectDirectory, IEnumerable <PackIncludeEntry> packageFiles, PackageBuilder packageBuilder, IList <DiagnosticMessage> diagnostics)
        {
            var rootDirectory = new DirectoryInfoWrapper(new DirectoryInfo(projectDirectory));

            foreach (var match in CollectAdditionalFiles(rootDirectory, packageFiles, _currentProject.ProjectFilePath, diagnostics))
            {
                packageBuilder.Files.Add(match);
            }
        }
Esempio n. 16
0
        public DisposableFileSystem(bool automaticCleanup = true)
        {
            _automaticCleanup = automaticCleanup;

            RootPath = Path.GetTempFileName();
            File.Delete(RootPath);
            Directory.CreateDirectory(RootPath);
            DirectoryInfo = new DirectoryInfoWrapper(new DirectoryInfo(RootPath));
        }
        public static void GetFilePath_GivenNullObjectName_ThrowsArgumentNullException()
        {
            var generator = GetViewGenerator();

            using var tempDir = new TemporaryDirectory();
            var baseDir = new DirectoryInfoWrapper(new FileSystem(), new DirectoryInfo(tempDir.DirectoryPath));

            Assert.That(() => generator.GetFilePath(baseDir, null), Throws.ArgumentNullException);
        }
Esempio n. 18
0
        public static IEnumerable <string> ExpandGlobs(IAsset asset, IHostingEnvironment env)
        {
            var files = new List <string>();

            foreach (string sourceFile in asset.SourceFiles)
            {
                string outSourceFile;
                var    provider = asset.GetFileProvider(env, sourceFile, out outSourceFile);

                if (provider.GetFileInfo(outSourceFile).Exists)
                {
                    if (!files.Contains(sourceFile))
                    {
                        files.Add(sourceFile);
                    }
                }
                else
                {
                    var    fileInfo = provider.GetFileInfo("/");
                    string root     = fileInfo.PhysicalPath;

                    if (root != null)
                    {
                        var dir     = new DirectoryInfoWrapper(new DirectoryInfo(root));
                        var matcher = new Matcher();

                        outSourceFile = outSourceFile.TrimStart('~', '/');

                        matcher.AddInclude(outSourceFile);
                        PatternMatchingResult globbingResult = matcher.Execute(dir);
                        IEnumerable <string>  fileMatches    = globbingResult.Files.Select(f => f.Path.Replace(root, string.Empty));

                        //if (!fileMatches.Any())
                        //{
                        //    throw new FileNotFoundException($"No files found matching \"{sourceFile}\" exist in \"{dir.FullName}\"");
                        //}

                        if (fileMatches.Any())
                        {
                            files.AddRange(fileMatches.Where(f => !files.Contains(f)));
                        }
                    }
                    else
                    {
                        if (!files.Contains(sourceFile))
                        {
                            files.Add(sourceFile);
                        }
                    }
                }
            }

            asset.Items[PhysicalFilesKey] = files;

            return(files);
        }
        public void GetParentDirectoryTest()
        {
            const string dirName = testFolder + "\\hello";

            Directory.CreateDirectory(dirName);
            var info   = new DirectoryInfoWrapper(dirName);
            var entity = new DirectoryEntity(info);

            Assert.AreEqual("testFolder", entity.GetParentDirectory().Name);
        }
        public void GetFiles()
        {
            File.WriteAllText(testFolder + "\\first", null);
            var info   = new DirectoryInfoWrapper(testFolder);
            var entity = new DirectoryEntity(info);
            var files  = new List <FileSystemEntity>(entity.GetFiles());

            Assert.AreEqual(1, files.Count);
            Assert.AreEqual("first", files[0].Name);
        }
        public void GetDirectories()
        {
            Directory.CreateDirectory(testFolder + "\\dir");
            var info   = new DirectoryInfoWrapper(testFolder);
            var entity = new DirectoryEntity(info);
            var dirs   = new List <FileSystemEntity>(entity.GetDirectories());

            Assert.AreEqual(1, dirs.Count);
            Assert.AreEqual("dir", dirs[0].Name);
        }
Esempio n. 22
0
 /// <summary>
 ///   Creates a new copy pair.
 /// </summary>
 /// <param name="source"> Source directory. </param>
 /// <param name="target"> Traget directory path. </param>
 public CopyPair(DirectoryInfo source, string target)
 {
     if (target == null)
     {
         throw new ArgumentNullException("target", "Target is null.");
     }
     IsFile     = false;
     SourceInfo = new DirectoryInfoWrapper(source);
     TargetInfo = CreateTargetFileSystemInfo(target);
     Initialize(SourceInfo, TargetInfo);
 }
Esempio n. 23
0
 private void addressToolBar_PathChanged(object sender, EventArgs e)
 {
     try {
         var path = addressToolBar.Path;
         var info = new DirectoryInfoWrapper(path);
         directory = new DirectoryEntity(info);
     } catch (FileEntityNotFoundException ex) {
         messageHelper.Show(ex.Message, ex.Message);
     }
     RefreshDirectory();
 }
        public void Length_TestWithInnerFolder()
        {
            File.WriteAllBytes(testFolder + "\\first.txt", new byte[] { 1, 2, 3 });
            const string innerFolder = testFolder + "\\inner";

            Directory.CreateDirectory(innerFolder);
            File.WriteAllBytes(testFolder + "\\second.bin", new byte[] { 4, 5, 6, 7 });
            wrapper = new DirectoryInfoWrapper(testFolder);

            Assert.AreEqual(7, wrapper.Length);
        }
        /// <summary>
        ///   Scans a specified path and collects all files and directories that are under the path.
        /// </summary>
        /// <param name="path"> Path name to scan. </param>
        /// <param name="files"> Collection to which all files will be added. </param>
        /// <param name="directories"> Collection to which all directories will be added. </param>
        public void Scan(string path, ICollection <IFileInfo> files, ICollection <IDirectoryInfo> directories)
        {
            if (path == null)
            {
                _log.Error("Path is null.");
                throw new ArgumentNullException("path", "Path cannot be null.");
            }
            var directory = new DirectoryInfoWrapper(path);

            Scan(directory, files, directories);
        }
Esempio n. 26
0
        private static IEnumerable <FilePatternMatch> GetMatchingFiles(CommandOptions options)
        {
            Matcher matcher = new Matcher(StringComparison.InvariantCulture);

            matcher.AddInclude(options.FileGlobPattern);
            var directoryInfo        = new DirectoryInfo(string.IsNullOrWhiteSpace(options.SourceDirectoryPath) ? Directory.GetCurrentDirectory() : options.SourceDirectoryPath);
            var directoryInfoWrapper = new DirectoryInfoWrapper(directoryInfo);
            var files = matcher.Execute(directoryInfoWrapper).Files;

            return(files);
        }
Esempio n. 27
0
        public void FilesAreEnumerated()
        {
            using (var scenario = new DisposableFileSystem()
                                  .CreateFile("alpha.txt"))
            {
                var contents = new DirectoryInfoWrapper(scenario.DirectoryInfo).EnumerateFileSystemInfos();
                var alphaTxt = contents.OfType <FileInfoBase>().Single();

                Assert.Equal(1, contents.Count());
                Assert.Equal("alpha.txt", alphaTxt.Name);
            }
        }
        private void OnDebug()
        {
            var matcher = new Matcher();

            matcher.AddExclude("**/*.meta");
            matcher.AddIncludePatterns(_includes);
            matcher.AddExcludePatterns(_excludes);

            var rootDirectory = new DirectoryInfoWrapper(new DirectoryInfo(Application.dataPath));

            _matches.Clear();
            _matches.AddRange(matcher.Execute(rootDirectory).Files.Select(w => $"Assets/{w.Path}"));
        }
Esempio n. 29
0
        public static List <string> LoadFiles(string basePath, string pattern)
        {
            var directoryInfo  = new DirectoryInfo(basePath);
            var matchDirectory = new DirectoryInfoWrapper(directoryInfo);

            var matcher = new Matcher();

            matcher.AddInclude(pattern);

            var matchResult = matcher.Execute(matchDirectory);

            return(matchResult.Files.Select(item => item.Path).ToList());
        }
        public static void GetFilePath_GivenNameWithOnlyLocalName_ReturnsExpectedPath()
        {
            var generator = GetViewGenerator();

            using var tempDir = new TemporaryDirectory();
            var          baseDir      = new DirectoryInfoWrapper(new FileSystem(), new DirectoryInfo(tempDir.DirectoryPath));
            const string testViewName = "view_name";
            var          expectedPath = Path.Combine(tempDir.DirectoryPath, "Views", testViewName + ".cs");

            var filePath = generator.GetFilePath(baseDir, testViewName);

            Assert.That(filePath.FullName, Is.EqualTo(expectedPath));
        }
    public void SetUp ()
    {
      _tempFile1 = new TempFile();
      _tempFile2 = new TempFile ();

      _folderSize = 0;
      _folderSize += _tempFile1.Length + _tempFile2.Length;
      
      _folder = Path.GetRandomFileName ();
      _path = Path.Combine (Path.GetTempPath(), _folder);
      Directory.CreateDirectory (_path);
      
      DirectoryInfo directoryInfo = new DirectoryInfo (_path);
      _directoryInfoWrapper = new DirectoryInfoWrapper (directoryInfo);
    }