require 'P4' # Rack middleware that cleans up any 'p4' handle added to the environment # during processing. # # This should always run, even in the face of exceptions. Make sure any # middleware configured after this step does *NOT* swallow exceptions. # # This expects that if a temporary workspace was generated, the 'p4_root' # variable was also added into the environment. See P4Helpers. class HWSP4Cleanup def initialize(app) @app = app end def call(env) ex = nil begin results = @app.call(env) rescue StandardError => e ex = e end # We need to convert any exception before attempting to delete, # otherwise the p4.messages and p4.errors will get reset at the next # method call. if ex.instance_of?(P4Exception) ex = Util.make_p4_error(p4) end if env.key?('p4') cleanup_p4(p4: env['p4'], p4_root: env['p4_root']) end raise ex unless ex.nil? results end def cleanup_p4(p4: nil, p4_root: nil) if p4 and p4.client != 'INVALID' p4.run_client('-d', p4.client) FileUtils.rmtree(p4_root) unless p4_root.nil? end p4.disconnect if p4 and p4.connected? end end