/// <summary>
        /// Unzips a compressed file
        /// </summary>
        public void UnzipFile()
        {
            if (IsSourcePathRelative != null && IsSourcePathRelative.ToUpper() == Constants.YES)
            {
                SourceFile = Environment.CurrentDirectory + @"\FitNesseRoot\" + SourceFile;
            }

            if (!File.Exists(SourceFile))
            {
                throw new ApplicationException(string.Format("Source file {0} does not exist!", SourceFile));
            }

            if (!SourceFile.EndsWith(".zip") && !SourceFile.EndsWith(".gz"))
            {
                throw new ApplicationException("SourceFile is not of the right file type.  Can only uncompress .zip or .gz files");
            }

            //CompressionLib compressionLib = new CompressionLib();
            //compressionLib.Extract(SourceFile, NewDirectoryName);
        }
Exemplo n.º 2
0
        public static void BuildArchive(string SourceDir, ModEntry metaData, string outputFilePath)
        {
            Debug.LogLine($"[BuildArchive] {SourceDir}.");
            HashingExtended.ReadDictionary();
            string buildDir = Directory.GetCurrentDirectory() + "\\_build";

            try
            {
                if (Directory.Exists(buildDir))
                {
                    Directory.Delete(buildDir, true);
                }
            }
            catch
            {
                Debug.LogLine(string.Format("[BuildArchive] preexisting _build directory could not be deleted: {0}", buildDir));
            }

            Directory.CreateDirectory("_build");

            List <string> fpkFiles = Directory.GetFiles(SourceDir, "*.fpk*", SearchOption.AllDirectories).ToList();

            for (int i = fpkFiles.Count - 1; i >= 0; i--)
            {
                string fpkFile = fpkFiles[i].Substring(SourceDir.Length + 1);
                if (!fpkFile.StartsWith("Assets"))
                {
                    string updatedFileName = HashingExtended.UpdateName(fpkFile);
                    if (updatedFileName != null)
                    {
                        updatedFileName = SourceDir + updatedFileName.Replace('/', '\\');
                        if (fpkFiles.Contains(updatedFileName))
                        {
                            fpkFiles.Remove(fpkFiles[i]);
                        }
                    }
                }
            }

            List <string> fpkFolders = ListFpkFolders(SourceDir);

            for (int i = fpkFolders.Count - 1; i >= 0; i--)
            {
                string fpkFolder = fpkFolders[i].Substring(SourceDir.Length + 1);
                if (!fpkFolder.StartsWith("Assets"))
                {
                    string updatedFileName = HashingExtended.UpdateName(fpkFolder.Replace("_fpk", ".fpk"));
                    if (updatedFileName != null)
                    {
                        updatedFileName = SourceDir + updatedFileName.Replace('/', '\\');
                        if (fpkFolders.Contains(updatedFileName.Replace(".fpk", "_fpk")) || fpkFiles.Contains(updatedFileName))
                        {
                            MessageBox.Show(string.Format("{0} was not packed or added to the build, because {1} (the unhashed filename of {0}) already exists in the mod directory.", Path.GetFileName(fpkFolders[i]), Path.GetFileName(updatedFileName)));
                            fpkFolders.Remove(fpkFolders[i]);
                        }
                    }
                }
            }

            // check for FPKs that must be built and build
            metaData.ModFpkEntries = new List <ModFpkEntry>();
            List <string> builtFpks = new List <string>();

            foreach (string FpkFullDir in fpkFolders)
            {
                foreach (ModFpkEntry fpkEntry in BuildFpk(FpkFullDir, SourceDir))
                {
                    metaData.ModFpkEntries.Add(fpkEntry);
                    if (!builtFpks.Contains(fpkEntry.FpkFile))
                    {
                        builtFpks.Add(fpkEntry.FpkFile);
                    }
                }
            }

            // check for other FPKs and build fpkentry data
            foreach (string SourceFile in Directory.GetFiles(SourceDir, "*.fpk*", SearchOption.AllDirectories))
            {
                //tex chunk0\Assets\tpp\pack\collectible\common\col_common_tpp_fpk\Assets\tpp\pack\resident\resident00.fpkl is the only fpkl, don't know what a fpkl is, but gzcore crashes on it.
                if (SourceFile.EndsWith(".fpkl") || SourceFile.EndsWith(".xml"))
                {
                    continue;
                }
                string FileName = Tools.ToQarPath(SourceFile.Substring(SourceDir.Length));
                if (!builtFpks.Contains(FileName))
                {
                    // unpack FPK and build FPK list
                    string fpkDir     = Tools.ToWinPath(FileName.Replace(".fpk", "_fpk"));
                    string fpkFullDir = Path.Combine(SourceDir, fpkDir);
                    if (!Directory.Exists(fpkFullDir))
                    {
                        GzsLib.ExtractArchive <FpkFile>(SourceFile, fpkFullDir);
                    }

                    var fpkContents = GzsLib.ListArchiveContents <FpkFile>(SourceFile);
                    foreach (string file in fpkContents)
                    {
                        if (!GzsLib.IsExtensionValidForArchive(file, fpkDir))
                        {
                            Debug.LogLine($"[BuildArchive] {file} is not a valid file for a {Path.GetExtension(fpkDir)} archive.");
                            continue;
                        }

                        metaData.ModFpkEntries.Add(new ModFpkEntry()
                        {
                            FilePath    = file,
                            FpkFile     = FileName,
                            ContentHash = Tools.GetMd5Hash(Path.Combine(SourceDir, fpkDir, Tools.ToWinPath(file)))
                        });
                    }
                }
            }

            // build QAR entries
            List <string> qarFiles = ListQarFiles(SourceDir);

            for (int i = qarFiles.Count - 1; i >= 0; i--)
            {
                string qarFile = qarFiles[i].Substring(SourceDir.Length + 1);
                if (!qarFile.StartsWith("Assets"))
                {
                    string updatedQarName = HashingExtended.UpdateName(qarFile);
                    if (updatedQarName != null)
                    {
                        updatedQarName = SourceDir + updatedQarName.Replace('/', '\\');
                        if (qarFiles.Contains(updatedQarName))
                        {
                            MessageBox.Show(string.Format("{0} was not added to the build, because {1} (the unhashed filename of {0}) already exists in the mod directory.", Path.GetFileName(qarFiles[i]), Path.GetFileName(updatedQarName)));
                            qarFiles.Remove(qarFiles[i]);
                        }
                    }
                }
            }

            metaData.ModQarEntries = new List <ModQarEntry>();
            foreach (string qarFile in qarFiles)
            {
                string subDir      = qarFile.Substring(0, qarFile.LastIndexOf("\\")).Substring(SourceDir.Length).TrimStart('\\'); // the subdirectory for XML output
                string qarFilePath = Tools.ToQarPath(qarFile.Substring(SourceDir.Length));

                if (!Directory.Exists(Path.Combine("_build", subDir)))
                {
                    Directory.CreateDirectory(Path.Combine("_build", subDir));                                                    // create file structure
                }
                File.Copy(qarFile, Path.Combine("_build", Tools.ToWinPath(qarFilePath)), true);

                ulong hash = Tools.NameToHash(qarFilePath);
                metaData.ModQarEntries.Add(new ModQarEntry()
                {
                    FilePath    = qarFilePath,
                    Compressed  = qarFile.EndsWith(".fpk") || qarFile.EndsWith(".fpkd") ? true : false,
                    ContentHash = Tools.GetMd5Hash(qarFile), Hash = hash
                });
            }

            //tex build external entries
            metaData.ModFileEntries = new List <ModFileEntry>();
            var externalFiles = ListExternalFiles(SourceDir);

            foreach (string externalFile in externalFiles)
            {
                string subDir           = externalFile.Substring(0, externalFile.LastIndexOf("\\")).Substring(SourceDir.Length).TrimStart('\\'); // the subdirectory for XML output
                string externalFilePath = Tools.ToQarPath(externalFile.Substring(SourceDir.Length));

                if (!Directory.Exists(Path.Combine("_build", subDir)))
                {
                    Directory.CreateDirectory(Path.Combine("_build", subDir));                                                    // create file structure
                }
                File.Copy(externalFile, Path.Combine("_build", Tools.ToWinPath(externalFilePath)), true);
                string strip = "/" + ExternalDirName;
                if (externalFilePath.StartsWith(strip))
                {
                    externalFilePath = externalFilePath.Substring(strip.Length);
                }
                //ulong hash = Tools.NameToHash(qarFilePath);
                metaData.ModFileEntries.Add(new ModFileEntry()
                {
                    FilePath = externalFilePath, ContentHash = Tools.GetMd5Hash(externalFile)
                });
            }

            metaData.SBVersion.Version = Application.ProductVersion;

            metaData.SaveToFile("_build\\metadata.xml");

            // build archive
            FastZip zipper = new FastZip();

            zipper.CreateZip(outputFilePath, "_build", true, "(.*?)");

            try
            {
                Directory.Delete("_build", true);
            }
            catch (Exception e)
            {
                Debug.LogLine(string.Format("[BuildArchive] _build directory could not be deleted: {0}", e.ToString()));
            }
        }
Exemplo n.º 3
0
        protected override void ProcessRecord()
        {
            #if USING_RESTABLE_CMDLET
            if (Remote)
            {
                ProcessRecordViaRest();
                return;
            }
#endif
            System.Environment.CurrentDirectory = (SessionState.PSVariable.GetValue("pwd") ?? "").ToString();

            var replacements = Overrides != null?Overrides.Keys.Cast <object>().ToDictionary(k => new Regex(k.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase), k => Overrides[k].ToString()) : new Dictionary <Regex, string>();

            using (dynamic ps = Runspace.DefaultRunspace.Dynamic()) {
                Project project = null;
                string  tmpFile = null;

                try {
                    SourceFile = SourceFile.GetFullPath();
                    OutputFile = OutputFile.GetFullPath();

                    if (!File.Exists(SourceFile))
                    {
                        throw new ClrPlusException("Source file '{0}' does not exist.".format(SourceFile));
                    }

                    if (!SourceFile.EndsWith(".vcxproj", StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new ClrPlusException("Source file '{0}' does not have a .vcxproj extension.".format(SourceFile));
                    }

                    if (Force && File.Exists(OutputFile))
                    {
                        OutputFile.TryHardToDelete();
                    }

                    if (File.Exists(OutputFile))
                    {
#if DEBUG
                        OutputFile.TryHardToDelete();
#else
                        throw new ClrPlusException("Destination file '{0}' already exists.".format(OutputFile));
#endif
                    }

                    var text = System.IO.File.ReadAllText(SourceFile);
                    text = text.Replace("xmlns", "notxmlns");

                    var doc = XElement.Parse(text);

                    var elements = from e in doc.Descendants("Import") where ((string)e.Attribute("Project")).IndexOf("VCTargetsPath") > -1 select e;
                    elements.Remove();
                    elements = from e in doc.Descendants("Import") where ((string)e.Attribute("Project")).ToLower().IndexOf("microsoft.cpp") > -1 select e;
                    elements.Remove();

                    text    = doc.ToString().Replace("notxmlns", "xmlns");
                    tmpFile = SourceFile + ".tmp";

                    File.WriteAllText(tmpFile, text);

                    var proc = AsyncProcess.Start(
                        new ProcessStartInfo(MSBuildUtility.MsbuildExe.Path, "/pp /p:Configuration=Debug;Platform=Win32 {0}".format(tmpFile))
                    {
                        WindowStyle = ProcessWindowStyle.Normal,
                    });
                    proc.WaitForExit();

                    // get the processed script.
                    text = proc.StandardOutput.Aggregate((c, e) => c + "\r\n" + e);
                    text = text.Replace("xmlns", "notxmlns");

                    // now we can maniuplate the whole source document
                    doc = XElement.Parse(text);

                    // use our cmdlet to make the project file.
                    ps.NewVCProject(OutputFile).Wait();

                    var outputFolder          = Path.GetDirectoryName(OutputFile);
                    var originalProjectFolder = Path.GetDirectoryName(SourceFile);
                    Environment.CurrentDirectory = originalProjectFolder;

                    project = new Project(OutputFile);

                    doc.CopyItemsToProject(project, outputFolder, "ClCompile", "C Source Files");
                    doc.CopyItemsToProject(project, outputFolder, "ClInclude", "C Header Files");
                    doc.CopyItemsToProject(project, outputFolder, "ResourceCompile", "Resource Files");

                    using (var local = CurrentTask.Local.Events) {
                        var propertiesReferenced = new Queue <string>();
                        var propertiesFinished   = new HashSet <string>();

                        local.Events += new ProjectExtensions.PropertyReferenced(name => {
                            if (!propertiesReferenced.Contains(name) && !propertiesFinished.Contains(name))
                            {
                                propertiesReferenced.Enqueue(name);
                            }
                        });

                        local.Events += new ProjectExtensions.CustomReplacement(value => {
                            foreach (var rx in replacements.Keys)
                            {
                                value = rx.Replace(value, replacements[rx]);
                            }
                            return(value);
                        });

                        var configurations = doc.GetConfigurations().ToArray();

                        // remove the common one from the peers
                        var conditionedConfigurations = configurations.Where(each => each.Condition.Is()).ToArray();

                        // common stuff
                        configurations.Where(each => string.IsNullOrEmpty(each.Condition)).ProcessConfiguration(project, "", outputFolder);


                        conditionedConfigurations.ProcessConfiguration(project, "", outputFolder);

                        conditionedConfigurations.Where(each => each.IsDebug).ProcessConfiguration(project, "$(IS_DEBUG)", outputFolder);
                        conditionedConfigurations.Where(each => each.IsRelease).ProcessConfiguration(project, "$(IS_RELEASE)", outputFolder);

                        conditionedConfigurations.Where(each => each.IsStatic).ProcessConfiguration(project, "$(IS_STATIC) Or $(IS_LTCG)", outputFolder);
                        conditionedConfigurations.Where(each => each.IsDynamic).ProcessConfiguration(project, "$(IS_DYNAMIC)", outputFolder);

                        // conditionedConfigurations.Where(each => !each.IsStatic && each.IsLibrary).ProcessConfiguration(project, "$(IS_DYNAMIC) And $(IS_LIBRARY)", outputFolder);
                        // conditionedConfigurations.Where(each => !each.IsDynamic && each.IsLibrary).ProcessConfiguration(project, "($(IS_STATIC) Or $(IS_LTCG)) And $(IS_LIBRARY)", outputFolder);

                        conditionedConfigurations.Where(each => each.IsLibrary).ProcessConfiguration(project, "", outputFolder);
                        conditionedConfigurations.Where(each => each.IsApplication).ProcessConfiguration(project, "", outputFolder);

                        // if this is an app, set the configuration type.
                        if (conditionedConfigurations.Any(each => each.IsApplication))
                        {
                            var pgpe = project.FindOrCreatePropertyGroup("Globals");
                            pgpe.Properties.FirstOrDefault(each => each.Name == "ConfigurationType").Value = "Application";
                        }

                        // now do the referenced variables

                        while (propertiesReferenced.Any())
                        {
                            var propRefd = propertiesReferenced.Dequeue();
                            propertiesFinished.Add(propRefd);

                            configurations.Where(each => string.IsNullOrEmpty(each.Condition)).ProcessReferenceVariables(project, "", propRefd);


                            conditionedConfigurations.ProcessReferenceVariables(project, "", propRefd);

                            conditionedConfigurations.Where(each => each.IsDebug).ProcessReferenceVariables(project, "$(IS_DEBUG)", propRefd);
                            conditionedConfigurations.Where(each => each.IsRelease).ProcessReferenceVariables(project, "$(IS_RELEASE)", propRefd);

                            conditionedConfigurations.Where(each => each.IsStatic).ProcessReferenceVariables(project, "$(IS_STATIC) Or $(IS_LTCG)", propRefd);
                            conditionedConfigurations.Where(each => each.IsDynamic).ProcessReferenceVariables(project, "$(IS_DYNAMIC)", propRefd);

                            conditionedConfigurations.Where(each => each.IsLibrary).ProcessReferenceVariables(project, "", propRefd);
                            conditionedConfigurations.Where(each => each.IsApplication).ProcessReferenceVariables(project, "", propRefd);
                        }
                        // more likely, we'd like the customsettings to be in the opposite order.
                        var customSettings = project.FindOrCreatePropertyGroup("CustomSettings");
                        var xml            = customSettings.XmlElement();
                        var nodes          = xml.ChildNodes.Cast <XmlElement>().Reverse().ToArray();
                        customSettings.RemoveAllChildren();

                        foreach (var i in nodes)
                        {
                            xml.AppendChild(i);
                        }
                    }

                    project.FindOrCreateItemGroup("C Source Files").Label = "";
                    project.FindOrCreateItemGroup("C Header Files").Label = "";
                    project.FindOrCreateItemGroup("Resource Files").Label = "";


                    project.Save();
                } finally {
                    if (project != null && ProjectCollection.GlobalProjectCollection.LoadedProjects.Contains(project))
                    {
                        ProjectCollection.GlobalProjectCollection.UnloadProject(project);
                    }

#if DEBUG
#else
                    tmpFile.TryHardToDelete();
#endif
                }
            }
        }
Exemplo n.º 4
0
        internal void Install(Progress Progress, ProgressBar ProgressBar)
        {
            List <string> Names = new List <string>();

            using (FileStream Stream = OpenRead($@"{Path}\mod.info"))
            {
                ReadString(Stream);
                byte[] Buffer = new byte[4];
                Stream.Read(Buffer, 0, 4);
                int ItemsCount = ToInt32(Buffer, 0);
                for (int Iterator = 0; Iterator < ItemsCount; Iterator++)
                {
                    Names.Add(ReadString(Stream));
                }
            }
            Dictionary <string, string> Meta = new Dictionary <string, string>();

            using (FileStream Stream = OpenRead($@"{Path}\modmeta.info"))
            {
                byte[] Buffer = new byte[4];
                Stream.Read(Buffer, 0, 4);
                int ItemsCount = ToInt32(Buffer, 0);
                for (int Iterator = 0; Iterator < ItemsCount; Iterator++)
                {
                    Meta[ReadString(Stream)] = ReadString(Stream);
                }
            }
            DeletePath(ModsPath);
            DeletePath(ModFilePath);
            string FilesPath           = $@"{Path}\WindowsNoEditor";
            IEnumerable <string> Files = Directory.EnumerateFiles(FilesPath, "*", SearchOption.AllDirectories);

            if (!(Progress is null))
            {
                Progress.Total = Files.Count();
                Current.Dispatcher.Invoke(ProgressBar.SetNumericMode);
            }
            foreach (string SourceFile in Files)
            {
                string DestinationFile = SourceFile.Replace(FilesPath, ModsPath);
                Directory.CreateDirectory(System.IO.Path.GetDirectoryName(DestinationFile));
                if (SourceFile.EndsWith(".z"))
                {
                    using (FileStream Reader = OpenRead(SourceFile), Writer = Create(DestinationFile.Substring(0, DestinationFile.Length - 2)))
                    {
                        long Size = new ChunkMeta(Reader).UncompressedSize;
                        if (Size == 1641380927L)
                        {
                            Size = 131072L;
                        }
                        else if (Size == 0L)
                        {
                            Size = 1L;
                        }
                        int         ChunksCount = (int)((new ChunkMeta(Reader).UncompressedSize + Size - 1L) / Size);
                        ChunkMeta[] ChunkSizes  = new ChunkMeta[ChunksCount];
                        for (int Iterator = 0; Iterator < ChunksCount; Iterator++)
                        {
                            ChunkSizes[Iterator] = new ChunkMeta(Reader);
                        }
                        foreach (ChunkMeta ChunkSize in ChunkSizes)
                        {
                            new ZlibDecompressor(Reader, Writer, ChunkSize.CompressedSize, ChunkSize.UncompressedSize).DecompressChunk();
                        }
                    }
                }
                else if (!SourceFile.EndsWith(".uncompressed_size"))
                {
                    Copy(SourceFile, DestinationFile, true);
                }
                if (!(Progress is null))
                {
                    Progress.Increase();
                }
            }
            using (FileStream Stream = Create(ModFilePath))
            {
                Stream.Write(GetBytes(ID), 0, 8);
                WriteString(Stream, Details.Status == 1 ? Details.Name : "ModName");
                WriteString(Stream, $"../../../ShooterGame/Content/Mods/{ID}");
                Stream.Write(GetBytes(Names.Count), 0, 4);
                foreach (string Name in Names)
                {
                    WriteString(Stream, Name);
                }
                Stream.Write(GetBytes(4280483635U), 0, 4);
                Stream.Write(GetBytes(2), 0, 4);
                Stream.WriteByte((byte)(Meta.ContainsKey("ModType") ? int.Parse(Meta["ModType"]) : 0));
                Stream.Write(GetBytes(Meta.Count), 0, 4);
                foreach (KeyValuePair <string, string> Item in Meta)
                {
                    WriteString(Stream, Item.Key);
                    WriteString(Stream, Item.Value);
                }
            }
            IsInstalled = true;
        }