<commit_before>#!/usr/bin/env node

const TOKEN = require('./token');
const inquirer = require('inquirer');
const axios = require('axios');
const chalk = require('chalk');
const ora = require('ora');
const logUpdate = require('log-update');
const dns = require('dns');

dns.lookup('github.com', err => {
    if (err) {
        logUpdate(`\n${chalk.red.bold(' ✘')}${chalk.dim('  Can\'t create the repository. Check your inetrnet connection!\n')}`);
        process.exit(1);
    } else {
        const headers = {
            'Authorization': `token ${TOKEN}`
        };

        const parameter = [{
            type: 'input',
            name: 'name',
            message: 'Repository name: '
        }, {
            type: 'input',
            name: 'description',
            message: 'Description: '
        }, {
            type: 'rawlist',
            name: 'auto_init',
            message: 'Initialize Readme?',
            choices: [
                "Yes",
                "No",
            ]
        }, {
            type: 'list',
            name: 'private',
            message: 'Make Repository Private?',
            choices: [
                "Yes",
                "No",
            ]
        }, ]

        inquirer.prompt(parameter).then(function(answers) {
            var data = {
                name: answers.name,
                description: answers.description,
                gitignore_template: "nanoc"
            };

            if (answers.auto_init === 'Yes') {
                data.auto_init = true;
            } else {
                data.auto_init = false;
            }

            if (answers.private === 'Yes') {
                data.private = true;
            } else {
                data.private = false;
            }

            axios({
                    method: 'post',
                    url: '/user/repos',
                    baseURL: 'https://api.github.com',
                    headers: headers,
                    data: data
                }).then(function(response) {
                    const link = response.data.ssh_url;
                    console.log(chalk.bold.cyan('Repo Created, SSH URL is: ') + link);
                })
                .catch(function(error) {
                    const errorMessage = error.message;
                    console.log(chalk.red(errorMessage));
                });
        });
    }
})<commit_msg>minor fix<commit_after>#!/usr/bin/env node

const TOKEN = require('./token');
const inquirer = require('inquirer');
const axios = require('axios');
const chalk = require('chalk');
const ora = require('ora');
const logUpdate = require('log-update');
const dns = require('dns');

dns.lookup('github.com', err => {
    if (err) {
        logUpdate(`\n${chalk.red.bold(' ✘')}${chalk.dim('  Can\'t create the repository. Check your internet connection!\n')}`);
        process.exit(1);
    } else {
        const headers = {
            'Authorization': `token ${TOKEN}`
        };

        const parameter = [{
            type: 'input',
            name: 'name',
            message: 'Repository name: '
        }, {
            type: 'input',
            name: 'description',
            message: 'Description: '
        }, {
            type: 'rawlist',
            name: 'auto_init',
            message: 'Initialize Readme?',
            choices: [
                "Yes",
                "No",
            ]
        }, {
            type: 'list',
            name: 'private',
            message: 'Make Repository Private?',
            choices: [
                "Yes",
                "No",
            ]
        }, ]

        inquirer.prompt(parameter).then(function(answers) {
            var data = {
                name: answers.name,
                description: answers.description,
                gitignore_template: "nanoc"
            };

            if (answers.auto_init === 'Yes') {
                data.auto_init = true;
            } else {
                data.auto_init = false;
            }

            if (answers.private === 'Yes') {
                data.private = true;
            } else {
                data.private = false;
            }

            axios({
                    method: 'post',
                    url: '/user/repos',
                    baseURL: 'https://api.github.com',
                    headers: headers,
                    data: data
                }).then(function(response) {
                    const link = response.data.ssh_url;
                    console.log(chalk.bold.cyan('Repo Created, SSH URL is: ') + link);
                })
                .catch(function(error) {
                    const errorMessage = error.message;
                    console.log(chalk.red(errorMessage));
                });
        });
    }
})
<|endoftext|>


<commit_before>var SSR_NODE = 1
var TEXT_NODE = 3
var EMPTY_OBJ = {}
var EMPTY_ARR = []
var SVG_NS = "http://www.w3.org/2000/svg"

var id = (a) => a
var map = EMPTY_ARR.map
var isArray = Array.isArray
var enqueue =
  typeof requestAnimationFrame !== "undefined"
    ? requestAnimationFrame
    : setTimeout

var createClass = (obj) => {
  var out = ""

  if (typeof obj === "string") return obj

  if (isArray(obj)) {
    for (var k = 0, tmp; k < obj.length; k++) {
      if ((tmp = createClass(obj[k]))) {
        out += (out && " ") + tmp
      }
    }
  } else {
    for (var k in obj) {
      if (obj[k]) out += (out && " ") + k
    }
  }

  return out
}

var shouldRestart = (a, b) => {
  for (var k in { ...a, ...b }) {
    if (typeof (isArray(a[k]) ? a[k][0] : a[k]) === "function") {
      b[k] = a[k]
    } else if (a[k] !== b[k]) return true
  }
}

var patchSubs = (oldSubs, newSubs, dispatch) => {
  for (
    var subs = [], i = 0, oldSub, newSub;
    i < oldSubs.length || i < newSubs.length;
    i++
  ) {
    oldSub = oldSubs[i]
    newSub = newSubs[i]

    subs.push(
      newSub && newSub !== true
        ? !oldSub ||
          newSub[0] !== oldSub[0] ||
          shouldRestart(newSub[1], oldSub[1])
          ? [
              newSub[0],
              newSub[1],
              (oldSub && oldSub[2](), newSub[0](dispatch, newSub[1])),
            ]
          : oldSub
        : oldSub && oldSub[2]()
    )
  }
  return subs
}

var getKey = (vdom) => (vdom == null ? vdom : vdom.key)

var patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  if (key === "key") {
  } else if (key === "style") {
    for (var k in { ...oldValue, ...newValue }) {
      oldValue = newValue == null || newValue[k] == null ? "" : newValue[k]
      if (k[0] === "-") {
        node[key].setProperty(k, oldValue)
      } else {
        node[key][k] = oldValue
      }
    }
  } else if (key[0] === "o" && key[1] === "n") {
    if (
      !((node.events || (node.events = {}))[(key = key.slice(2))] = newValue)
    ) {
      node.removeEventListener(key, listener)
    } else if (!oldValue) {
      node.addEventListener(key, listener)
    }
  } else if (!isSvg && key !== "list" && key !== "form" && key in node) {
    node[key] = newValue == null ? "" : newValue
  } else if (
    newValue == null ||
    newValue === false ||
    (key === "class" && !(newValue = createClass(newValue)))
  ) {
    node.removeAttribute(key)
  } else {
    node.setAttribute(key, newValue)
  }
}

var createNode = (vdom, listener, isSvg) => {
  var props = vdom.props
  var node =
    vdom.type === TEXT_NODE
      ? document.createTextNode(vdom.tag)
      : (isSvg = isSvg || vdom.tag === "svg")
      ? document.createElementNS(SVG_NS, vdom.tag, { is: props.is })
      : document.createElement(vdom.tag, { is: props.is })

  for (var k in props) {
    patchProperty(node, k, null, props[k], listener, isSvg)
  }

  for (var i = 0; i < vdom.children.length; i++) {
    node.appendChild(
      createNode(
        (vdom.children[i] = maybeVNode(vdom.children[i])),
        listener,
        isSvg
      )
    )
  }

  return (vdom.node = node)
}

var patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  if (oldVNode === newVNode) {
  } else if (
    oldVNode != null &&
    oldVNode.type === TEXT_NODE &&
    newVNode.type === TEXT_NODE
  ) {
    if (oldVNode.tag !== newVNode.tag) node.nodeValue = newVNode.tag
  } else if (oldVNode == null || oldVNode.tag !== newVNode.tag) {
    node = parent.insertBefore(
      createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
      node
    )
    if (oldVNode != null) {
      parent.removeChild(oldVNode.node)
    }
  } else {
    var tmpVKid
    var oldVKid

    var oldKey
    var newKey

    var oldProps = oldVNode.props
    var newProps = newVNode.props

    var oldVKids = oldVNode.children
    var newVKids = newVNode.children

    var oldHead = 0
    var newHead = 0
    var oldTail = oldVKids.length - 1
    var newTail = newVKids.length - 1

    isSvg = isSvg || newVNode.tag === "svg"

    for (var i in { ...oldProps, ...newProps }) {
      if (
        (i === "value" || i === "selected" || i === "checked"
          ? node[i]
          : oldProps[i]) !== newProps[i]
      ) {
        patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
      }
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldHead])) == null ||
        oldKey !== getKey(newVKids[newHead])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldHead].node,
        oldVKids[oldHead],
        (newVKids[newHead] = maybeVNode(
          newVKids[newHead++],
          oldVKids[oldHead++]
        )),
        listener,
        isSvg
      )
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldTail])) == null ||
        oldKey !== getKey(newVKids[newTail])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldTail].node,
        oldVKids[oldTail],
        (newVKids[newTail] = maybeVNode(
          newVKids[newTail--],
          oldVKids[oldTail--]
        )),
        listener,
        isSvg
      )
    }

    if (oldHead > oldTail) {
      while (newHead <= newTail) {
        node.insertBefore(
          createNode(
            (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
            listener,
            isSvg
          ),
          (oldVKid = oldVKids[oldHead]) && oldVKid.node
        )
      }
    } else if (newHead > newTail) {
      while (oldHead <= oldTail) {
        node.removeChild(oldVKids[oldHead++].node)
      }
    } else {
      for (var keyed = {}, newKeyed = {}, i = oldHead; i <= oldTail; i++) {
        if ((oldKey = oldVKids[i].key) != null) {
          keyed[oldKey] = oldVKids[i]
        }
      }

      while (newHead <= newTail) {
        oldKey = getKey((oldVKid = oldVKids[oldHead]))
        newKey = getKey(
          (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
        )

        if (
          newKeyed[oldKey] ||
          (newKey != null && newKey === getKey(oldVKids[oldHead + 1]))
        ) {
          if (oldKey == null) {
            node.removeChild(oldVKid.node)
          }
          oldHead++
          continue
        }

        if (newKey == null || oldVNode.type === SSR_NODE) {
          if (oldKey == null) {
            patch(
              node,
              oldVKid && oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newHead++
          }
          oldHead++
        } else {
          if (oldKey === newKey) {
            patch(
              node,
              oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newKeyed[newKey] = true
            oldHead++
          } else {
            if ((tmpVKid = keyed[newKey]) != null) {
              patch(
                node,
                node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
                tmpVKid,
                newVKids[newHead],
                listener,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patch(
                node,
                oldVKid && oldVKid.node,
                null,
                newVKids[newHead],
                listener,
                isSvg
              )
            }
          }
          newHead++
        }
      }

      while (oldHead <= oldTail) {
        if (getKey((oldVKid = oldVKids[oldHead++])) == null) {
          node.removeChild(oldVKid.node)
        }
      }

      for (var i in keyed) {
        if (newKeyed[i] == null) {
          node.removeChild(keyed[i].node)
        }
      }
    }
  }

  return (newVNode.node = node)
}

var propsChanged = (a, b) => {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var maybeVNode = (newVNode, oldVNode) =>
  newVNode !== true && newVNode !== false && newVNode
    ? typeof newVNode.tag === "function"
      ? ((!oldVNode ||
          oldVNode.memo == null ||
          propsChanged(oldVNode.memo, newVNode.memo)) &&
          ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
        oldVNode)
      : newVNode
    : text("")

var recycleNode = (node) =>
  node.nodeType === TEXT_NODE
    ? text(node.nodeValue, node)
    : createVNode(
        node.nodeName.toLowerCase(),
        EMPTY_OBJ,
        map.call(node.childNodes, recycleNode),
        SSR_NODE,
        node
      )

var createVNode = (tag, props, children, type, node) => ({
  tag,
  props,
  key: props.key,
  children,
  type,
  node,
})

export var memo = (tag, memo) => ({ tag, memo })

export var text = (value, node) =>
  createVNode(value, EMPTY_OBJ, EMPTY_ARR, TEXT_NODE, node)

export var h = (tag, props, children = EMPTY_ARR) =>
  createVNode(tag, props, isArray(children) ? children : [children])

export var app = ({ init, view, subscriptions, dispatch = id, node }) => {
  var vdom = node && recycleNode(node)
  var subs = []
  var state
  var busy

  var setState = (newState) => {
    if (state !== newState) {
      state = newState
      if (subscriptions) {
        subs = patchSubs(subs, subscriptions(state), dispatch)
      }
      if (view && !busy) enqueue(render, (busy = true))
    }
  }

  var render = () =>
    (node = patch(
      node.parentNode,
      node,
      vdom,
      (vdom = view(state)),
      listener,
      (busy = false)
    ))

  var listener = function (event) {
    dispatch(this.events[event.type], event)
  }

  return (
    (dispatch = dispatch((action, props) =>
      typeof action === "function"
        ? dispatch(action(state, props))
        : isArray(action)
        ? typeof action[0] === "function"
          ? dispatch(action[0], action[1])
          : action
              .slice(1)
              .map(
                (fx) => fx && fx !== true && fx[0](dispatch, fx[1]),
                setState(action[0])
              )
        : action == null
        ? patchSubs(subs, EMPTY_ARR, (dispatch = id))
        : setState(action)
    ))(init),
    dispatch
  )
}
<commit_msg>Make init optional<commit_after>var SSR_NODE = 1
var TEXT_NODE = 3
var EMPTY_OBJ = {}
var EMPTY_ARR = []
var SVG_NS = "http://www.w3.org/2000/svg"

var id = (a) => a
var map = EMPTY_ARR.map
var isArray = Array.isArray
var enqueue =
  typeof requestAnimationFrame !== "undefined"
    ? requestAnimationFrame
    : setTimeout

var createClass = (obj) => {
  var out = ""

  if (typeof obj === "string") return obj

  if (isArray(obj)) {
    for (var k = 0, tmp; k < obj.length; k++) {
      if ((tmp = createClass(obj[k]))) {
        out += (out && " ") + tmp
      }
    }
  } else {
    for (var k in obj) {
      if (obj[k]) out += (out && " ") + k
    }
  }

  return out
}

var shouldRestart = (a, b) => {
  for (var k in { ...a, ...b }) {
    if (typeof (isArray(a[k]) ? a[k][0] : a[k]) === "function") {
      b[k] = a[k]
    } else if (a[k] !== b[k]) return true
  }
}

var patchSubs = (oldSubs, newSubs, dispatch) => {
  for (
    var subs = [], i = 0, oldSub, newSub;
    i < oldSubs.length || i < newSubs.length;
    i++
  ) {
    oldSub = oldSubs[i]
    newSub = newSubs[i]

    subs.push(
      newSub && newSub !== true
        ? !oldSub ||
          newSub[0] !== oldSub[0] ||
          shouldRestart(newSub[1], oldSub[1])
          ? [
              newSub[0],
              newSub[1],
              (oldSub && oldSub[2](), newSub[0](dispatch, newSub[1])),
            ]
          : oldSub
        : oldSub && oldSub[2]()
    )
  }
  return subs
}

var getKey = (vdom) => (vdom == null ? vdom : vdom.key)

var patchProperty = (node, key, oldValue, newValue, listener, isSvg) => {
  if (key === "key") {
  } else if (key === "style") {
    for (var k in { ...oldValue, ...newValue }) {
      oldValue = newValue == null || newValue[k] == null ? "" : newValue[k]
      if (k[0] === "-") {
        node[key].setProperty(k, oldValue)
      } else {
        node[key][k] = oldValue
      }
    }
  } else if (key[0] === "o" && key[1] === "n") {
    if (
      !((node.events || (node.events = {}))[(key = key.slice(2))] = newValue)
    ) {
      node.removeEventListener(key, listener)
    } else if (!oldValue) {
      node.addEventListener(key, listener)
    }
  } else if (!isSvg && key !== "list" && key !== "form" && key in node) {
    node[key] = newValue == null ? "" : newValue
  } else if (
    newValue == null ||
    newValue === false ||
    (key === "class" && !(newValue = createClass(newValue)))
  ) {
    node.removeAttribute(key)
  } else {
    node.setAttribute(key, newValue)
  }
}

var createNode = (vdom, listener, isSvg) => {
  var props = vdom.props
  var node =
    vdom.type === TEXT_NODE
      ? document.createTextNode(vdom.tag)
      : (isSvg = isSvg || vdom.tag === "svg")
      ? document.createElementNS(SVG_NS, vdom.tag, { is: props.is })
      : document.createElement(vdom.tag, { is: props.is })

  for (var k in props) {
    patchProperty(node, k, null, props[k], listener, isSvg)
  }

  for (var i = 0; i < vdom.children.length; i++) {
    node.appendChild(
      createNode(
        (vdom.children[i] = maybeVNode(vdom.children[i])),
        listener,
        isSvg
      )
    )
  }

  return (vdom.node = node)
}

var patch = (parent, node, oldVNode, newVNode, listener, isSvg) => {
  if (oldVNode === newVNode) {
  } else if (
    oldVNode != null &&
    oldVNode.type === TEXT_NODE &&
    newVNode.type === TEXT_NODE
  ) {
    if (oldVNode.tag !== newVNode.tag) node.nodeValue = newVNode.tag
  } else if (oldVNode == null || oldVNode.tag !== newVNode.tag) {
    node = parent.insertBefore(
      createNode((newVNode = maybeVNode(newVNode)), listener, isSvg),
      node
    )
    if (oldVNode != null) {
      parent.removeChild(oldVNode.node)
    }
  } else {
    var tmpVKid
    var oldVKid

    var oldKey
    var newKey

    var oldProps = oldVNode.props
    var newProps = newVNode.props

    var oldVKids = oldVNode.children
    var newVKids = newVNode.children

    var oldHead = 0
    var newHead = 0
    var oldTail = oldVKids.length - 1
    var newTail = newVKids.length - 1

    isSvg = isSvg || newVNode.tag === "svg"

    for (var i in { ...oldProps, ...newProps }) {
      if (
        (i === "value" || i === "selected" || i === "checked"
          ? node[i]
          : oldProps[i]) !== newProps[i]
      ) {
        patchProperty(node, i, oldProps[i], newProps[i], listener, isSvg)
      }
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldHead])) == null ||
        oldKey !== getKey(newVKids[newHead])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldHead].node,
        oldVKids[oldHead],
        (newVKids[newHead] = maybeVNode(
          newVKids[newHead++],
          oldVKids[oldHead++]
        )),
        listener,
        isSvg
      )
    }

    while (newHead <= newTail && oldHead <= oldTail) {
      if (
        (oldKey = getKey(oldVKids[oldTail])) == null ||
        oldKey !== getKey(newVKids[newTail])
      ) {
        break
      }

      patch(
        node,
        oldVKids[oldTail].node,
        oldVKids[oldTail],
        (newVKids[newTail] = maybeVNode(
          newVKids[newTail--],
          oldVKids[oldTail--]
        )),
        listener,
        isSvg
      )
    }

    if (oldHead > oldTail) {
      while (newHead <= newTail) {
        node.insertBefore(
          createNode(
            (newVKids[newHead] = maybeVNode(newVKids[newHead++])),
            listener,
            isSvg
          ),
          (oldVKid = oldVKids[oldHead]) && oldVKid.node
        )
      }
    } else if (newHead > newTail) {
      while (oldHead <= oldTail) {
        node.removeChild(oldVKids[oldHead++].node)
      }
    } else {
      for (var keyed = {}, newKeyed = {}, i = oldHead; i <= oldTail; i++) {
        if ((oldKey = oldVKids[i].key) != null) {
          keyed[oldKey] = oldVKids[i]
        }
      }

      while (newHead <= newTail) {
        oldKey = getKey((oldVKid = oldVKids[oldHead]))
        newKey = getKey(
          (newVKids[newHead] = maybeVNode(newVKids[newHead], oldVKid))
        )

        if (
          newKeyed[oldKey] ||
          (newKey != null && newKey === getKey(oldVKids[oldHead + 1]))
        ) {
          if (oldKey == null) {
            node.removeChild(oldVKid.node)
          }
          oldHead++
          continue
        }

        if (newKey == null || oldVNode.type === SSR_NODE) {
          if (oldKey == null) {
            patch(
              node,
              oldVKid && oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newHead++
          }
          oldHead++
        } else {
          if (oldKey === newKey) {
            patch(
              node,
              oldVKid.node,
              oldVKid,
              newVKids[newHead],
              listener,
              isSvg
            )
            newKeyed[newKey] = true
            oldHead++
          } else {
            if ((tmpVKid = keyed[newKey]) != null) {
              patch(
                node,
                node.insertBefore(tmpVKid.node, oldVKid && oldVKid.node),
                tmpVKid,
                newVKids[newHead],
                listener,
                isSvg
              )
              newKeyed[newKey] = true
            } else {
              patch(
                node,
                oldVKid && oldVKid.node,
                null,
                newVKids[newHead],
                listener,
                isSvg
              )
            }
          }
          newHead++
        }
      }

      while (oldHead <= oldTail) {
        if (getKey((oldVKid = oldVKids[oldHead++])) == null) {
          node.removeChild(oldVKid.node)
        }
      }

      for (var i in keyed) {
        if (newKeyed[i] == null) {
          node.removeChild(keyed[i].node)
        }
      }
    }
  }

  return (newVNode.node = node)
}

var propsChanged = (a, b) => {
  for (var k in a) if (a[k] !== b[k]) return true
  for (var k in b) if (a[k] !== b[k]) return true
}

var maybeVNode = (newVNode, oldVNode) =>
  newVNode !== true && newVNode !== false && newVNode
    ? typeof newVNode.tag === "function"
      ? ((!oldVNode ||
          oldVNode.memo == null ||
          propsChanged(oldVNode.memo, newVNode.memo)) &&
          ((oldVNode = newVNode.tag(newVNode.memo)).memo = newVNode.memo),
        oldVNode)
      : newVNode
    : text("")

var recycleNode = (node) =>
  node.nodeType === TEXT_NODE
    ? text(node.nodeValue, node)
    : createVNode(
        node.nodeName.toLowerCase(),
        EMPTY_OBJ,
        map.call(node.childNodes, recycleNode),
        SSR_NODE,
        node
      )

var createVNode = (tag, props, children, type, node) => ({
  tag,
  props,
  key: props.key,
  children,
  type,
  node,
})

export var memo = (tag, memo) => ({ tag, memo })

export var text = (value, node) =>
  createVNode(value, EMPTY_OBJ, EMPTY_ARR, TEXT_NODE, node)

export var h = (tag, props, children = EMPTY_ARR) =>
  createVNode(tag, props, isArray(children) ? children : [children])

export var app = ({
  init = EMPTY_OBJ,
  view,
  subscriptions,
  dispatch = id,
  node,
}) => {
  var vdom = node && recycleNode(node)
  var subs = []
  var state
  var busy

  var setState = (newState) => {
    if (state !== newState) {
      state = newState
      if (subscriptions) {
        subs = patchSubs(subs, subscriptions(state), dispatch)
      }
      if (view && !busy) enqueue(render, (busy = true))
    }
  }

  var render = () =>
    (node = patch(
      node.parentNode,
      node,
      vdom,
      (vdom = view(state)),
      listener,
      (busy = false)
    ))

  var listener = function (event) {
    dispatch(this.events[event.type], event)
  }

  return (
    (dispatch = dispatch((action, props) =>
      typeof action === "function"
        ? dispatch(action(state, props))
        : isArray(action)
        ? typeof action[0] === "function"
          ? dispatch(action[0], action[1])
          : action
              .slice(1)
              .map(
                (fx) => fx && fx !== true && fx[0](dispatch, fx[1]),
                setState(action[0])
              )
        : action == null
        ? patchSubs(subs, EMPTY_ARR, (dispatch = id))
        : setState(action)
    ))(init),
    dispatch
  )
}
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var childProcess = require('child_process');
var args = require('args');
var rimraf = require('rimraf');
var request = require('sync-request');

const versionedObjectTypes = ['datasets','interfaces','pipelines','publications','subscriptions','views'];

args.option('repo', 'Absolute path to local repository with project metadata', '');
args.option('targetDir', 'Relative path to directory where resulting js file should be put', '');
args.option('include', 'Relative path to file describing subset of metadata to be included in result (optional)', '');
args.option('includeOrg', 'Organization to be included in result (optional)', '');
args.option('pretty', 'Pretty-print output json (bigger file but human readable)', false);
args.option('json', 'Generate json files instead of metadata.js', false);
args.option('servicetoken', 'Get metadata from backend service (not git) using specified access token', '');
args.option('skipresources', 'Skip downloading of resources from views', false);

var flags = args.parse(process.argv);

if (!flags.repo) {
    throw "Provide path to local metadata repository";
}
if (flags.json && flags.repo == flags.targetDir) {
	throw "Target directory should be different from source directory";
}
if (flags.includeOrg && flags.include) {
	throw "Only one of includeOrg and include flags can be used";
}

var metadataPathFilter = false;

var metadata = {};

function cloneRepo () {

    try {
        childProcess.execSync('git clone --local ' + flags.repo + ' .mdtmp');
		childProcess.execSync('cd .mdtmp && git checkout master && cd ..');
        return true;
    } catch (err) {
        return false;
    }
}

function deleteRepo () {
    try {
        //childProcess.execSync('rm -rf ./.mdtmp');
		rimraf('.mdtmp', (err)=>{
			if (err)
				console.log(err);
		});
        return true;
    } catch (err) {
		console.log(err);
        return false;
    }
}

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

function getFiles(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return !fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

function getFullUri(obj) {
    if (!obj.object)
        return "";
    if (!obj.object.parent) {
        return '/organizations/' + obj.identity.name;
    }

    //console.log('parent',obj.object.parent.name,'parts',parts,'res=',parentUri);

    if (!obj.object.type) {
        //console.log(obj.object);
    }

    return obj.object.parent.name + '/' + obj.object.type + 's/' + obj.identity.name;
}

function nonCSCompare(str1, str2) {
  if (!str1 && !str2) {
    // This is two empty strings case, we consider it equal
    return true;
  } else if ( (str1 && !(typeof str1 === 'string')) || (str2  && !(typeof str2 === 'string'))) {
    // We compare null or different types
    console.warn("nonCSCompare one of arguments is falsy", str1, str2);
    return false;
  } else if (!str1 || !str2) {
      // We are compare null with string
      return false;
  } else {
    // Let's compare strings
    return str1.toLowerCase() === str2.toLowerCase();
  }
}

function getVersionStatus(version) {
  // SEfalt status is draft
  var status = 'draft';
  if (!version || !version.object || !version.object.history || !version.object.history.completions)
  {
  //console.log("getVersionStatus:draft for ",JSON.stringify(version));
  if(version&&version.object&&version.object.history)
    //console.log("getVersionStatus:draft for ",version.identity.name,JSON.stringify(version.object.history));
    return status;
  }

  var completions = version.object.history.completions;

  // Analize completion to have version status
  if (completions) {
    if (completions.reduce((p, c, i) => nonCSCompare(c.status, "Approved") ? true : p, false))
      status = 'approved';
    else if (completions.reduce((p, c, i) => nonCSCompare(c.status, "Finalized") ? true : p, false))
      status = 'finalized';
    //console.log("getVersionStatus:draft for ",completions,status);
  }
  return status;
}

function refToFileName(ref) {
//const clearedPath = path.replace(/\/versions\/\d\.\d\.\d/g, '').replace(/:/g,"%");
	var version = "";
	if (ref.indexOf('/versions/') != -1)
	{
		var match = ref.match(/\/versions\/(\d+\.\d+\.\d+)/);
		console.log("match", match, ref);
		version = "-" + match[1];
	}
	var ret = ref.replace(/\/versions\/\d+\.\d+\.\d+/g, '').replace(/:/g,"%");
	ret = ret + version + ".json";
	console.log("refToFileName", ref, ret);
	return ret;
}

/**
 * Recursively goes through md project and imports JSON objects
 * @param {string} dir
 * @returns {{}}
 */
function scanDirectory (dir, metapath) {
    // console.log(dir);

    var dirs = getDirectories(dir).filter(function (dirName) {
        return dirName.charAt(0) !== '.';
    });
    var obj = {};
	var dir_parts = dir.split('/');
	var type = dir_parts[dir_parts.length - 1];

    var files = getFiles(dir).filter(function (fileName) {
        return fileName.indexOf('.json') >= 1;
    });

    for (var j = 0; j < files.length; j++) {
        var f = files[j];
        var objName = f.replace(/.json/, '').replace(/\./g, '_').replace(/-/g, '[v]');

        if (objName.indexOf('[v]') > -1)
            continue;

		if (metadataPathFilter && metadataPathFilter.length > 0)
		{
			//console.log("Looking for ", (metapath + '/' + objName).toLowerCase(), " in ", metadataPathFilter);
			var found = false;
			for (var fi = 0; fi < metadataPathFilter.length; fi++)
			{
				if ((metapath + '/' + objName).toLowerCase().indexOf(metadataPathFilter[fi].toLowerCase()) !== -1)
				{
					found = true;
					break;
				}
			}
			if (!found)
				continue;
		}

//		console.log("metapath", metapath + '/' + objName);
		if (flags.servicetoken && metapath.indexOf('/organizations') !== -1) {
			console.log("will fetch ", 'https://metaserviceprod.azurewebsites.net/api' + metapath + '/' + objName);
			try {
				obj[objName.toLowerCase()] = JSON.parse(request('GET', 'https://metaserviceprod.azurewebsites.net/api' + metapath + '/' + objName,  {
				  headers: {
					'Authorization': 'Bearer ' + flags.servicetoken,
				  },
				}).getBody());
				console.log("fetched ", objName.toLowerCase());
			} catch (e) {
				console.error("could not fetch " + metapath + '/' + objName, e);
				obj[objName.toLowerCase()] = require(path.join(dir, f));
			}
		} else {
			obj[objName.toLowerCase()] = require(path.join(dir, f));
		}
		let object = obj[objName.toLowerCase()];
		object._path = getFullUri(object);
		console.log("next metadata item: ", object._path);

		// object status
		if (versionedObjectTypes.indexOf(type) !== -1 || (object.object && object.object.history && object.object.history.completions))
		{
			object._status = getVersionStatus(object);
			console.log("found versioned object, status=", object._status);
		}

		// paths of datasets in publication
		if (type == "publications")
		{
			console.log("found publication", object.datasets, object.interfaces);
			if (object.datasets)
			{
			var appPath = object._path;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.datasets.map(dataset => {
				dataset._path = appPath + '/datasets/' + dataset.identity.name;
			});
			}
			if (object.interfaces)
			{
			var appPath = object._path;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.interfaces.map(dataset => {
				dataset._path = appPath + '/interfaces/' + dataset.identity.name;
			});
			}
		}

		if (type == "subscriptions")
		{
			console.log("found subscription", object.datasets, object.interfaces);
			if (object.datasets)
			{
			var appPath = object.publication.identity.name;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.datasets.map(dataset => {
				dataset._path = appPath + '/datasets/' + dataset.identity.name;
			});
			}
			if (object.interfaces)
			{
			var appPath = object.publication.identity.name;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.interfaces.map(dataset => {
				dataset._path = appPath + '/interfaces/' + dataset.identity.name;
			});
			}
		}

		// Dataset fields, layout details are not embedded in Pipeline JSON

		if (type == "pipelines")
		{
			console.log("pipeline", object._path);
			console.log(object.activities);
			if (object.activities)
			{
				object.activities.map(activity => {
					console.log("activity", activity);
					if (activity.inputs) {
						activity.inputs.map(input => {
							if (input.inputMode == "Dataset")
							{
								var ref = input.component.reference;
								var fileName = refToFileName(ref);
								console.log("load input dataset from", path.join((flags.repo ? flags.repo : ''), fileName));
								var dataset = require(path.join((flags.repo ? flags.repo : ''), fileName));
								input._dataset = dataset;
							}
						});
					}
					if (activity.outputs) {
						activity.outputs.map(output => {
							if (output.outputMode == "Dataset")
							{
								var ref = output.component.reference;
								var fileName = refToFileName(ref);
								console.log("load output dataset from", path.join((flags.repo ? flags.repo : ''), fileName));
								var dataset = require(path.join((flags.repo ? flags.repo : ''), fileName));
								output._dataset = dataset;
							}
						});
					}
				});
			}
		}

		if (type == "views" && object.definitions &&!flags.skipresources)
		{
			object.definitions.map(def => {
				if (def.elements)
				{
					def.elements.map(element => {
						if (element.image)
						{
							var imageUrl = element.image.replace(/[^A-Za-z_0-9-]+/g,'_') + '.png';
							if (!fs.existsSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources', imageUrl)))
							{
								console.log("Found external resource: " + element.image + " in object " + object._path);
								var imageData = request('GET', element.image.replace('https://bias-metadata-service.difhub.com','https://apdax-metadata-service-dev.azurewebsites.net')).getBody();
								//fs.writeFileSync(path.join((flags.targetDir ? flags.targetDir : ''), object._path) + '__' + element.identity.name + '.png');
								//var imageUrl = element.image.replace('http://','').replace('https://','').replace('/','_').replace('\\','_').replace('?','_').replace('=','_');

								console.log("Downloaded, saving to ",imageUrl);
								fs.mkdirSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources'), { recursive: true });
								fs.writeFileSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources', imageUrl), imageData);
							}
						}
					});
				}
			});
		}

		if (flags.json)
		{
			const filePath = path.join((flags.targetDir ? flags.targetDir : ''), object._path) + '.json';
			fs.mkdirSync(path.dirname(filePath), { recursive: true });
			fs.writeFile(filePath, (flags.pretty !== false ? JSON.stringify(object, null, 2) :JSON.stringify(object)), () => {

			});
		}

		obj[objName.toLowerCase()] = object;
    }

    if (dirs.length === 0) {
        return obj;
    }

    for (var i = 0; i < dirs.length; i++) {
        var d = dirs[i];

        obj[d.toLowerCase()] = scanDirectory(dir + '/' + d, metapath == '' ? ('/organizations/' + d) : (metapath + '/' + d));
    }

    // console.log(rootObj, typeof rootObj);

    return obj;
}

function findByPath(path) {
    if (!path)
        return null;

    // remove versions from path
    const clearedPath = path.replace(/\/versions\/\d+\.\d+\.\d+/g, '').replace(/:/g,"%");

    let splitPath = clearedPath.split('/').map(el => el.toLowerCase());
    let res;

    while (splitPath.length) {
        var step = splitPath.shift();

        if (!res)
            res = metadata[step];
        else
            res = res[step];
    }

    return res;
}

const metadata_apdax = require('./metadata_apdax.js').metadata;
const metadataApi = require('./metadataApi.js');

//console.log("metadata_apdax", metadata_apdax);
//console.log("metadataApi", metadataApi);

let metadataApiString = "";
//
let exportsString = "module.exports = {metadata: metadata, findByPath: findByPath, metadata_apdax:metadata_apdax";
for (let item in metadataApi)
{
	//console.log("item", item, metadataApi[item]);
	if (typeof(metadataApi[item]) === 'function')
		metadataApiString += "var " + item + " = " + (metadataApi[item].toString()) + "; ";
	else
		metadataApiString += "var " + item + " = " + JSON.stringify(metadataApi[item]) + "; ";
	exportsString += ", " + item + ":" + item;
}
exportsString += "}; ";

if (cloneRepo()) {
    // path to temp repo
    var p = path.join(process.cwd(), '.mdtmp/organizations');

	if (flags.include)
	{
		var include_str = fs.readFileSync(flags.include, "utf-8");
		metadataPathFilter = include_str.split("\n").map(s => s.trim());
	}
	if (flags.includeOrg)
	{
		metadataPathFilter = "/organizations/" + flags.includeOrg;
	}

    var obj = scanDirectory(p, '');

	var outputFilename = path.join((flags.targetDir ? flags.targetDir : ''), 'metadata.js');

	if (!flags.json)
		fs.writeFile(
			outputFilename,
			"var metadata_apdax = " + JSON.stringify(metadata_apdax, null, 2) + ";" +
			"var metadata = " + (flags.pretty !== false ? JSON.stringify(obj, null, 2) :JSON.stringify(obj)) + ";" +
			findByPath.toString() +
			metadataApiString +
			exportsString,		//"module.exports = {metadata: metadata, findByPath: findByPath};",
			() => {
				console.log("Metadata saved to", outputFilename);
			}
		);
}

deleteRepo();
<commit_msg>print process of creating metadata.<commit_after>var path = require('path');
var fs = require('fs');
var childProcess = require('child_process');
var args = require('args');
var rimraf = require('rimraf');
var request = require('sync-request');

const versionedObjectTypes = ['datasets','interfaces','pipelines','publications','subscriptions','views'];

args.option('repo', 'Absolute path to local repository with project metadata', '');
args.option('targetDir', 'Relative path to directory where resulting js file should be put', '');
args.option('include', 'Relative path to file describing subset of metadata to be included in result (optional)', '');
args.option('includeOrg', 'Organization to be included in result (optional)', '');
args.option('pretty', 'Pretty-print output json (bigger file but human readable)', false);
args.option('json', 'Generate json files instead of metadata.js', false);
args.option('servicetoken', 'Get metadata from backend service (not git) using specified access token', '');
args.option('skipresources', 'Skip downloading of resources from views', false);

var flags = args.parse(process.argv);

if (!flags.repo) {
    throw "Provide path to local metadata repository";
}
if (flags.json && flags.repo == flags.targetDir) {
	throw "Target directory should be different from source directory";
}
if (flags.includeOrg && flags.include) {
	throw "Only one of includeOrg and include flags can be used";
}

var metadataPathFilter = false;

var metadata = {};

function cloneRepo () {

    try {
        childProcess.execSync('git clone --local ' + flags.repo + ' .mdtmp');
		childProcess.execSync('cd .mdtmp && git checkout master && cd ..');
        return true;
    } catch (err) {
        return false;
    }
}

function deleteRepo () {
    try {
        //childProcess.execSync('rm -rf ./.mdtmp');
		rimraf('.mdtmp', (err)=>{
			if (err)
				console.log(err);
		});
        return true;
    } catch (err) {
		console.log(err);
        return false;
    }
}

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

function getFiles(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return !fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

function getFullUri(obj) {
    if (!obj.object)
        return "";
    if (!obj.object.parent) {
        return '/organizations/' + obj.identity.name;
    }

    //console.log('parent',obj.object.parent.name,'parts',parts,'res=',parentUri);

    if (!obj.object.type) {
        //console.log(obj.object);
    }

    return obj.object.parent.name + '/' + obj.object.type + 's/' + obj.identity.name;
}

function nonCSCompare(str1, str2) {
  if (!str1 && !str2) {
    // This is two empty strings case, we consider it equal
    return true;
  } else if ( (str1 && !(typeof str1 === 'string')) || (str2  && !(typeof str2 === 'string'))) {
    // We compare null or different types
    console.warn("nonCSCompare one of arguments is falsy", str1, str2);
    return false;
  } else if (!str1 || !str2) {
      // We are compare null with string
      return false;
  } else {
    // Let's compare strings
    return str1.toLowerCase() === str2.toLowerCase();
  }
}

function getVersionStatus(version) {
  // SEfalt status is draft
  var status = 'draft';
  if (!version || !version.object || !version.object.history || !version.object.history.completions)
  {
  //console.log("getVersionStatus:draft for ",JSON.stringify(version));
  if(version&&version.object&&version.object.history)
    //console.log("getVersionStatus:draft for ",version.identity.name,JSON.stringify(version.object.history));
    return status;
  }

  var completions = version.object.history.completions;

  // Analize completion to have version status
  if (completions) {
    if (completions.reduce((p, c, i) => nonCSCompare(c.status, "Approved") ? true : p, false))
      status = 'approved';
    else if (completions.reduce((p, c, i) => nonCSCompare(c.status, "Finalized") ? true : p, false))
      status = 'finalized';
    //console.log("getVersionStatus:draft for ",completions,status);
  }
  return status;
}

function refToFileName(ref) {
//const clearedPath = path.replace(/\/versions\/\d\.\d\.\d/g, '').replace(/:/g,"%");
	var version = "";
	if (ref.indexOf('/versions/') != -1)
	{
		var match = ref.match(/\/versions\/(\d+\.\d+\.\d+)/);
		console.log("match", match, ref);
		version = "-" + match[1];
	}
	var ret = ref.replace(/\/versions\/\d+\.\d+\.\d+/g, '').replace(/:/g,"%");
	ret = ret + version + ".json";
	console.log("refToFileName", ref, ret);
	return ret;
}

/**
 * Recursively goes through md project and imports JSON objects
 * @param {string} dir
 * @returns {{}}
 */
function scanDirectory (dir, metapath) {
    console.log('Graber:DIR', dir, metapath, flags, metadataPathFilter);

    var dirs = getDirectories(dir).filter(function (dirName) {
        return dirName.charAt(0) !== '.';
    });
    var obj = {};
	var dir_parts = dir.split('/');
	var type = dir_parts[dir_parts.length - 1];

    var files = getFiles(dir).filter(function (fileName) {
        return fileName.indexOf('.json') >= 1;
    });

    console.log('Graber:FILES', dirs, files);

    for (var j = 0; j < files.length; j++) {
        var f = files[j];
        var objName = f.replace(/.json/, '').replace(/\./g, '_').replace(/-/g, '[v]');

        if (objName.indexOf('[v]') > -1)
            continue;

		if (metadataPathFilter && metadataPathFilter.length > 0)
		{
			//console.log("Looking for ", (metapath + '/' + objName).toLowerCase(), " in ", metadataPathFilter);
			var found = false;
			for (var fi = 0; fi < metadataPathFilter.length; fi++)
			{
				if ((metapath + '/' + objName).toLowerCase().indexOf(metadataPathFilter[fi].toLowerCase()) !== -1)
				{
					found = true;
					break;
				}
			}
			if (!found)
				continue;
		}

//		console.log("metapath", metapath + '/' + objName);
		if (flags.servicetoken && metapath.indexOf('/organizations') !== -1) {
			console.log("will fetch ", 'https://metaserviceprod.azurewebsites.net/api' + metapath + '/' + objName);
			try {
				obj[objName.toLowerCase()] = JSON.parse(request('GET', 'https://metaserviceprod.azurewebsites.net/api' + metapath + '/' + objName,  {
				  headers: {
					'Authorization': 'Bearer ' + flags.servicetoken,
				  },
				}).getBody());
				console.log("fetched ", objName.toLowerCase());
			} catch (e) {
				console.error("could not fetch " + metapath + '/' + objName, e);
				obj[objName.toLowerCase()] = require(path.join(dir, f));
			}
		} else {
			obj[objName.toLowerCase()] = require(path.join(dir, f));
		}
		let object = obj[objName.toLowerCase()];
		object._path = getFullUri(object);
		console.log("next metadata item: ", object._path);

		// object status
		if (versionedObjectTypes.indexOf(type) !== -1 || (object.object && object.object.history && object.object.history.completions))
		{
			object._status = getVersionStatus(object);
			console.log("found versioned object, status=", object._status);
		}

		// paths of datasets in publication
		if (type == "publications")
		{
			console.log("found publication", object.datasets, object.interfaces);
			if (object.datasets)
			{
			var appPath = object._path;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.datasets.map(dataset => {
				dataset._path = appPath + '/datasets/' + dataset.identity.name;
			});
			}
			if (object.interfaces)
			{
			var appPath = object._path;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.interfaces.map(dataset => {
				dataset._path = appPath + '/interfaces/' + dataset.identity.name;
			});
			}
		}

		if (type == "subscriptions")
		{
			console.log("found subscription", object.datasets, object.interfaces);
			if (object.datasets)
			{
			var appPath = object.publication.identity.name;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.datasets.map(dataset => {
				dataset._path = appPath + '/datasets/' + dataset.identity.name;
			});
			}
			if (object.interfaces)
			{
			var appPath = object.publication.identity.name;
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			appPath = appPath.substr(0, appPath.lastIndexOf('/'));
			object.interfaces.map(dataset => {
				dataset._path = appPath + '/interfaces/' + dataset.identity.name;
			});
			}
		}

		// Dataset fields, layout details are not embedded in Pipeline JSON

		if (type == "pipelines")
		{
			console.log("pipeline", object._path);
			console.log(object.activities);
			if (object.activities)
			{
				object.activities.map(activity => {
					console.log("activity", activity);
					if (activity.inputs) {
						activity.inputs.map(input => {
							if (input.inputMode == "Dataset")
							{
								var ref = input.component.reference;
								var fileName = refToFileName(ref);
								console.log("load input dataset from", path.join((flags.repo ? flags.repo : ''), fileName));
								var dataset = require(path.join((flags.repo ? flags.repo : ''), fileName));
								input._dataset = dataset;
							}
						});
					}
					if (activity.outputs) {
						activity.outputs.map(output => {
							if (output.outputMode == "Dataset")
							{
								var ref = output.component.reference;
								var fileName = refToFileName(ref);
								console.log("load output dataset from", path.join((flags.repo ? flags.repo : ''), fileName));
								var dataset = require(path.join((flags.repo ? flags.repo : ''), fileName));
								output._dataset = dataset;
							}
						});
					}
				});
			}
		}

		if (type == "views" && object.definitions &&!flags.skipresources)
		{
			object.definitions.map(def => {
				if (def.elements)
				{
					def.elements.map(element => {
						if (element.image)
						{
							var imageUrl = element.image.replace(/[^A-Za-z_0-9-]+/g,'_') + '.png';
							if (!fs.existsSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources', imageUrl)))
							{
								console.log("Found external resource: " + element.image + " in object " + object._path);
								var imageData = request('GET', element.image.replace('https://bias-metadata-service.difhub.com','https://apdax-metadata-service-dev.azurewebsites.net')).getBody();
								//fs.writeFileSync(path.join((flags.targetDir ? flags.targetDir : ''), object._path) + '__' + element.identity.name + '.png');
								//var imageUrl = element.image.replace('http://','').replace('https://','').replace('/','_').replace('\\','_').replace('?','_').replace('=','_');

								console.log("Downloaded, saving to ",imageUrl);
								fs.mkdirSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources'), { recursive: true });
								fs.writeFileSync(path.join((flags.targetDir ? flags.targetDir : ''), 'resources', imageUrl), imageData);
							}
						}
					});
				}
			});
		}

		if (flags.json)
		{
			const filePath = path.join((flags.targetDir ? flags.targetDir : ''), object._path) + '.json';
			fs.mkdirSync(path.dirname(filePath), { recursive: true });
			fs.writeFile(filePath, (flags.pretty !== false ? JSON.stringify(object, null, 2) :JSON.stringify(object)), () => {

			});
		}

		obj[objName.toLowerCase()] = object;
    }

    if (dirs.length === 0) {
        return obj;
    }

    for (var i = 0; i < dirs.length; i++) {
        var d = dirs[i];

        obj[d.toLowerCase()] = scanDirectory(dir + '/' + d, metapath == '' ? ('/organizations/' + d) : (metapath + '/' + d));
    }

    // console.log(rootObj, typeof rootObj);

    return obj;
}

function findByPath(path) {
    if (!path)
        return null;

    // remove versions from path
    const clearedPath = path.replace(/\/versions\/\d+\.\d+\.\d+/g, '').replace(/:/g,"%");

    let splitPath = clearedPath.split('/').map(el => el.toLowerCase());
    let res;

    while (splitPath.length) {
        var step = splitPath.shift();

        if (!res)
            res = metadata[step];
        else
            res = res[step];
    }

    return res;
}

const metadata_apdax = require('./metadata_apdax.js').metadata;
const metadataApi = require('./metadataApi.js');

//console.log("metadata_apdax", metadata_apdax);
//console.log("metadataApi", metadataApi);

let metadataApiString = "";
//
let exportsString = "module.exports = {metadata: metadata, findByPath: findByPath, metadata_apdax:metadata_apdax";
for (let item in metadataApi)
{
	//console.log("item", item, metadataApi[item]);
	if (typeof(metadataApi[item]) === 'function')
		metadataApiString += "var " + item + " = " + (metadataApi[item].toString()) + "; ";
	else
		metadataApiString += "var " + item + " = " + JSON.stringify(metadataApi[item]) + "; ";
	exportsString += ", " + item + ":" + item;
}
exportsString += "}; ";

if (cloneRepo()) {
    // path to temp repo
    var p = path.join(process.cwd(), '.mdtmp/organizations');

	if (flags.include)
	{
		var include_str = fs.readFileSync(flags.include, "utf-8");
		metadataPathFilter = include_str.split("\n").map(s => s.trim());
	}
	if (flags.includeOrg)
	{
		metadataPathFilter = "/organizations/" + flags.includeOrg;
	}

    var obj = scanDirectory(p, '');

	var outputFilename = path.join((flags.targetDir ? flags.targetDir : ''), 'metadata.js');

	if (!flags.json)
		fs.writeFile(
			outputFilename,
			"var metadata_apdax = " + JSON.stringify(metadata_apdax, null, 2) + ";" +
			"var metadata = " + (flags.pretty !== false ? JSON.stringify(obj, null, 2) :JSON.stringify(obj)) + ";" +
			findByPath.toString() +
			metadataApiString +
			exportsString,		//"module.exports = {metadata: metadata, findByPath: findByPath};",
			() => {
				console.log("Metadata saved to", outputFilename);
			}
		);
}

deleteRepo();
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var Duplex = require('stream').Duplex;

function FirstChunkStream(options, cb) {
	var _this = this;
	var manager;
	var errorHandler;

	if (!(this instanceof FirstChunkStream)) {
		return new FirstChunkStream(options, cb);
	}

	options = options || {};

	if (!(cb instanceof Function)) {
		throw new Error('FirstChunkStream constructor requires a callback as its second argument.');
	}

	if ('number' !== typeof options.chunkLength) {
		throw new Error('FirstChunkStream constructor requires options.chunkLength to be a number.');
	}

	if (options.objectMode) {
		throw new Error('FirstChunkStream doesn\'t support the objectMode yet.');
	}

	Duplex.call(this, options);

	manager = createReadStreamBackpressureManager(this);
	errorHandler = function firstChunkStreamErrorHandler(err) {
		setImmediate(function() {
			_this.removeListener('error', errorHandler);
		});
		this.__firstChunkSent = true;
		cb(err, Buffer.concat(_this.__firstChunkBuffer), {}.undef, function (err, buf) {
			if(err) {
				setImmediate(function() {
					return _this.emit('error', err);
				});
			}
			manager.programPush(buf, {}.undef, function() {});
		});
	};
	this.on('error', errorHandler);

	if (1 > options.chunkLength) {
		this.__firstChunkSent = true;
	} else {
		this.__firstChunkSent = false;
	}

	this.__firstChunkBuffer = [];
	this.__firstChunkBufferSize = 0;

	this._write = function firstChunkStreamWrite(chunk, encoding, done) {
		if(_this.__firstChunkSent) {
      manager.programPush(chunk, encoding, done);
		} else {
			if(chunk.length < options.chunkLength - _this.__firstChunkBufferSize) {
				_this.__firstChunkBuffer.push(chunk);
				_this.__firstChunkBufferSize += chunk.length;
				done();
			} else {
				_this.__firstChunkBuffer.push(chunk.slice(0, options.chunkLength - _this.__firstChunkBufferSize));
				chunk = chunk.slice(options.chunkLength - _this.__firstChunkBufferSize);
				_this.__firstChunkBufferSize += _this.__firstChunkBuffer[_this.__firstChunkBuffer.length - 1].length;
				cb(null, Buffer.concat(_this.__firstChunkBuffer), encoding, function(err, buf) {
					_this.removeListener('error', errorHandler);
					_this.__firstChunkSent = true;
					if(!(buf.length || chunk.length)) {
						return done();
					}
					manager.programPush(Buffer.concat([buf, chunk]), encoding, done);
				});
			}
		}
	};

  this.on('finish', function firstChunkStreamFinish() {
		if(!_this.__firstChunkSent) {
			return cb(null, Buffer.concat(_this.__firstChunkBuffer), {}.undef, function(err, buf) {
				_this.removeListener('error', errorHandler);
				_this.__firstChunkSent = true;
				if(buf.length) {
					manager.programPush(buf, {}.undef, function() {});
				}
		    manager.programPush(null, {}.undef, function() {});
			});
		}
    manager.programPush(null, {}.undef, function() {});
  });
}

util.inherits(FirstChunkStream, Duplex);

// Utils to manage readable stream backpressure
function createReadStreamBackpressureManager(readableStream) {
  var manager = {
    waitPush: true,
    programmedPushs: [],
    programPush: function programPush(chunk, encoding, done) {
      // Store the current write
      manager.programmedPushs.push([chunk, encoding, done]);
      // Need to be async to avoid nested push attempts
      // Programm a push attempt
      setImmediate(manager.attemptPush);
      // Let's say we're ready for a read
      readableStream.emit('readable');
      readableStream.emit('drain');
    },
    attemptPush: function attemptPush() {
      var nextPush;

      if(manager.waitPush) {
        if(manager.programmedPushs.length) {
          nextPush = manager.programmedPushs.shift();
          manager.waitPush = readableStream.push(nextPush[0], nextPush[1]);
          (nextPush[2])();
        }
      } else {
        setImmediate(function() {
          // Need to be async to avoid nested push attempts
          readableStream.emit('readable');
        });
      }
    },
  };

  // Patch the readable stream to manage reads
  readableStream._read = function streamFilterRestoreRead() {
    manager.waitPush = true;
    // Need to be async to avoid nested push attempts
    setImmediate(manager.attemptPush);
  };

  return manager;
}

module.exports = FirstChunkStream;
<commit_msg>Setting encoding properly<commit_after>'use strict';

var util = require('util');
var Duplex = require('stream').Duplex;

function FirstChunkStream(options, cb) {
	var _this = this;
	var manager;
	var errorHandler;

	if (!(this instanceof FirstChunkStream)) {
		return new FirstChunkStream(options, cb);
	}

	options = options || {};

	if (!(cb instanceof Function)) {
		throw new Error('FirstChunkStream constructor requires a callback as its second argument.');
	}

	if ('number' !== typeof options.chunkLength) {
		throw new Error('FirstChunkStream constructor requires options.chunkLength to be a number.');
	}

	if (options.objectMode) {
		throw new Error('FirstChunkStream doesn\'t support the objectMode yet.');
	}

	Duplex.call(this, options);

	manager = createReadStreamBackpressureManager(this);
	errorHandler = function firstChunkStreamErrorHandler(err) {
		setImmediate(function() {
			_this.removeListener('error', errorHandler);
		});
		this.__firstChunkSent = true;
		cb(err, Buffer.concat(_this.__firstChunkBuffer), {}.undef, function (err, buf) {
			if(err) {
				setImmediate(function() {
					return _this.emit('error', err);
				});
			}
			manager.programPush(buf, {}.undef, function() {});
		});
	};
	this.on('error', errorHandler);

	if (1 > options.chunkLength) {
		this.__firstChunkSent = true;
	} else {
		this.__firstChunkSent = false;
	}

	this.__firstChunkBuffer = [];
	this.__firstChunkBufferSize = 0;

	this._write = function firstChunkStreamWrite(chunk, encoding, done) {
	  this.__firstChunkEncoding = encoding;
		if(this.__firstChunkSent) {
      manager.programPush(chunk, this.__firstChunkEncoding, done);
		} else {
			if(chunk.length < options.chunkLength - _this.__firstChunkBufferSize) {
				_this.__firstChunkBuffer.push(chunk);
				_this.__firstChunkBufferSize += chunk.length;
				done();
			} else {
				_this.__firstChunkBuffer.push(chunk.slice(0, options.chunkLength - _this.__firstChunkBufferSize));
				chunk = chunk.slice(options.chunkLength - _this.__firstChunkBufferSize);
				_this.__firstChunkBufferSize += _this.__firstChunkBuffer[_this.__firstChunkBuffer.length - 1].length;
				cb(null, Buffer.concat(_this.__firstChunkBuffer), _this.__firstChunkEncoding, function(err, buf) {
					_this.removeListener('error', errorHandler);
					_this.__firstChunkSent = true;
					if(!(buf.length || chunk.length)) {
						return done();
					}
					manager.programPush(Buffer.concat([buf, chunk]), _this.__firstChunkEncoding, done);
				});
			}
		}
	};

  this.on('finish', function firstChunkStreamFinish() {
		var _this = this;
		if(!_this.__firstChunkSent) {
			return cb(null, Buffer.concat(_this.__firstChunkBuffer), this.__firstChunkEncoding, function(err, buf) {
				_this.removeListener('error', errorHandler);
				_this.__firstChunkSent = true;
				if(buf.length) {
					manager.programPush(buf, _this.__firstChunkEncoding, function() {});
				}
		    manager.programPush(null, _this.__firstChunkEncoding, function() {});
			});
		}
    manager.programPush(null, this.__firstChunkEncoding, function() {});
  });
}

util.inherits(FirstChunkStream, Duplex);

// Utils to manage readable stream backpressure
function createReadStreamBackpressureManager(readableStream) {
  var manager = {
    waitPush: true,
    programmedPushs: [],
    programPush: function programPush(chunk, encoding, done) {
      // Store the current write
      manager.programmedPushs.push([chunk, encoding, done]);
      // Need to be async to avoid nested push attempts
      // Programm a push attempt
      setImmediate(manager.attemptPush);
      // Let's say we're ready for a read
      readableStream.emit('readable');
      readableStream.emit('drain');
    },
    attemptPush: function attemptPush() {
      var nextPush;

      if(manager.waitPush) {
        if(manager.programmedPushs.length) {
          nextPush = manager.programmedPushs.shift();
          manager.waitPush = readableStream.push(nextPush[0], nextPush[1]);
          (nextPush[2])();
        }
      } else {
        setImmediate(function() {
          // Need to be async to avoid nested push attempts
          readableStream.emit('readable');
        });
      }
    },
  };

  // Patch the readable stream to manage reads
  readableStream._read = function streamFilterRestoreRead() {
    manager.waitPush = true;
    // Need to be async to avoid nested push attempts
    setImmediate(manager.attemptPush);
  };

  return manager;
}

module.exports = FirstChunkStream;
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	childProcess = require('child_process'),
	os = require('os'),

	jsonSchemaDefaults = require('json-schema-defaults'),
	yaml = require('js-yaml'),
	clone = require('clone'),
	temp = require('temp'),
	tv4 = require('tv4'),

	applyDefaults = require('./applyDefaults.js'),
	configSchema = yaml.safeLoad(
		fs.readFileSync(path.join(__dirname, 'configSchema.yaml'))
	),
	nodeSlicer = {}

function getBinaryPath () {

	var binPath

	if (os.platform() === 'darwin')
		binPath = '~/Applications/Slic3r.app/Contents/MacOS/slic3r'
	else
		binPath = 'slic3r'

	return binPath
}

function yesNoify (value) {
	if (value)
		return 'yes'
	else
		return 'no'
}

function getShellCommand (o) {

	var shellCommand

	o.outputFile = o.outputFile || temp.path({suffix: '.gcode'})

	shellCommand = [
		getBinaryPath(),
		'--output ' + o.outputFile,

		// Non-slicing actions
		o.repair ? '--repair' : '',
		o.cut ? '--cut' : '',
		o.split ? '--split' : '',
		o.info ? '--info' : '',
		'--threads ' + o.threads,

		// Output options
		o.outputFilenameFormat ?
		'--output-filename-format ' + o.outputFilenameFormat : '',
		o.postProcess !== [] ?
		o.postProcessScripts.map(function (script) {
			return '--post-process ' + script
		}).join(' ') : '',
		o.exportSvg ? '--export-svg' : '',
		o.merge ? '--merge' : '',

		// Printer options
		'--nozzle-diameter ' + o.nozzleDiameter,
		'--print-center ' + o.printCenter.x + ',' + o.printCenter.y,
		'--z-offset ' + o.zOffset,
		'--gcode-flavor ' + o.gcodeFlavor,
		'--use-relative-e-distances ' + yesNoify(o.useRelativeEDistances),
		'--use-firmware-retraction ' + yesNoify(o.useFirmwareRetraction),
		'--use-volumetric-e ' + yesNoify(o.useVolumetricE),
		o.gcodeArcs ? '--gcode-arcs' : '',
		o.g0 ? '--g0' : '',
		o.gcodeComments ? '--gcode-comments' : '',
		'--vibration-limit ' + o.vibrationLimit,
		'--pressure-advance ' + o.pressureAdvance,

		// Filament options
		'--filament-diameter ' + o.filamentDiameter,
		'--extrusion-multiplier ' + o.extrusionMultiplier,
		'--temperature ' + o.temperature,
		'--first-layer-temperature ' + o.firstLayerTemperature,
		'--bed-temperature ' + o.bedTemperature,
		'--first-layer-bed-temperature ' + o.firstLayerBedTemperature,

		// Speed options
		'--travel-speed ' + o.travelSpeed,
		'--perimeter-speed ' + o.perimeterSpeed,
		'--small-perimeter-speed ' + o.smallPerimeterSpeed,
		'--external-perimeter-speed ' + o.externalPerimeterSpeed,
		'--infill-speed ' + o.infillSpeed,
		'--solid-infill-speed ' + o.solidInfillSpeed,
		'--top-solid-infill-speed ' + o.topSolidInfillSpeed,
		'--support-material-speed ' + o.supportMaterialSpeed,
		'--support-material-interface-speed ' + o.supportMaterialInterfaceSpeed,
		'--bridge-speed ' + o.bridgeSpeed,
		'--gap-fill-speed ' + o.gapFillSpeed,
		'--first-layer-speed ' + o.firstLayerSpeed
	]

	return shellCommand.join(' ')
}

nodeSlicer.render = function (options, callback) {

	var validationResult = tv4.validateResult(
		options, configSchema, null, true
	)

	if (!validationResult.valid)
		return console.error(validationResult.error.message)

	options = applyDefaults(jsonSchemaDefaults(clone(configSchema)), options)

	childProcess.exec(
		getShellCommand(options),
		function (error, stdout, stderr) {

			if (error) {
				callback(error)
				return
			}

			if (!options.outputFile)
				fs.readFile(options.outputFile, {}, function (error, data) {

					if (error) {
						callback(error)
						return
					}
					else
						callback(null, data)

					fs.unlink(options.outputFile, function (error) {
						if (error && error.code !== 'ENOENT')
							throw error
					})
				})

			else
				callback()
		}
	)
}

module.exports = nodeSlicer
<commit_msg>Add accelerator, accuracy and print options<commit_after>var fs = require('fs'),
	path = require('path'),
	childProcess = require('child_process'),
	os = require('os'),

	jsonSchemaDefaults = require('json-schema-defaults'),
	yaml = require('js-yaml'),
	clone = require('clone'),
	temp = require('temp'),
	tv4 = require('tv4'),

	applyDefaults = require('./applyDefaults.js'),
	configSchema = yaml.safeLoad(
		fs.readFileSync(path.join(__dirname, 'configSchema.yaml'))
	),
	nodeSlicer = {}

function getBinaryPath () {

	var binPath

	if (os.platform() === 'darwin')
		binPath = '~/Applications/Slic3r.app/Contents/MacOS/slic3r'
	else
		binPath = 'slic3r'

	return binPath
}

function getShellCommand (o) {

	var shellCommand

	o.outputFile = o.outputFile || temp.path({suffix: '.gcode'})

	shellCommand = [
		getBinaryPath(),
		'--output ' + o.outputFile,

		// Non-slicing actions
		o.repair ? '--repair' : '',
		o.cut ? '--cut' : '',
		o.split ? '--split' : '',
		o.info ? '--info' : '',
		'--threads ' + o.threads,

		// Output options
		o.outputFilenameFormat ?
		'--output-filename-format ' + o.outputFilenameFormat : '',
		o.postProcess !== [] ?
		o.postProcessScripts.map(function (script) {
			return '--post-process ' + script
		}).join(' ') : '',
		o.exportSvg ? '--export-svg' : '',
		o.merge ? '--merge' : '',

		// Printer options
		'--nozzle-diameter ' + o.nozzleDiameter,
		'--print-center ' + o.printCenter.x + ',' + o.printCenter.y,
		'--z-offset ' + o.zOffset,
		'--gcode-flavor ' + o.gcodeFlavor,
		o.useRelativeEDistances ? '--use-relative-e-distances ' : '',
		o.useFirmwareRetraction ? '--use-firmware-retraction ' : '',
		o.useVolumetricE ? '--use-volumetric-e ' : '',
		o.gcodeArcs ? '--gcode-arcs' : '',
		o.g0 ? '--g0' : '',
		o.gcodeComments ? '--gcode-comments' : '',
		'--vibration-limit ' + o.vibrationLimit,
		'--pressure-advance ' + o.pressureAdvance,

		// Filament options
		'--filament-diameter ' + o.filamentDiameter,
		'--extrusion-multiplier ' + o.extrusionMultiplier,
		'--temperature ' + o.temperature,
		'--first-layer-temperature ' + o.firstLayerTemperature,
		'--bed-temperature ' + o.bedTemperature,
		'--first-layer-bed-temperature ' + o.firstLayerBedTemperature,

		// Speed options
		'--travel-speed ' + o.travelSpeed,
		'--perimeter-speed ' + o.perimeterSpeed,
		'--small-perimeter-speed ' + o.smallPerimeterSpeed,
		'--external-perimeter-speed ' + o.externalPerimeterSpeed,
		'--infill-speed ' + o.infillSpeed,
		'--solid-infill-speed ' + o.solidInfillSpeed,
		'--top-solid-infill-speed ' + o.topSolidInfillSpeed,
		'--support-material-speed ' + o.supportMaterialSpeed,
		'--support-material-interface-speed ' + o.supportMaterialInterfaceSpeed,
		'--bridge-speed ' + o.bridgeSpeed,
		'--gap-fill-speed ' + o.gapFillSpeed,
		'--first-layer-speed ' + o.firstLayerSpeed,

		// Accelerator options
		'--perimeter-acceleration ' + o.perimeterAcceleration,
		'--infill-acceleration ' + o.infillAcceleration,
		'--bridge-acceleration ' + o.bridgeAcceleration,
		'--first-layer-acceleration ' + o.firstLayerAcceleration,
		'--default-acceleration ' + o.defaultAcceleration,

		// Accuracy options
		'--layer-height ' + o.layerHeight,
		'--first-layer-height ' + o.firstLayerHeight,
		'--infill-every-layers ' + o.infillEveryLayers,
		'--solid-infill-every-layers ' + o.solidInfillEveryLayers,

		// Print Options
		'--perimeters ' + o.perimeters,
		'--top-solid-layers ' + o.topSolidLayers,
		'--bottom-solid-layers ' + o.bottomSolidLayers,
		o.solidLayers ? '--solid-layers' : '',
		'--fill-density ' + o.fillDensity,
		'--fill-angle ' + o.fillAngle,
		'--fill-pattern ' + o.fillPattern,
		'--solid-fill-pattern ' + o.solidFillPattern,
		o.startGcode ? '--start-gcode' : '',
		o.endGcode ? '--end-gcode ' : '',
		o.layerGcode ? '--layer-gcode ' : '',
		o.toolchangeGcode ? '--toolchange-gcode ' : '',
		'--seam-position ' + o.seamPosition,
		o.externalPerimetersFirst ? '--external-perimeters-first ' : '',
		o.spiralVase ? '--spiral-vase ' : '',
		o.onlyRetractWhenCrossingPerimeters ?
			'--only-retract-when-crossing-perimeters ' : '',
		'--solid-infill-below-area ' + o.solidInfillBelowArea,
		o.infillOnlyWhereNeeded ? '--infill-only-where-needed ' : '',
		o.infillFirst ? '--infill-first ' : ''
	]

	return shellCommand.join(' ')
}

nodeSlicer.render = function (options, callback) {

	var validationResult = tv4.validateResult(
		options, configSchema, null, true
	)

	if (!validationResult.valid)
		return console.error(validationResult.error.message)

	options = applyDefaults(jsonSchemaDefaults(clone(configSchema)), options)

	childProcess.exec(
		getShellCommand(options),
		function (error, stdout, stderr) {

			if (error) {
				callback(error)
				return
			}

			if (!options.outputFile)
				fs.readFile(options.outputFile, {}, function (error, data) {

					if (error) {
						callback(error)
						return
					}
					else
						callback(null, data)

					fs.unlink(options.outputFile, function (error) {
						if (error && error.code !== 'ENOENT')
							throw error
					})
				})

			else
				callback()
		}
	)
}

module.exports = nodeSlicer
<|endoftext|>


<commit_before>/*global require:false, console:false, module:false, setTimeout: false, process: false*/

var data = require('./src/data');
var renderer = require('./src/renderer');
var nav = require('./src/navigation');
var notification = require('./src/notification');
var config = require('./src/config');

var currentGroup = 0;
var currentPost = null;
var currentCache = null;
var lastCreatedPost = null;
var FB = null;
var stopRender = false;
var follows = [];

var renderGroupMenu = function () {
    var groups = [];

    config.groups.forEach(function(group, index) {
        groups.push({
            name: group.name,
            value: index
        });
    });

    renderer.clear();
    nav.showGroupList('Wybierz grupę', groups, function (answer) {
        currentCache = null;
        currentGroup = config.groups[answer.option];
        FB.setGroup(currentGroup.id);
        renderWall();
    });
};

var renderWallMenu = function () {
    var options = [
        {name: 'Otwórz post', value: 'open'},
        {name: 'Zobacz listę postów obserwowanych', value: 'followlist'},
        {name: 'Wybierz ponownie grupę', value: 'groups'},
        {name: 'Zamknij  aplikacje', value: 'close'}
    ];

    nav.showGroupList("Menu", options, wallActions);
};

var wallActions = function (answer) {
    answer = answer.option.toLowerCase();

    switch(answer) {
        case 'groups':
            renderer.clear();
            renderGroupMenu();
            break;
        case 'open':
            stopRender = true;
            nav.showMenu("Podaj numer postu do otwarcia (0-7)", openSinglePost, function (value) {
                var number = parseInt(value, 10);
                if (typeof number === 'number' && !Number.isNaN(number) && number < renderer.getNumberOfPosts()) {
                    return true;
                }

                return "Musisz podać liczbę z przedziału od 0 do 7";
            });
            break;
        case 'followlist':
            var choices = [];

            for (var i = 0, l = follows.length; i < l; i++) {
                choices.push({
                    name: follows[i].message.substr(0, 50).replace(/(?:\r\n|\r|\n)/g, ' ') + '...',
                    value: i
                });
            }
            stopRender = true;
            nav.showCheckBoxes('Zaznacz posty do usunięcia z listy obserwowanych', choices, function (answer) {
                removeFollowPost(answer);
            });
            break;
        case 'close':
            process.exit();
            break;
        default:
            renderWallMenu();
            break;
    }
};

var removeFollowPost = function (answer) {
    var option = answer.list;
    if (option.indexOf('all') > -1) {
        follows = [];
    } else if (option.length && option.indexOf('back') === -1) {
        for (var i = option.length-1; i > -1; i--) {
            follows.splice(parseInt(option[i], 10),1);
        }
    }

    stopRender = false;

    renderer.renderWall();
    renderWallMenu();
};

var openSinglePost = function (answer) {
    var key = answer.value;

    stopRender = false;
    currentPost = key;

    console.log(key);

    renderer.renderPost(key, true);
    renderPostMenu();
};

var renderPostMenu = function () {
    var followMsg = 'Obserwuj post';
    var followValue = 'follow';

    for (var i = 0, l = follows.length; i < l; i++) {
        if (follows[i].id === renderer.getPost(currentPost).id) {
            followMsg = 'Usuń z obserwowanych';
            followValue = 'unfollow.' + i;
        }
    }

    var options = [
        {name: 'Zobacz post w przeglądarce', value: 'browser'},
        {name: followMsg, value: followValue},
        {name: 'Wróć do listy postów', value: 'back'}
    ];

    nav.showGroupList("Menu", options, postActions);
};

var postActions = function (answer) {
    answer = answer.option.toLowerCase().split('.');

    switch(answer[0]) {
        case 'back':
            currentPost = null;
            renderer.renderWall();
            renderWallMenu();
            break;
        case 'follow':
            follows.push(renderer.getPost(currentPost));
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        case 'unfollow':
            follows.splice(parseInt(answer[1], 10), 1);
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        case 'browser':
            require('child_process').exec('open ' + renderer.getPostUrl(currentPost));
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        default:
            renderPostMenu();
            break;
    }
};

var checkLatestPost = function (post) {
    if (post.created_time === post.updated_time && lastCreatedPost !== post.id) {
        notification(
            currentGroup.name
            , post.from.name + ' dodał(a) nowy post'
            , post.message && post.message.substr(0, 50) + '...'
        );
        lastCreatedPost = post.id;
    }
};

var checkFollowPosts = function (post, id) {
    FB.getPost(post.id, function (err, data) {
        var followComCounts = post.comments ? post.comments.data.length : 0;
        var updatedComCounts = data.comments ? data.comments.data.length : 0;

        if (followComCounts !== updatedComCounts) {
            notification(
                currentGroup.name
                , post.from.name + ' skomentował(a) obserwowany post'
                , post.comments.data[followComCounts - 1].message.substr(0, 50) + '...'
            );
        }

        follows[id] = data;
    });
};

var renderWall = function () {
    FB.getWall(function (err, data) {
        setTimeout(renderWall, config.refreshTime);

        var dataString = JSON.stringify(data);

        if (currentCache && currentCache === dataString) return;

        currentCache = JSON.stringify(data);
        checkLatestPost(data[0]);
        for (var i = 0, l = follows.length; i < l; i++) {
            checkFollowPosts(follows[i], i);
        }

        renderer.setData(data);

        if (stopRender || currentPost) return;

        renderer.clear();
        renderer.renderWall();
        renderWallMenu();
    });
};

var renderSinglePost = function (id) {
    currentPost = id;
    renderer.renderPost(id, true);
    renderPostMenu();
};

var init = function () {
    data(function (err, api) {
        FB = api;
        renderGroupMenu();
    });
};

init();<commit_msg>follow post fix<commit_after>/*global require:false, console:false, module:false, setTimeout: false, process: false*/

var data = require('./src/data');
var renderer = require('./src/renderer');
var nav = require('./src/navigation');
var notification = require('./src/notification');
var config = require('./src/config');

var currentGroup = 0;
var currentPost = null;
var currentCache = null;
var lastCreatedPost = null;
var FB = null;
var stopRender = false;
var follows = [];

var renderGroupMenu = function () {
    var groups = [];

    config.groups.forEach(function(group, index) {
        groups.push({
            name: group.name,
            value: index
        });
    });

    renderer.clear();
    nav.showGroupList('Wybierz grupę', groups, function (answer) {
        currentCache = null;
        currentGroup = config.groups[answer.option];
        FB.setGroup(currentGroup.id);
        renderWall();
    });
};

var renderWallMenu = function () {
    var options = [
        {name: 'Otwórz post', value: 'open'},
        {name: 'Zobacz listę postów obserwowanych', value: 'followlist'},
        {name: 'Wybierz ponownie grupę', value: 'groups'},
        {name: 'Zamknij  aplikacje', value: 'close'}
    ];

    nav.showGroupList("Menu", options, wallActions);
};

var wallActions = function (answer) {
    answer = answer.option.toLowerCase();

    switch(answer) {
        case 'groups':
            renderer.clear();
            renderGroupMenu();
            break;
        case 'open':
            stopRender = true;
            nav.showMenu("Podaj numer postu do otwarcia (0-7)", openSinglePost, function (value) {
                var number = parseInt(value, 10);
                if (typeof number === 'number' && !Number.isNaN(number) && number < renderer.getNumberOfPosts()) {
                    return true;
                }

                return "Musisz podać liczbę z przedziału od 0 do 7";
            });
            break;
        case 'followlist':
            var choices = [];

            for (var i = 0, l = follows.length; i < l; i++) {
                choices.push({
                    name: follows[i].message.substr(0, 100).replace(/(?:\r\n|\r|\n)/g, ' ') + '...',
                    value: i
                });
            }
            stopRender = true;
            nav.showCheckBoxes('Zaznacz posty do usunięcia z listy obserwowanych', choices, function (answer) {
                removeFollowPost(answer);
            });
            break;
        case 'close':
            process.exit();
            break;
        default:
            renderWallMenu();
            break;
    }
};

var removeFollowPost = function (answer) {
    var option = answer.list;
    if (option.indexOf('all') > -1) {
        follows = [];
    } else if (option.length && option.indexOf('back') === -1) {
        for (var i = option.length-1; i > -1; i--) {
            follows.splice(parseInt(option[i], 10),1);
        }
    }

    stopRender = false;

    renderer.renderWall();
    renderWallMenu();
};

var openSinglePost = function (answer) {
    var key = answer.value;

    stopRender = false;
    currentPost = key;

    console.log(key);

    renderer.renderPost(key, true);
    renderPostMenu();
};

var renderPostMenu = function () {
    var followMsg = 'Obserwuj post';
    var followValue = 'follow';

    for (var i = 0, l = follows.length; i < l; i++) {
        if (follows[i].id === renderer.getPost(currentPost).id) {
            followMsg = 'Usuń z obserwowanych';
            followValue = 'unfollow.' + i;
        }
    }

    var options = [
        {name: 'Zobacz post w przeglądarce', value: 'browser'},
        {name: followMsg, value: followValue},
        {name: 'Wróć do listy postów', value: 'back'}
    ];

    nav.showGroupList("Menu", options, postActions);
};

var postActions = function (answer) {
    answer = answer.option.toLowerCase().split('.');

    switch(answer[0]) {
        case 'back':
            currentPost = null;
            renderer.renderWall();
            renderWallMenu();
            break;
        case 'follow':
            follows.push(renderer.getPost(currentPost));
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        case 'unfollow':
            follows.splice(parseInt(answer[1], 10), 1);
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        case 'browser':
            require('child_process').exec('open ' + renderer.getPostUrl(currentPost));
            renderer.renderPost(currentPost, true);
            renderPostMenu();
            break;
        default:
            renderPostMenu();
            break;
    }
};

var checkLatestPost = function (post) {
    if (post.created_time === post.updated_time && lastCreatedPost !== post.id) {
        notification(
            currentGroup.name
            , post.from.name + ' dodał(a) nowy post'
            , post.message && post.message.substr(0, 50) + '...'
        );
        lastCreatedPost = post.id;
    }
};

var checkFollowPosts = function (post, id) {
    FB.getPost(post.id, function (err, data) {
        var followComCounts = post.comments ? post.comments.data.length : 0;
        var updatedComCounts = data.comments ? data.comments.data.length : 0;

        if (followComCounts !== updatedComCounts) {
            notification(
                currentGroup.name
                , post.from.name + ' skomentował(a) obserwowany post'
                , post.comments.data[followComCounts - 1].message.substr(0, 50) + '...'
            );
        }

        follows[id] = data;
    });
};

var renderWall = function () {
    FB.getWall(function (err, data) {
        setTimeout(renderWall, config.refreshTime);

        var dataString = JSON.stringify(data);

        if (currentCache && currentCache === dataString) return;

        currentCache = JSON.stringify(data);
        checkLatestPost(data[0]);
        for (var i = 0, l = follows.length; i < l; i++) {
            checkFollowPosts(follows[i], i);
        }

        renderer.setData(data);

        if (stopRender || currentPost) return;

        renderer.clear();
        renderer.renderWall();
        renderWallMenu();
    });
};

var renderSinglePost = function (id) {
    currentPost = id;
    renderer.renderPost(id, true);
    renderPostMenu();
};

var init = function () {
    data(function (err, api) {
        FB = api;
        renderGroupMenu();
    });
};

init();<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import { NativeModules } from 'react-native';

export default class KeepAwake extends Component<{}> {
  static activate() {
    NativeModules.KCKeepAwake.activate();
  }

  static deactivate() {
    NativeModules.KCKeepAwake.deactivate();
  }

  componentDidMount() {
    KeepAwake.activate();
  }

  componentWillUnmount() {
    KeepAwake.deactivate();
  }

  render() {
    return null;
  }
}
<commit_msg>Implement instance counter and support multiple KeepAwake components (#44)<commit_after>// @flow

import React, { Component } from 'react';
import { NativeModules } from 'react-native';

let mounted = 0;

export default class KeepAwake extends Component<{}> {
  static activate() {
    NativeModules.KCKeepAwake.activate();
  }

  static deactivate() {
    NativeModules.KCKeepAwake.deactivate();
  }

  componentDidMount() {
    mounted++;
    KeepAwake.activate();
  }

  componentWillUnmount() {
    mounted--;
    if (!mounted) {
      KeepAwake.deactivate();
    }
  }

  render() {
    return null;
  }
}
<|endoftext|>