Esempio n. 1
0
        static Utils()
        {
            if (!Directory.Exists(Consts.LocalAppDataPath))
            {
                Directory.CreateDirectory(Consts.LocalAppDataPath);
            }

            var programName = Assembly.GetEntryAssembly()?.Location ?? "Wabbajack";

            LogFile    = Path.GetFileNameWithoutExtension(programName) + ".current.log";
            _startTime = DateTime.Now;


            if (LogFile.FileExists())
            {
                var new_path = Path.GetFileNameWithoutExtension(programName) + (new FileInfo(LogFile)).LastWriteTime.ToString(" yyyy-MM-dd HH_mm_ss") + ".log";
                File.Move(LogFile, new_path, MoveOptions.ReplaceExisting);
            }

            var watcher = new FileSystemWatcher(Consts.LocalAppDataPath);

            AppLocalEvents = Observable.Merge(Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h).Select(e => (FileEventType.Changed, e.EventArgs)),
                                              Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Created += h, h => watcher.Created -= h).Select(e => (FileEventType.Created, e.EventArgs)),
                                              Observable.FromEventPattern <FileSystemEventHandler, FileSystemEventArgs>(h => watcher.Deleted += h, h => watcher.Deleted -= h).Select(e => (FileEventType.Deleted, e.EventArgs)))
                             .ObserveOn(RxApp.TaskpoolScheduler);
            watcher.EnableRaisingEvents = true;
        }
Esempio n. 2
0
        private void DumpClassOpenResourceInfo(string host, string share)
        {
            Console.WriteLine("\n=== TEST ===");
            var tempPath = Path.LocalToUnc(share);

            Console.WriteLine("\nNetwork.Host.EnumerateOpenResources() from host: [{0}]", tempPath);

            System.IO.Directory.SetCurrentDirectory(tempPath);

            UnitTestConstants.StopWatcher(true);
            var cnt = 0;

            foreach (var openResource in Host.EnumerateOpenResources(host, null, null, false))
            {
                if (UnitTestConstants.Dump(openResource, -11))
                {
                    Console.Write("\n");
                    cnt++;
                }
            }

            Console.WriteLine(UnitTestConstants.Reporter());

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

            Console.WriteLine();
        }
Esempio n. 3
0
        private void DumpClassByHandleFileInfo(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tempPath = Path.GetTempPath("File.GetFileInfoByHandle()-" + Path.GetRandomFileName());

            if (!isLocal)
            {
                tempPath = Path.LocalToUnc(tempPath);
            }

            Console.WriteLine("\nInput File Path: [{0}]", tempPath);

            var stream = File.Create(tempPath);

            stream.WriteByte(1);

            UnitTestConstants.StopWatcher(true);
            var bhfi = File.GetFileInfoByHandle(stream.SafeFileHandle);

            Console.WriteLine(UnitTestConstants.Reporter());

            Assert.IsTrue(UnitTestConstants.Dump(bhfi, -18));

            Assert.AreEqual(System.IO.File.GetCreationTimeUtc(tempPath), bhfi.CreationTimeUtc);
            Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(tempPath), bhfi.LastAccessTimeUtc);
            Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(tempPath), bhfi.LastWriteTimeUtc);

            stream.Close();

            File.Delete(tempPath, true);
            Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed.");
            Console.WriteLine();
        }
Esempio n. 4
0
        public void ConvertModels(string inputDirectoryPath, string outputDirectoryPath, Exporter exporter)
        {
            string outputExtension = exporter.Options.OutputFormat.ToString().ToLower();

            ProgressUpdate("Enumerating files ...", 0, 1);
            List <string> inputFilePaths = EnumerateFiles(inputDirectoryPath, exporter.Options.InputFormat);

            ProgressUpdate("Converting resources ...", 0, 1);
            for (var i = 0; i < inputFilePaths.Count; i++)
            {
                string inputFilePath = inputFilePaths[i];

                string outputFilePath = Path.ChangeExtension(inputFilePath.Replace(inputDirectoryPath, outputDirectoryPath), outputExtension);

                FileManager.TryToCreateDirectory(outputFilePath);

                ProgressUpdate($"Converting: {inputFilePath}", i, inputFilePaths.Count);
                try
                {
                    Root model = LoadModel(inputFilePath, exporter.Options);
                    SaveModel(model, outputFilePath, exporter);
                }
                catch (Exception exc)
                {
                    ConversionError(inputFilePath, outputFilePath, exc);
                }
            }
        }
Esempio n. 5
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. 6
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. 7
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. 8
0
        private void CountData(string dir)
        {
            alarmImageList.Clear();
            foreach (var item in alarmImageListAll)
            {
                if (item.ImagePath.Contains(dir))
                {
                    alarmImageList.Add(item);
                }
            }

            if (alarmImageList.Count == 0)
            {
                MessageWindow.ShowDialog($"目录 [{dir}] 下无告警图片");
                return;
            }

            var view = CollectionViewSource.GetDefaultView(DataContext);

            view?.MoveCurrentToFirst();

            this.Title = $"[{1}/{alarmImageList.Count}] {Path.GetFileName(CurrentAlarmImage()?.ImagePath)}";
            SetSelectedSceneItem(CurrentAlarmImage()?.Scene);
            SetSelectedIncidentItem(CurrentAlarmImage()?.Incident);

            // 更新数据库
            SQLiteCommand cmd = new SQLiteCommand
            {
                Connection  = dbConnection, // 连接数据库
                CommandText = string.Format($"INSERT OR REPLACE INTO DataPathTab(Item, Path) VALUES ('LastImagePath', '{dir}')")
            };

            cmd.ExecuteNonQuery();
        }
Esempio n. 9
0
        public string AddManualDownload(Dictionary <string, byte[]> contents)
        {
            var name = RandomName() + ".zip";

            using (FileStream fs = new FileStream(Path.Combine(DownloadsFolder, name), FileMode.Create))
                using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
                {
                    contents.Do(kv =>
                    {
                        var entry = archive.CreateEntry(kv.Key);
                        using (var os = entry.Open())
                            os.Write(kv.Value, 0, kv.Value.Length);
                    });
                }

            File.WriteAllLines(Path.Combine(DownloadsFolder, name + Consts.MetaFileExtension),

                               new string[]
            {
                "[General]",
                "manualURL=<TESTING>"
            });

            return(name);
        }
Esempio n. 10
0
        public void File_WriteAllLines()
        {
            Console.WriteLine("File.WriteAllLines()");
            Console.WriteLine("\n Default AlphaFS Encoding: [{0}]", NativeMethods.DefaultFileEncoding.EncodingName);

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            var allLines = new[] { UnitTestConstants.TenNumbers, UnitTestConstants.TextHelloWorld, UnitTestConstants.TextGoodbyeWorld, UnitTestConstants.TextUnicode };

            // Create real UTF-8 file.
            File.WriteAllLines(tempFile, allLines, NativeMethods.DefaultFileEncoding);

            // Read filestream contents.
            using (var streamRead = File.OpenText(tempFile))
            {
                var line = streamRead.ReadToEnd();

                Console.WriteLine("\n Created: [{0}] filestream: [{1}]\n\n WriteAllLines content:\n{2}", streamRead.CurrentEncoding.EncodingName, tempFile, line);

                foreach (var line2 in allLines)
                {
                    Assert.IsTrue(line.Contains(line2));
                }
            }

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
Esempio n. 11
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. 12
0
        private void DumpReadAllLines(bool isLocal)
        {
            Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network);
            var tmp      = Path.Combine(Path.GetTempPath(), "File.SetAttributes()-" + Path.GetRandomFileName());
            var tempPath = isLocal ? tmp : Path.LocalToUnc(tmp);

            // Create file and append text.
            var tempFile = Path.GetTempFileName();

            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(tempFile, createText);

            Console.WriteLine("\nFile.ReadAllLines()\n");
            var readText = File.ReadAllLines(tempFile);

            foreach (var s in readText)
            {
                Console.WriteLine("\t{0}", s);
                Assert.IsTrue(createText.Contains(s));
            }

            Console.WriteLine("\nFile.ReadLines()\n");
            foreach (var s in File.ReadLines((tempFile)))
            {
                Console.WriteLine("\t{0}", s);
                Assert.IsTrue(createText.Contains(s));
            }

            File.Delete(tempFile, true);
            Assert.IsFalse(File.Exists(tempFile), "Cleanup failed: File should have been removed.");
        }
Esempio n. 13
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. 14
0
        private async Task DownloadMissingArchives(List <Archive> missing, bool download = true)
        {
            if (download)
            {
                foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
                {
                    var outputPath = Path.Combine(DownloadFolder, a.Name);
                    await a.State.Download(a, outputPath);
                }
            }

            await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
            .PMap(Queue, async archive =>
            {
                Info($"Downloading {archive.Name}");
                var outputPath = Path.Combine(DownloadFolder, archive.Name);

                if (download)
                {
                    if (outputPath.FileExists())
                    {
                        File.Delete(outputPath);
                    }
                }

                return(await DownloadArchive(archive, download));
            });
        }
Esempio n. 15
0
            public IncludeZEditPatches(Compiler 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.Warning(
                        $"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(compiler.MO2Folder, "mods", m.Key.name, m.Key.filename),
                        m => m.First());
            }
Esempio n. 16
0
        public void AlphaFS_Host_GetHostShareFromPath()
        {
            Console.WriteLine("Network.Host.GetHostShareFromPath\n");

            var uncPath      = UnitTestConstants.SysRoot32;
            var hostAndShare = Host.GetHostShareFromPath(uncPath);

            Console.WriteLine("Input local path: [{0}]", uncPath);
            Assert.AreEqual(null, hostAndShare);

            uncPath      = Path.GetLongPath(UnitTestConstants.SysRoot32);
            hostAndShare = Host.GetHostShareFromPath(uncPath);
            Console.WriteLine("Input local path: [{0}]", uncPath);
            Assert.AreEqual(null, hostAndShare);

            Console.WriteLine();

            uncPath      = Path.LocalToUnc(UnitTestConstants.SysRoot32);
            hostAndShare = Host.GetHostShareFromPath(uncPath);
            Console.WriteLine("Input UNC path: [{0}]", uncPath);
            Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
            Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

            Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());

            Console.WriteLine();

            uncPath      = Path.LocalToUnc(UnitTestConstants.SysRoot32, true);
            hostAndShare = Host.GetHostShareFromPath(uncPath);
            Console.WriteLine("Input UNC path: [{0}]", uncPath);
            Console.WriteLine("\tHost : [{0}]", hostAndShare[0]);
            Console.WriteLine("\tShare: [{0}]", hostAndShare[1]);

            Assert.AreEqual(Environment.MachineName, hostAndShare[0].ToUpperInvariant());
        }
Esempio n. 17
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. 18
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(!string.IsNullOrWhiteSpace(gmCn));
                Assert.IsTrue(!string.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. 19
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. 20
0
 public static string FileHash(this string file, bool nullOnIOError = false)
 {
     try
     {
         var hash = new xxHashConfig();
         hash.HashSizeInBits = 64;
         hash.Seed           = 0x42;
         using (var fs = File.OpenRead(file))
         {
             var config = new xxHashConfig();
             config.HashSizeInBits = 64;
             using (var f = new StatusFileStream(fs, $"Hashing {Path.GetFileName(file)}"))
             {
                 var value = xxHashFactory.Instance.Create(config).ComputeHash(f);
                 return(value.AsBase64String());
             }
         }
     }
     catch (IOException ex)
     {
         if (nullOnIOError)
         {
             return(null);
         }
         throw ex;
     }
 }
Esempio n. 21
0
 private async Task InstallIncludedFiles()
 {
     Info("Writing inline files");
     await ModList.Directives
     .OfType <InlineFile>()
     .PMap(Queue, directive =>
     {
         Status($"Writing included file {directive.To}");
         var outPath = Path.Combine(OutputFolder, directive.To);
         if (File.Exists(outPath))
         {
             File.Delete(outPath);
         }
         if (directive is RemappedInlineFile)
         {
             WriteRemappedFile((RemappedInlineFile)directive);
         }
         else if (directive is CleanedESM)
         {
             GenerateCleanedESM((CleanedESM)directive);
         }
         else
         {
             File.WriteAllBytes(outPath, LoadBytesFromPath(directive.SourceDataID));
         }
     });
 }
Esempio n. 22
0
        private void GenerateCleanedESM(CleanedESM directive)
        {
            var filename = Path.GetFileName(directive.To);
            var gameFile = Path.Combine(GameFolder, "Data", filename);

            Info($"Generating cleaned ESM for {filename}");
            if (!File.Exists(gameFile))
            {
                throw new InvalidDataException($"Missing {filename} at {gameFile}");
            }
            Status($"Hashing game version of {filename}");
            var sha = gameFile.FileHash();

            if (sha != directive.SourceESMHash)
            {
                throw new InvalidDataException(
                          $"Cannot patch {filename} from the game folder because the hashes do not match. Have you already cleaned the file?");
            }

            var patchData = LoadBytesFromPath(directive.SourceDataID);
            var toFile    = Path.Combine(OutputFolder, directive.To);

            Status($"Patching {filename}");
            using (var output = File.Open(toFile, FileMode.Create))
                using (var input = File.OpenRead(gameFile))
                {
                    BSDiff.Apply(input, () => new MemoryStream(patchData), output);
                }
        }
Esempio n. 23
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, "mods", v);

                        if (!Directory.Exists(mod))
                        {
                            Directory.CreateDirectory(mod);
                        }
                    });
                }
            });
        }
Esempio n. 24
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. 25
0
        public void DriveConnection()
        {
            Console.WriteLine("Network.Host.DriveConnection()");

            #region Using last available drive to share

            string share = Path.LocalToUnc(LocalHostShare);
            bool   connectOk;
            Console.WriteLine("\nUsing IDisposable class.");
            try
            {
                StopWatcher(true);
                using (Host.DriveConnection connection = new Host.DriveConnection(share))
                {
                    Console.WriteLine("\nUsing DriveConnection(): [{0}] to: [{1}]\n\n\t{2}\n", connection.LocalName, share, Reporter(true));
                    connectOk = true;
                }
            }
            catch (Exception ex)
            {
                connectOk = false;
                Console.WriteLine("\nFailed DriveConnection() to: [{0}]", share);
                Console.WriteLine("\nCaught Exception: [{0}]", ex.Message.Replace(Environment.NewLine, "  "));
            }

            Assert.IsTrue(connectOk);

            #endregion // Using last available drive to share
        }
Esempio n. 26
0
        public static string FindzEditPath(Compiler compiler)
        {
            var executables = compiler.MO2Ini.customExecutables;

            if (executables.size == null)
            {
                return(null);
            }

            foreach (var idx in Enumerable.Range(1, int.Parse(executables.size)))
            {
                var path = (string)executables[$"{idx}\\binary"];
                if (path == null)
                {
                    continue;
                }

                if (path.EndsWith("zEdit.exe"))
                {
                    return(Path.GetDirectoryName(path));
                }
            }

            return(null);
        }
Esempio n. 27
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. 28
0
        public async Task DownloadMissingArchives(List <Archive> missing, bool download = true)
        {
            if (download)
            {
                foreach (var a in missing.Where(a => a.State.GetType() == typeof(ManualDownloader.State)))
                {
                    var outputPath = DownloadFolder.Combine(a.Name);
                    await a.State.Download(a, outputPath);
                }
            }

            await missing.Where(a => a.State.GetType() != typeof(ManualDownloader.State))
            .PMap(Queue, async archive =>
            {
                Info($"Downloading {archive.Name}");
                var outputPath = DownloadFolder.Combine(archive.Name);

                if (download)
                {
                    if (outputPath.Exists)
                    {
                        var origName  = Path.GetFileNameWithoutExtension(archive.Name);
                        var ext       = Path.GetExtension(archive.Name);
                        var uniqueKey = archive.State.PrimaryKeyString.StringSha256Hex();
                        outputPath    = DownloadFolder.Combine(origName + "_" + uniqueKey + "_" + ext);
                        outputPath.Delete();
                    }
                }

                return(await DownloadArchive(archive, download, outputPath));
            });
        }
Esempio n. 29
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);
        }
        public static string MakePartFilename(string path, int part)
        {
            string dirName   = Path.GetDirectoryName(path);
            string baseName  = Path.GetFileNameWithoutExtension(path);
            string extension = Path.GetExtension(path);

            return($"{dirName}/{baseName}_{part}{extension}");
        }