lilydjwg/swapview-rosetta

example with CoffeeScript and Promise

tiye opened this issue · 0 comments

tiye commented
fs = require 'fs'
Promise = require 'promise'

readdir = Promise.denodeify fs.readdir
read = Promise.denodeify fs.readFile

addString = (sum, line) -> sum + (Number (line.match /\d+/)[0])
addSecond = (sum, aaa) -> sum + aaa[1]

formatSize0 = (n) ->
  formatSize = (acc, n) ->
    if (n > 1100) and (acc <= 3)
    then formatSize (acc + 1), (n /= 1024)
    else
      unit = 'KMGT'[acc]
      num = n.toFixed(1)
      "#{num}#{unit}iB"
  formatSize 0, n

fillLength = (n, str) ->
  if str.length < n
  then fillLength n, " #{str}"
  else str

readdir('/proc')
.then (files) ->
  list = files
  .filter (file) -> file.match /\d+/
  .map (file) ->
    (read "/proc/#{file}/smaps", 'utf8')
    .then (text) ->
      text.split('\n').filter (line) -> line.match(/^Swap/)
    .then (lines) ->
      (read "/proc/#{file}/cmdline", 'utf8')
      .then (text) ->
        cmdline = text.replace /\0/g, ' '
        [file, lines, cmdline]
  (Promise.all list)
  .then (res) ->
    out = res
    .filter (aaa) -> aaa[1].length > 0
    .map (aaa) ->
      aaa[1] = aaa[1].reduce(addString, 0)
      aaa
    .sort (aaa, bbb) -> aaa[1] - bbb[1]
    output out
.then null, (error) ->
  console.error 'error', error

output = (res) ->
  console.log [
    fillLength 5, 'PID'
    fillLength 9, 'SWAP'
    'COMMAND'
  ].join(' ')

  str = res
  .map (aaa) ->
    [
      fillLength 5, aaa[0]
      fillLength 9, (formatSize0 aaa[1])
      aaa[2]
    ].join(' ')
  .join('\n')
  console.log str

  console.log [
    'Total:'
    formatSize0 (res.reduce addSecond, 0)
  ].join('')
  # fs.writeFileSync 'data.json', JSON.stringify(res, null, 2)