-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafe_filename.go
97 lines (73 loc) · 2.03 KB
/
safe_filename.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
///////////////////////////////////////////////////////////////////////////////
//
// rmweb/safe_filename.go
// John Simpson <[email protected]> 2023-12-18
//
// Given a filename, return a possibly modified filename which doesn't
// already exist.
package main
import (
"fmt"
"log"
"os"
"strings"
)
///////////////////////////////////////////////////////////////////////////////
//
// Does a file exist or not?
func file_exists( name string ) bool {
_,err := os.Stat( name )
if err == nil {
return true
}
if os.IsNotExist( err ) {
return false
}
log.Fatal( fmt.Sprintf( "file_exists('%s'): %v\n" , name , err ) )
os.Exit( 1 )
return false
}
///////////////////////////////////////////////////////////////////////////////
//
// Return a possibly modified filename which doesn't already exist
func safe_filename( name string ) string {
if flag_debug {
fmt.Printf( "safe_filename('%s') starting\n" , name )
}
rv := name
////////////////////////////////////////
// Find extension in filename
base := rv
ext := ""
dotp := strings.LastIndex( rv , "." )
if dotp >= 0 {
base = rv[:dotp]
ext = rv[dotp:]
}
if flag_debug {
fmt.Printf( "safe_filename() base='%s' ext='%s'\n" , base , ext )
}
////////////////////////////////////////
// Try numbers until we find one which doesn't exist yet
if file_exists( rv ) {
n := 1
x := fmt.Sprintf( "%s-%d%s" , base , n , ext )
if flag_debug {
fmt.Printf( "safe_filename() x='%s'\n" , x )
}
for file_exists( x ) {
n ++
x = fmt.Sprintf( "%s-%d%s" , base , n , ext )
if flag_debug {
fmt.Printf( "safe_filename() x='%s'\n" , x )
}
}
rv = x
}
////////////////////////////////////////
// Return what we found
if flag_debug {
fmt.Printf( "safe_filename('%s') returning '%s'\n" , name , rv )
}
return rv
}