gopkg.in/ubuntu-core/snappy.v0@v0.0.0-20210902073436-25a8614f10a6/osutil/disks/labels.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2020 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package disks
    21  
    22  import (
    23  	"bytes"
    24  	"fmt"
    25  	"strings"
    26  	"unicode/utf8"
    27  )
    28  
    29  // BlkIDEncodeLabel encodes a name for use as a partition or filesystem
    30  // label symlink by udev. The result matches the output of blkid_encode_string()
    31  // from libblkid.
    32  func BlkIDEncodeLabel(in string) string {
    33  	const allowed = `#+-.:=@_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`
    34  
    35  	buf := &bytes.Buffer{}
    36  
    37  	for _, r := range in {
    38  		switch {
    39  		case utf8.RuneLen(r) > 1:
    40  			buf.WriteRune(r)
    41  		case !strings.ContainsRune(allowed, r):
    42  			fmt.Fprintf(buf, `\x%x`, r)
    43  		default:
    44  			buf.WriteRune(r)
    45  		}
    46  	}
    47  	return buf.String()
    48  }