syncthing/lib/config/size.go
Jakob Borg da34f27546 gui, lib/config, lib/model: Allow absolute values for minimum disk free space (fixes #3307)
This deprecates the current minDiskFreePct setting and introduces
minDiskFree. The latter is, in it's serialized form, a string with a
unit. We accept percentages ("2.35%") and absolute values ("250 k", "12.5
Gi"). Common suffixes are understood. The config editor lets the user
enter the string, and validates it.

We still default to "1 %", but the user can change that to an absolute
value at will.

GitHub-Pull-Request: https://github.com/syncthing/syncthing/pull/4087
LGTM: AudriusButkevicius, imsodin
2017-04-12 09:01:19 +00:00

76 lines
1.4 KiB
Go

// Copyright (C) 2017 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package config
import (
"fmt"
"strconv"
"strings"
)
type Size struct {
Value float64 `json:"value" xml:",chardata"`
Unit string `json:"unit" xml:"unit,attr"`
}
func ParseSize(s string) (Size, error) {
s = strings.TrimSpace(s)
if len(s) == 0 {
return Size{}, nil
}
var num, unit string
for i := 0; i < len(s) && (s[i] >= '0' && s[i] <= '9' || s[i] == '.' || s[i] == ','); i++ {
num = s[:i+1]
}
var i = len(num)
for i < len(s) && s[i] == ' ' {
i++
}
unit = s[i:]
val, err := strconv.ParseFloat(num, 64)
if err != nil {
return Size{}, err
}
return Size{val, unit}, nil
}
func (s Size) BaseValue() float64 {
unitPrefix := s.Unit
if len(unitPrefix) > 1 {
unitPrefix = unitPrefix[:1]
}
mult := 1.0
switch unitPrefix {
case "k", "K":
mult = 1000
case "m", "M":
mult = 1000 * 1000
case "g", "G":
mult = 1000 * 1000 * 1000
case "t", "T":
mult = 1000 * 1000 * 1000 * 1000
}
return s.Value * mult
}
func (s Size) Percentage() bool {
return strings.Contains(s.Unit, "%")
}
func (s Size) String() string {
return fmt.Sprintf("%v %s", s.Value, s.Unit)
}
func (Size) ParseDefault(s string) (interface{}, error) {
return ParseSize(s)
}