github.com/ncw/rclone@v1.48.1-0.20190724201158-a35aa1360e3e/backend/opendrive/replace.go (about)

     1  /*
     2  Translate file names for OpenDrive
     3  
     4  OpenDrive reserved characters
     5  
     6  The following characters are OpenDrive reserved characters, and can't
     7  be used in OpenDrive folder and file names.
     8  
     9  \ / : * ? " < > |
    10  
    11  OpenDrive files and folders can't have leading or trailing spaces also.
    12  
    13  */
    14  
    15  package opendrive
    16  
    17  import (
    18  	"regexp"
    19  	"strings"
    20  )
    21  
    22  // charMap holds replacements for characters
    23  //
    24  // OpenDrive has a restricted set of characters compared to other cloud
    25  // storage systems, so we to map these to the FULLWIDTH unicode
    26  // equivalents
    27  //
    28  // http://unicode-search.net/unicode-namesearch.pl?term=SOLIDUS
    29  var (
    30  	charMap = map[rune]rune{
    31  		'\\': '\', // FULLWIDTH REVERSE SOLIDUS
    32  		':':  ':', // FULLWIDTH COLON
    33  		'*':  '*', // FULLWIDTH ASTERISK
    34  		'?':  '?', // FULLWIDTH QUESTION MARK
    35  		'"':  '"', // FULLWIDTH QUOTATION MARK
    36  		'<':  '<', // FULLWIDTH LESS-THAN SIGN
    37  		'>':  '>', // FULLWIDTH GREATER-THAN SIGN
    38  		'|':  '|', // FULLWIDTH VERTICAL LINE
    39  		' ':  '␠', // SYMBOL FOR SPACE
    40  	}
    41  	fixStartingWithSpace = regexp.MustCompile(`(/|^) `)
    42  	fixEndingWithSpace   = regexp.MustCompile(` (/|$)`)
    43  	invCharMap           map[rune]rune
    44  )
    45  
    46  func init() {
    47  	// Create inverse charMap
    48  	invCharMap = make(map[rune]rune, len(charMap))
    49  	for k, v := range charMap {
    50  		invCharMap[v] = k
    51  	}
    52  }
    53  
    54  // replaceReservedChars takes a path and substitutes any reserved
    55  // characters in it
    56  func replaceReservedChars(in string) string {
    57  	// Filenames can't start with space
    58  	in = fixStartingWithSpace.ReplaceAllString(in, "$1"+string(charMap[' ']))
    59  	// Filenames can't end with space
    60  	in = fixEndingWithSpace.ReplaceAllString(in, string(charMap[' '])+"$1")
    61  	return strings.Map(func(c rune) rune {
    62  		if replacement, ok := charMap[c]; ok && c != ' ' {
    63  			return replacement
    64  		}
    65  		return c
    66  	}, in)
    67  }
    68  
    69  // restoreReservedChars takes a path and undoes any substitutions
    70  // made by replaceReservedChars
    71  func restoreReservedChars(in string) string {
    72  	return strings.Map(func(c rune) rune {
    73  		if replacement, ok := invCharMap[c]; ok {
    74  			return replacement
    75  		}
    76  		return c
    77  	}, in)
    78  }