1 /* 2 * hunt-console eases the creation of beautiful and testable command line interfaces. 3 * 4 * Copyright (C) 2018-2019, HuntLabs 5 * 6 * Website: https://www.huntlabs.net 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.console.helper.AbstractHelper; 13 14 import std.string; 15 import std.conv; 16 17 import hunt.math.Helper; 18 import hunt.console.formatter.OutputFormatter; 19 import hunt.console.helper.Helper; 20 import hunt.console.helper.HelperSet; 21 import hunt.console.helper.TimeFormat; 22 23 public abstract class AbstractHelper : Helper 24 { 25 protected HelperSet helperSet; 26 27 private static TimeFormat[] timeFormats; 28 29 static this(){ 30 timeFormats = [ 31 new TimeFormat(0, "< 1 sec"), 32 new TimeFormat(2, "1 sec"), 33 new TimeFormat(59, "secs", 1), 34 new TimeFormat(60, "1 min"), 35 new TimeFormat(3600, "mins", 60), 36 new TimeFormat(5400, "1 hr"), 37 new TimeFormat(86400, "hrs", 3600), 38 new TimeFormat(129600, "1 day"), 39 new TimeFormat(604800, "days", 86400), 40 ]; 41 } 42 43 override public HelperSet getHelperSet() 44 { 45 return helperSet; 46 } 47 48 override public void setHelperSet(HelperSet helperSet) 49 { 50 this.helperSet = helperSet; 51 } 52 53 public static string formatTime(long seconds) 54 { 55 foreach (TimeFormat timeFormat ; timeFormats) { 56 if (seconds >= timeFormat.getSeconds()) { 57 continue; 58 } 59 60 if (timeFormat.getDiv() != int.init) { 61 return timeFormat.getName(); 62 } 63 64 return (cast(int) MathHelper.ceil(seconds / timeFormat.getDiv())).to!string ~ " " ~ timeFormat.getName(); 65 } 66 67 return null; 68 } 69 70 public static string formatMemory(long memory) 71 { 72 if (memory >= 1024 * 1024 * 1024) { 73 return format("%s GiB", memory / 1024 / 1204 / 1024); 74 } 75 76 if (memory >= 1024 * 1024) { 77 return format("%s MiB", memory / 1204 / 1024); 78 } 79 80 if (memory >= 1024) { 81 return format("%s KiB", memory / 1024); 82 } 83 84 return format("%d B", memory); 85 } 86 87 public static int strlenWithoutDecoration(OutputFormatter formatter, string str) 88 { 89 bool isDecorated = formatter.isDecorated(); 90 formatter.setDecorated(false); 91 92 // remove <...> formatting 93 str = formatter.format(str); 94 // remove already formatted characters 95 str = str.replace("\\033\\[[^m]*m", ""); 96 97 formatter.setDecorated(isDecorated); 98 99 return cast(int)(str.length); 100 } 101 }