gitee.com/mysnapcore/mysnapd@v0.1.0/cmd/snap-update-ns/xdg.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2017 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 main
    21  
    22  import (
    23  	"fmt"
    24  	"strings"
    25  
    26  	"gitee.com/mysnapcore/mysnapd/dirs"
    27  	"gitee.com/mysnapcore/mysnapd/osutil"
    28  )
    29  
    30  // xdgRuntimeDir returns the path to XDG_RUNTIME_DIR for a given user ID.
    31  func xdgRuntimeDir(uid int) string {
    32  	return fmt.Sprintf("%s/%d", dirs.XdgRuntimeDirBase, uid)
    33  }
    34  
    35  // expandPrefixVariable expands variable at the beginning of a path-like string.
    36  func expandPrefixVariable(path, variable, value string) string {
    37  	if strings.HasPrefix(path, variable) {
    38  		if len(path) == len(variable) {
    39  			return value
    40  		}
    41  		if len(path) > len(variable) && path[len(variable)] == '/' {
    42  			return value + path[len(variable):]
    43  		}
    44  	}
    45  	return path
    46  }
    47  
    48  // expandXdgRuntimeDir expands the $XDG_RUNTIME_DIR variable in the given mount profile.
    49  func expandXdgRuntimeDir(profile *osutil.MountProfile, uid int) {
    50  	variable := "$XDG_RUNTIME_DIR"
    51  	value := xdgRuntimeDir(uid)
    52  	for i := range profile.Entries {
    53  		profile.Entries[i].Name = expandPrefixVariable(profile.Entries[i].Name, variable, value)
    54  		profile.Entries[i].Dir = expandPrefixVariable(profile.Entries[i].Dir, variable, value)
    55  	}
    56  }