Esempio n. 1
0
        /// <summary>
        /// Attempt to extract a stream from an archive
        /// </summary>
        /// <param name="entryName">Name of the entry to be extracted</param>
        /// <param name="realEntry">Output representing the entry name that was found</param>
        /// <returns>MemoryStream representing the entry, null on error</returns>
        public virtual (MemoryStream, string) CopyToStream(string entryName)
        {
            MemoryStream ms        = new MemoryStream();
            string       realentry = null;

            // Copy single file from the current folder to the output directory, if exists
            try
            {
                // Make sure the folders exist
                Directory.CreateDirectory(_filename);

                // Get all files from the input directory
                List <string> files = Utilities.RetrieveFiles(_filename, new List <string>());

                // Now sort through to find the first file that matches
                string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault();

                // If we had a file, copy that over to the new name
                if (!String.IsNullOrWhiteSpace(match))
                {
                    Utilities.TryOpenRead(match).CopyTo(ms);
                    realentry = match;
                }
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex.ToString());
                return(ms, realentry);
            }

            return(ms, realentry);
        }
Esempio n. 2
0
        /// <summary>
        /// Attempt to extract a file from an archive
        /// </summary>
        /// <param name="entryName">Name of the entry to be extracted</param>
        /// <param name="outDir">Output directory for archive extraction</param>
        /// <returns>Name of the extracted file, null on error</returns>
        public virtual string CopyToFile(string entryName, string outDir)
        {
            string realentry = null;

            // Copy single file from the current folder to the output directory, if exists
            try
            {
                // Make sure the folders exist
                Directory.CreateDirectory(_filename);
                Directory.CreateDirectory(outDir);

                // Get all files from the input directory
                List <string> files = Utilities.RetrieveFiles(_filename, new List <string>());

                // Now sort through to find the first file that matches
                string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault();

                // If we had a file, copy that over to the new name
                if (!String.IsNullOrWhiteSpace(match))
                {
                    realentry = match;
                    File.Copy(match, Path.Combine(outDir, entryName));
                }
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex.ToString());
                return(realentry);
            }

            return(realentry);
        }
Esempio n. 3
0
        // 解析测试视频
        private List <TestVideo> ParseTestVideo(string videoPath)
        {
            if (Directory.Exists(videoPath))
            {
                List <TestVideo> testVideos = new List <TestVideo>();
                var videos = Utility.Director(videoPath).Where(f =>
                {
                    string ex = Path.GetExtension(f);
                    return(ex == ".ts" || ex == ".mp4" || ex == ".flv" || ex == ".avi");
                }).ToList();

                foreach (var item in videos)
                {
                    var _testVideoItem = new TestVideo {
                        VideoName = Path.GetFileName(item), VideoPath = Path.GetDirectoryName(item)
                    };
                    testVideos.Add(_testVideoItem);
                }

                return(testVideos);
            }
            else
            {
                MessageWindow.ShowDialog($"无法访问文件夹 [{videoPath}]", this);
            }

            return(null);
        }
Esempio n. 4
0
        private void DumpGetDriveNameForNtDeviceName(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===\n", isLocal ? "LOCAL" : "NETWORK");
            int cnt = 0;

            // Get Logical Drives from Local Host.
            foreach (string drive in Directory.GetLogicalDrives())
            {
                string tempPath = isLocal ? drive : Path.LocalToUnc(drive);

                foreach (string dosDev in Volume.QueryDosDevice(tempPath))
                {
                    Console.WriteLine("#{0:000}\tInput Path                    : [{1}]", ++cnt, dosDev);

                    string result = Volume.GetDriveNameForNtDeviceName(dosDev);
                    Console.WriteLine("\tGetDriveNameForNtDeviceName() : [{0}]", result ?? "null");
                    Assert.AreEqual(drive, result);

                    result = Volume.GetVolumeGuidForNtDeviceName(dosDev);
                    Console.WriteLine("\tGetVolumeGuidForNtDeviceName(): [{0}]\n", result ?? "null");
                }
            }
            Console.WriteLine("\t{0}\n", Reporter(true));
            if (isLocal)
            {
                Assert.IsTrue(cnt > 0, "Nothing was enumerated.");
            }
        }
Esempio n. 5
0
        private void SetScreenSizeInPrefs()
        {
            var config = new IniParserConfiguration {
                AllowDuplicateKeys = true, AllowDuplicateSections = true
            };

            foreach (var file in Directory.EnumerateFiles(Path.Combine(OutputFolder, "profiles"), "*refs.ini",
                                                          DirectoryEnumerationOptions.Recursive))
            {
                try
                {
                    var parser = new FileIniDataParser(new IniDataParser(config));
                    var data   = parser.ReadFile(file);
                    if (data.Sections["Display"] == null)
                    {
                        return;
                    }

                    if (data.Sections["Display"]["iSize W"] != null && data.Sections["Display"]["iSize H"] != null)
                    {
                        data.Sections["Display"]["iSize W"] = SystemParameters.ScreenWidth.ToString(CultureInfo.CurrentCulture);
                        data.Sections["Display"]["iSize H"] = SystemParameters.ScreenHeight.ToString(CultureInfo.CurrentCulture);
                    }

                    parser.WriteFile(file, data);
                }
                catch (Exception ex)
                {
                    Utils.Log($"Skipping screen size remap for {file} due to parse error.");
                    continue;
                }
            }
        }
Esempio n. 6
0
        private void DumpGetProperties(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var path = isLocal ? UnitTestConstants.SysRoot32 : Path.LocalToUnc(UnitTestConstants.SysRoot32);

            Console.WriteLine("\n\tAggregated properties of file system objects from Directory: [{0}]\n", path);

            UnitTestConstants.StopWatcher(true);
            var props  = Directory.GetProperties(path, DirectoryEnumerationOptions.FilesAndFolders | DirectoryEnumerationOptions.Recursive | DirectoryEnumerationOptions.ContinueOnException);
            var report = UnitTestConstants.Reporter();

            var total = props["Total"];
            var file  = props["File"];
            var size  = props["Size"];
            var cnt   = 0;

            foreach (var key in props.Keys)
            {
                Console.WriteLine("\t\t#{0:000}\t{1, -17} = [{2}]", ++cnt, key, props[key]);
            }

            Console.WriteLine("\n\t{0}", report);

            if (cnt == 0)
            {
                Assert.Inconclusive("Nothing is enumerated, but it is expected.");
            }

            Assert.IsTrue(total > 0, "0 Objects.");
            Assert.IsTrue(file > 0, "0 Files.");
            Assert.IsTrue(size > 0, "0 Size.");
            Console.WriteLine();
        }
Esempio n. 7
0
 public void Dispose()
 {
     if (Directory.Exists(FullName))
     {
         Utils.DeleteDirectory(FullName);
     }
 }
Esempio n. 8
0
        public Action Stage(IEnumerable <VirtualFile> files)
        {
            var grouped = files.SelectMany(f => f.FilesInPath)
                          .Distinct()
                          .Where(f => f.ParentArchive != null)
                          .GroupBy(f => f.ParentArchive)
                          .OrderBy(f => f.Key == null ? 0 : f.Key.Paths.Length)
                          .ToList();

            List <string> Paths = new List <string>();

            foreach (var group in grouped)
            {
                var tmp_path = Path.Combine(_stagedRoot, Guid.NewGuid().ToString());
                FileExtractor.ExtractAll(group.Key.StagedPath, tmp_path);
                Paths.Add(tmp_path);
                foreach (var file in group)
                {
                    file._stagedPath = Path.Combine(tmp_path, file.Paths[group.Key.Paths.Length]);
                }
            }

            return(() =>
            {
                Paths.Do(p =>
                {
                    if (Directory.Exists(p))
                    {
                        DeleteDirectory(p);
                    }
                });
            });
        }
Esempio n. 9
0
        private async Task BuildBSAs()
        {
            var bsas = ModList.Directives.OfType <CreateBSA>().ToList();

            Info($"Building {bsas.Count} bsa files");

            foreach (var bsa in bsas)
            {
                Status($"Building {bsa.To}");
                var sourceDir = Path.Combine(OutputFolder, Consts.BSACreationDir, bsa.TempID);

                using (var a = bsa.State.MakeBuilder())
                {
                    await bsa.FileStates.PMap(Queue, state =>
                    {
                        Status($"Adding {state.Path} to BSA");
                        using (var fs = File.OpenRead(Path.Combine(sourceDir, state.Path)))
                        {
                            a.AddFile(state, fs);
                        }
                    });

                    Info($"Writing {bsa.To}");
                    a.Build(Path.Combine(OutputFolder, bsa.To));
                }
            }

            var bsaDir = Path.Combine(OutputFolder, Consts.BSACreationDir);

            if (Directory.Exists(bsaDir))
            {
                Info($"Removing temp folder {Consts.BSACreationDir}");
                Utils.DeleteDirectory(bsaDir);
            }
        }
Esempio n. 10
0
        private static void SaveJson(IPrefetch pf, bool pretty, string outDir)
        {
            try
            {
                if (Directory.Exists(outDir) == false)
                {
                    Directory.CreateDirectory(outDir);
                }

                var outName =
                    $"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}_{Path.GetFileName(pf.SourceFilename)}.json";
                var outFile = Path.Combine(outDir, outName);


                if (pretty)
                {
                    File.WriteAllText(outFile, pf.Dump());
                }
                else
                {
                    File.WriteAllText(outFile, pf.ToJson());
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"Error exporting json. Error: {ex.Message}");
            }
        }
Esempio n. 11
0
        public void AlphaFS_Path_LocalToUnc()
        {
            Console.WriteLine("Path.LocalToUnc()");

            Console.WriteLine("\nInput Path: [{0}]\n", UnitTestConstants.SysRoot);

            var cnt = 0;

            UnitTestConstants.StopWatcher(true);
            foreach (var path2 in Directory.EnumerateFileSystemEntries(UnitTestConstants.SysRoot))
            {
                var uncPath = Path.LocalToUnc(path2);
                Console.WriteLine("\t#{0:000}\tLocal: [{1}]\t\t\tUNC: [{2}]", ++cnt, path2, uncPath);

                Assert.IsTrue(Path.IsUncPath(uncPath));
            }
            Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true));

            if (cnt == 0)
            {
                Assert.Inconclusive("Nothing was enumerated, but it was expected.");
            }

            Console.WriteLine();
        }
Esempio n. 12
0
        public void AlphaFS_Path_GetMappedConnectionName()
        {
            Console.WriteLine("Path.GetMappedConnectionName()");

            var cnt = 0;

            UnitTestConstants.StopWatcher(true);
            foreach (var drive in Directory.GetLogicalDrives().Where(drive => new DriveInfo(drive).IsUnc))
            {
                ++cnt;

                UnitTestConstants.StopWatcher(true);
                var gmCn = Path.GetMappedConnectionName(drive);
                var gmUn = Path.GetMappedUncName(drive);
                Console.WriteLine("\n\tMapped drive: [{0}]\tGetMappedConnectionName(): [{1}]", drive, gmCn);
                Console.WriteLine("\tMapped drive: [{0}]\tGetMappedUncName()       : [{1}]", drive, gmUn);

                Assert.IsTrue(!Utils.IsNullOrWhiteSpace(gmCn));
                Assert.IsTrue(!Utils.IsNullOrWhiteSpace(gmUn));
            }
            Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true));

            if (cnt == 0)
            {
                Assert.Inconclusive("Nothing was enumerated because no mapped drives were found.");
            }
        }
Esempio n. 13
0
        private void DumpGetDriveNameForNtDeviceName(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===\n", isLocal ? "LOCAL" : "NETWORK");
            var cnt = 0;

            // Get Logical Drives from UnitTestConstants.Local Host.
            foreach (var drive in Directory.GetLogicalDrives())
            {
                var tempPath = isLocal ? drive : Path.LocalToUnc(drive);

                foreach (var dosDev in Volume.QueryDosDevice(tempPath))
                {
                    Console.WriteLine("#{0:000}\tInput Path                 : [{1}]", ++cnt, dosDev);

                    var result = Volume.GetDriveNameForNtDeviceName(dosDev);
                    Console.WriteLine("\tGetDriveNameForNtDeviceName() : [{0}]", result ?? "null");
                    Assert.AreEqual(drive, result);

                    result = Volume.GetVolumeGuidForNtDeviceName(dosDev);
                    Console.WriteLine("\tGetVolumeGuidForNtDeviceName(): [{0}]\n", result ?? "null");
                }
            }
            Console.WriteLine("\t{0}\n", UnitTestConstants.Reporter(true));

            if (isLocal && cnt == 0)
            {
                Assert.Inconclusive("Nothing was enumerated, but it was expected.");
            }
        }
Esempio n. 14
0
        public void StartMonitor()
        {
            foreach (string efi in this.mDoc.SearchFolders)
            {
                if (!Directory.Exists(efi)) //Does not exist
                {
                    continue;
                }

                if ((File.GetAttributes(efi) & FileAttributes.Directory) != (FileAttributes.Directory))  // not a folder
                {
                    continue;
                }


                FileSystemWatcher watcher = new FileSystemWatcher(efi);
                watcher.Changed += new FileSystemEventHandler(watcher_Changed);
                watcher.Created += new FileSystemEventHandler(watcher_Changed);
                watcher.Renamed += new RenamedEventHandler(watcher_Changed);
                //watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
                //watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.CreationTime;
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents   = true;
                Watchers.Add(watcher);
                logger.Trace("Starting logger for {0}", efi);
            }
        }
Esempio n. 15
0
        public void AlphaFS_Directory_HasInheritedPermissions()
        {
            Console.WriteLine("Directory.HasInheritedPermissions()\n");

            var searchPattern = Path.WildcardStarMatchAll;
            var searchOption  = SearchOption.TopDirectoryOnly;

            var cnt = 0;

            UnitTestConstants.StopWatcher(true);
            foreach (var dir in Directory.EnumerateDirectories(UnitTestConstants.SysRoot, searchPattern, searchOption))
            {
                try
                {
                    var hasIp = Directory.HasInheritedPermissions(dir);

                    if (hasIp)
                    {
                        Console.WriteLine("\t#{0:000}\t[{1}]\t\tDirectory has inherited permissions: [{2}]", ++cnt, hasIp, dir);
                    }

                    Assert.AreEqual(hasIp, HasInheritedPermissions(dir));
                }
                catch (Exception ex)
                {
                    Console.Write("\t#{0:000}\tCaught {1} for directory: [{2}]\t[{3}]\n", cnt, ex.GetType().FullName, dir, ex.Message.Replace(Environment.NewLine, "  "));
                }
            }
            Console.Write("\n{0}", UnitTestConstants.Reporter());
        }
Esempio n. 16
0
            public IncludeZEditPatches(ACompiler compiler) : base(compiler)
            {
                var zEditPath = FindzEditPath(compiler);
                var havezEdit = zEditPath != null;

                Utils.Log(havezEdit ? $"Found zEdit at {zEditPath}" : $"zEdit not detected, disabling zEdit routines");

                if (!havezEdit)
                {
                    _mergesIndexed = new Dictionary <string, zEditMerge>();
                    return;
                }

                var merges = Directory.EnumerateFiles(Path.Combine(zEditPath, "profiles"),
                                                      DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive)
                             .Where(f => f.EndsWith("\\merges.json"))
                             .SelectMany(f => f.FromJSON <List <zEditMerge> >())
                             .GroupBy(f => (f.name, f.filename));

                merges.Where(m => m.Count() > 1)
                .Do(m =>
                {
                    Utils.Log(
                        $"WARNING, you have two patches named {m.Key.name}\\{m.Key.filename} in your zEdit profiles. We'll pick one at random, this probably isn't what you want.");
                });

                _mergesIndexed =
                    merges.ToDictionary(
                        m => Path.Combine(_mo2Compiler.MO2Folder, "mods", m.Key.name, m.Key.filename),
                        m => m.First());
            }
Esempio n. 17
0
        public static IEnumerable <string> EnumerateFiles(string path, IList <string> patterns,
                                                          Gitignore gitignore, FileFilter filter)
        {
            if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
            {
                return(Enumerable.Empty <string>());
            }

            if (patterns == null)
            {
                throw new ArgumentNullException(nameof(patterns));
            }
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            bool simpleSearch = filter.IncludeHidden && filter.MaxSubfolderDepth == -1 &&
                                (gitignore == null || gitignore.IsEmpty) &&
                                string.IsNullOrWhiteSpace(filter.NamePatternToExclude);

            if (simpleSearch)
            {
                return(EnumerateAllFiles(path, patterns, filter.IncludeArchive, filter.IncludeSubfolders, filter.FollowSymlinks));
            }
            else
            {
                return(EnumerateFilesWithFilters(path, patterns, gitignore, filter));
            }
        }
Esempio n. 18
0
        private void CreateOutputMods()
        {
            Directory.EnumerateFiles(Path.Combine(OutputFolder, "profiles"), "settings.ini", DirectoryEnumerationOptions.Recursive).Do(f =>
            {
                var ini = f.LoadIniFile();
                if (ini == null)
                {
                    Utils.Log($"settings.ini is null for {f}, skipping");
                    return;
                }

                var overwrites = ini.custom_overwrites;
                if (overwrites == null)
                {
                    Utils.Log("No custom overwrites found, skipping");
                    return;
                }

                if (overwrites is SectionData data)
                {
                    data.Coll.Do(keyData =>
                    {
                        var v   = keyData.Value;
                        var mod = Path.Combine(OutputFolder, Consts.MO2ModFolderName, v);

                        if (!Directory.Exists(mod))
                        {
                            Directory.CreateDirectory(mod);
                        }
                    });
                }
            });
        }
Esempio n. 19
0
        private void IndexPath(string path)
        {
            var file_list = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).ToList();

            Utils.Log($"Updating the cache for {file_list.Count} files");
            file_list.PMap(f => UpdateFile(f));
            SyncToDisk();
        }
Esempio n. 20
0
        public string AddProfile(string name = null)
        {
            string profile_name = name ?? RandomName();

            Directory.CreateDirectory(Path.Combine(MO2Folder, "profiles", profile_name));
            Profiles.Add(profile_name);
            return(profile_name);
        }
Esempio n. 21
0
 public TemporaryDirectory(string name)
 {
     FullName = name;
     if (!Directory.Exists(FullName))
     {
         Directory.CreateDirectory(FullName);
     }
 }
Esempio n. 22
0
        /// <summary>
        /// Adds a file to the given mod with a given path in the mod. Fills it with random data unless
        /// random_fill == 0;
        /// </summary>
        /// <param name="mod_name"></param>
        /// <param name="path"></param>
        /// <param name="random_fill"></param>
        /// <returns></returns>
        public string AddModFile(string mod_name, string path, int random_fill = 128)
        {
            var full_path = Path.Combine(ModsFolder, mod_name, path);

            Directory.CreateDirectory(Path.GetDirectoryName(full_path));

            GenerateRandomFileData(full_path, random_fill);
            return(full_path);
        }
Esempio n. 23
0
        private static IEnumerable <string> EnumerateAllFiles(string path, IList <string> patterns, bool includeArchive, bool recursive, bool followSymlinks)
        {
            // without filters, just enumerate files, which is faster

            var fileOptions = baseFileOptions;

            if (recursive)
            {
                fileOptions |= DirectoryEnumerationOptions.Recursive;
            }
            if (followSymlinks)
            {
                fileOptions &= ~DirectoryEnumerationOptions.SkipReparsePoints;
            }

            DirectoryEnumerationFilters fileFilters = new DirectoryEnumerationFilters
            {
                ErrorFilter = (errorCode, errorMessage, pathProcessed) =>
                {
                    logger.Error($"Find file error {errorCode}: {errorMessage} on {pathProcessed}");
                    return(true);
                }
            };


            bool includeAllFiles = patterns.Count == 0 ||
                                   (patterns.Count == 1 && (patterns[0] == "*.*" || patterns[0] == "*"));

            if (!includeAllFiles)
            {
                fileFilters.InclusionFilter = fsei =>
                {
                    foreach (string pattern in patterns)
                    {
                        if (WildcardMatch(fsei.FileName, pattern, true))
                        {
                            return(true);
                        }
                    }

                    if (includeArchive)
                    {
                        foreach (string pattern in ArchiveDirectory.Patterns)
                        {
                            if (WildcardMatch(fsei.FileName, pattern, true))
                            {
                                return(true);
                            }
                        }
                    }

                    return(false);
                };
            }

            return(Directory.EnumerateFiles(path, fileOptions, fileFilters, PathFormat.FullPath));
        }
Esempio n. 24
0
        private static List <string> EnumerateFiles(string path, ExportFormat format)
        {
            if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                path += Path.DirectorySeparatorChar;
            }

            return(Directory.EnumerateFiles(path, $"*.{format.ToString().ToLower()}", SearchOption.AllDirectories).ToList());
        }
Esempio n. 25
0
        public string AddMod(string name = null)
        {
            string mod_name   = name ?? RandomName();
            var    mod_folder = Path.Combine(MO2Folder, "mods", mod_name);

            Directory.CreateDirectory(mod_folder);
            File.WriteAllText(Path.Combine(mod_folder, "meta.ini"), "[General]");
            Mods.Add(mod_name);
            return(mod_name);
        }
Esempio n. 26
0
        public void GetDirectoryRoot_WithRelativePath_ReturnsCurrentDirRoot()
        {
            var originalDir = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(@"C:\Windows\");
            var root = Directory.GetDirectoryRoot(@"\Windows");

            Assert.That(root, Is.EqualTo(@"C:\"));
            Directory.SetCurrentDirectory(originalDir);
        }
Esempio n. 27
0
        private static List <string> GetRecycleBinFiles(string dir)
        {
            var files = new List <string>();

            Privilege[] privs = { Privilege.EnableDelegation, Privilege.Impersonate, Privilege.Tcb };
            using (new PrivilegeEnabler(Privilege.Backup, privs))
            {
                var filters = new DirectoryEnumerationFilters
                {
                    // Used to abort the enumeration.
                    // CancellationToken = cancelSource.Token,

                    // Filter to decide whether to recurse into subdirectories.
                    RecursionFilter = entryInfo =>
                    {
                        if (!entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink)
                        {
                            return(true);
                        }

                        return(false);
                    },

                    // Filter to process Exception handling.
                    ErrorFilter = delegate(int errorCode, string errorMessage, string pathProcessed)
                    {
                        _logger.Error($"Error accessing '{pathProcessed}'. Error: {errorMessage}");

                        // Return true to continue, false to throw the Exception.
                        return(true);
                    },

                    // Filter to in-/exclude file system entries during the enumeration.
                    InclusionFilter = entryInfo =>
                    {
                        if (entryInfo.FileName == "INFO2" || entryInfo.FileName.StartsWith("$I"))
                        {
                            _logger.Debug($"Found match: '{entryInfo.FullPath}'");
                            return(true);
                        }

                        return(false);
                    }
                };

                var dirEnumOptions =
                    DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive | DirectoryEnumerationOptions.ContinueOnException |
                    DirectoryEnumerationOptions.SkipReparsePoints;

                files.AddRange(Directory.EnumerateFileSystemEntryInfos <string>(dir, dirEnumOptions, filters).Where(File.Exists));
            }

            return(files);
        }
Esempio n. 28
0
        /// <summary>
        /// The user may already have some files in the OutputFolder. If so we can go through these and
        /// figure out which need to be updated, deleted, or left alone
        /// </summary>
        public async Task OptimizeModlist()
        {
            Utils.Log("Optimizing Modlist directives");
            var indexed = ModList.Directives.ToDictionary(d => d.To);

            UpdateTracker.NextStep("Looking for files to delete");
            await Directory.EnumerateFiles(OutputFolder, "*", DirectoryEnumerationOptions.Recursive)
            .PMap(Queue, UpdateTracker, f =>
            {
                var relative_to = f.RelativeTo(OutputFolder);
                Utils.Status($"Checking if modlist file {relative_to}");
                if (indexed.ContainsKey(relative_to) || f.IsInPath(DownloadFolder))
                {
                    return;
                }

                Utils.Log($"Deleting {relative_to} it's not part of this modlist");
                File.Delete(f);
            });

            UpdateTracker.NextStep("Looking for unmodified files");
            (await indexed.Values.PMap(Queue, UpdateTracker, d =>
            {
                // Bit backwards, but we want to return null for
                // all files we *want* installed. We return the files
                // to remove from the install list.
                Status($"Optimizing {d.To}");
                var path = Path.Combine(OutputFolder, d.To);
                if (!File.Exists(path))
                {
                    return(null);
                }

                var fi = new FileInfo(path);
                if (fi.Length != d.Size)
                {
                    return(null);
                }

                return(path.FileHash() == d.Hash ? d : null);
            }))
            .Where(d => d != null)
            .Do(d => indexed.Remove(d.To));

            UpdateTracker.NextStep("Updating Modlist");
            Utils.Log($"Optimized {ModList.Directives.Count} directives to {indexed.Count} required");
            var requiredArchives = indexed.Values.OfType <FromArchive>()
                                   .GroupBy(d => d.ArchiveHashPath[0])
                                   .Select(d => d.Key)
                                   .ToHashSet();

            ModList.Archives   = ModList.Archives.Where(a => requiredArchives.Contains(a.Hash)).ToList();
            ModList.Directives = indexed.Values.ToList();
        }
Esempio n. 29
0
        public void Directory_GetParent()
        {
            Console.WriteLine("Directory.GetParent()");

            var pathCnt  = 0;
            var errorCnt = 0;

            UnitTestConstants.StopWatcher(true);
            foreach (var path in UnitTestConstants.InputPaths)
            {
                string expected   = null;
                string actual     = null;
                var    skipAssert = false;

                Console.WriteLine("\n#{0:000}\tInput Path: [{1}]", ++pathCnt, path);

                // System.IO
                try
                {
                    var result = System.IO.Directory.GetParent(path);
                    expected = result == null ? null : result.FullName;
                }
                catch (Exception ex)
                {
                    skipAssert = ex is ArgumentException;

                    Console.WriteLine("\tCaught [System.IO] {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
                }
                Console.WriteLine("\t   System.IO : [{0}]", expected ?? "null");


                // AlphaFS
                try
                {
                    var result = Directory.GetParent(path);
                    actual = result == null ? null : result.FullName;

                    if (!skipAssert)
                    {
                        Assert.AreEqual(expected, actual);
                    }
                }
                catch (Exception ex)
                {
                    errorCnt++;

                    Console.WriteLine("\tCaught [AlphaFS] {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, "  "));
                }
                Console.WriteLine("\t   AlphaFS   : [{0}]", actual ?? "null");
            }
            Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true));

            Assert.AreEqual(0, errorCnt, "Encountered paths where AlphaFS != System.IO");
        }
Esempio n. 30
0
        public void EnumerateVolumeMountPoints()
        {
            Console.WriteLine("Volume.EnumerateVolumeMountPoints()");

            if (!IsAdmin())
            {
                Assert.Fail();
            }

            #region Logical Drives

            int cnt = 0;
            Console.WriteLine("\nLogical Drives\n");

            // Get Logical Drives from Local Host, .IsReady Drives only.
            foreach (string drive in Directory.GetLogicalDrives(false, true))
            {
                try
                {
                    // Logical Drives --> Volumes --> Volume Mount Points.
                    string uniqueVolName = Volume.GetUniqueVolumeNameForPath(drive);

                    if (!string.IsNullOrWhiteSpace(uniqueVolName) && !uniqueVolName.Equals(drive, StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (string mountPoint in Volume.EnumerateVolumeMountPoints(uniqueVolName).Where(mp => !string.IsNullOrWhiteSpace(mp)))
                        {
                            StopWatcher(true);

                            string guid = null;
                            try { guid = Volume.GetVolumeGuid(Path.Combine(drive, mountPoint)); }
                            catch (Exception ex)
                            {
                                Console.Write("\n\tCaught Exception (0): [{0}]", ex.Message.Replace(Environment.NewLine, "  "));
                            }

                            Console.WriteLine("\t#{0:000}\tLogical Drive: [{1}]\tGUID: [{2}]\n\t\tDestination  : [{3}]\n\t{4}", ++cnt, drive, guid ?? "null", mountPoint, Reporter(true));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("\n\tCaught Exception (1): [{0}]", ex.Message.Replace(Environment.NewLine, "  "));
                }
            }

            // No Assert(); there might be no Mount Points.
            if (cnt == 0)
            {
                Console.WriteLine("\tNo Volume Mount Points found.");
            }

            #endregion // Logical Drives
        }