github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/cmd/snap-update-ns/sorting.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  	"strings"
    24  
    25  	"github.com/snapcore/snapd/osutil"
    26  )
    27  
    28  // byOriginAndMagicDir allows sorting an array of entries by the source of mount
    29  // entry (overname, layout, content) and lexically by mount point name.
    30  // Automagically adds a trailing slash to paths.
    31  type byOriginAndMagicDir []osutil.MountEntry
    32  
    33  func (c byOriginAndMagicDir) Len() int      { return len(c) }
    34  func (c byOriginAndMagicDir) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
    35  func (c byOriginAndMagicDir) Less(i, j int) bool {
    36  	iMe := c[i]
    37  	jMe := c[j]
    38  
    39  	iOrigin := iMe.XSnapdOrigin()
    40  	jOrigin := jMe.XSnapdOrigin()
    41  	if iOrigin != jOrigin {
    42  		// overname entries should always be sorted first, before
    43  		// entries from layouts or content interface
    44  		if iOrigin == "overname" {
    45  			// overname ith element should be sorted before
    46  			return true
    47  		}
    48  		if jOrigin == "overname" {
    49  			// non-overname ith element should be sorted after
    50  			return false
    51  		}
    52  	}
    53  
    54  	iDir := c[i].Dir
    55  	jDir := c[j].Dir
    56  	if !strings.HasSuffix(iDir, "/") {
    57  		iDir = iDir + "/"
    58  	}
    59  	if !strings.HasSuffix(jDir, "/") {
    60  		jDir = jDir + "/"
    61  	}
    62  	return iDir < jDir
    63  }