Files
UnrealEngineUWP/Engine/Source/Programs/AutomationTool/AutomationUtils/CommandUtils.cs
Ben Marsh 348616bd78 Copying //UE4/Release-Staging-4.19 to //UE4/Dev-Main (Source: //UE4/Release-4.19 @ 3873914)
============================
  MAJOR FEATURES & CHANGES
============================

Change 3873906 by Dan.Oconnor

	Revised fix for preventing delegate functions from appearing in context menu when using the compilation manager - needed to run after CallDelegateHandler changed statement type

	#jira UE-51726

Change 3873614 by Dan.Oconnor

	Prevent delegate functions from appearing in context menu when using the compilation manager and prevent crash if such a function is somehow compiled

	#jira UE-51726

Change 3873428 by Ben.Zeigler

	#jira UE-54753 Fix class pin on SpawnActorFromClass to correctly support browse. It was inherting from the wrong pin widget
	Copy of 3873408

Change 3873083 by Ethan.Geller

	[4.19]#jira UE-54865 fix seconds -> milliseconds conversion issue. #rb aaron.mcleran #lockdown cristina.riveron

Change 3872714 by Dan.Oconnor

	Further revise fix for UE-53840, mistakenly reverted to old behavior when compiling synchronously
	#jira UE-53840

Change 3872648 by Ben.Zeigler

	#jira UE-54845 Fix crash in NextDebugTarget when there are no valid debug targets
	Copy of CL #3872636

Change 3872500 by Arne.Schober

	Back out changelist 3870283
	#jira UE-54838

Change 3872412 by Mark.Satterthwaite

	Remove now unnecessary r.Metal.ManualVertexFetch from the device profiles.

	#jira UE-54853

Change 3872313 by Martin.Wilson

	Add UI to Live Link Client to warn live link users about background performance throttling

	#jira none

Change 3872272 by Martin.Wilson

	Fix crash when clearing a skeletal mesh on a skeletal mesh component with an active Post Process Anim Instance

	#jira none

Change 3872238 by Mark.Satterthwaite

	Duplicate CL #3871025
	Make Manual Vertex Fetch a property of the shader platform for Metal - only the desktop platforms (METAL SM5/SM5_NoTess/MRT) will use manual vertex fetch. The mobile platforms use vertex descriptors. Prevents problems with cooked versions of games not working properly on Metal due to a mismatch between the runtime's Manual-Vertex-Fetch state versus the state used by the cooker when compiling shaders.

	#jira UE-54843

Change 3872087 by Yasiman.Ahsani

	Adding Python, libdisasm, musl, and LSS licenses.

	#JIRA n/a - adding licenses for new TPS

Change 3872037 by Ben.Marsh

	BuildGraph: Add a task for compiling MSBuild projects.

	#jira

Change 3871934 by Lina.Halper

	#jira: UE-54703

Change 3871595 by Michael.Trepka

	Fixed a problem with Mac editor not exiting with error code returned from GuardedMain function

	#jira UE-54830

Change 3870829 by Joe.Barnes

	Fix unintentional change to PhysX libs used in Debug builds.

	#jira ue-54817

Change 3870820 by Nick.Atamas

	Copying //Tasks/UE4/Dev-VR-4.19a@3870772 to Release-4.19 (//UE4/Release-4.19)

	#jira UE-54816

Change 3870755 by Chance.Ivey

	Min Android version set - should fix camera permissions issue found in #JIRA UE-54024 #rb none #fyi nick.atamas

Change 3870547 by Krzysztof.Narkowicz

	Fixed FreezeRendering on non editor builds: ComputeAndMarkRelevanceForViewParallel was calling FrozenMatricesGuard on multiple threads, reading and writing view matrices state in parallel.

	#jira UE-53640

Change 3870546 by Krzysztof.Narkowicz

	Fixed tesselation shader tex/uniform initialization in OpenGL3/4 path

	#jira UE-54471

Change 3870284 by Ben.Zeigler

	#jira UE-54583 Fix issue where loading multiple already loaded assets via Async Load Asset node could return the wrong asset on the loaded pin. The assign variable node was happening at a slightly wrong time
	Copy of CL #3870279

Change 3870283 by Arne.Schober

	SafeRelease SRVs that might be hold by the Vertexfactories (maybe due to indirect use in GlobalResources)
	Note that the VFs are not owners of the data, e.g the underlying Buffers might be released before this and this reference counting should be uneccessary

	#jira none

Change 3870098 by Ben.Marsh

	Fix OptimizeCode = CodeOptimization.Always causing compile errors in Linux debug builds. bUseInlining was not set correctly on the global compile environment used to build shared PCHs. Also fixed other settings not being propogated down from the target correctly.

	#jira UE-53855

Change 3870013 by Ben.Marsh

	UBT: Add an error if a user attempts to clean a target through hot-reload, rather than just failing to delete DLLs because they are locked.

	#jira UE-54179

Change 3870010 by Ben.Marsh

	UBT: Add an option to format output messages in a form that can be parsed by MSBuild. Prevents errors showing as "EXEC: Error:", and displays them correctly in the error list window.

	#jira

Change 3869814 by Ben.Marsh

	UBT: Unify command line arguments to use -Name=Value syntax. -Module <Name>, -ModuleWithSuffix <Name> <Suffix>, -Plugin <Path> and -Receipt <Path> are no longer supported.

	Also remove the RemoteRoot option, which was not used anywhere.

	#jira

Change 3869786 by Martin.Wilson

	Fix Live Link Remove Source button not working

	#Jira UE-54652

Change 3869660 by Martin.Wilson

	Fix missing message bus sources in the live link client (not repolling for new sources)

	#Jira UE-54712

Change 3869659 by Guillaume.Abadie

	Fixes SimpleComposure's BP_AdvancedCompositing keep allocating memory every frame.

	Credits for fixing the issue to Ron Radeztsk.

	#jira UE-54780

Change 3869401 by Lauren.Ridge

	Adding to the conditional in FindAllAncestorNamedSlotHostWidgetsForContent

	#jira UE-51470

Change 3869384 by Brandon.Schaefer

	Open the project in the explorer when NullSourceCodeAccess is done creating the project

	#jira UE-54630

Change 3869308 by Ben.Marsh

	PR #4452: Fixed FindFilesRecursively in IPlatformFilePak (Contributed by user37337)


	#jira UE-54568

Change 3869265 by Martin.Wilson

	Fix crash and subsequently found issues with unloading/reloading Maya Live Link plugin
	-Crash on reload due to core code getting reinitialize, made this a one time only thing (as Maya never gets rid of the module from memory)
	-Added manual ticking of FTicker, allows message bus objects to be cleaned up properly (cannot do this as part of normal flow as it is in engine code which we dont have)
	-rebuild binaries for Engine/Extras

	#Jira UE-54643

Change 3869206 by Benn.Gallagher

	Fixed crash updating clothing paint mode after tab spawners have been destroyed by the hosting application.

	#jira UE-54116

Change 3869064 by Benn.Gallagher

	Resolved skeletal mesh data changes and clothing section disable changes after collision. Re-added ability to disable sections at the mesh level and removed the ability to strip editor sections as these are required for a number of other features to correctly function.

	#jira UE-52557

Change 3869062 by Guillaume.Abadie

	Fixes "dynamic resolution is not supported on this platform" warning message being always visible.

	#jira UE-54655

Change 3868202 by Lauren.Ridge

	Fix for assert on expanding vector param in layered material
	#jira UE-54737

Change 3868161 by zak.parrish

	Replacing FaceARDebugUI with a blank UI until a new one can be created, due to a crash bug. #rb none #JIRA UE-54639

Change 3867750 by Ethan.Geller

	[4.19] #jira UE-54725 Fix for Envelope attack and release values not being properly set on Synth Components #rb aaron.mcleran #lockdown cristina.riveron

Change 3867657 by Lauren.Ridge

	Adding if with editor wrapper to new function
	#jira cis fix

Change 3867646 by Aaron.McLeran

	#jira UE-53867 Access violation on Switch when playing sound with specified time out of range

Change 3867340 by Lauren.Ridge

	Fixes to Material Layers from 4.19 preview feedback
	-Need to pass through base attributes better/have better default nodes in layer (optional Example Layers and Blends checkbox now enables this in Experimental Settings)
	-Parent in function should be editable
	-Enforce only two layers in a blend
	-Mat layer should warn if it has incorrect output in the layer itself
	-Enforce not being able to delete outputs
	-Warn about creating a MAL node inside a function

	#jira UETOOL-1312

Change 3867317 by Aaron.McLeran

	#jira UE-53867 Access violation on Switch when playing sound with specified time out of range

Change 3867000 by Lauren.Ridge

	Fix for folder favorites possibly becoming very large
	#jira UE-54704

Change 3866892 by Martin.Wilson

	Fix crash if clicking ok on message bus add source without having a source selected

	#jira UE-54572

Change 3866391 by Matt.Kuhlenschmidt

	Fix static analysis

	#jira UE-53379

Change 3866241 by Ryan.Vance

	#jira UE-54681
	Fixed missing Vulkan texture GetNativeResource implementation that was lost in a bad merge.

Change 3866071 by Nick.Shin

	UDN 412414

	update HTMl5 readme file

	#jira none

Change 3866005 by Max.Preussner

	Messaging: Preventing dangling references when removing message subscribers

	#jira UE-54680

Change 3865988 by Simon.Tourangeau

	Fix static analysis warnings

	#jira none

Change 3865895 by zachary.wilson

	Renaming QA-PhysicalLightUnits to TM-PhysicalLightUnits in QAGame.

	#JIRA UE-29618

Change 3865469 by Simon.Tourangeau

	Support for DX11 quad buffer stereo rendering

	#jira UEENT-704

Change 3865461 by Chris.Babcock

	Add a wait for audio thread to pause audio on going to background
	#jira UE-54301
	#ue4
	#android

Change 3865350 by Matt.Kuhlenschmidt

	Fix issue where cascade emitter UI would disapper

	#jira UE-53379

Change 3865336 by Arne.Schober

	REL - Fix UE-52356 Bone Weight

	#jira UE-52356

Change 3865257 by Ben.Marsh

	Fix editor failing to load content-only projects when compiled in DebugGame.

	#jira UE-54661

Change 3865238 by Simon.Tovey

	Pulling Olaf's fix from 3832595 over to release

	#tests EngineTests boots in vulkan
	#JIRA UE-54394

Change 3865191 by Sorin.Gradinaru

	UE-54317 DXT apps fail on first launch when 'For Distribution' enabled, Unsupported Texture Format

	#jira UE-54317
	#Android
	#4.19

	From //Dev-Mobile/3863322

Change 3865190 by Sorin.Gradinaru

	UE-54175 Selecting For Distribution no longer sets configuration to Shipping

	#UE4
	#4.19
	#jira UE-54175

	From //Dev-Mobile/3863371
	"For Distribution" enable-> reset "Build COnfiguration" to Shipping and force serialization to DefaultGame.ini (see UE-52845)

Change 3865056 by Jamie.Dale

	Fixed culture being incorrect when added via the Localization Dashboard

	#jira none

Change 3864826 by Max.Preussner

	WmfMedia: Added missing scope lock

	#jira UE-54365

Change 3864055 by Aaron.McLeran

	#jira UE-54213

	Crash fix for GC'd plugin settings objects. Adding to AddReferencedObjects.

Change 3863775 by Andrew.Porter

	MediaFrameworkTest: Removing Platform Media Source TVOS test content

	#jira UE-29618

Change 3863714 by Dan.Oconnor

	Make array, set, and map nodes no longer switch object type when a pin is disconnected. Also, you can no longer attach unrelated map types to the MakeMap node if only the value pin has been inferred

	#jira UE-54634

Change 3863696 by Max.Chen

	Sequencer: Fix crash open a new sequence while another is still active.

	#jira UE-54620
	#jira UE-54624

Change 3863638 by Dan.Oconnor

	Make sure all blueprints that are skeleton compiled get a BroadcastChanged notification, also run BroadcastChanged after reinstancing, matching pre compilation manager behavior
	#jira UE-54193

Change 3863494 by Jamie.Dale

	Ensure Py_SetPythonHome is set correctly before the embedded Python interpreter is initialized

	#jira UE-54345

Change 3863433 by Max.Preussner

	MediaPlayerEditor: Removed tvOS from list of available platforms in Platform Media Source assets

	tvOS currently reports itself as iOS, so it cannot have its own setting.

	#jira UE-54559

Change 3863406 by Lauren.Ridge

	Fix for a crash when filtering a dropdown with no set value
	#jira UE-54631

Change 3863238 by Michael.Kirzinger

	#jira UE-52730: Fix mac voip crash

Change 3862586 by Marc.Audy

	Clean up rendering thread heartbeat checks that got mangled in various integrations

	#jira

Change 3862247 by Guillaume.Abadie

	Fixes editor lines that were using a simple element blending mode that was generating an incorrect alpha channel.

	#jira UE-53830

Change 3862120 by Guillaume.Abadie

	Fixes USceneCaptureComponent::HiddenActors always staying gray out in world editor.

	#jira UE-51458

Change 3861363 by Jamie.Dale

	Static analysis fixes

	#jira none

Change 3861150 by Matt.Kuhlenschmidt

	Fix static mesh editor displaying 0 for all stats on LODs > 0

	#jira UE-53776

Change 3860990 by Dan.Oconnor

	Clear subobjects not recreated on load, e.g. because we're running with -game and the subobject was created using CreateEditorOnlySubobject
	#jira UE-54551

Change 3860972 by Nick.Shin

	HTML5 - detect "SyntaxError: " and do a forced reload

	- an actual syntax error would be caught during compile time
	- this is usually error condition is usually seen when browser is running "old/partial" cached data and it's fairly safe to just reload the page

	#jira UE-54017  QAGame fails to launch properly on HTML5 Firefox 64 bit

Change 3860951 by Arne.Schober

	Fix not releaseing SRV on render thread for FPositionVertexBuffer, FStaticMeshVertexBuffer, FColorVertexBuffer, FStaticMeshInstanceBuffer.

	#jira UE-54587

Change 3860950 by tim.gautier

	QAGame: Updating ML_Stone to include Texture Coordinate and Panner functions
	#jira UE-29618

Change 3860833 by Michael.Dupuis

	#jira UE-54181: Repopulate the foliage list when existing simulate mode
	Let the GC know that internal struct hold UObject ptr

Change 3860762 by Jamie.Dale

	Ensure we invoke the correct version of Python from UBT

	#jira UE-54345

Change 3860676 by Simon.Tourangeau

	Remove DirectoryWatcher warning in output log

	#jira UEENT-846

Change 3860598 by Lauren.Ridge

	Fix for crash on opening new material instance
	#jira UE-54589

Change 3860338 by Michael.Lentine

	Integrate changes for fixing MorphTargets.

	#jira 54398

Change 3860215 by Ben.Marsh

	UAT: Fix exception consturcting target rules assembly inside UAT, now that there's an abstract TargetRules class.

	#jira UE-54578

Change 3860186 by Matt.Kuhlenschmidt

	Fix crash top 10 with the font editor shutting down and then a dpi event occuring

	#jira UE-54543

Change 3859854 by Graeme.Thornton

	PR #4124: VSCode: Changed VisualStudioCodeSourceCodeAccessor to work with non-default VSCode install paths on Linux (Contributed by christopherreed)


	#jira UE-51289

Change 3859848 by Graeme.Thornton

	Fix crypto.cs reading the wrong ini setting names for uasset encryption settings

	#jira UE-54566

Change 3859684 by Ben.Marsh

	PR #4436: Fix compile error when building BlankProgram because incorrect directory path (Contributed by windkey)


	#jira UE-54392

Change 3859657 by Ben.Marsh

	Fix FTransform being passed by value, causing alignment error when compiling for Win32.

	#jira

Change 3859312 by nick.bullard

	Updating AEOverviewMan to remove reference to sub-level AEOverviewSWP which was deleted in 3859278
	Still need to update menu to remove selection

	#jira UE-50784

Change 3859278 by Nick.Bullard

	Deleteing AEOverviewSWP.umap per request of Developer. Also updated TM-AnimPhys which refereneced this map as well.

	"This test map is a custom C++ implementation of a "procedural sound wave". This code is super janky and not worth fixing up. I'm sure there's a legit thread safety problem in there but the code is in QAGame only.

	We've since implemented "synth components" which do what this test does in a much safer/better way and maintaining/testing this old thing is *not* worth the time."

	#jira UE-50784

Change 3859124 by Dan.Oconnor

	Fix long standing crash when duplicating a blueprint that is missing its parent class. Entries in CrashReport go back to 4.16

	#jira UE-54468

Change 3859086 by Ryan.Vance

	#jira UE-54470

	We need to set the viewport in both cases.

Change 3859006 by Dan.Oconnor

	Revise fix for archetype lookup when reinstancing. During compilation we do not want to force use of the up to date class

	#jira UE-54541

Change 3858990 by mason.seay

	Cleaned up blueprints to remove compile errors

	#jira UE-29618

Change 3858945 by Aaron.McLeran

	#jira UE-54265

	PR #4428: Fixing Envelope Bug in AudioMixer (Contributed by Chrispykins)


Change 3858719 by Aaron.McLeran

	#jira UE-54552 Fix for sample buffer reader

Change 3858647 by Ethan.Geller

	PR #4439: Removes ambiX -> FuMa conversion (Contributed by mgorzel)

	#jira UE-54407

Change 3858364 by Michael.Dupuis

	#jira UE-52049: There was a case where adding and removing multiple time would lead to reordering the instances and this would cause the regeneration of the random stream for all the reorded instances.

Change 3858268 by Dan.Oconnor

	Prevent postload logic running on REINST and SKEL classes

	#jira UE-54531

Change 3858205 by Mitchell.Wilson

	Removed particle looping from some emitters to resolve anim notify warnings.
	#jira UE-53823

Change 3858148 by Lauren.Ridge

	Changes based on Material Layer Feedback from previews
	- (Temporary) Disabled being able to create a layer or blend in the asset dropdown
	- Sections of the stack that have been disabled now inactivate that part of the UI
	- Create Function Instance now indicates if you are making a layer or a blend
	- Parent dropdown has been removed from layers and blends. Where relevant, a filter button has been added instead.

	#jira UETOOL-1328

Change 3857933 by Michael.Dupuis

	#jira UE-45854: Properly unregister callback when replacing foliage type with another one

Change 3857898 by Michael.Dupuis

	#jira UE-54396: Remove the Ensure as it could be possible that the Landscape Info is invalid during an undo operation

Change 3857878 by Max.Chen

	Sequencer: Assign the sequence id after the template is compiled.

	Copy from Dev-Sequencer

	#jira UE-54462

Change 3857808 by Michael.Dupuis

	#jira UE-54421: Prevent edition during Simulate when clicking on actor

Change 3857786 by Rolando.Caloca

	UE4.19 - Fix recompute tangents and skin cache for OpenGL

	#jira UE-42108
	PR #3271

Change 3857549 by Lina.Halper

	another jittering issue due to revision number change
	clear the motion vector after compile

	#jira: UE-53930

Change 3857439 by Lina.Halper

	Clear motion vector when end of sequencer when in editor world

	#jira:UE-54057

Change 3857384 by Graeme.Thornton

	Restore fix for visual studio source code accessor not correctly determining that a content project has no solution and opening a fresh instance of visual studio

	#jira UE-50020

Change 3856596 by Chris.Babcock

	Fix ResonanceAudioApi Android library architecture filtering
	#jira UE-54478
	#ue4
	#android

Change 3856449 by Michael.Dupuis

	#jira UE-35097: Various cosmetic changes that were done in phase 2 that help improve clarity of the design.

Change 3856415 by Dan.Oconnor

	Fix regression when loading instances that have had their class deleted. Issue detected by static analysis

	#jira UE-54467

Change 3856332 by Ben.Marsh

	Resaving TP_HandheldARBP assets to fix version again.

	#jira

Change 3856319 by Ben.Marsh

	Back out changelist 3855588

	Causes build failure in UFE because it introduces a dependency on the Engine module. UFE compiles with WITH_ENGINE = 0.

	#jira UE-54472

Change 3856292 by Ben.Marsh

	Fix app-local dependencies not being included in binary builds, and only working for code projects in source builds.

	#jira UE-54448

Change 3856190 by Martin.Wilson

	Fix bone access mismatch between raw mesh bones and final bones (that include virtual bones too)

	#jira UE-54266

Change 3856169 by Ben.Marsh

	Tag XGEControlWorker.exe as a build product, so it's included in the binary distro.

	#jira UE-54283

Change 3856123 by Chris.Babcock

	Fix missing ARCore file
	#jira UE-54453
	#ue4
	#android

Change 3856005 by Richard.Wallis

	Clone of Dev-Rendering CL 3855993 - turn off FShaderCache.

	#jira UE-52928

Change 3855961 by Jian.Ru

	Copy 3855047 - fix DFAO Nan problem
	#jira UE-54403

Change 3855811 by Martin.Wilson

	Add build process for Maya Live Link plugin (standalone, manually triggered) + add built binaries to Engine/Extras (Maya 2016, Maya 2017, Maya 2018)

	#jira none

Change 3855758 by Cosmin.Sulea

	UE-53569 - tvOS does not package or launch-on

	#jira UE-53569

Change 3855727 by Ben.Marsh

	Resaving assets with a versioned build in the editor, to fix warnings building DDC.

	#jira

Change 3855626 by Adrian.Siminciuc

	https://jira.it.epicgames.net/browse/UE-50979 (MP4 doesn't resume playback when iOS 11 device wakes from sleep)

	#jira UE-50979

Change 3855588 by Graeme.Thornton

	Fix visual studio solution path being incorrect for content projects

	#jira UE-50020

Change 3855283 by Ben.Marsh

	Fix race condition where stdout/stderr write handles could be inherited by multiple processes, resulting in them not being closed (and the process exit being detected) until all processes that inherited them had been closed. Improves performance of ParallelExecutor.

	#jira

Change 3855009 by Chance.Ivey

	Resaving with version number. #JIRA-54330 #rb none

Change 3854943 by Dan.Oconnor

	Fix archetype lookup when searching hierarchy that has been partially reinstanced

	#jira UE-53840

Change 3854882 by Ryan.Vance

	#jira UE-54438

	Removing vr related references to screen percentage.
	Removing previously removed gvr screen percentage code that came back in an integration from google.

Change 3854806 by Mike.Beach

	Mirroring part of CL 3802176 to fix a crash that can occur when users try to use the default 'DisplayModel' on MotionController components. Also provided users a better error message to explain why a model might not be showing up.

	#jira UE-54214

Change 3854680 by Chance.Ivey

	Saving assets with version number#JIRA UE-54330 #rb none

Change 3854652 by Uriel.Doyon

	Added a tooltip to the EV100 slider in the exposure menu.
	Using game settings now disables the slider.
	#jira UE-53945

Change 3854605 by Dan.Oconnor

	Make sure we don't create objects outered to a placeholder object, also make sure that archetypes that are reinstanced on load are relinked in to the linker table so that they are postload'd (and the old instance isn't)

	#jira UE-53954

Change 3854274 by Brandon.Schaefer

	Changes in CL 3842286 changed the function glslang::GlslangToSpv and requires a rebuild on Linux

	#jira UE-54302

	#codeview Arciel.Rekman

Change 3854255 by Phillip.Kavan

	Fix a scoping issue for local instanced subobject references in nativized Blueprint C++ code. Also, don't emit redundant assignment statements for instanced subobject reference properties.

	- Mirrored from //UE4/Dev-Framework (3853349).

	#jira UE-53960

Change 3854177 by Ethan.Geller

	#jira UE-54415 set EnabledByDefault to false for Resonance Audio

Change 3854123 by Ethan.Geller

	#jira UE-54410 set AudioComponentID

Change 3853775 by Lauren.Ridge

	Minor cleanup
	#jira UE-54054

Change 3853772 by Lauren.Ridge

	Don't create widgets when just testing if the selected widget is a replacement candidate
	#jira UE-54054

Change 3853715 by Rolando.Caloca

	UE4.19 - Fix for OpenGL overwriting texture units

	#jira UE-54401

Change 3853655 by Ben.Marsh

	Add a retry loop on creating the first directory before copying files. Attempt to work around problems copying to shared folders.

	#jira

Change 3853535 by Ben.Marsh

	Expose the engine compatible changelist to Perforce. If EnginePatchVersion > 0, this will be the changelist of the original .0 release.

	#jira

Change 3852583 by Nick.Atamas

	Resaved assets so they don't produce DDC warnings.
	#jira none

Change 3852552 by Uriel.Doyon

	Fixed Pre-Exposure shader compilation and Temporal AA issue.

	#jira UE-54276

Change 3852354 by Nick.Atamas

	Hopefully fixes the static analysis warning from jira issue.
	#jira UE-54332

Change 3852281 by Nick.Atamas

	Merging CL 3851690 from //Tasks/UE4/Dev-VR-4.19a/... to //UE4/Telease-4.19/...
	#jira UE-54331

Change 3852274 by Simon.Tourangeau

	Back out changelist 3851041 until Win7 issue is resolved.

	#jira UE-54354

Change 3852208 by Jamie.Dale

	Merging CL# 3821754 from //UE4/Dev-Enterprise

	Class property conversion now goes through NativizeClass/PythonizeClass

	This allows it to coerce from Python wrapped object types

	#jira none

Change 3852202 by Jamie.Dale

	More explicit handling of EngineDir for Python SDK

	#jira UE-54345

Change 3851982 by Brandon.Schaefer

	Workaround using a hardcoded path

	#jira UE-54136

Change 3851748 by Michael.Dupuis

	#jira UE-53904: Put the code back to what it was before, as we really only want to perform this code if bIsLayerThumbnail is true, it was changed to fix another issue complaining about a missing shader, that end up being added to the existing functions

Change 3851545 by Marc.Audy

	Remove debugging code that slipped in

	#jira none

Change 3851461 by Ben.Marsh

	Fix #includes with backslashes from crashing UBT.

	#jira UE-53996

Change 3851391 by Jamie.Dale

	Updated Python to prefer our TPS SDK

	#jira UE-54345

Change 3851372 by Jamie.Dale

	Added bat file to copy the Python SDK into TPS

	#jira UE-54345

Change 3851218 by Ben.Marsh

	Add missing template to installed engine build.

	#jira UE-54339

Change 3851117 by andrew.porter

	QAGame: Removing duplicate map

	#jira UE-29618

Change 3851041 by Simon.Tourangeau

	Support for DX11 quad buffer stereo rendering

	#jira UEENT-704

Change 3850548 by Ben.Marsh

	Add TP_HandheldARBP to installed engine build.

	#jira

Change 3850424 by Ben.Zeigler

	Fix reported memory for asset registry to be correct, extracted from a larger change

	#jira none

Change 3850324 by Ryan.Vance

	#jira UEVR-1050

	Hook up the Rift dynamic res to the new IDynamicResolutionState framework

Change 3849819 by JeanLuc.Corenthin

	Unhide Datasmith plugins in "regular" projects to allow easy project conversion

	#jira UEENT-795

Change 3849302 by Martin.Wilson

	Live Link is no longer experimental in 4.19 (moved from experimental folder to Animation)

	#jira none

Change 3849238 by Max.Chen

	Sequencer: Remove bKeepStaleTracks so that stale tracks are now always purged.

	#jira UE-54248

Change 3849211 by Michael.Dupuis

	#jira UE-54181: Prevent foliage edition during PIE or simulate mode

	#coderevire jack.porter

Change 3849123 by Benn.Gallagher

	Fixed crash in clothing actor creation when the clothing simulation mesh has no simulated vertices

	#jira UE-53741

Change 3849120 by Benn.Gallagher

	Fixed crash adding empty materials to destructible meshes in the destructible mesh editor

	#jira UE-53938

Change 3849047 by Jurre.deBaare

	Move material baking out of experimental
	#fix follow-up also remove the entry from experimental settings
	#jira UE-52685

Change 3848808 by Michael.Dupuis

	#jira UE-35097: Remove IncludeTessellationInShadowLOD & RestrictTessellationToShadowCascade from 4.19 as there is currently a bug regarding this in the dynamic rendering code path and would be too risky to fix for now.
	Fixed dynamic shadow code path issue vs static code path

Change 3848659 by Lina.Halper

	Fix issue with animation resetting in the sequencer

	#jira: UE-54047

Change 3848635 by Rolando.Caloca

	UE4.19 - Fix static analysis

	#jira UE-50449

Change 3848515 by Sorin.Gradinaru

	Unshelved from pending changelist '3843541':

	WebBrowser Android crash on 4.4.3

	#jira UE-53247
	#Android
	#4.19

	Crash on Android 4.x.x caused by a call to a Api Level 21 method

Change 3848514 by Jurre.deBaare

	Moving over:
	CL 3832173
	"Failed to import Alembic files
	#jira UE-53941
	#fix Change Alembic thirdparty library setup
		- Removed old unused library files
		- Updated batch files for building HDF5 ILMBase and Alembic libraries to use new AlembicDeploy path
		- HDF5 is now build as a Dynamic library (which also enableds multi-threading)
		- Added DLLs for HDF5 to build.cs file

	CL 3838053
	"Adding missing hdf5 dynamic libraries

Change 3848245 by Ben.Marsh

	Downgrade warning about not using XGE shader compilation to a log message. Build machines do not have XGE.

	#jira UE-54237

Change 3847300 by Phillip.Kavan

	Fix shadowed local variable.

	#jira UE-54141

Change 3846922 by Max.Preussner

	ImgMedia: Fixed image media player never finished initialization if loading failed

	Copied from Dev-Sequencer CL# 3846902

	#jira UE-54247

Change 3846831 by Arciel.Rekman

	Linux: only use lld for x86_64 (UE-54144).

	- lld support for other architectures seems to not ready for prime time.

	#jira UE-54144

Change 3846771 by Lauren.Ridge

	Material window now uses the background color set in preview scene.
	#jira UE-52215

Change 3846705 by Ben.Marsh

	Fix batch file paths not being quoted correctly when run through XGE.

	#jira

Change 3846550 by Lauren.Ridge

	Toggling Show Background now updates the background as well
	#jira UE-52250

Change 3846417 by Matt.Kuhlenschmidt

	Fix crash resizing shootergame window

	#jira UE-53137

Change 3846295 by Rolando.Caloca

	UE4.19 - New Vulkan descriptor pooling mechanism (enabled on non-android)

	#jira UE-50449

Change 3846273 by tim.gautier

	QAGame: Updating Material Layer test assets to include more Params
	- Added temp assets, quicker repros for bugs
	#jira UE-54176, UE-54165

Change 3846255 by Lauren.Ridge

	Parameter tab is the primary tab for material instances

	#jira UE-54092

Change 3846086 by Chris.Babcock

	Add missing SecureHash.h include
	#jira UE-54026
	#PR #4417
	#ue4
	#android

Change 3846049 by Martin.Wilson

	Fix Set Root Motion Enabled Anim Data Modifier node (previously didn't set the enabled flag)

	#jira UE-54220

Change 3846033 by Martin.Wilson

	Fix root motion being repeatedly applied ( Clear() call only clears bHasRootMotion flag, not the transform itself )

	#Jira UE-54219

Change 3845991 by andrew.porter

	QAGame: Updating bindings on activechannels sequencer test content

	#jira UE-29618

Change 3845933 by Lauren.Ridge

	Check for original material being valid

	#jira UE-54166

Change 3845920 by Martin.Wilson

	Optimized redundant key removal

	#jira UE-51303

Change 3845812 by Matt.Kuhlenschmidt

	Fix not being able to change BSP brush shape

	#jira UE-53738

Change 3845790 by Martin.Wilson

	Fix for assert failure when accumulating root motion in debug.

	#jira UE-53955

Change 3845730 by JeanLuc.Corenthin

	Fix build breakage
	warning: resaved disc.uasset with 4.19.0 preview #1
	failure: set the correct default mesh for AreaLightStruct.uasset

	#jira none

Change 3845693 by Lina.Halper

	Fix issue with previewing pose asset with curve data

	#jira: UE-53967

Change 3845533 by Andrew.Rodham

	Sequencer: Fixed sub sequences potentially being loaded during AddReferencedObjects

	#jira UE-54173

Change 3845472 by Thomas.Sarkanen

	Prevented debug object selection dropdown from displaying objects with pending kill outers

	#jira UE-54045 - Animation Blueprint Editor Crashes on Compile if the Debug Instance Selection is Other Than No Object or Preview Instance

Change 3845401 by Yannick.Lange

	Reverting thumbnail capture from viewport.
	#jira UE-53775
	#jira UE-53701

Change 3844693 by JeanMichel.Dignard

	Changed IES texture brightness to be the max candela value and set the texture multiplier to be 1. This fixes the IES lights intensity being too high.

	#jira UEENT-632

Change 3844689 by JeanLuc.Corenthin

	Update Datasmith content assets to latest

	Copying fix from Dev-Enterprise by Jean-Luc Corenthin CL 3809803
	Updated assets with correct release version
	Cleanup some paths on static meshes and texture

	#jira UEENT-759
	#jira UEENT-657

Change 3844571 by Martin.Wilson

	Fix motion controller motion source pin still showing when pin is connected to something

	#Jira UE-53236

Change 3844564 by Martin.Wilson

	Due to previously fixed bug some anim blueprint nodes could have duplicated guids, this fixes them

	#Jira UE-54174

Change 3844545 by Jamie.Dale

	No longer attempt to parse group separators for numeric inputs

	This avoids some ambiguity when parsing numbers for languages such as German

	#jira UE-54170

Change 3844221 by Nick.Shin

	HTML5 - filter out "windows/super" keys - these are not used in UE4

	- but, keycode are not the expected "91 or 92" values, SDL keys are "227 & 231" instead...

	#jira UE-54056  HTML5 crashes inside browser upon pressing windows key

Change 3843937 by JeanMichel.Dignard

	Fixed a crash when right clicking on a static mesh for which its AssetImportData class is currently unavailable (ie: in an unloaded plugin).

	#jira UEENT-764

Change 3843929 by Peter.Sauerbrei

	pull over fix for bad directory when copying launch images
	#jira UE-53177

Change 3843658 by Thomas.Sarkanen

	Text is red again in anim viewports

	#jira UE-53224 - Colouring removed from "Animation is being edited" warning messages

Change 3843657 by Thomas.Sarkanen

	Enable picking via Enter for details panel asset pickers

	The previous (4.18) behavior was to only allow selection of the previous/next item in the list with arrow keys. A fix (CL 3783114) for pickers with many assets broke this. This change now allows for selection of any item by navigating with arrow keys and pressing Enter, as suggested in the Jira.

	#jira UE-53440 - Unable to select assets within modal Asset Selection dropdowns after navigating with keyboard entry

Change 3843120 by Dan.Oconnor

	Avoid fixing component template games outside the editor, this logic does not work for games that have been nativized
	#jira UE-54009

Change 3842841 by Ben.Zeigler

	#jira UE-50020
	Switch visual studio module back to using absolute paths so go to definition works, broken in CL #3796157

Change 3842582 by Lauren.Ridge

	Guards against the widget passed to scrollwidgetintoview being null
	#jira UE-54037

Change 3842575 by Max.Chen

	Sequence Recorder: Stop recording if the preview window is destroyed.

	#jira UE-49778

Change 3842551 by Michael.Dupuis

	#jira UE-35097: Minor bug fix, documentation, etc. to the landscape optim that was done in the phase 2 that have 0 risk.

Change 3842371 by Max.Preussner

	Media: Merged 4.19 fixes from Dev-Sequencer

	CL 3807293 WmfMedia: Fixed YUY2 video format strides
	CL 3827988 MediaPlayerAssets: Fixed Media Texture is not linked to Media Player when created together
	CL 3805414 MediaAssets: Setting valid GUID when initializing media texture resource
	CL 3804183 MediaAssets: Added missing lock in media sound component
	CL 3831580 MfMedia: Media open events generated in same order as on other platforms
	CL 3807193 WmfMedia: Fixed incorrect buffer stride for RGB32 video tracks

	#jira UE-53532
	#jira UE-53328

Change 3842356 by Max.Preussner

	ImgMedia: Fixed ensure when cooking project that uses ImgMediaSource

	#jira UE-51631

Change 3842335 by Aaron.McLeran

	#jira UE-54087

	PR #4419: Fixes a crash due to nullptr dereference (Contributed by mgorzel)


Change 3842286 by Rolando.Caloca

	UE4.19 - Fix for static analysis
	- Glslang 1.0.65.1

	#jira UE-54128

Change 3842222 by andrew.porter

	QAGame: Updating framerate of EXR_Sequence

	#jira UE-29618

Change 3842211 by Ben.Marsh

	Fix determination of Windows version string. The manifest for UE4 applications declares compatibility with Windows 10 nowadays, so we get accurate version numbers returned from GetOSVersionInfo().

	#jira UE-54035

Change 3842163 by Cosmin.Sulea

	UE-53303 - We do not check for remote connection before attempting remote shader compile, causing crashes when misconfigured

	#jira UE-53303

Change 3841770 by Max.Chen

	Sequencer: Fix to allow keying of an arbitrarily deep property path.

	#jira UE-54095

Change 3841758 by Max.Chen

	Sequencer: Fix unbound possessable components when pasting spawnables.

	#jira UE-54104

Change 3841415 by Lauren.Ridge

	Renaming a material layer or material layer blend will no longer cause the asset to appear removed from the stack
	#jira UE-53942

Change 3841327 by Arciel.Rekman

	Linux: fix Debug build (UE-53855)

	- A workaround. UBT should be using proper PCH files instead.

	#jira UE-53855

Change 3840975 by Rolando.Caloca

	UE4.19 - Updated VulkanRHI
	- Fixes for GPU frame time
	- Fixes for CPU performance

	#jira UE-50449

Change 3840838 by Michael.Dupuis

	#jira UE-53944: Make sure the LOD generated is in the valid range to prevent the crash

Change 3840693 by Ben.Zeigler

	#jira UE-53923 Fix regression in 4.19 where PrintScriptCallstack is not always safe to call from the immediate window. I narrowed down the issue to some confusing optimized code so I turned off optimization
	Copy of CL #3840692

Change 3840680 by Aaron.McLeran

	Bringing fixes from Dev-AnimPhys to 4.19.

	#jira UE-53903 crash on load with oculus audio and old audio engine
	#jira UE-52786, UE-53910 Fix for broken spatialization on xaudio2, old audio engine.

Change 3840663 by Rolando.Caloca

	UE4.19 - Fix for layout ensure on HMD projects on Vulkan

	#jira UE-50265

Change 3840577 by Rolando.Caloca

	UE4.19 - Fix for CPUs with more than 16 cores

	#jira UE-53434

Change 3840551 by andrew.porter

	QAGame: Setting Allow Bindings from Asset to false

	#jira UE-29618

Change 3840491 by Ben.Zeigler

	#jira UE-31662 Fix regression with renaming parent inherited function. It was not correctly searching the parent's skeleton class during the child's recompile so it was erroneously detecting the parent function as missing
	Copy of CL #3840489

Change 3840297 by Max.Chen

	Sequencer: Fix copy/paste crash for lights

	#jira UE-54084

Change 3840284 by Michael.Dupuis

	#jira UE-53053: Was having a mismatch between the remove reorder and the actual remove

Change 3840215 by Sorin.Gradinaru

	Unshelved from pending changelist '3812852':

	UE-53550 Level doesn't render on Lenovo 939
	UE-53592 Assertion right after rendering scene on Lenovo S939

	#jira UE-53550
	#jira UE-53592
	#4.19
	#Android

	UE-53550
	Removed force disabling texture2DLodEXT and textureCubeLodEXT on Mali-400 devices
	The problem was that the shader compiler complains about code lines before the #extension directives.
	Placeholder // end extensions in the original shader code - to be replaced with round() functions

	UE-53592
	Always use a new task for devices that have GIsThreadedRendering=false, even when the call is from the rendering thread

Change 3840048 by Michael.Dupuis

	#jira UE-52975: Was always performing the equivalent of an Add, so now we use the Transform during the duplicate

Change 3840005 by Richard.Wallis

	Clone of CL 3835252

	Fix for shader library not working with iterative cooking, also fixes native Metal library not working with iterative cook.  This works by saving a "backup" of the shader library file - this is reloaded only during iterative cook and adds back in shaders that are missing from the current cook.

	Fix for extracting/searching .metal files in different directories so debug tgz archiving wasn't working correctly and also support iterative cook.

	Includes first pass code review suggestions by Mark Sat and Dmitriy Dyomin.

	#jira UE-53815

Change 3839968 by Michael.Dupuis

	#jira UE-52289: When OnRegister is called on the component make sure our PerInstanceRenderData is up to date
	Prevent a possible crash if ClearInstanceSelection was called on a component with no PerInstanceRenderData existing

	##codereview jack.porter

Change 3839924 by Richard.Wallis

	Clone of CL 3838093

	Fix for rewind / seek bugs in AvfMediaPlayer.

	- Don't initialise and send audio buffers that have a duration of Zero from the audio tap.  This chokes the audio sink and adds overhead we don't need.
	- Don't faff around with current play rates during loop operation - normal seek doesn't do this so loop seek shouldn't either.
	- SetRate() should not required to be passed to media tracks - should be enough to do this on audio track select only.

	#jira UE-54019, UE-53027

Change 3839321 by andrew.porter

	QAGame: Adding missing bookmark to QA-Sequencer_Blending

	#jira UE-29618

Change 3839286 by Marcus.Wassmer

	Duplicate CL: 3823296
	#jira UE-52784

Change 3839229 by Brandon.Schaefer

	Fix audio clean up crash when exiting PIE

	#jira UE-54050

	#review-3839109 @Arciel.Rekman, @Aaron.McLeran

Change 3839223 by andrew.porter

	QAGame: Rebinding pointlight actor to sequences

	#jira UE-29618

Change 3839098 by andrew.porter

	QAGame: Fixing missing sequencer blending test content

	#jira UE-29618

Change 3838919 by Mike.Erwin

	glTF: binary format's BIN chunk is not necessarily right after the JSON chunk.

	Discussed this with glTF spec authors. See https://github.com/KhronosGroup/glTF/issues/1177

	Rearranged how we read "chunks" from the file since they are not fixed in number or order, besides JSON always being first.

	#jira UE-50695

Change 3838909 by Mike.Erwin

	glTF: base64 decoding of data buffers and images

	Data can be encoded inside the glTF JSON as a Base64 data URI. This CL addresses a known limitation of initial commit CL 3793018. I added this after because base64 is expected to be uncommon in the wild. Authoring software will typically use external BIN files (.gltf) or a BIN chunk (.glb) to store data.

	#jira UE-50695

Change 3838812 by Uriel.Doyon

	Integrated CL 3838576, 3838581 and 3831760 from DevRendering, fixing issues with texture streaming.

	#jira none

Change 3838773 by Lauren.Ridge

	Fixing material layer filters

	#jira UE-54064

Change 3838748 by Michael.Trepka

	Fixed EngineTest runtime warning caused by CL 3838626

	#jira UE-53893

Change 3838730 by Max.Chen

	Sequencer: Add notification when the blend type is changed.

	#jira UE-54046

Change 3838626 by Michael.Trepka

	Changed FMacMenu to store MultiBox and MenuEntryBox as weak pointers instead of shared pointers. This way we avoid a situation where FMacMenu would try to release them on the main Cocoa thread or where we'd try to execute a menu action for menu items that Slate considers released.

	#jira UE-53893

Change 3838392 by Arciel.Rekman

	Fix assert on a policy removal (UE-54042).

	- Applying Gil's safe fix which just sweeps the problem under the rug.

	#jira UE-54042

Change 3838162 by Arciel.Rekman

	Linux: fix crash due to lambda lifetime issues (UE-54040).

	- The lambda goes out of scope in FBufferVisualizationMenuCommands::CreateVisualizationCommands, crashing the editor if compiled with a recent clang (5.0+).

	#jira UE-54040

	(Edigrating 3819174 to Release-4.19)

Change 3838156 by Rolando.Caloca

	UE4.19 - Support for Vulkan devices that have no cached memory type

	#jira UE-54039

Change 3838096 by Brandon.Schaefer

	Set sound to unfocused volume multiplier if not focused

	#jira UE-51327

	#review-3835736 arciel.rekman

Change 3838087 by Brandon.Schaefer

	Fix arm server building. A fix from CL 3617084 remove inheriting from IHeadMountedDisplayVulkanExtensions. Remove overrides

	#jira UE-53901

	#review-3838088 arciel.rekman

Change 3837072 by Phillip.Kavan

	Fix for a build failure that could occur with Blueprint nativization enabled and EDL disabled. This was a regression introduced in 4.18.

	- Mirrored from //UE4/Dev-Framework (3836768).

	#jira UE-53908

Change 3837071 by Phillip.Kavan

	Emit proper syntax for set/map fields containing converted assets to generated C++ Blueprint class headers when Blueprint nativization is enabled.

	- Mirrored from //UE4/Dev-Framework (3835944, 3835965).

	#jira UE-42614

Change 3837070 by Phillip.Kavan

	#4202 -  Blueprint nativization bug fixes (PR).

	- Mirrored from //UE4/Dev-Framework (3830562, 3832292).

	#jira UE-52188

Change 3836507 by Ryan.Vance

	#jira UE-53992

	Due to hijacking the depth target directly from the scene context, we can't support depth compositing if it's being scaled by screen percentage since it wont match our color render target dimensions.

Change 3836390 by Dan.Oconnor

	Fix failure to resolve archetype when using the compilation manager

	#jira UE-53840

Change 3836251 by Ryan.Vance

	#jira UE-53992

Change 3835852 by Mark.Satterthwaite

	Fix tessellation shaders in Metal with Manual Vertex Fetch enabled:
	- The control points idnex buffer shouldn't collide with anything else.
	- We can't use the optimisation of loading texture width & height from the buffer meta-table in tessellation shaders as the combined stages don't guarantee not to clobber unused buffer slots and screw it up when we use linear textures.

	#jira UE-53851

Change 3835802 by JeanMichel.Dignard

	UBT changes for Enterprise deployment
	- Allow building enterprise against an installed engine version
	- Added enterprise to the cleanup process if its not installed

	#jira UEENT-748

Change 3835625 by Bogdan.Vasilache

	UE-50257 --> (Skeletal meshes silently fail to render if they have more than 75 bones) --> changed logged error with a warning
	#jira UE-50257

Change 3833649 by Mike.Beach

	Enabling debug layer when multiview is enabled.

	#jira UE-49954

Change 3833525 by Ethan.Geller

	Fix copyright in ActiveSound.cpp #jira none #rb none

Change 3642649 by Stewart.Lynch

	Renamed loctext key to stop it clashing with an existing entry

	#jira UE-49432

Change 3644762 by Stewart.Lynch

	LLM update: Added Total, Untracked and FMalloc Unused to LLMFULL stat page. Fixed occasionally missing allocs/frees. Removed platform csv.

	* removed CheckSize arg from OnLowLevelFree
	* show a warning in LLM Map when replacing existing value. This means that there has been an alloc/free mismatch.
	* minor optimization in LLMMap::GetMaxIndex - cache Mask value
	* added Total and Untracked stats to LLMFULL. LLMFULL now tracks almost all of the memory that LLMPlatform does, so there is no real need to use LLMPlatform. Removed the LLMPlatform csv.
	* added FMalloc Unused stat to LLMFULL to account for memory Binned2 has allocated internally. This can be used to track Binned2 fragmentation over time.
	* renamed Binned stats to FMemory to make it more general
	* added Default tracking to CustomVirtualAlloc and disable it where necessary. This catches the few VirtualAlloc calls that were missed.
	* added AllocType arg to all allocation tracking. This was needed in order to track the FMalloc total, and also to fix the pausing
	* fixed a bug in pausing where alloc/frees were being missed. Now only pauses a specific allocation type.
	* Trackers now maintain totals for each enum tag
	* tracking of Texture and mesh allocation on Windows D3D11 & D3D12

Change 3651334 by Joe.Barnes

	Fix misspelled function name.

	#jira 39441
	#3016

Change 3653857 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3653675 to //UE4/Dev-Console/...

Change 3656553 by Joe.Barnes

	Add path for SCS_DeviceDepth.

Change 3662703 by Ben.Woodhouse

	Merging CL 3659069 from //Fortnite/Main/... to to //ue4/dev-console/...:

	[FORTNITE] [CONSOLE] [+] Improved frame syncing mechanism
	 - Improves input latency by allowing the game thread to sync to the swap chain flip of the previous frame.
	 - Added "r.GTSyncType" CVar to control how the game thread syncs with the rest of the pipe.
	 - r.GTSyncType 2 will sync the game thread with the flip of the swap chain, preventing the pipe from getting too long and causing excess input latency.

	Platforms are required to implement RHIWaitForFlip and RHISignalFlipEvent, and call RHIInitializeFlipTracking on RHI startup.
	A separate thread monitors the progress of frame flips and signals task graph events as they pass their corresponding frame index.
	In r.GTSyncType 2 mode, the game thread is signaled by this flip tracking thread.

	[~] Unified platform specific sync interval CVars into one: rhi.SyncInterval
	 - 1 == 60Hz
	 - 2 == 30Hz
	 - 3 == 20Hz

Change 3675239 by Keith.Judge

	Fixed thread priorities for Windows so that BelowNormal and SlightlyBelowNormal are the same. Bumped Lowest down a notch so they all fit.

	#jira UE-50626

Change 3676709 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3675008 to //UE4/Dev-Console/...

Change 3689712 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3687781 to //UE4/Dev-Console/...

Change 3701778 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3699491 to //UE4/Dev-Console/...

Change 3677043 by Ben.Woodhouse

	From StewartL:
	I also found that on Windows Fortnite is overflowing int32 values due to the number of allocations. I changed LLMArray and LLMMap to use uint32 and it seems to be Ok now. I didn't want to check this in at the last minute, so here's the shelf: 3645336

Change 3726532 by Luke.Thatcher

	[CONSOLE] [~] Enable XGE shader compilation by default.
	 - Also set XGE mode to "force interception". With XGE on by default, we don't want people with an old Incredibuild version using the old system inadvertently.

Change 3726554 by Luke.Thatcher

	[CONSOLE] [+] Improved Scoped Named Events
	 - Added SCOPED_NAMED_EVENT(_FSTRING/_TEXT/_F) macros to allow use of string literals, FString and printf in scoped named event strings.
	 - Replaced explicit use of FPlatformMisc::Begin/EndNamedEvent throughout the engine with macros, so the events can be compiled out.
	 - Fixed performance issues on various platforms with named events. SCOPED_NAMED_EVENT macros were not considering whether the platform uses wide or ansi char strings.

Change 3751378 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3748735 to //UE4/Dev-Console/...

Change 3751812 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3750870 to //UE4/Dev-Console/...

Change 3728571 by Luke.Thatcher

	[CONSOLE] [!] Drop another XGE controller warning to log.

Change 3747150 by Joe.Barnes

	Add AuthoringToolHelper.bat file to installed build copy list.

Change 3768585 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3767531 to //UE4/Dev-Console/...

Change 3772333 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3771573 to //UE4/Dev-Console/...

Change 3786872 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3786785 to //UE4/Dev-Console/...

Change 3787279 by Luke.Thatcher

	[CONSOLE] [~] Unified present threshold CVars.
	 - CVars are now in RHIUtilities.cpp, and are renamed to rhi.PresentThreshold.Top and rhi.PresentThreshold.Bottom.
	 - Platform implementations will be checked in shortly.

Change 3787445 by Luke.Thatcher

	[CONSOLE] [^] Merging (as edit) improvements to low-latency frame syncing from //Fortnite/Main to //UE4/Dev-Console

	Original CLs
	 - 3708949 - Added rhi.SyncSlackMS cvar to allow an offset of the game thread sync time by a number of milliseconds.
	 - 3712693 - Fix for crash on startup in new frame syncing.
	 - 3735765 - Fix r.GTSyncType logic when vsync is disabled (falls back to old behaviour when vsync is off).

Change 3788417 by Ben.Woodhouse

	Duplicate from FN CL 3712515
	CSV profiler GPU and pre-declared stat support
	- refactor the GPU profiler so it's no longer dependent on the stats system and can work in Test builds
	- add support for pre-declared CSV stats, using FNames (these are required for GPU stats)
	- add DECLARE_GPU_STAT macro which handles STATS and CsvProfiler declarations
	Note: still a few issues to resolve with GPU stats: these randomly go to 0 at times during a replay on XB1, the GPU total is lower than the stat unit number, and the unaccounted stat is too large due to missing stats

Change 3807818 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3803271 to //UE4/Dev-Console/...

Change 3818577 by Ben.Woodhouse

	Integrate from //UE4/Main/...@3812936 to //UE4/Dev-Console/...

Change 3821198 by Ben.Woodhouse

	Integrate from //UE4/Release-4.19/...@3820127 to //UE4/Dev-Console/...

Change 3821519 by Ben.Woodhouse

	Integrate from //UE4/Release-4.19/...@3820753 to //UE4/Dev-Console/...
	#robomerge none

Change 3813513 by Ben.Woodhouse

	CSV profiler refactor+ bug fix
	- Move the CSV profiler to core, so we can use it in modules other than engine
	- Profiler no longer enqueues RT commands - this is handled by a new core delegate type
	- Make begin/end requests more robust, enqueued via a command queue and processed in order
	- Defer end capture requests by a frame. This ensures stats on threads other than the gamethread (e.g. renderthread etc) are complete, so the last frame is not truncated
	- Fix long-standing bug with multiple captures where old/stale frames would appear in the first <128 frames of captures
	- Move unit stats and dynamic resolution out of the profiler itself and into the engine. Only frametime is recorded in the profiler now
	- Fix longstanding bug in first frame renderthread time in the engine

Change 3814039 by Ben.Woodhouse

	More Csvprofiler improvements
	- Event support (via CSV_EVENT macros). These appear in the "EVENTS" column of the CSV and can be used to add context to the stat data
	- Reduced memory overhead for timestamps through bit-packing (now 16 bytes per marker instead of 24), and splitting stats into different types

Change 3814041 by Ben.Woodhouse

	Integrate as edit CL 3796390 from Fortnite/Main:

	Fix CsvProfiler not compiling in shipping for now

Change 3814229 by Ben.Woodhouse

	Integrate + refactor of CL 3792591 to reduce complexity and fix bugs

	Original changelist description:
	CSV profiler improvements:
	- The CSV profiler is now always compiled in on the server
	- The CSV profiler can now handle both int32 and float stats
	- In BeginCapture, the function can take additional arguments for some customization of filenames

	Fixes to the above:
	 - Remove FCustomValue class
		- Fixes bug where all timestamp values from CSV_SCOPED_STATs were garbage (due to issues resulting from FCustomValue type ambiguity when adding values together)
		- FCsvCustomStat now just uses simple union + bitfield flag to reduce size and complexity (4 bytes instead of 8 per value)
		- FCsvColumn class modified to use doubles, which can represent both ints and floats without loss of precision - this class is not memory or time critical
	 - Replace multiple overrides used by the server for filenameprefix/folder/postfix etc with a single FilenameOverride

Change 3814242 by Ben.Woodhouse

	Disable CSV unit stats on the dedicated server

Change 3817339 by Ben.Woodhouse

	Duplicate from 3816641: CSV profiler improvements
	- Added a low-pri processing thread to compress raw timing data into a much more efficient format
	   - Reduces memory usage for 15 minute 30k frame capture with GPU stats enabled from 110MB to 3.4MB
	   - Processing time : 0.1ms per frame
	- Improved name handling for char literal stats. We now use the string as the ID rather than the pointer so multiple stat uses of the same name string apply only to  a single stat
	- Reworked thread data access to eliminate locking for anything time-critical. Frame boundaries now handled via a lock-free helper class
	-  Fixed bug with queue implementation where 1 in 128 reads would duplicate the last block of stat data
	-  Reduced #include dependencies for CSVProfiler.h
	-  Removed AccumulateMax because it doesn't work, and implementing properly would add a lot of complexity
	-  Added a simple test harness

Change 3817582 by Ben.Woodhouse

	Fix android compile warning

Change 3823242 by Ben.Woodhouse

	Integrate as edit from Fortnite/Main 3820067:

	Fix threading issue with D3D12 pipeline state caches for windows. This was caused by the usage of FRwScopeLock::RaiseLockToWrite. A pointer read before RaiseLockToWrite was called was invalidated because RaiseLockToWrite has to release the read lock before acquiring the write lock.

	Rename FRwScopeLock::RaiseLockToWrite to ReleaseReadOnlyLockAndAcquireWriteLock_USE_WITH_CAUTION to make it more explicit what's happening. As the comment says:

		// This function should be used with caution.
		// It releases the read lock _before_ acquiring a new write lock. This is not an atomic operation and the caller should
		// not treat it as such.
		// E.g. Pointers read from protected data structures prior to this call may be invalid after the function is called.

Change 3823840 by Ben.Woodhouse

	Edigrate from 3823816
	Fix an issue where the csvprofile console commands would sometimes result in an empty CSV. The root cause was GFrameNumber incrementing between the console command being read and FCSVProfiler::EndFrame(). We now use our own frame counter which is updated in EndFrame, so this can't happen

	Also fix an issue where calling csvprofile stop twice would cause all further commands to be ignored.

Change 3827787 by Ben.Woodhouse

	Integrate-as-edit CL 3820678 from Fortnite/Main
	Allow the CSV Profiler to be compiled in to shipping dedicated server builds

Change 3827842 by Ben.Woodhouse

	Integrate-as-edit CL 3827079 from Fortnite/Main
	CSV profiler category support

Change 3827918 by Luke.Thatcher

	[CONSOLE] [!] Fix compile error in CSV custom stats.

Change 3827964 by Luke.Thatcher

	[CONSOLE] [!] Fix inverted logic and spelling of boolean.
	 - Functionally, the boolean did the correct thing, but the logic was backwards inside the build tool.

Change 3831661 by Ben.Woodhouse

	Integrate-as-edit CL 3830630 from Fortnite/Main
	Fix CSVProfiler assert in dev builds on XB1

Change 3860300 by Joe.Barnes

	Use same method for src and dest rect calculation as other post processing passes so rects match between passes. Prevents read of unprocessed pixels.

Change 3860347 by Joe.Barnes

	Delete existing SourceConfigFile before allocating a new one to prevent them leaking.

Change 3860348 by Joe.Barnes

	Completely encapsulate GetLLMAlloc() in #ifdef.

Change 3861772 by Ben.Woodhouse

	Integrate-as-edit CL 3861688 from Fortnite/Main: Forward lighting GPU crash fixes

Change 3861774 by Ben.Woodhouse

	Integrate as edit CL 3833918 from dev-rendering (courtesy of DanielW):
	D3D12 RHI: only refcount uniform buffers if GRHINeedsExtraDeletionLatency is false, which is no longer the case for PC. The refcounting was heavy on performance as reported by a licensee because FRHIResource uses atomics for refcounting, which is only necessary when GRHINeedsExtraDeletionLatency is disabled.

Change 3862214 by Ben.Woodhouse

	Integrate-as-edit CL 3859637 from Fortnite/Main
			Dynamic resolution console tweaks
			- Dynamic resolution high level switch driven by a cvar instead of code
			- Disable user settings dynamic resolution handling on non-desktop platforms. DynamicRes as a user setting does not make sense on consoles/mobile - we'll drive it from device profiles/scalability
			- Modify naming of GPUHeadRoom to make it clear that it's a percentage, not millseconds

Change 3863919 by Ben.Woodhouse

	[Copy] Integrate console dynamic resolution interface changes from CL 3863354, 3862754, 3862639

Change 3864347 by Ben.Woodhouse

	Fix the editor build. This will need a proper fix before 4.19 ships.

#lockdown Nick.Penwarden
#rb none

[CL 3913399 by Ben Marsh in Main branch]
2018-02-27 17:30:35 -05:00

2937 lines
96 KiB
C#

// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using UnrealBuildTool;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Tools.DotNETCommon;
using System.Xml;
using System.Xml.Serialization;
namespace AutomationTool
{
#region ParamList
/// <summary>
/// Wrapper around List with support for multi parameter constructor, i.e:
/// var Maps = new ParamList<string>("Map1", "Map2");
/// </summary>
/// <typeparam name="T"></typeparam>
public class ParamList<T> : List<T>
{
public ParamList(params T[] Args)
{
AddRange(Args);
}
public ParamList(ICollection<T> Collection)
: base(Collection != null ? Collection : new T[] {})
{
}
public override string ToString()
{
var Text = "";
for (int Index = 0; Index < Count; ++Index)
{
if (Index > 0)
{
Text += ", ";
}
Text += this[Index].ToString();
}
return Text;
}
}
#endregion
#region PathSeparator
public enum PathSeparator
{
Default = 0,
Slash,
Backslash,
Depot,
Local
}
#endregion
/// <summary>
/// Base utility function for script commands.
/// </summary>
public partial class CommandUtils
{
#region Environment Setup
static private CommandEnvironment CmdEnvironment;
/// <summary>
/// BuildEnvironment to use for this buildcommand. This is initialized by InitBuildEnvironment. As soon
/// as the script execution in ExecuteBuild begins, the BuildEnv is set up and ready to use.
/// </summary>
static public CommandEnvironment CmdEnv
{
get
{
if (CmdEnvironment == null)
{
throw new AutomationException("Attempt to use CommandEnvironment before it was initialized.");
}
return CmdEnvironment;
}
}
/// <summary>
/// Initializes build environment. If the build command needs a specific env-var mapping or
/// has an extended BuildEnvironment, it must implement this method accordingly.
/// </summary>
/// <returns>Initialized and ready to use BuildEnvironment</returns>
static internal void InitCommandEnvironment()
{
CmdEnvironment = new CommandEnvironment();
}
#endregion
#region Logging
/// <summary>
/// Writes formatted text to log (with LogEventType.Console).
/// </summary>
/// <param name="Format">Format string</param>
/// <param name="Args">Parameters</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Log(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Console, Format, Args);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Console).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Log(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Console, Message);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Error).
/// </summary>
/// <param name="Format">Format string</param>
/// <param name="Args">Parameters</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogError(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Error, Format, Args);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Error).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogError(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Error, Message);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Warning).
/// </summary>
/// <param name="Format">Format string</param>
/// <param name="Args">Parameters</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogWarning(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Warning, Format, Args);
}
/// <summary>
/// Writes a message to log (with LogEventType.Warning).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogWarning(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Warning, Message);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Verbose).
/// </summary>
/// <param name="Foramt">Format string</param>
/// <param name="Args">Arguments</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogVerbose(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Verbose, Format, Args);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Verbose).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogVerbose(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Verbose, Message);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.VeryVerbose).
/// </summary>
/// <param name="Foramt">Format string</param>
/// <param name="Args">Arguments</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogVeryVerbose(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.VeryVerbose, Format, Args);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.VeryVerbose).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogVeryVerbose(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.VeryVerbose, Message);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Log).
/// </summary>
/// <param name="Foramt">Format string</param>
/// <param name="Args">Arguments</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogLog(string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Log, Format, Args);
}
/// <summary>
/// Writes formatted text to log (with LogEventType.Log).
/// </summary>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogLog(string Message)
{
UnrealBuildTool.Log.WriteLine(1, UnrealBuildTool.LogEventType.Log, Message);
}
/// <summary>
/// Writes formatted text to log.
/// </summary>
/// <param name="Verbosity">Verbosity</param>
/// <param name="Format">Format string</param>
/// <param name="Args">Arguments</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogWithVerbosity(UnrealBuildTool.LogEventType Verbosity, string Format, params object[] Args)
{
UnrealBuildTool.Log.WriteLine(1, Verbosity, Format, Args);
}
/// <summary>
/// Writes formatted text to log.
/// </summary>
/// <param name="Verbosity">Verbosity</param>
/// <param name="Message">Text</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogWithVerbosity(UnrealBuildTool.LogEventType Verbosity, string Message)
{
UnrealBuildTool.Log.WriteLine(1, Verbosity, Message);
}
/// <summary>
/// Dumps exception to log.
/// </summary>
/// <param name="Verbosity">Verbosity</param>
/// <param name="Ex">Exception</param>
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void LogWithVerbosity(UnrealBuildTool.LogEventType Verbosity, Exception Ex)
{
UnrealBuildTool.Log.WriteLine(1, Verbosity, LogUtils.FormatException(Ex));
}
#endregion
#region Progress Logging
public static void LogPushProgress(bool bShowProgress, int Numerator, int Denominator)
{
if(bShowProgress)
{
Log("[@progress push {0}/{1} skipline]", Numerator, Denominator);
}
}
public static void LogPopProgress(bool bShowProgress)
{
if(bShowProgress)
{
Log("[@progress pop skipline]");
}
}
public static void LogIncrementProgress(bool bShowProgress, int Numerator, int Denominator)
{
if(bShowProgress)
{
Log("[@progress increment {0}/{1} skipline]", Numerator, Denominator);
}
}
public static void LogSetProgress(bool bShowProgress, string Format, params string[] Args)
{
if(bShowProgress)
{
Log("[@progress '{0}' skipline]", String.Format(Format, Args));
}
}
public static void LogSetProgress(bool bShowProgress, int Numerator, int Denominator, string Format, params string[] Args)
{
if(bShowProgress)
{
Log("[@progress {0}/{1} '{2}' skipline]", Numerator, Denominator, String.Format(Format, Args));
}
}
#endregion
#region IO
/// <summary>
/// Finds files in specified paths.
/// </summary>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static string[] FindFiles(string SearchPattern, bool Recursive, string PathToSearch)
{
List<string> FoundFiles = new List<string>();
var NormalizedPath = ConvertSeparators(PathSeparator.Default, PathToSearch);
if (DirectoryExists(NormalizedPath))
{
var FoundInPath = InternalUtils.SafeFindFiles(NormalizedPath, SearchPattern, Recursive);
if (FoundInPath == null)
{
throw new AutomationException(String.Format("Failed to find files in '{0}'", NormalizedPath));
}
FoundFiles.AddRange(FoundInPath);
}
return FoundFiles.ToArray();
}
/// <summary>
/// Finds files in specified paths.
/// </summary>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static FileReference[] FindFiles(string SearchPattern, bool Recursive, DirectoryReference PathToSearch)
{
return FindFiles(SearchPattern, Recursive, PathToSearch.FullName).Select(x => new FileReference(x)).ToArray();
}
/// <summary>
/// Finds files in specified paths.
/// </summary>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static string[] FindFiles_NoExceptions(string SearchPattern, bool Recursive, string PathToSearch)
{
List<string> FoundFiles = new List<string>();
var NormalizedPath = ConvertSeparators(PathSeparator.Default, PathToSearch);
if (DirectoryExists(NormalizedPath))
{
var FoundInPath = InternalUtils.SafeFindFiles(NormalizedPath, SearchPattern, Recursive);
if (FoundInPath != null)
{
FoundFiles.AddRange(FoundInPath);
}
}
return FoundFiles.ToArray();
}
/// <summary>
/// Finds files in specified paths.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static string[] FindFiles_NoExceptions(bool bQuiet, string SearchPattern, bool Recursive, string PathToSearch)
{
List<string> FoundFiles = new List<string>();
var NormalizedPath = ConvertSeparators(PathSeparator.Default, PathToSearch);
if (DirectoryExists(NormalizedPath))
{
var FoundInPath = InternalUtils.SafeFindFiles(NormalizedPath, SearchPattern, Recursive, bQuiet);
if (FoundInPath != null)
{
FoundFiles.AddRange(FoundInPath);
}
}
return FoundFiles.ToArray();
}
/// <summary>
/// Finds files in specified paths.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static string[] FindDirectories(bool bQuiet, string SearchPattern, bool Recursive, string PathToSearch)
{
List<string> FoundDirs = new List<string>();
var NormalizedPath = ConvertSeparators(PathSeparator.Default, PathToSearch);
if (DirectoryExists(NormalizedPath))
{
var FoundInPath = InternalUtils.SafeFindDirectories(NormalizedPath, SearchPattern, Recursive, bQuiet);
if (FoundInPath == null)
{
throw new AutomationException(String.Format("Failed to find directories in '{0}'", NormalizedPath));
}
FoundDirs.AddRange(FoundInPath);
}
return FoundDirs.ToArray();
}
/// <summary>
/// Finds Directories in specified paths.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="SearchPattern">Pattern</param>
/// <param name="Recursive">Recursive search</param>
/// <param name="Paths">Paths to search</param>
/// <returns>An array of files found in the specified paths</returns>
public static string[] FindDirectories_NoExceptions(bool bQuiet, string SearchPattern, bool Recursive, string PathToSearch)
{
List<string> FoundDirs = new List<string>();
var NormalizedPath = ConvertSeparators(PathSeparator.Default, PathToSearch);
if (DirectoryExists(NormalizedPath))
{
var FoundInPath = InternalUtils.SafeFindDirectories(NormalizedPath, SearchPattern, Recursive, bQuiet);
if (FoundInPath != null)
{
FoundDirs.AddRange(FoundInPath);
}
}
return FoundDirs.ToArray();
}
/// <summary>
/// Deletes a file(s).
/// If the file does not exist, silently succeeds.
/// If the deletion of the file fails, this function throws an Exception.
/// </summary>
/// <param name="Filenames">Filename</param>
public static void DeleteFile(string FileName)
{
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, FileName);
if (!InternalUtils.SafeDeleteFile(NormalizedFilename))
{
throw new AutomationException(String.Format("Failed to delete file '{0}'", NormalizedFilename));
}
}
/// <summary>
/// Deletes a file(s).
/// If the file does not exist, silently succeeds.
/// If the deletion of the file fails, this function throws an Exception.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="Filenames">Filename</param>
public static void DeleteFile(bool bQuiet, string FileName)
{
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, FileName);
if (!InternalUtils.SafeDeleteFile(NormalizedFilename, bQuiet))
{
throw new AutomationException(String.Format("Failed to delete file '{0}'", NormalizedFilename));
}
}
/// <summary>
/// Deletes a file(s).
/// If the deletion of the file fails, prints a warning.
/// </summary>
/// <param name="Filenames">Filename</param>
public static bool DeleteFile_NoExceptions(string FileName)
{
bool Result = true;
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, FileName);
if (!InternalUtils.SafeDeleteFile(NormalizedFilename))
{
LogWarning("Failed to delete file '{0}'", NormalizedFilename);
Result = false;
}
return Result;
}
/// <summary>
/// Deletes a file(s).
/// If the deletion of the file fails, prints a warning.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="bQuiet">if true, then don't retry and don't print much.</param>
public static bool DeleteFile_NoExceptions(string Filename, bool bQuiet = false)
{
bool Result = true;
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, Filename);
if (!InternalUtils.SafeDeleteFile(NormalizedFilename, bQuiet))
{
LogWithVerbosity(bQuiet ? LogEventType.Log : LogEventType.Warning, "Failed to delete file '{0}'", NormalizedFilename);
Result = false;
}
return Result;
}
/// <summary>
/// Deletes a directory(or directories) including its contents (recursively, will delete read-only files).
/// If the deletion of the directory fails, this function throws an Exception.
/// </summary>
/// <param name="bQuiet">Suppresses log output if true</param>
/// <param name="Directories">Directories</param>
public static void DeleteDirectory(bool bQuiet, string Directory)
{
var NormalizedDirectory = ConvertSeparators(PathSeparator.Default, Directory);
if (!InternalUtils.SafeDeleteDirectory(NormalizedDirectory, bQuiet))
{
throw new AutomationException(String.Format("Failed to delete directory '{0}'", NormalizedDirectory));
}
}
/// <summary>
/// Deletes a directory(or directories) including its contents (recursively, will delete read-only files).
/// If the deletion of the directory fails, this function throws an Exception.
/// </summary>
/// <param name="Directories">Directories</param>
public static void DeleteDirectory(string Directory)
{
DeleteDirectory(false, Directory);
}
/// <summary>
/// Deletes a directory(or directories) including its contents (recursively, will delete read-only files).
/// If the deletion of the directory fails, prints a warning.
/// </summary>
/// <param name="bQuiet">Suppresses log output if true</param>
/// <param name="Directories">Directories</param>
public static bool DeleteDirectory_NoExceptions(bool bQuiet, string Directory)
{
bool Result = true;
var NormalizedDirectory = ConvertSeparators(PathSeparator.Default, Directory);
try
{
if (!InternalUtils.SafeDeleteDirectory(NormalizedDirectory, bQuiet))
{
LogWarning("Failed to delete directory '{0}'", NormalizedDirectory);
Result = false;
}
}
catch (Exception Ex)
{
if (!bQuiet)
{
LogWarning("Failed to delete directory, exception '{0}'", NormalizedDirectory);
LogWarning(Ex.Message);
}
Result = false;
}
return Result;
}
/// <summary>
/// Deletes a directory(or directories) including its contents (recursively, will delete read-only files).
/// If the deletion of the directory fails, prints a warning.
/// </summary>
/// <param name="Directories">Directories</param>
public static bool DeleteDirectory_NoExceptions(string DirectoryName)
{
return DeleteDirectory_NoExceptions(false, DirectoryName);
}
/// <summary>
/// Attempts to delete a directory, if that fails deletes all files and folder from the specified directory.
/// This works around the issue when the user has a file open in a notepad from that directory. Somehow deleting the file works but
/// deleting the directory with the file that's open, doesn't.
/// </summary>
/// <param name="DirectoryName"></param>
public static void DeleteDirectoryContents(string DirectoryName)
{
LogVerbose("DeleteDirectoryContents({0})", DirectoryName);
const bool bQuiet = true;
var Files = CommandUtils.FindFiles_NoExceptions(bQuiet, "*", false, DirectoryName);
foreach (var Filename in Files)
{
CommandUtils.DeleteFile_NoExceptions(Filename);
}
var Directories = CommandUtils.FindDirectories_NoExceptions(bQuiet, "*", false, DirectoryName);
foreach (var SubDirectoryName in Directories)
{
CommandUtils.DeleteDirectory_NoExceptions(bQuiet, SubDirectoryName);
}
}
/// <summary>
/// Checks if a directory(or directories) exists.
/// </summary>
/// <param name="Directories">Directories</param>
/// <returns>True if the directory exists, false otherwise.</returns>
public static bool DirectoryExists(string DirectoryName)
{
var NormalizedDirectory = ConvertSeparators(PathSeparator.Default, DirectoryName);
return System.IO.Directory.Exists(NormalizedDirectory);
}
/// <summary>
/// Checks if a directory(or directories) exists.
/// </summary>
/// <param name="Directories">Directories</param>
/// <returns>True if the directory exists, false otherwise.</returns>
public static bool DirectoryExists_NoExceptions(string DirectoryName)
{
var NormalizedDirectory = ConvertSeparators(PathSeparator.Default, DirectoryName);
try
{
return System.IO.Directory.Exists(NormalizedDirectory);
}
catch (Exception Ex)
{
LogWarning("Unable to check if directory exists: {0}", NormalizedDirectory);
LogWarning(Ex.Message);
return false;
}
}
/// <summary>
/// Creates a directory. Throws an exception on failure.
/// </summary>
/// <param name="DirectoryName">Name of the directory to create</param>
public static void CreateDirectory(string DirectoryName)
{
string NormalizedDirectory = ConvertSeparators(PathSeparator.Default, DirectoryName);
try
{
Directory.CreateDirectory(DirectoryName);
}
catch (Exception Ex)
{
throw new AutomationException(Ex, "Failed to create directory '{0}'", NormalizedDirectory);
}
}
/// <summary>
/// Creates a directory. Throws an exception on failure.
/// </summary>
/// <param name="Location">Name of the directory to create</param>
public static void CreateDirectory(DirectoryReference Location)
{
CreateDirectory(Location.FullName);
}
/// <summary>
/// Renames/moves a file.
/// If the rename of the file fails, this function throws an Exception.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="OldName">Old name</param>
/// <param name="NewName">new name</param>
public static void RenameFile(string OldName, string NewName, bool bQuiet = false)
{
var OldNormalized = ConvertSeparators(PathSeparator.Default, OldName);
var NewNormalized = ConvertSeparators(PathSeparator.Default, NewName);
if (!InternalUtils.SafeRenameFile(OldNormalized, NewNormalized, bQuiet))
{
throw new AutomationException(String.Format("Failed to rename/move file '{0}' to '{1}'", OldNormalized, NewNormalized));
}
}
/// <summary>
/// Renames/moves a file.
/// If the rename of the file fails, this function prints a warning.
/// </summary>
/// <param name="OldName">Old name</param>
/// <param name="NewName">new name</param>
public static bool RenameFile_NoExceptions(string OldName, string NewName)
{
var OldNormalized = ConvertSeparators(PathSeparator.Default, OldName);
var NewNormalized = ConvertSeparators(PathSeparator.Default, NewName);
var Result = InternalUtils.SafeRenameFile(OldNormalized, NewNormalized);
if (!Result)
{
LogWarning("Failed to rename/move file '{0}' to '{1}'", OldName, NewName);
}
return Result;
}
/// <summary>
/// Checks if a file(s) exists.
/// </summary>
/// <param name="Filenames">Filename.</param>
/// <returns>True if the file exists, false otherwise.</returns>
public static bool FileExists(string FileName)
{
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, FileName);
return InternalUtils.SafeFileExists(NormalizedFilename);
}
/// <summary>
/// Checks if a file(s) exists.
/// </summary>
/// <param name="Filenames">Filename.</param>
/// <returns>True if the file exists, false otherwise.</returns>
public static bool FileExists_NoExceptions(string FileName)
{
// Standard version doesn't throw, but keep this function for consistency.
return FileExists(FileName);
}
/// <summary>
/// Checks if a file(s) exists.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="Filenames">Filename.</param>
/// <returns>True if the file exists, false otherwise.</returns>
public static bool FileExists(bool bQuiet, string FileName)
{
var NormalizedFilename = ConvertSeparators(PathSeparator.Default, FileName);
return InternalUtils.SafeFileExists(NormalizedFilename, bQuiet);
}
/// <summary>
/// Checks if a file(s) exists.
/// </summary>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <param name="Filenames">Filename.</param>
/// <returns>True if the file exists, false otherwise.</returns>
public static bool FileExists_NoExceptions(bool bQuiet, string FileName)
{
// Standard version doesn't throw, but keep this function for consistency.
return FileExists(bQuiet, FileName);
}
static Stack<string> WorkingDirectoryStack = new Stack<string>();
/// <summary>
/// Pushes the current working directory onto a stack and sets CWD to a new value.
/// </summary>
/// <param name="WorkingDirectory">New working direcotry.</param>
public static void PushDir(string WorkingDirectory)
{
string OrigCurrentDirectory = Environment.CurrentDirectory;
WorkingDirectory = ConvertSeparators(PathSeparator.Default, WorkingDirectory);
try
{
Environment.CurrentDirectory = WorkingDirectory;
}
catch (Exception Ex)
{
throw new AutomationException(Ex, "Unable to change current directory to {0}", WorkingDirectory);
}
WorkingDirectoryStack.Push(OrigCurrentDirectory);
}
/// <summary>
/// Pushes the current working directory onto a stack and sets CWD to a new value.
/// </summary>
/// <param name="WorkingDirectory">New working direcotry.</param>
public static bool PushDir_NoExceptions(string WorkingDirectory)
{
bool Result = true;
string OrigCurrentDirectory = Environment.CurrentDirectory;
WorkingDirectory = ConvertSeparators(PathSeparator.Default, WorkingDirectory);
try
{
Environment.CurrentDirectory = WorkingDirectory;
WorkingDirectoryStack.Push(OrigCurrentDirectory);
}
catch
{
LogWarning("Unable to change current directory to {0}", WorkingDirectory);
Result = false;
}
return Result;
}
/// <summary>
/// Pops the last working directory from a stack and sets it as the current working directory.
/// </summary>
public static void PopDir()
{
if (WorkingDirectoryStack.Count > 0)
{
Environment.CurrentDirectory = WorkingDirectoryStack.Pop();
}
else
{
throw new AutomationException("Unable to PopDir. WorkingDirectoryStack is empty.");
}
}
/// <summary>
/// Pops the last working directory from a stack and sets it as the current working directory.
/// </summary>
public static bool PopDir_NoExceptions()
{
bool Result = true;
if (WorkingDirectoryStack.Count > 0)
{
Environment.CurrentDirectory = WorkingDirectoryStack.Pop();
}
else
{
LogWarning("Unable to PopDir. WorkingDirectoryStack is empty.");
Result = false;
}
return Result;
}
/// <summary>
/// Clears the directory stack
/// </summary>
public static void ClearDirStack()
{
while (WorkingDirectoryStack.Count > 0)
{
PopDir();
}
}
/// <summary>
/// Changes the current working directory.
/// </summary>
/// <param name="WorkingDirectory">New working directory.</param>
public static void ChDir(string WorkingDirectory)
{
WorkingDirectory = ConvertSeparators(PathSeparator.Default, WorkingDirectory);
try
{
Environment.CurrentDirectory = WorkingDirectory;
}
catch (Exception Ex)
{
throw new ArgumentException(String.Format("Unable to change current directory to {0}", WorkingDirectory), Ex);
}
}
/// <summary>
/// Changes the current working directory.
/// </summary>
/// <param name="WorkingDirectory">New working directory.</param>
public static bool ChDir_NoExceptions(string WorkingDirectory)
{
bool Result = true;
WorkingDirectory = ConvertSeparators(PathSeparator.Default, WorkingDirectory);
try
{
Environment.CurrentDirectory = WorkingDirectory;
}
catch
{
LogWarning("Unable to change current directory to {0}", WorkingDirectory);
Result = false;
}
return Result;
}
/// <summary>
/// Updates a file with the specified modified and access date, creating the file if it does not already exist.
/// An exception will be thrown if the directory does not already exist.
/// </summary>
/// <param name="Filename">The filename to touch, will be created if it does not exist.</param>
/// <param name="UtcDate">The accessed and modified date to set. If not specified, defaults to the current date and time.</param>
public static void TouchFile(string Filename, DateTime? UtcDate = null)
{
var Date = UtcDate ?? DateTime.UtcNow;
Filename = ConvertSeparators(PathSeparator.Slash, Filename);
if (!File.Exists(Filename))
{
var Dir = GetDirectoryName(Filename);
if (!DirectoryExists_NoExceptions(Dir))
{
throw new AutomationException(new DirectoryNotFoundException("Directory not found: " + Dir), "Unable to create file {0} as directory does not exist.", Filename);
}
File.Create(Filename).Dispose();
}
File.SetLastAccessTimeUtc(Filename, Date);
File.SetLastWriteTimeUtc(Filename, Date);
}
/// <summary>
/// Determines whether the given file is read-only
/// </summary>
/// <param name="Filename">Filename</param>
/// <returns>True if the file is read-only</returns>
public static bool IsReadOnly(string Filename)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!File.Exists(Filename))
{
throw new AutomationException(new FileNotFoundException("File not found.", Filename), "Unable to set attributes for a non-existing file.");
}
FileAttributes Attributes = File.GetAttributes(Filename);
return (Attributes & FileAttributes.ReadOnly) != 0;
}
/// <summary>
/// Sets file attributes. Will not change attributes that have not been specified.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="ReadOnly">Read-only attribute</param>
/// <param name="Hidden">Hidden attribute.</param>
/// <param name="Archive">Archive attribute.</param>
public static void SetFileAttributes(string Filename, bool? ReadOnly = null, bool? Hidden = null, bool? Archive = null)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!File.Exists(Filename))
{
throw new AutomationException(new FileNotFoundException("File not found.", Filename), "Unable to set attributes for a non-existing file.");
}
FileAttributes Attributes = File.GetAttributes(Filename);
Attributes = InternalSetAttributes(ReadOnly, Hidden, Archive, Attributes);
File.SetAttributes(Filename, Attributes);
}
/// <summary>
/// Sets file attributes. Will not change attributes that have not been specified.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="ReadOnly">Read-only attribute</param>
/// <param name="Hidden">Hidden attribute.</param>
/// <param name="Archive">Archive attribute.</param>
public static bool SetFileAttributes_NoExceptions(string Filename, bool? ReadOnly = null, bool? Hidden = null, bool? Archive = null)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!File.Exists(Filename))
{
LogWarning("Unable to set attributes for a non-exisiting file ({0})", Filename);
return false;
}
bool Result = true;
try
{
FileAttributes Attributes = File.GetAttributes(Filename);
Attributes = InternalSetAttributes(ReadOnly, Hidden, Archive, Attributes);
File.SetAttributes(Filename, Attributes);
}
catch (Exception Ex)
{
LogWarning("Error trying to set file attributes for: {0}", Filename);
LogWarning(Ex.Message);
Result = false;
}
return Result;
}
private static FileAttributes InternalSetAttributes(bool? ReadOnly, bool? Hidden, bool? Archive, FileAttributes Attributes)
{
if (ReadOnly != null)
{
if ((bool)ReadOnly)
{
Attributes |= FileAttributes.ReadOnly;
}
else
{
Attributes &= ~FileAttributes.ReadOnly;
}
}
if (Hidden != null)
{
if ((bool)Hidden)
{
Attributes |= FileAttributes.Hidden;
}
else
{
Attributes &= ~FileAttributes.Hidden;
}
}
if (Archive != null)
{
if ((bool)Archive)
{
Attributes |= FileAttributes.Archive;
}
else
{
Attributes &= ~FileAttributes.Archive;
}
}
return Attributes;
}
/// <summary>
/// Writes a line of formatted string to a file. Creates the file if it does not exists.
/// If the file does exists, appends a new line.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Text">Text to write</param>
public static void WriteToFile(string Filename, string Text)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
try
{
File.AppendAllText(Filename, Text + Environment.NewLine);
}
catch (Exception Ex)
{
throw new AutomationException(Ex, "Failed to Write to file {0}", Filename);
}
}
/// <summary>
/// Reads all text lines from a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <returns>Array of lines of text read from the file. null if the file did not exist or could not be read.</returns>
public static string[] ReadAllLines(string Filename)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
return InternalUtils.SafeReadAllLines(Filename);
}
/// <summary>
/// Reads all text from a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <returns>All text read from the file. null if the file did not exist or could not be read.</returns>
public static string ReadAllText(string Filename)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
return InternalUtils.SafeReadAllText(Filename);
}
/// <summary>
/// Writes lines to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Lines">Text</param>
public static void WriteAllLines(string Filename, string[] Lines)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!InternalUtils.SafeWriteAllLines(Filename, Lines))
{
throw new AutomationException("Unable to write to file: {0}", Filename);
}
}
/// <summary>
/// Writes lines to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Lines">Text</param>
public static bool WriteAllLines_NoExceptions(string Filename, string[] Lines)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
return InternalUtils.SafeWriteAllLines(Filename, Lines);
}
/// <summary>
/// Writes text to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Text">Text</param>
public static void WriteAllText(string Filename, string Text)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!InternalUtils.SafeWriteAllText(Filename, Text))
{
throw new AutomationException("Unable to write to file: {0}", Filename);
}
}
/// <summary>
/// Writes text to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Text">Text</param>
public static bool WriteAllText_NoExceptions(string Filename, string Text)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
return InternalUtils.SafeWriteAllText(Filename, Text);
}
/// <summary>
/// Writes byte array to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Bytes">Byte array</param>
public static void WriteAllBytes(string Filename, byte[] Bytes)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
if (!InternalUtils.SafeWriteAllBytes(Filename, Bytes))
{
throw new AutomationException("Unable to write to file: {0}", Filename);
}
}
/// <summary>
/// Writes byte array to a file.
/// </summary>
/// <param name="Filename">Filename</param>
/// <param name="Bytes">Byte array</param>
public static bool WriteAllBytes_NoExceptions(string Filename, byte[] Bytes)
{
Filename = ConvertSeparators(PathSeparator.Default, Filename);
return InternalUtils.SafeWriteAllBytes(Filename, Bytes);
}
/// <summary>
/// Gets a character representing the specified separator type.
/// </summary>
/// <param name="SeparatorType">Separator type.</param>
/// <returns>Separator character</returns>
public static char GetPathSeparatorChar(PathSeparator SeparatorType)
{
char Separator;
switch (SeparatorType)
{
case PathSeparator.Slash:
case PathSeparator.Depot:
Separator = '/';
break;
case PathSeparator.Backslash:
Separator = '\\';
break;
default:
Separator = Path.DirectorySeparatorChar;
break;
}
return Separator;
}
/// <summary>
/// Checks if the character is one of the two sperator types ('\' or '/')
/// </summary>
/// <param name="Character">Character to check.</param>
/// <returns>True if the character is a separator, false otherwise.</returns>
public static bool IsPathSeparator(char Character)
{
return (Character == '/' || Character == '\\');
}
/// <summary>
/// Combines paths and replaces all path separators with the system default separator.
/// </summary>
/// <param name="Paths"></param>
/// <returns>Combined Path</returns>
public static string CombinePaths(params string[] Paths)
{
return CombinePaths(PathSeparator.Default, Paths);
}
/// <summary>
/// Combines paths and replaces all path separators wth the system specified separator.
/// </summary>
/// <param name="SeparatorType">Type of separartor to use when combining paths.</param>
/// <param name="Paths"></param>
/// <returns>Combined Path</returns>
public static string CombinePaths(PathSeparator SeparatorType, params string[] Paths)
{
// Pick a separator to use.
var SeparatorToUse = GetPathSeparatorChar(SeparatorType);
var SeparatorToReplace = SeparatorToUse == '/' ? '\\' : '/';
// Allocate string builder
int CombinePathMaxLength = 0;
foreach (var PathPart in Paths)
{
CombinePathMaxLength += (PathPart != null) ? PathPart.Length : 0;
}
CombinePathMaxLength += Paths.Length;
var CombinedPath = new StringBuilder(CombinePathMaxLength);
// Combine all paths
CombinedPath.Append(Paths[0]);
for (int PathIndex = 1; PathIndex < Paths.Length; ++PathIndex)
{
var NextPath = Paths[PathIndex];
if (String.IsNullOrEmpty(NextPath) == false)
{
int NextPathStartIndex = 0;
if (CombinedPath.Length != 0)
{
var LastChar = CombinedPath[CombinedPath.Length - 1];
var NextChar = NextPath[0];
var IsLastCharPathSeparator = IsPathSeparator(LastChar);
var IsNextCharPathSeparator = IsPathSeparator(NextChar);
// Check if a separator between paths is required
if (!IsLastCharPathSeparator && !IsNextCharPathSeparator)
{
CombinedPath.Append(SeparatorToUse);
}
// Check if one of the saprators needs to be skipped.
else if (IsLastCharPathSeparator && IsNextCharPathSeparator)
{
NextPathStartIndex = 1;
}
}
CombinedPath.Append(NextPath, NextPathStartIndex, NextPath.Length - NextPathStartIndex);
}
}
// Make sure there's only one separator type used.
CombinedPath.Replace(SeparatorToReplace, SeparatorToUse);
return CombinedPath.ToString();
}
/// <summary>
/// Converts all separators in path to the specified separator type.
/// </summary>
/// <param name="ToSperatorType">Desired separator type.</param>
/// <param name="PathToConvert">Path</param>
/// <returns>Path where all separators have been converted to the specified type.</returns>
public static string ConvertSeparators(PathSeparator ToSperatorType, string PathToConvert)
{
return CombinePaths(ToSperatorType, PathToConvert);
}
/// <summary>
/// Copies a file, throwing an exception on failure.
/// </summary>
/// <param name="Source"></param>
/// <param name="Dest"></param>
/// <param name="bQuiet">When true, logging is suppressed.</param>
public static void CopyFile(string Source, string Dest, bool bQuiet = false)
{
Source = ConvertSeparators(PathSeparator.Default, Source);
Dest = ConvertSeparators(PathSeparator.Default, Dest);
String DestDirName = "";
try
{
DestDirName = Path.GetDirectoryName(Dest);
}
catch (Exception Ex)
{
throw new AutomationException(String.Format("Failed to get directory name for dest: {0}, {1}", Dest, Ex.Message));
}
if (InternalUtils.SafeFileExists(Dest, true))
{
InternalUtils.SafeDeleteFile(Dest, bQuiet);
}
else if (!InternalUtils.SafeDirectoryExists(DestDirName, true))
{
if (!InternalUtils.SafeCreateDirectory(DestDirName, bQuiet))
{
throw new AutomationException("Failed to create directory {0} for copy", DestDirName);
}
}
if (InternalUtils.SafeFileExists(Dest, true))
{
throw new AutomationException("Failed to delete {0} for copy", Dest);
}
if (!InternalUtils.SafeCopyFile(Source, Dest, bQuiet))
{
throw new AutomationException("Failed to copy {0} to {1}", Source, Dest);
}
}
/// <summary>
/// Copies a file. Does not throw exceptions.
/// </summary>
/// <param name="Source"></param>
/// <param name="Dest"></param>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
public static bool CopyFile_NoExceptions(string Source, string Dest, bool bQuiet = false)
{
Source = ConvertSeparators(PathSeparator.Default, Source);
Dest = ConvertSeparators(PathSeparator.Default, Dest);
if (InternalUtils.SafeFileExists(Dest, true))
{
InternalUtils.SafeDeleteFile(Dest, bQuiet);
}
else if (!InternalUtils.SafeDirectoryExists(Path.GetDirectoryName(Dest), true))
{
if (!InternalUtils.SafeCreateDirectory(Path.GetDirectoryName(Dest)))
{
return false;
}
}
if (InternalUtils.SafeFileExists(Dest, true))
{
return false;
}
return InternalUtils.SafeCopyFile(Source, Dest, bQuiet);
}
/// <summary>
/// Copies a file if the dest doesn't exist or (optionally) if the dest timestamp is different; after a copy, copies the timestamp
/// </summary>
/// <param name="Source">The full path to the source file</param>
/// <param name="Dest">The full path to the destination file</param>
/// <param name="bAllowDifferingTimestamps">If true, will always skip a file if the destination exists, even if timestamp differs; defaults to false</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
public static void CopyFileIncremental(FileReference Source, FileReference Dest, bool bAllowDifferingTimestamps = false, bool bFilterSpecialLinesFromIniFiles = false)
{
if (InternalUtils.SafeFileExists(Dest.FullName, true))
{
if (bAllowDifferingTimestamps == true)
{
LogVerbose("CopyFileIncremental Skipping {0}, already exists", Dest);
return;
}
TimeSpan Diff = File.GetLastWriteTimeUtc(Dest.FullName) - File.GetLastWriteTimeUtc(Source.FullName);
if (Diff.TotalSeconds > -1 && Diff.TotalSeconds < 1)
{
LogVerbose("CopyFileIncremental Skipping {0}, up to date.", Dest);
return;
}
InternalUtils.SafeDeleteFile(Dest.FullName);
}
else if (!InternalUtils.SafeDirectoryExists(Path.GetDirectoryName(Dest.FullName), true))
{
if (!InternalUtils.SafeCreateDirectory(Path.GetDirectoryName(Dest.FullName)))
{
throw new AutomationException("Failed to create directory {0} for copy", Path.GetDirectoryName(Dest.FullName));
}
}
if (InternalUtils.SafeFileExists(Dest.FullName, true))
{
throw new AutomationException("Failed to delete {0} for copy", Dest);
}
if (!InternalUtils.SafeCopyFile(Source.FullName, Dest.FullName, bFilterSpecialLinesFromIniFiles:bFilterSpecialLinesFromIniFiles))
{
throw new AutomationException("Failed to copy {0} to {1}", Source, Dest);
}
FileAttributes Attributes = File.GetAttributes(Dest.FullName);
if ((Attributes & FileAttributes.ReadOnly) != 0)
{
File.SetAttributes(Dest.FullName, Attributes & ~FileAttributes.ReadOnly);
}
File.SetLastWriteTimeUtc(Dest.FullName, File.GetLastWriteTimeUtc(Source.FullName));
}
/// <summary>
/// Copies a directory and all of it's contents recursively. Does not throw exceptions.
/// </summary>
/// <param name="Source"></param>
/// <param name="Dest"></param>
/// <param name="bQuiet">When true, logging is suppressed.</param>
/// <returns>True if the operation was successful, false otherwise.</returns>
public static bool CopyDirectory_NoExceptions(string Source, string Dest, bool bQuiet = false)
{
Source = ConvertSeparators(PathSeparator.Default, Source);
Dest = ConvertSeparators(PathSeparator.Default, Dest);
Dest = Dest.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
if (InternalUtils.SafeDirectoryExists(Dest))
{
InternalUtils.SafeDeleteDirectory(Dest, bQuiet);
if (InternalUtils.SafeDirectoryExists(Dest, true))
{
return false;
}
}
if (!InternalUtils.SafeCreateDirectory(Dest, bQuiet))
{
return false;
}
foreach (var SourceSubDirectory in Directory.GetDirectories(Source))
{
string DestPath = Dest + GetPathSeparatorChar(PathSeparator.Default) + GetLastDirectoryName(SourceSubDirectory + GetPathSeparatorChar(PathSeparator.Default));
if (!CopyDirectory_NoExceptions(SourceSubDirectory, DestPath, bQuiet))
{
return false;
}
}
foreach (var SourceFile in Directory.GetFiles(Source))
{
int FilenameStart = SourceFile.LastIndexOf(GetPathSeparatorChar(PathSeparator.Default));
string DestPath = Dest + SourceFile.Substring(FilenameStart);
if (!CopyFile_NoExceptions(SourceFile, DestPath, bQuiet))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns directory name without filename.
/// The difference between this and Path.GetDirectoryName is that this
/// function will not throw away the last name if it doesn't have an extension, for example:
/// D:\Project\Data\Asset -> D:\Project\Data\Asset
/// D:\Project\Data\Asset.ussset -> D:\Project\Data
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetDirectoryName(string FilePath)
{
var LastSeparatorIndex = Math.Max(FilePath.LastIndexOf('/'), FilePath.LastIndexOf('\\'));
var ExtensionIndex = FilePath.LastIndexOf('.');
if (ExtensionIndex > LastSeparatorIndex || LastSeparatorIndex == (FilePath.Length - 1))
{
return FilePath.Substring(0, LastSeparatorIndex);
}
else
{
return FilePath;
}
}
/// <summary>
/// Returns the last directory name in the path string.
/// For example: D:\Temp\Project\File.txt -> Project, Data\Samples -> Samples
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetLastDirectoryName(string FilePath)
{
var LastDir = GetDirectoryName(FilePath);
var LastSeparatorIndex = Math.Max(LastDir.LastIndexOf('/'), LastDir.LastIndexOf('\\'));
if (LastSeparatorIndex >= 0)
{
LastDir = LastDir.Substring(LastSeparatorIndex + 1);
}
return LastDir;
}
/// <summary>
/// Removes multi-dot extensions from a filename (i.e. *.automation.csproj)
/// </summary>
/// <param name="Filename">Filename to remove the extensions from</param>
/// <returns>Clean filename.</returns>
public static string GetFilenameWithoutAnyExtensions(string Filename)
{
do
{
Filename = Path.GetFileNameWithoutExtension(Filename);
}
while (Filename.IndexOf('.') >= 0);
return Filename;
}
/// <summary>
/// Reads a file manifest and returns it
/// </summary>
/// <param name="ManifestName">ManifestName</param>
/// <returns></returns>
public static UnrealBuildTool.BuildManifest ReadManifest(string ManifestName)
{
// Create a new default instance of the type
UnrealBuildTool.BuildManifest Instance = new UnrealBuildTool.BuildManifest();
XmlReader XmlStream = null;
try
{
// Use the default reader settings if none are passed in
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.CloseInput = true;
ReaderSettings.IgnoreComments = true;
// Get the xml data stream to read from
XmlStream = XmlReader.Create( ManifestName, ReaderSettings );
// Creates an instance of the XmlSerializer class so we can read the settings object
XmlSerializer ObjectReader = new XmlSerializer( typeof( UnrealBuildTool.BuildManifest ) );
// Create an object from the xml data
Instance = ( UnrealBuildTool.BuildManifest )ObjectReader.Deserialize( XmlStream );
}
catch( Exception Ex )
{
Debug.WriteLine( Ex.Message );
}
finally
{
if( XmlStream != null )
{
// Done with the file so close it
XmlStream.Close();
}
}
return Instance;
}
private static void CloneDirectoryRecursiveWorker(string SourcePathBase, string TargetPathBase, List<string> ClonedFiles, bool bIncremental = false)
{
bool bDirectoryCreated = InternalUtils.SafeCreateDirectory(TargetPathBase);
if (!bIncremental && !bDirectoryCreated)
{
throw new AutomationException("Failed to create directory {0} for copy", TargetPathBase);
}
else if (bIncremental && !CommandUtils.DirectoryExists_NoExceptions(TargetPathBase))
{
throw new AutomationException("Target directory {0} does not exist", TargetPathBase);
}
DirectoryInfo SourceDirectory = new DirectoryInfo(SourcePathBase);
DirectoryInfo[] SourceSubdirectories = SourceDirectory.GetDirectories();
// Copy the files
FileInfo[] SourceFiles = SourceDirectory.GetFiles();
foreach (FileInfo SourceFI in SourceFiles)
{
string TargetFilename = CommandUtils.CombinePaths(TargetPathBase, SourceFI.Name);
if (!bIncremental || !CommandUtils.FileExists(TargetFilename))
{
SourceFI.CopyTo(TargetFilename);
if (ClonedFiles != null)
{
ClonedFiles.Add(TargetFilename);
}
}
}
// Recurse into subfolders
foreach (DirectoryInfo SourceSubdir in SourceSubdirectories)
{
string NewSourcePath = CommandUtils.CombinePaths(SourcePathBase, SourceSubdir.Name);
string NewTargetPath = CommandUtils.CombinePaths(TargetPathBase, SourceSubdir.Name);
CloneDirectoryRecursiveWorker(NewSourcePath, NewTargetPath, ClonedFiles, bIncremental);
}
}
/// <summary>
/// Clones a directory.
/// Warning: Will delete all of the existing files in TargetPath
/// This is recursive, copying subfolders too.
/// </summary>
/// <param name="SourcePath">Source directory.</param>
/// <param name="TargetPath">Target directory.</param>
/// <param name="ClonedFiles">List of cloned files.</param>
public static void CloneDirectory(string SourcePath, string TargetPath, List<string> ClonedFiles = null)
{
DeleteDirectory_NoExceptions(TargetPath);
CloneDirectoryRecursiveWorker(SourcePath, TargetPath, ClonedFiles);
}
/// <summary>
/// Clones a directory, skipping any files which already exist in the destination.
/// This is recursive, copying subfolders too.
/// </summary>
/// <param name="SourcePath">Source directory.</param>
/// <param name="TargetPath">Target directory.</param>
/// <param name="ClonedFiles">List of cloned files.</param>
public static void CloneDirectoryIncremental(string SourcePath, string TargetPath, List<string> ClonedFiles = null)
{
CloneDirectoryRecursiveWorker(SourcePath, TargetPath, ClonedFiles, bIncremental: true);
}
#endregion
#region Threaded Copy
/// <summary>
/// Copies files using multiple threads
/// </summary>
/// <param name="SourceDirectory"></param>
/// <param name="DestDirectory"></param>
/// <param name="MaxThreads"></param>
public static void ThreadedCopyFiles(string SourceDirectory, string DestDirectory, int MaxThreads = 64)
{
CreateDirectory(DestDirectory);
var SourceFiles = Directory.EnumerateFiles(SourceDirectory, "*", SearchOption.AllDirectories).ToList();
var DestFiles = SourceFiles.Select(SourceFile => CommandUtils.MakeRerootedFilePath(SourceFile, SourceDirectory, DestDirectory)).ToList();
ThreadedCopyFiles(SourceFiles, DestFiles, MaxThreads);
}
/// <summary>
/// Copies files using multiple threads
/// </summary>
/// <param name="Source"></param>
/// <param name="Dest"></param>
/// <param name="MaxThreads"></param>
public static void ThreadedCopyFiles(List<string> Source, List<string> Dest, int MaxThreads = 64, bool bQuiet = false)
{
if(!bQuiet)
{
Log("Copying {0} file(s) using max {1} thread(s)", Source.Count, MaxThreads);
}
if (Source.Count != Dest.Count)
{
throw new AutomationException("Source count ({0}) does not match Dest count ({1})", Source.Count, Dest.Count);
}
Parallel.ForEach(Source.Zip(Dest, (Src, Dst) => new { SourceFile = Src, DestFile = Dst }), new ParallelOptions { MaxDegreeOfParallelism = MaxThreads }, (Pair) =>
{
CommandUtils.CopyFile(Pair.SourceFile, Pair.DestFile, true);
});
}
/// <summary>
/// Copies a set of files from one folder to another
/// </summary>
/// <param name="SourceDir">Source directory</param>
/// <param name="TargetDir">Target directory</param>
/// <param name="RelativePaths">Paths relative to the source directory to copy</param>
/// <param name="MaxThreads">Maximum number of threads to create</param>
/// <returns>List of filenames copied to the target directory</returns>
public static List<string> ThreadedCopyFiles(string SourceDir, string TargetDir, List<string> RelativePaths, int MaxThreads = 64)
{
var SourceFileNames = RelativePaths.Select(RelativePath => CommandUtils.CombinePaths(SourceDir, RelativePath)).ToList();
var TargetFileNames = RelativePaths.Select(RelativePath => CommandUtils.CombinePaths(TargetDir, RelativePath)).ToList();
CommandUtils.ThreadedCopyFiles(SourceFileNames, TargetFileNames, MaxThreads);
return TargetFileNames;
}
/// <summary>
/// Copies a set of files from one folder to another
/// </summary>
/// <param name="SourceDir">Source directory</param>
/// <param name="TargetDir">Target directory</param>
/// <param name="Filter">Filter which selects files from the source directory to copy</param>
/// <param name="bIgnoreSymlinks">Whether to ignore symlinks during the copy</param>
/// <param name="MaxThreads">Maximum number of threads to create</param>
/// <returns>List of filenames copied to the target directory</returns>
public static List<string> ThreadedCopyFiles(string SourceDir, string TargetDir, FileFilter Filter, bool bIgnoreSymlinks, int MaxThreads = 64)
{
// Filter all the relative paths
Log("Applying filter to {0}...", SourceDir);
DirectoryReference SourceDirRef = new DirectoryReference(SourceDir);
var RelativePaths = Filter.ApplyToDirectory(SourceDirRef, bIgnoreSymlinks).Select(x => x.MakeRelativeTo(SourceDirRef)).ToList();
return ThreadedCopyFiles(SourceDir, TargetDir, RelativePaths);
}
/// <summary>
/// Moves files in parallel
/// </summary>
/// <param
/// <param name="SourceAndTargetPairs">Pairs of source and target files</param>
public static void ParallelMoveFiles(IEnumerable<KeyValuePair<FileReference, FileReference>> SourceAndTargetPairs)
{
try
{
Parallel.ForEach(SourceAndTargetPairs, x => MoveFile(x.Key, x.Value));
}
catch (AggregateException Ex)
{
throw new AutomationException(Ex, "Failed to thread-copy files.");
}
}
/// <summary>
/// Move a file from one place to another
/// </summary>
/// <param name="SourceAndTarget">Source and target file</param>
public static void MoveFile(FileReference SourceFile, FileReference TargetFile)
{
// Create the directory for the target file
try
{
Directory.CreateDirectory(TargetFile.Directory.FullName);
}
catch(Exception Ex)
{
throw new AutomationException(Ex, "Unable to create directory {0} while moving {1} to {2}", TargetFile.Directory, SourceFile, TargetFile);
}
// Move the file
try
{
File.Move(SourceFile.FullName, TargetFile.FullName);
}
catch(Exception Ex)
{
throw new AutomationException(Ex, "Unable to move {0} to {1}", SourceFile, TargetFile);
}
}
#endregion
#region Environment variables
/// <summary>
/// Gets environment variable value.
/// </summary>
/// <param name="Name">Name of the environment variable</param>
/// <returns>Environment variable value as string.</returns>
public static string GetEnvVar(string Name)
{
return InternalUtils.GetEnvironmentVariable(Name, "");
}
/// <summary>
/// Gets environment variable value.
/// </summary>
/// <param name="Name">Name of the environment variable</param>
/// <param name="DefaultValue">Default value of the environment variable if the variable is not set.</param>
/// <returns>Environment variable value as string.</returns>
public static string GetEnvVar(string Name, string DefaultValue)
{
return InternalUtils.GetEnvironmentVariable(Name, DefaultValue);
}
/// <summary>
/// Sets environment variable.
/// </summary>
/// <param name="Name">Variable name.</param>
/// <param name="Value">Variable value.</param>
/// <returns>True if the value has been set, false otherwise.</returns>
public static void SetEnvVar(string Name, object Value)
{
try
{
LogLog("SetEnvVar {0}={1}", Name, Value);
Environment.SetEnvironmentVariable(Name, Value.ToString());
}
catch (Exception Ex)
{
throw new AutomationException(Ex, "Failed to set environment variable {0} to {1}", Name, Value);
}
}
/// <summary>
/// Sets the environment variable if it hasn't been already.
/// </summary>
/// <param name="VarName">Environment variable name</param>
/// <param name="Value">New value</param>
public static void ConditionallySetEnvVar(string VarName, string Value)
{
if (String.IsNullOrEmpty(CommandUtils.GetEnvVar(VarName)))
{
Environment.SetEnvironmentVariable(VarName, Value);
}
}
#endregion
#region CommandLine
/// <summary>
/// Converts a list of arguments to a string where each argument is separated with a space character.
/// </summary>
/// <param name="Args">Arguments</param>
/// <returns>Single string containing all arguments separated with a space.</returns>
public static string FormatCommandLine(IEnumerable<string> Arguments)
{
StringBuilder Result = new StringBuilder();
foreach(string Argument in Arguments)
{
if(Result.Length > 0)
{
Result.Append(" ");
}
Result.Append(FormatArgumentForCommandLine(Argument));
}
return Result.ToString();
}
/// <summary>
/// Format a single argument for passing on the command line, inserting quotes as necessary.
/// </summary>
/// <param name="Argument">The argument to quote</param>
/// <returns>The argument, with quotes if necessary</returns>
public static string FormatArgumentForCommandLine(string Argument)
{
// Check if the argument contains a space. If not, we can just pass it directly.
int SpaceIdx = Argument.IndexOf(' ');
if(SpaceIdx == -1)
{
return Argument;
}
// If it does have a space, and it's formatted as an option (ie. -Something=), try to insert quotes after the equals character
int EqualsIdx = Argument.IndexOf('=');
if(Argument.StartsWith("-") && EqualsIdx != -1 && EqualsIdx < SpaceIdx)
{
return String.Format("{0}=\"{1}\"", Argument.Substring(0, EqualsIdx), Argument.Substring(EqualsIdx + 1));
}
else
{
return String.Format("\"{0}\"", Argument);
}
}
/// <summary>
/// Parses the argument list for a parameter and returns whether it is defined or not.
/// </summary>
/// <param name="ArgList">Argument list.</param>
/// <param name="Param">Param to check for.</param>
/// <returns>True if param was found, false otherwise.</returns>
public static bool ParseParam(string[] ArgList, string Param)
{
string ValueParam = Param;
if (!ValueParam.EndsWith("="))
{
ValueParam += "=";
}
foreach (string ArgStr in ArgList)
{
if (ArgStr.Equals(Param, StringComparison.InvariantCultureIgnoreCase) || ArgStr.StartsWith(ValueParam, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
/// <summary>
/// Parses the argument list for a parameter and reads its value.
/// Ex. ParseParamValue(Args, "map=")
/// </summary>
/// <param name="ArgList">Argument list.</param>
/// <param name="Param">Param to read its value.</param>
/// <returns>Returns the value or Default if the parameter was not found.</returns>
public static string ParseParamValue(object[] ArgList, string Param, string Default = null)
{
if (!Param.EndsWith("="))
{
Param += "=";
}
foreach (object Arg in ArgList)
{
string ArgStr = Arg.ToString();
if (ArgStr.StartsWith(Param, StringComparison.InvariantCultureIgnoreCase))
{
return ArgStr.Substring(Param.Length);
}
}
return Default;
}
/// <summary>
/// Parses the argument list for any number of parameters.
/// </summary>
/// <param name="ArgList">Argument list.</param>
/// <param name="Param">Param to read its value.</param>
/// <returns>Returns an array of values for this parameter (or an empty array if one was not found.</returns>
public static string[] ParseParamValues(object[] ArgList, string Param)
{
string ParamEquals = Param;
if (!ParamEquals.EndsWith("="))
{
ParamEquals += "=";
}
List<string> Values = new List<string>();
foreach (object Arg in ArgList)
{
string ArgStr = Arg.ToString();
if (ArgStr.StartsWith(ParamEquals, StringComparison.InvariantCultureIgnoreCase))
{
Values.Add(ArgStr.Substring(ParamEquals.Length));
}
}
return Values.ToArray();
}
/// <summary>
/// Makes sure path can be used as a command line param (adds quotes if it contains spaces)
/// </summary>
/// <param name="InPath">Path to convert</param>
/// <returns></returns>
public static string MakePathSafeToUseWithCommandLine(string InPath)
{
if (InPath.Contains(' ') && InPath[0] != '\"')
{
InPath = "\"" + InPath + "\"";
}
return InPath;
}
#endregion
#region Other
public static string EscapePath(string InPath)
{
return InPath.Replace(":", "").Replace("/", "+").Replace("\\", "+").Replace(" ", "+");
}
/// <summary>
/// Checks if collection is either null or empty.
/// </summary>
/// <param name="Collection">Collection to check.</param>
/// <returns>True if the collection is either nur or empty.</returns>
public static bool IsNullOrEmpty(ICollection Collection)
{
return Collection == null || Collection.Count == 0;
}
#endregion
#region Properties
/// <summary>
/// Checks if this command is running on a build machine.
/// </summary>
public static bool IsBuildMachine
{
get { return Automation.IsBuildMachine; }
}
/// <summary>
/// Path to the root directory
/// </summary>
public static readonly DirectoryReference RootDirectory = new DirectoryReference(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetOriginalLocation()), "..", "..", ".."));
/// <summary>
/// Path to the engine directory
/// </summary>
public static readonly DirectoryReference EngineDirectory = DirectoryReference.Combine(RootDirectory, "Engine");
/// <summary>
/// Telemetry data for the current run. Add -WriteTelemetry=<Path> to the command line to export to disk.
/// </summary>
public static TelemetryData Telemetry = new TelemetryData();
#endregion
/// <summary>
/// Cached location of the build root storage because the logic to compute it is a little non-trivial.
/// </summary>
private static string CachedRootBuildStorageDirectory;
/// <summary>
/// "P:\Builds" or "/Volumes/Builds". Root Folder for all build storage.
/// </summary>
/// <returns>"P:\Builds" or "/Volumes/Builds" unless overridden by -UseLocalBuildStorage from the commandline, where is uses Engine\Saved\LocalBuilds\.</returns>
public static string RootBuildStorageDirectory()
{
if (string.IsNullOrEmpty(CachedRootBuildStorageDirectory))
{
if (GlobalCommandLine.UseLocalBuildStorage)
{
CachedRootBuildStorageDirectory = CombinePaths(CmdEnv.LocalRoot, "Engine", "Saved", "LocalBuilds");
// Must create the directory because much of the system assumes it is already there.
CreateDirectory(CombinePaths(CachedRootBuildStorageDirectory, "UE4"));
}
else
{
CachedRootBuildStorageDirectory = Utils.IsRunningOnMono ? "/Volumes/Builds" : CombinePaths("P:", "Builds");
}
}
return CachedRootBuildStorageDirectory;
}
public static bool DirectoryExistsAndIsWritable_NoExceptions(string Dir)
{
if (!DirectoryExists_NoExceptions(Dir))
{
LogLog("Directory {0} does not exist", Dir);
return false;
}
try
{
string Filename = CombinePaths(Dir, Guid.NewGuid().ToString() + ".Temp.txt");
string NativeFilename = ConvertSeparators(PathSeparator.Default, Filename);
using(StreamWriter Writer = new StreamWriter(NativeFilename))
{
Writer.Write("Test");
}
if(File.Exists(NativeFilename))
{
DeleteFile_NoExceptions(Filename, true);
LogLog("Directory {0} is writable", Dir);
return true;
}
}
catch(Exception)
{
}
LogLog("Directory {0} is not writable", Dir);
return false;
}
public static void CleanFormalBuilds(string ParentDir, string SearchPattern, int MaximumDaysToKeepTempStorage = 4)
{
if (!IsBuildMachine || !ParentDir.StartsWith(RootBuildStorageDirectory()))
{
return;
}
try
{
DirectoryInfo DirInfo = new DirectoryInfo(ParentDir);
Log("Looking for directories to delete in {0}", ParentDir);
foreach (DirectoryInfo ThisDirInfo in DirInfo.EnumerateDirectories(SearchPattern))
{
double AgeDays = (DateTime.UtcNow - ThisDirInfo.CreationTimeUtc).TotalDays;
if (AgeDays > MaximumDaysToKeepTempStorage)
{
Log("Deleting formal build directory {0}, because it is {1} days old (maximum {2}).", ThisDirInfo.FullName, (int)AgeDays, MaximumDaysToKeepTempStorage);
DeleteDirectory_NoExceptions(true, ThisDirInfo.FullName);
}
else
{
LogVerbose("Not deleting formal build directory {0}, because it is {1} days old (maximum {2}).", ThisDirInfo.FullName, (int)AgeDays, MaximumDaysToKeepTempStorage);
}
}
}
catch (Exception Ex)
{
LogWarning("Unable to clean formal builds from directory: {0}", ParentDir);
LogWarning(" Exception was {0}", LogUtils.FormatException(Ex));
}
}
/// <summary>
/// Returns the generic name for a given platform (eg. "Windows" for Win32/Win64)
/// </summary>
/// <param name="Platform">Specific platform</param>
public static string GetGenericPlatformName(UnrealBuildTool.UnrealTargetPlatform Platform)
{
if(Platform == UnrealTargetPlatform.Win32 || Platform == UnrealTargetPlatform.Win64)
{
return "Windows";
}
else
{
return Enum.GetName(typeof(UnrealBuildTool.UnrealTargetPlatform), Platform);
}
}
/// <summary>
/// Creates a zip file containing the given input files
/// </summary>
/// <param name="ZipFileName">Filename for the zip</param>
/// <param name="Filter">Filter which selects files to be included in the zip</param>
/// <param name="BaseDirectory">Base directory to store relative paths in the zip file to</param>
public static void ZipFiles(FileReference ZipFileName, DirectoryReference BaseDirectory, FileFilter Filter)
{
// Ionic.Zip.Zip64Option.Always option produces broken archives on Mono, so we use system zip tool instead
if (Utils.IsRunningOnMono)
{
CommandUtils.CreateDirectory(Path.GetDirectoryName(ZipFileName.FullName));
CommandUtils.PushDir(BaseDirectory.FullName);
string FilesList = "";
foreach (FileReference FilteredFile in Filter.ApplyToDirectory(BaseDirectory, true))
{
FilesList += " \"" + FilteredFile.MakeRelativeTo(BaseDirectory) + "\"";
if (FilesList.Length > 32000)
{
CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFileName + "\"" + FilesList);
FilesList = "";
}
}
if (FilesList.Length > 0)
{
CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFileName + "\"" + FilesList);
}
CommandUtils.PopDir();
}
else
{
using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(Encoding.UTF8))
{
Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
foreach (FileReference FilteredFile in Filter.ApplyToDirectory(BaseDirectory, true))
{
Zip.AddFile(FilteredFile.FullName, Path.GetDirectoryName(FilteredFile.MakeRelativeTo(BaseDirectory)));
}
CommandUtils.CreateDirectory(Path.GetDirectoryName(ZipFileName.FullName));
Zip.Save(ZipFileName.FullName);
}
}
}
/// <summary>
/// Creates a zip file containing the given input files
/// </summary>
/// <param name="ZipFile">Filename for the zip</param>
/// <param name="BaseDirectory">Base directory to store relative paths in the zip file to</param>
/// <param name="Files">Files to include in the archive</param>
public static void ZipFiles(FileReference ZipFile, DirectoryReference BaseDirectory, IEnumerable<FileReference> Files)
{
// Ionic.Zip.Zip64Option.Always option produces broken archives on Mono, so we use system zip tool instead
if (Utils.IsRunningOnMono)
{
CommandUtils.CreateDirectory(ZipFile.Directory.FullName);
CommandUtils.PushDir(BaseDirectory.FullName);
string FilesList = "";
foreach(FileReference File in Files)
{
FilesList += " \"" + File.MakeRelativeTo(BaseDirectory) + "\"";
if (FilesList.Length > 32000)
{
CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFile.FullName + "\"" + FilesList);
FilesList = "";
}
}
if (FilesList.Length > 0)
{
CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFile.FullName + "\"" + FilesList);
}
CommandUtils.PopDir();
}
else
{
Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(Encoding.UTF8);
Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
foreach(FileReference File in Files)
{
Zip.AddFile(File.FullName, Path.GetDirectoryName(File.MakeRelativeTo(BaseDirectory)));
}
CommandUtils.CreateDirectory(ZipFile.Directory.FullName);
Zip.Save(ZipFile.FullName);
}
}
/// <summary>
/// Extracts the contents of a zip file
/// </summary>
/// <param name="ZipFileName">Name of the zip file</param>
/// <param name="BaseDirectory">Output directory</param>
/// <returns>List of files written</returns>
public static IEnumerable<string> UnzipFiles(string ZipFileName, string BaseDirectory)
{
List<string> OutputFileNames = new List<string>();
if (Utils.IsRunningOnMono)
{
CommandUtils.CreateDirectory(BaseDirectory);
// Use system unzip tool as there have been instances of Ionic not being able to open zips created with Mac zip tool
string Output = CommandUtils.RunAndLog("unzip", "\"" + ZipFileName + "\" -d \"" + BaseDirectory + "\"", Options: ERunOptions.Default | ERunOptions.SpewIsVerbose);
// Split log output into lines
string[] Lines = Output.Split(new char[] { '\n', '\r' });
foreach (string LogLine in Lines)
{
CommandUtils.Log(LogLine);
// Split each line into two by whitespace
string[] SplitLine = LogLine.Split(new char[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (SplitLine.Length == 2)
{
// Second part of line should be a path
string FilePath = SplitLine[1].Trim();
CommandUtils.Log(FilePath);
if (File.Exists(FilePath) && !OutputFileNames.Contains(FilePath) && FilePath != ZipFileName)
{
if (CommandUtils.IsProbablyAMacOrIOSExe(FilePath))
{
FixUnixFilePermissions(FilePath);
}
OutputFileNames.Add(FilePath);
}
}
}
if (OutputFileNames.Count == 0)
{
CommandUtils.LogWarning("Unable to parse unzipped files from {0}", ZipFileName);
}
}
else
{
// manually extract the files. There was a problem with the Ionic.Zip library that required this on non-PC at one point,
// but that problem is now fixed. Leaving this code as is as we need to return the list of created files anyway.
using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(ZipFileName))
{
foreach (Ionic.Zip.ZipEntry Entry in Zip.Entries.Where(x => !x.IsDirectory))
{
string OutputFileName = Path.Combine(BaseDirectory, Entry.FileName);
Directory.CreateDirectory(Path.GetDirectoryName(OutputFileName));
using (FileStream OutputStream = new FileStream(OutputFileName, FileMode.Create, FileAccess.Write))
{
Entry.Extract(OutputStream);
}
OutputFileNames.Add(OutputFileName);
}
}
}
return OutputFileNames;
}
/// <summary>
/// Resolve an arbitrary file specification against a directory. May contain any number of p4 wildcard operators (?, *, ...).
/// </summary>
/// <param name="DefaultDir">Base directory for relative paths</param>
/// <param name="Pattern">Pattern to match</param>
/// <param name="ExcludePatterns">List of patterns to be excluded. May be null.</param>
/// <returns>Sequence of file references matching the given pattern</returns>
public static IEnumerable<FileReference> ResolveFilespec(DirectoryReference DefaultDir, string Pattern, IEnumerable<string> ExcludePatterns)
{
List<FileReference> Files = new List<FileReference>();
// Check if it contains any wildcards. If not, we can just add the pattern directly without searching.
int WildcardIdx = FileFilter.FindWildcardIndex(Pattern);
if(WildcardIdx == -1)
{
// Construct a filter which removes all the excluded filetypes
FileFilter Filter = new FileFilter(FileFilterType.Include);
if(ExcludePatterns != null)
{
Filter.AddRules(ExcludePatterns, FileFilterType.Exclude);
}
// Match it against the given file
FileReference File = FileReference.Combine(DefaultDir, Pattern);
if(Filter.Matches(File.FullName))
{
Files.Add(File);
}
}
else
{
// Find the base directory for the search. We construct this in a very deliberate way including the directory separator itself, so matches
// against the OS root directory will resolve correctly both on Mac (where / is the filesystem root) and Windows (where / refers to the current drive).
int LastDirectoryIdx = Pattern.LastIndexOfAny(new char[]{ Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, WildcardIdx);
DirectoryReference BaseDir = DirectoryReference.Combine(DefaultDir, Pattern.Substring(0, LastDirectoryIdx + 1));
// Construct the absolute include pattern to match against, re-inserting the resolved base directory to construct a canonical path.
string IncludePattern = BaseDir.FullName.TrimEnd(new char[]{ Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }) + "/" + Pattern.Substring(LastDirectoryIdx + 1);
// Construct a filter and apply it to the directory
if(DirectoryReference.Exists(BaseDir))
{
FileFilter Filter = new FileFilter();
Filter.AddRule(IncludePattern, FileFilterType.Include);
if(ExcludePatterns != null)
{
Filter.AddRules(ExcludePatterns, FileFilterType.Exclude);
}
Files.AddRange(Filter.ApplyToDirectory(BaseDir, BaseDir.FullName, true));
}
}
return Files;
}
static public Dictionary<Version, string> GetBuildVersionPathMap(string[] BuildFolders)
{
Dictionary<Version, string> BuildVersionPaths = new Dictionary<Version, string>();
foreach (string buildFolder in BuildFolders)
{
string XboxoneReleaseVersion = Path.GetFileName(buildFolder);
// The name of all recent archived builds either start with "EA" or only contain version
string VersionPrefix = "EA";
if (XboxoneReleaseVersion.StartsWith(VersionPrefix))
{
XboxoneReleaseVersion.Substring(VersionPrefix.Length); // Length of "EA"
}
Version ReleaseVersion;
if (Version.TryParse(XboxoneReleaseVersion, out ReleaseVersion))
{
BuildVersionPaths.Add(ReleaseVersion, buildFolder);
}
}
return BuildVersionPaths;
}
static public string GetPreviousXboxOneReleaseArchiveDir(string XboxOneReleasesArchiveDir)
{
var BuildFolders = Directory.GetDirectories(XboxOneReleasesArchiveDir);
if (BuildFolders.Length > 0)
{
Dictionary<Version, string> BuildVersionPathMap = GetBuildVersionPathMap(BuildFolders);
if (BuildVersionPathMap.Count > 0)
{
return BuildVersionPathMap.Where(archiveDir => DirectoryExists(CombinePaths(archiveDir.Value, "Paks"))).OrderByDescending(versionPathPair => versionPathPair.Key).First().Value;
}
else
{
throw new AutomationException(String.Format("No valid builds were found in %s", XboxOneReleasesArchiveDir));
}
}
else
{
throw new AutomationException(String.Format("No builds were found in %s", XboxOneReleasesArchiveDir));
}
}
public static string FormatSizeString(long Size)
{
string[] Units = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
int UnitIndex = 0;
double AbsSize = Math.Abs(Size);
while (AbsSize >= 1024)
{
AbsSize /= 1024;
++UnitIndex;
}
return String.Format("{0} {1}", AbsSize.ToString("N2"), Units[UnitIndex]);
}
}
/// <summary>
/// Valid units for telemetry data
/// </summary>
public enum TelemetryUnits
{
Count,
Milliseconds,
Seconds,
Minutes,
Bytes,
Megabytes,
}
/// <summary>
/// Sample for telemetry data
/// </summary>
public class TelemetrySample
{
/// <summary>
/// Name of this sample
/// </summary>
public string Name;
/// <summary>
/// The value for this sample
/// </summary>
public double Value;
/// <summary>
/// Units for this sample
/// </summary>
public TelemetryUnits Units;
}
/// <summary>
/// Stores a set of key/value telemetry samples which can be read and written to a JSON file
/// </summary>
public class TelemetryData
{
/// <summary>
/// The current file version
/// </summary>
const int CurrentVersion = 1;
/// <summary>
/// Maps from a sample name to its value
/// </summary>
public List<TelemetrySample> Samples = new List<TelemetrySample>();
/// <summary>
/// Adds a telemetry sample
/// </summary>
/// <param name="Name">Name of the sample</param>
/// <param name="Value">Value of the sample</param>
/// <param name="Units">Units for the sample value</param>
public void Add(string Name, double Value, TelemetryUnits Units)
{
Samples.RemoveAll(x => x.Name == Name);
Samples.Add(new TelemetrySample() { Name = Name, Value = Value, Units = Units });
}
/// <summary>
/// Add samples from another telemetry block into this one
/// </summary>
/// <param name="Prefix">Prefix for the telemetry data</param>
/// <param name="Other">The other telemetry data</param>
public void Merge(string Prefix, TelemetryData Other)
{
foreach(TelemetrySample Sample in Other.Samples)
{
Add(Sample.Name, Sample.Value, Sample.Units);
}
}
/// <summary>
/// Tries to read the telemetry data from the given file
/// </summary>
/// <param name="FileName">The file to read from</param>
/// <param name="Telemetry">On success, the read telemetry data</param>
/// <returns>True if a telemetry object was read</returns>
public static bool TryRead(FileReference FileName, out TelemetryData Telemetry)
{
// Try to read the raw json object
JsonObject RawObject;
if (!JsonObject.TryRead(FileName, out RawObject))
{
Telemetry = null;
return false;
}
// Check the version is valid
int Version;
if(!RawObject.TryGetIntegerField("Version", out Version) || Version != CurrentVersion)
{
Telemetry = null;
return false;
}
// Read all the samples
JsonObject[] RawSamples;
if (!RawObject.TryGetObjectArrayField("Samples", out RawSamples))
{
Telemetry = null;
return false;
}
// Parse out all the samples
Telemetry = new TelemetryData();
foreach (JsonObject RawSample in RawSamples)
{
Telemetry.Add(RawSample.GetStringField("Name"), RawSample.GetDoubleField("Value"), RawSample.GetEnumField<TelemetryUnits>("Units"));
}
return true;
}
/// <summary>
/// Writes out the telemetry data to a file
/// </summary>
/// <param name="FileName"></param>
public void Write(string FileName)
{
using (JsonWriter Writer = new JsonWriter(FileName))
{
Writer.WriteObjectStart();
Writer.WriteValue("Version", CurrentVersion);
Writer.WriteArrayStart("Samples");
foreach(TelemetrySample Sample in Samples)
{
Writer.WriteObjectStart();
Writer.WriteValue("Name", Sample.Name);
Writer.WriteValue("Value", Sample.Value);
Writer.WriteValue("Units", Sample.Units.ToString());
Writer.WriteObjectEnd();
}
Writer.WriteArrayEnd();
Writer.WriteObjectEnd();
}
}
}
/// <summary>
/// Timer class used for telemetry reporting.
/// </summary>
public class TelemetryStopwatch : IDisposable
{
string Name;
DateTime StartTime;
bool bFinished;
public TelemetryStopwatch(string Format, params object[] Args)
{
Name = String.Format(Format, Args);
StartTime = DateTime.Now;
}
public void Cancel()
{
bFinished = true;
}
/// <summary>
/// Flushes the time to <see cref="CmdEnv.CSVFile"/> if we are the build machine and that environment variable is specified.
/// Call Finish manually with an alternate name to use that one instead. Useful for dynamically generated names that you can't specify at construction.
/// </summary>
/// <param name="AlternateName">Used in place of the Name specified during construction.</param>
public void Finish(string AlternateName = null)
{
if(!bFinished)
{
if (!String.IsNullOrEmpty(AlternateName))
{
Name = AlternateName;
}
var OutputStr = String.Format("UAT,{0},{1},{2}" + Environment.NewLine, Name, StartTime, DateTime.Now);
CommandUtils.LogVerbose(OutputStr);
if (CommandUtils.IsBuildMachine && !String.IsNullOrEmpty(CommandUtils.CmdEnv.CSVFile) && CommandUtils.CmdEnv.CSVFile != "nul")
{
try
{
File.AppendAllText(CommandUtils.CmdEnv.CSVFile, OutputStr);
}
catch (Exception Ex)
{
CommandUtils.LogWarning("Could not append to csv file ({0}) : {1}", CommandUtils.CmdEnv.CSVFile, Ex.ToString());
}
}
}
bFinished = true;
}
public void Dispose()
{
Finish();
}
}
/// <summary>
/// Stopwatch that uses DateTime.UtcNow for timing. Not hi-res, but also not subject to short time limitations of System.Diagnostics.Stopwatch.
/// </summary>
public class DateTimeStopwatch
{
public static DateTimeStopwatch Start()
{
return new DateTimeStopwatch();
}
/// <summary>
/// Hide public ctor.
/// </summary>
private DateTimeStopwatch() { }
readonly DateTime StartTime = DateTime.UtcNow;
public TimeSpan ElapsedTime { get { return DateTime.UtcNow - StartTime; } }
}
/// <summary>
/// Use with "using" syntax to push and pop directories in a convenient, exception-safe way
/// </summary>
public class PushedDirectory : IDisposable
{
public PushedDirectory(string DirectoryName)
{
CommandUtils.PushDir(DirectoryName);
}
public void Dispose()
{
CommandUtils.PopDir();
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Use with "using" syntax to temporarily set and environment variable in a convenient, exception-safe way
/// </summary>
public class ScopedEnvVar : IDisposable
{
private string StoredEnvVar = null;
public ScopedEnvVar(string EnvVar, string Value)
{
StoredEnvVar = EnvVar;
CommandUtils.SetEnvVar(StoredEnvVar, Value);
}
public void Dispose()
{
CommandUtils.SetEnvVar(StoredEnvVar, "");
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Helper class to associate a file and its contents
/// </summary>
public class EMSFileInfo
{
public string FileName { get; set; }
public byte[] Bytes { get; set; }
}
/// <summary>
/// Wrapper class for the enumerate files JSON response from MCP
/// </summary>
[DataContract]
public sealed class EnumerationResponse
{
[DataMember(Name = "doNotCache", IsRequired = true)]
public Boolean DoNotCache { get; set; }
[DataMember(Name = "uniqueFilename", IsRequired = true)]
public string UniqueFilename { get; set; }
[DataMember(Name = "filename", IsRequired = true)]
public string Filename { get; set; }
[DataMember(Name = "hash", IsRequired = true)]
public string Hash { get; set; }
[DataMember(Name = "length", IsRequired = true)]
public long Length { get; set; }
[DataMember(Name = "uploaded", IsRequired = true)]
public string Uploaded { get; set; }
}
/// <summary>
/// Code signing
/// </summary>
[Help("NoSign", "Skips signing of code/content files.")]
public class CodeSign
{
/// <summary>
/// If so, what is the signing identity to search for?
/// </summary>
public static string SigningIdentity = "Epic Games";
/// <summary>
/// Should we use the machine store?
/// </summary>
public static bool bUseMachineStoreInsteadOfUserStore = false;
/// <summary>
/// How long to keep re-trying code signing for
/// </summary>
public static TimeSpan CodeSignTimeOut = new TimeSpan(0, 3, 0); // Keep trying to sign one file for up to 3 minutes
/// <summary>
/// Finds the path to SignTool.exe, or throws an exception.
/// </summary>
/// <returns>Path to signtool.exe</returns>
public static string GetSignToolPath()
{
string[] PossibleSignToolNames =
{
"C:/Program Files (x86)/Windows Kits/8.1/bin/x86/SignTool.exe",
"C:/Program Files (x86)/Windows Kits/10/bin/x86/SignTool.exe"
};
foreach(string PossibleSignToolName in PossibleSignToolNames)
{
if(File.Exists(PossibleSignToolName))
{
return PossibleSignToolName;
}
}
throw new AutomationException("SignTool not found at '{0}' (are you missing the Windows SDK?)", String.Join("' or '", PossibleSignToolNames));
}
/// <summary>
/// Code signs the specified file
/// </summary>
public static void SignSingleExecutableIfEXEOrDLL(string Filename, bool bIgnoreExtension = false)
{
if (UnrealBuildTool.Utils.IsRunningOnMono)
{
CommandUtils.LogLog(String.Format("Can't sign '{0}', we are running under mono.", Filename));
return;
}
if (!CommandUtils.FileExists(Filename))
{
throw new AutomationException("Can't sign '{0}', file does not exist.", Filename);
}
// Make sure the file isn't read-only
FileInfo TargetFileInfo = new FileInfo(Filename);
// Executable extensions
List<string> Extensions = new List<string>();
Extensions.Add(".dll");
Extensions.Add(".exe");
bool IsExecutable = bIgnoreExtension;
foreach (var Ext in Extensions)
{
if (TargetFileInfo.FullName.EndsWith(Ext, StringComparison.InvariantCultureIgnoreCase))
{
IsExecutable = true;
break;
}
}
if (!IsExecutable)
{
CommandUtils.LogLog(String.Format("Won't sign '{0}', not an executable.", TargetFileInfo.FullName));
return;
}
string SignToolName = GetSignToolPath();
TargetFileInfo.IsReadOnly = false;
// Code sign the executable
string[] TimestampServer = { "http://timestamp.verisign.com/scripts/timestamp.dll",
"http://timestamp.globalsign.com/scripts/timstamp.dll",
"http://timestamp.comodoca.com/authenticode",
"http://www.startssl.com/timestamp"
};
int TimestampServerIndex = 0;
string SpecificStoreArg = bUseMachineStoreInsteadOfUserStore ? " /sm" : "";
DateTime StartTime = DateTime.Now;
int NumTrials = 0;
for (; ; )
{
//@TODO: Verbosity choosing
// /v will spew lots of info
// /q does nothing on success and minimal output on failure
string CodeSignArgs = String.Format("sign{0} /a /n \"{1}\" /t {2} /d \"{3}\" /v \"{4}\"", SpecificStoreArg, SigningIdentity, TimestampServer[TimestampServerIndex], TargetFileInfo.Name, TargetFileInfo.FullName);
IProcessResult Result = CommandUtils.Run(SignToolName, CodeSignArgs, null, CommandUtils.ERunOptions.AllowSpew);
++NumTrials;
if (Result.ExitCode != 1)
{
if (Result.ExitCode == 2)
{
CommandUtils.LogError(String.Format("Signtool returned a warning."));
}
// Success!
break;
}
else
{
// try another timestamp server on the next iteration
TimestampServerIndex++;
if (TimestampServerIndex >= TimestampServer.Count())
{
// loop back to the first timestamp server
TimestampServerIndex = 0;
}
// Keep retrying until we run out of time
TimeSpan RunTime = DateTime.Now - StartTime;
if (RunTime > CodeSignTimeOut)
{
throw new AutomationException("Failed to sign executable '{0}' {1} times over a period of {2}", TargetFileInfo.FullName, NumTrials, RunTime);
}
}
}
}
/// <summary>
/// Code signs the specified file or folder
/// </summary>
public static void SignMacFileOrFolder(string InPath, bool bIgnoreExtension = false)
{
bool bExists = CommandUtils.FileExists(InPath) || CommandUtils.DirectoryExists(InPath);
if (!bExists)
{
throw new AutomationException("Can't sign '{0}', file or folder does not exist.", InPath);
}
// Executable extensions
List<string> Extensions = new List<string>();
Extensions.Add(".dylib");
Extensions.Add(".app");
Extensions.Add(".framework");
bool IsExecutable = bIgnoreExtension || (Path.GetExtension(InPath) == "" && !InPath.EndsWith("PkgInfo"));
foreach (var Ext in Extensions)
{
if (InPath.EndsWith(Ext, StringComparison.InvariantCultureIgnoreCase))
{
IsExecutable = true;
break;
}
}
if (!IsExecutable)
{
CommandUtils.LogLog(String.Format("Won't sign '{0}', not an executable.", InPath));
return;
}
// Use the old codesigning tool after the upgrade due to segmentation fault on Sierra
string SignToolName = "/usr/local/bin/codesign_old";
// unless it doesn't exist, then use the Sierra one.
if(!File.Exists(SignToolName))
{
SignToolName = "/usr/bin/codesign";
}
string CodeSignArgs = String.Format("-f --deep -s \"{0}\" -v \"{1}\" --no-strict", "Developer ID Application", InPath);
DateTime StartTime = DateTime.Now;
int NumTrials = 0;
for (; ; )
{
IProcessResult Result = CommandUtils.Run(SignToolName, CodeSignArgs, null, CommandUtils.ERunOptions.AllowSpew);
int ExitCode = Result.ExitCode;
++NumTrials;
if (ExitCode == 0)
{
// Success!
break;
}
else
{
// Keep retrying until we run out of time
TimeSpan RunTime = DateTime.Now - StartTime;
if (RunTime > CodeSignTimeOut)
{
throw new AutomationException("Failed to sign '{0}' {1} times over a period of {2}", InPath, NumTrials, RunTime);
}
}
}
}
/// <summary>
/// Codesigns multiple files, but skips anything that's not an EXE or DLL file
/// Will automatically skip signing if -NoSign is specified in the command line.
/// </summary>
/// <param name="Files">List of files to sign</param>
public static void SignMultipleIfEXEOrDLL(BuildCommand Command, IEnumerable<string> Files)
{
if (!Command.ParseParam("NoSign"))
{
CommandUtils.Log("Signing up to {0} files...", Files.Count());
UnrealBuildTool.UnrealTargetPlatform TargetPlatform = UnrealBuildTool.BuildHostPlatform.Current.Platform;
if (TargetPlatform == UnrealBuildTool.UnrealTargetPlatform.Mac)
{
foreach (var File in Files)
{
SignMacFileOrFolder(File);
}
}
else
{
List<FileReference> FilesToSign = new List<FileReference>();
foreach (string File in Files)
{
if (!(Path.GetDirectoryName(File).Replace("\\", "/")).Contains("Binaries/XboxOne"))
{
FilesToSign.Add(new FileReference(File));
}
}
SignMultipleFilesIfEXEOrDLL(FilesToSign);
}
}
else
{
CommandUtils.LogLog("Skipping signing {0} files due to -nosign.", Files.Count());
}
}
public static void SignListFilesIfEXEOrDLL(string FilesToSign)
{
string SignToolName = GetSignToolPath();
// nothing to sign
if (String.IsNullOrEmpty(FilesToSign))
{
return;
}
// Code sign the executable
string[] TimestampServer = { "http://timestamp.verisign.com/scripts/timestamp.dll",
"http://timestamp.globalsign.com/scripts/timstamp.dll",
"http://timestamp.comodoca.com/authenticode",
"http://www.startssl.com/timestamp"
};
string SpecificStoreArg = bUseMachineStoreInsteadOfUserStore ? " /sm" : "";
Stopwatch Stopwatch = Stopwatch.StartNew();
int NumTrials = 0;
for (; ; )
{
//@TODO: Verbosity choosing
// /v will spew lots of info
// /q does nothing on success and minimal output on failure
string CodeSignArgs = String.Format("sign{0} /a /n \"{1}\" /t {2} /debug {3}", SpecificStoreArg, SigningIdentity, TimestampServer[NumTrials % TimestampServer.Length], FilesToSign);
IProcessResult Result = CommandUtils.Run(SignToolName, CodeSignArgs, null, CommandUtils.ERunOptions.AllowSpew);
++NumTrials;
if (Result.ExitCode != 1)
{
if (Result.ExitCode == 2)
{
CommandUtils.LogError(String.Format("Signtool returned a warning."));
}
// Success!
break;
}
else
{
// Keep retrying until we run out of time
TimeSpan RunTime = Stopwatch.Elapsed;
if (RunTime > CodeSignTimeOut && NumTrials >= TimestampServer.Length)
{
throw new AutomationException("Failed to sign executables {0} times over a period of {1}", NumTrials, RunTime);
}
}
}
}
public static void SignMultipleFilesIfEXEOrDLL(List<FileReference> Files, bool bIgnoreExtension = false)
{
if (UnrealBuildTool.Utils.IsRunningOnMono)
{
CommandUtils.LogLog(String.Format("Can't sign we are running under mono."));
return;
}
List<string> FinalFiles = new List<string>();
foreach (string Filename in Files.Select(x => x.FullName))
{
FileInfo TargetFileInfo = new FileInfo(Filename);
// Executable extensions
List<string> Extensions = new List<string>();
Extensions.Add(".dll");
Extensions.Add(".exe");
Extensions.Add(".msi");
Extensions.Add(".dle");
bool IsExecutable = bIgnoreExtension;
foreach (var Ext in Extensions)
{
if (TargetFileInfo.FullName.EndsWith(Ext, StringComparison.InvariantCultureIgnoreCase))
{
// force file writable
TargetFileInfo.IsReadOnly = false;
IsExecutable = true;
break;
}
}
if (IsExecutable && CommandUtils.FileExists(Filename))
{
FinalFiles.Add(Filename);
}
}
StringBuilder FilesToSignBuilder = new StringBuilder();
List<string> FinalListSignStrings = new List<string>();
foreach(string File in FinalFiles)
{
FilesToSignBuilder.Append("\"" + File + "\" ");
if(FilesToSignBuilder.Length > 1900)
{
string AddFilesToFinalList = FilesToSignBuilder.ToString();
FinalListSignStrings.Add(AddFilesToFinalList);
FilesToSignBuilder.Clear();
}
}
FinalListSignStrings.Add(FilesToSignBuilder.ToString());
foreach(string FilesToSign in FinalListSignStrings)
{
SignListFilesIfEXEOrDLL(FilesToSign);
}
}
}
}