#NEWLINE# def safe_filename( name , extension = None , digest = None , max_length = _MAX_FILENAME_LENGTH ) : #NEWLINE# #INDENT# 'Creates filename from name and extension ensuring that the final length is within the\n  max_length constraint.\n\n  By default the length is capped to work on most filesystems and the fallback to achieve\n  shortening is a sha1 hash of the proposed name.\n\n  Raises ValueError if the proposed name is not a simple filename but a file path.\n  Also raises ValueError when the name is simple but cannot be satisfactorily shortened with the\n  given digest.\n\n  :API: public\n\n  name:       the proposed filename without extension\n  extension:  an optional extension to append to the filename\n  digest:     the digest to fall back on for too-long name, extension concatenations - should\n              support the hashlib digest api of update(string) and hexdigest\n  max_length: the maximum desired file name length\n  ' #NEWLINE# if ( os . path . basename ( name ) != name ) : #NEWLINE# #INDENT# raise ValueError ( 'Name must be a filename, handed a path: {}' . format ( name ) ) #NEWLINE# #UNINDENT# ext = ( extension or '' ) #NEWLINE# filename = ( name + ext ) #NEWLINE# if ( len ( filename ) <= max_length ) : #NEWLINE# #INDENT# return filename #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# digest = ( digest or hashlib . sha1 ( ) ) #NEWLINE# digest . update ( name ) #NEWLINE# safe_name = ( digest . hexdigest ( ) + ext ) #NEWLINE# if ( len ( safe_name ) > max_length ) : #NEWLINE# #INDENT# raise ValueError ( 'Digest {} failed to produce a filename <= {} characters for {} - got {}' . format ( name , max_length , filename , safe_name ) ) #NEWLINE# #UNINDENT# return safe_name