All files / src/linux linux.js

100% Statements 165/165
100% Branches 60/60
100% Functions 48/48
100% Lines 134/134

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 2351x 1x     1x           115x   12x 12x 12x 12x 12x 12x 12x 12x     27x 27x 27x 27x 27x 27x 27x     10x 5x   42x 95x 14x 23x 23x 23x       5x   14x   141x 141x                                         9x 81x 9x 3x   9x 9x 9x 9x     27x 243x 27x 8x   27x 27x 27x 27x 27x 27x 27x     3x 5x   5x 45x   5x 38x 304x   38x 11x   27x     5x     73x 11x 11x 1x   10x 10x 10x 9x   10x 10x 10x   44x 10x 10x 10x       10x     8x   52x 14x 14x 1x   13x 13x 13x 5x   13x 13x 13x         2x 4x 4x 17x 10x 7x 6x     4x 4x 4x 4x 97x 97x   17x   17x 80x 73x   97x   4x         17x 122x 120x 1x   119x   120x     4x   4x 47x     4x 105x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x           3x 20x 5x     5x             5x        
import F from '../functional';
import { lasti as lastIndex, hasSubstr } from '../utilities';
const { compose, map, reduce, filter } = F.R;
 
export const COMMAND = 'df -T && ' +
  'echo "" && echo "**********" && echo "" && ' +
  'fdisk -l && ' +
  'echo "" && echo "**********" && echo "" && ' +
  'lsblk -o kname,fstype,mountpoint,label,ro,rm,model,type -P';
 
export const getNodeId = (node) => lastIndex(node.split('/').filter((s) => s.trim()));
 
export const createNewDevice = (emptyDevice) => (id, node = null) => {
  const device = emptyDevice();
  device.id = id;
  device.node = node || `/dev/${id}`;
  device.name = id;
  device.whole = true;
  device.parent = id;
  return device;
};
 
export const createNewVolume = (emptyVolume) => (id, node = null) => {
  const volume = emptyVolume();
  volume.id = id;
  volume.node = node || `/dev/${id}`;
  volume.name = id;
  volume.parent = id.match(/[a-z]+/)[0];
  return volume;
};
 
export const mergeVolumesAndDevicesLinux = (emptyDevice) => ({ devices, volumes }) => {
  const vkeys = Object.keys(volumes);
  // Merge volumes to devices
  Object.entries(devices).forEach(([key, dev]) => {
    const vkeysForDev = vkeys.filter((k) => hasSubstr(k, key)); // volume keys that belong to current device
    dev.volumes = vkeysForDev.map((k) => {
      const volume = volumes[k];
      if(dev.volumeBlockSize) volume.blockSize = dev.volumeBlockSize;
      return volume;
    });
  });
  // Remove the volumeBlockSize property from the devices
  return {
    devices: map(
      (d) => reduce(
        (a, v, k) => {
          if(k !== 'volumeBlockSize') a[k] = v;
          return a;
        },
        emptyDevice()
      )(d),
      devices
    ),
  };
};
 
// Values Example
// ['sdc1', 'vfat', '/media/user/KINGSTON', 'KINGSTON', '0', '1', '', 'part']
/*
 * 0: KNAME
 * 1: FSTYPE
 * 2: MOUNTPOINT
 * 3: LABEL
 * 4: RO
 * 5: RM
 * 6: MODEL
 * 7: TYPE
 */
export const parselsblkDeviceData = (createNewDevice) => (acc) =>
  ([id, fs, mountPoint, label, readOnly, removable, model, _]) => {
    if(!acc.devices[id]){
      acc.devices[id] = createNewDevice(id);
    }
    acc.devices[id].readOnly = !!parseInt(readOnly);
    acc.devices[id].removable = !!parseInt(removable);
    acc.devices[id].description = acc.devices[id].description || label || null;
    return acc;
  };
 
export const parselsblkVolumeData = (createNewVolume) => (acc) =>
  ([id, fs, mountPoint, label, readOnly, removable, model, _]) => {
    if(!acc.volumes[id]){
      acc.volumes[id] = createNewVolume(id);
    }
    acc.volumes[id].fs = fs || null;
    acc.volumes[id].mounted = !!mountPoint;
    acc.volumes[id].mountPoint = mountPoint || null;
    acc.volumes[id].readOnly = !!parseInt(readOnly);
    acc.volumes[id].removable = !!parseInt(removable);
    acc.volumes[id].description = acc.volumes[id].description || label || null;
    return acc;
  };
 
export const parselsblk = (parselsblkDeviceData, parselsblkVolumeData) =>
  (lsblk) => (acc) => {
    const lines =
      lsblk.split('\n') // Split by line
        .filter((s) => s.trim()); // Remove empty lines
 
    lines.forEach((line) => {
      const fields = line.match(/([A-Z]+="[^"]*")+/g);
      const values = fields.map((field) => field.replace(/"/g, '').split('=')[1]);
 
      if(values[values.length - 1] === 'disk'){
        return parselsblkDeviceData(acc)(values);
      }
      return parselsblkVolumeData(acc)(values);
    });
 
    return acc;
  };
 
export const parsefdisklDeviceData = (getNodeId, createNewDevice) => (acc) => ([head, ...tail]) => {
  const matches = head.match(/Disk\s(.*):\s.*,\s(\d+)\sbytes,\s(\d+) sectors/);
  if(matches == null){
    throw new Error(`parsefdisklDeviceData: error on parsing (head = ${head})`);
  }
  const [node, size, blocks] = matches.slice(1);
  const id = getNodeId(node);
  if(!acc.devices[id]){
    acc.devices[id] = createNewDevice(id, node);
  }
  acc.devices[id].blocks = parseInt(blocks);
  acc.devices[id].size = parseInt(size);
  tail.forEach(
    (line) => {
      if(line.match(/Sector.*:\s\d+\sbytes/)){
        const [logical, physical] = line.match(/(\d+)\s.*\s(\d+)\s/).slice(1);
        acc.devices[id].blockSize = parseInt(physical);
        acc.devices[id].volumeBlockSize = parseInt(logical);
      }
    }
  );
  return acc;
};
 
export const parsefdisklVolumeData = (getNodeId, createNewVolume) => (acc) => (lines) =>
  lines.reduce(
    (acc, line) => {
      const matches = line.match(/([\w\\/]+)\s+.*\s(\d+)\s+[\w.]+\s(.*)/);
      if(matches == null){
        throw new Error(`parsefdisklVolumeData: error on parsing (line = ${line})`);
      }
      const [node, sectors, description] = matches.slice(1);
      const id = getNodeId(node);
      if(!acc.volumes[id]){
        acc.volumes[id] = createNewVolume(id, node);
      }
      acc.volumes[id].blocks = parseInt(sectors);
      acc.volumes[id].description = description;
      return acc;
    },
    acc
  );
 
export const parsefdiskl = (parsefdisklDeviceData, parsefdisklVolumeData) =>
  (fdiskl) => (acc) => {
    const processblock = (block) => {
      if(block[0].startsWith('Disk')) {
        return parsefdisklDeviceData(acc)(block);
      }else if(block[0].startsWith('Device')) {
        return parsefdisklVolumeData(acc)(block.slice(1));
      }
    };
    const lines = fdiskl.split('\n');
    var block = [];
    var i = 0;
    while(i < lines.length) {
      var item = lines[i];
      if(item === '' && block.length > 0) {
        // process previous block
        processblock(block);
        // start new block
        block = [];
      }else if(item !== '') {
        block.push(item);
      }
      i++;
    };
    return acc;
  };
 
// split by space, except if space is preceeded by \ (paths with spaces)
// This is used instead of a negative lookbehind (`(?<!\\)\s+`)
export const splitdfTLine = (line) =>
  line.split(/\s+/).filter((s) => s.trim()).reduce((a, field) => {
    if(lastIndex(a) && lastIndex(lastIndex(a)) === '\\'){
      a[a.length - 1] += ` ${field}`;
    }else{
      a.push(field);
    }
    return a;
  }, []);
 
export const parsedfT = (getNodeId, createNewVolume, splitdfTLine) => (dft) => (acc) => {
  const lines =
    dft.split('\n')
      .filter((s) => s.trim() && !hasSubstr(s, 'tmpfs')) // remove empty lines & tmp file systems
      .slice(1); // remove table header
 
  return lines.reduce(
    (acc, line) => {
      const [ node, filesystem, size, used, available, , mountPoint ] = splitdfTLine(line);
      const id = getNodeId(node);
      acc.volumes[id] = createNewVolume(id, node);
      acc.volumes[id].mounted = true;
      acc.volumes[id].mountPoint = mountPoint;
      acc.volumes[id].fs = filesystem === 'vfat' ? 'FAT32' : filesystem;
      acc.volumes[id].space.total = parseInt(size) * 1024;
      acc.volumes[id].space.available = parseInt(available) * 1024;
      acc.volumes[id].space.used = parseInt(used) * 1024;
      return acc;
    },
    acc
  );
};
 
export const parseLinux = (mergeVolumesAndDevicesLinux, parselsblk, parsefdiskl, parsedfT) =>
  (userFilter) => (output) => {
    const parts = output.split('\n**********\n\n');
    const [dft, fdiskl, lsblk] = parts;
 
    const accumulator = compose(
      mergeVolumesAndDevicesLinux,
      parselsblk(lsblk),
      parsefdiskl(fdiskl),
      parsedfT(dft)
    )({ devices: {}, volumes: {} });
 
    return {
      devices: filter(userFilter, accumulator.devices),
    };
  };