@@ -112,6 +112,11 @@ type FileType struct {
112112var (
113113 headerPool * pool.BufferPool
114114 initializeOnce sync.Once
115+ versionRegex = regexp .MustCompile (`\d+\.\d+\.\d+$` )
116+ // Magic byte constants for common file signatures.
117+ elfMagic = []byte {0x7f , 'E' , 'L' , 'F' }
118+ gzipMagic = []byte {0x1f , 0x8b }
119+ ZMagic = []byte {0x78 , 0x5E }
115120)
116121
117122const headerSize int = 512
@@ -137,19 +142,15 @@ func GetExt(path string) string {
137142
138143 // Handle files with version numbers in the name
139144 // e.g. file1.2.3.tar.gz -> .tar.gz
140- re := regexp .MustCompile (`\d+\.\d+\.\d+$` )
141- base = re .ReplaceAllString (base , "" )
145+ base = versionRegex .ReplaceAllString (base , "" )
142146
143147 ext := filepath .Ext (base )
144148
145149 if ext != "" && strings .Contains (base , "." ) {
146150 parts := strings .Split (base , "." )
147151 if len (parts ) > 2 {
148152 subExt := fmt .Sprintf (".%s%s" , parts [len (parts )- 2 ], ext )
149- if isValidExt := func (ext string ) bool {
150- _ , ok := ArchiveMap [ext ]
151- return ok
152- }(subExt ); isValidExt {
153+ if _ , ok := ArchiveMap [subExt ]; ok {
153154 return subExt
154155 }
155156 }
@@ -252,9 +253,7 @@ func File(path string) (*FileType, error) {
252253 return nil , nil
253254 }
254255
255- initializeOnce .Do (func () {
256- headerPool = pool .NewBufferPool (runtime .GOMAXPROCS (0 ))
257- })
256+ initializeHeaderPool ()
258257
259258 buf := headerPool .Get (int64 (headerSize ))
260259 defer headerPool .Put (buf )
@@ -289,7 +288,7 @@ func File(path string) (*FileType, error) {
289288 }
290289
291290 switch {
292- case hdr [ 0 ] == '\x7f' && (hdr [ 1 ] == 'E' && hdr [ 2 ] == 'L' && hdr [ 3 ] == 'F' ):
291+ case bytes . HasPrefix (hdr , elfMagic ):
293292 return Path (".elf" ), nil
294293 case bytes .Contains (hdr , []byte ("<?php" )):
295294 return Path (".php" ), nil
@@ -316,14 +315,20 @@ func File(path string) (*FileType, error) {
316315 return Path (".c" ), nil
317316 case bytes .Contains (hdr , []byte ("BEAMAtU8" )):
318317 return Path (".beam" ), nil
319- case hdr [ 0 ] == '\x1f' && hdr [ 1 ] == '\x8b' :
318+ case bytes . HasPrefix ( hdr , gzipMagic ) :
320319 return Path (".gzip" ), nil
321- case hdr [ 0 ] == '\x78' && hdr [ 1 ] == '\x5E' :
320+ case bytes . HasPrefix ( hdr , ZMagic ) :
322321 return Path (".Z" ), nil
323322 }
324323 return nil , nil
325324}
326325
326+ func initializeHeaderPool () {
327+ initializeOnce .Do (func () {
328+ headerPool = pool .NewBufferPool (runtime .GOMAXPROCS (0 ))
329+ })
330+ }
331+
327332// Path returns a filetype based strictly on file path.
328333func Path (path string ) * FileType {
329334 ext := strings .ReplaceAll (filepath .Ext (path ), "." , "" )
0 commit comments