github.com/elliott5/community@v0.14.1-0.20160709191136-823126fb026a/wordsmith/utility/beautify.go (about)

     1  // Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
     2  //
     3  // This software (Documize Community Edition) is licensed under 
     4  // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
     5  //
     6  // You can operate outside the AGPL restrictions by purchasing
     7  // Documize Enterprise Edition and obtaining a commercial license
     8  // by contacting <sales@documize.com>. 
     9  //
    10  // https://documize.com
    11  
    12  package utility
    13  
    14  import (
    15  	"path/filepath"
    16  	"strings"
    17  	"unicode"
    18  )
    19  
    20  // BeautifyFilename takes a filename and attempts to turn it into a readable form,
    21  // as TitleCase natural language, suitable for the top level of a Document.
    22  func BeautifyFilename(fn string) string {
    23  	_, file := filepath.Split(fn)
    24  	splits := strings.Split(file, ".")
    25  	r := []rune(strings.Join(splits[:len(splits)-1], "."))
    26  
    27  	// make any non-letter/digit characters space
    28  	for i := range r {
    29  		if !(unicode.IsLetter(r[i]) || unicode.IsDigit(r[i]) || r[i] == '.') {
    30  			r[i] = ' '
    31  		}
    32  	}
    33  
    34  	// insert spaces in front of any Upper/Lowwer 2-letter combinations
    35  addSpaces:
    36  	for i := range r {
    37  		if i > 1 { // do not insert a space at the start of the file name
    38  			if unicode.IsLower(r[i]) && unicode.IsUpper(r[i-1]) && r[i-2] != ' ' {
    39  				n := make([]rune, len(r)+1)
    40  				for j := 0; j < i-1; j++ {
    41  					n[j] = r[j]
    42  				}
    43  				n[i-1] = ' '
    44  				for j := i - 1; j < len(r); j++ {
    45  					n[j+1] = r[j]
    46  				}
    47  				r = n
    48  				goto addSpaces
    49  			}
    50  		}
    51  	}
    52  
    53  	// make the first letter of each word upper case
    54  	for i := range r {
    55  		switch i {
    56  		case 0:
    57  			r[i] = unicode.ToUpper(r[i])
    58  		case 1: // the zero element should never be space
    59  		default:
    60  			if r[i-1] == ' ' {
    61  				r[i] = unicode.ToUpper(r[i])
    62  			}
    63  		}
    64  	}
    65  	return string(r)
    66  }