Ejemplo n.º 1
0
Trace.prototype.graphViz = function () {
  var g = graphviz.digraph('G')

  // First build the list of nodes.
  var nodes = {}
  for (var k in this._eventMap) {
    var e = this._eventMap[k]
    if (!(k in nodes)) {
      var color = getColor(e)
      var timing = getTimingLabel(e.durations) + ' (µ)'
      var label = k + '(' + e.durations.length + ') \\n' + timing
      nodes[k] = g.addNode(k, {'fillcolor': color, 'style': 'filled', 'label': label})
    }
  }

  // Then create the edges.
  for (var k in this._eventMap) {
    var e = this._eventMap[k]
    var inputs = e.props.inputKeys
    for (var i = 0; i < inputs.length; ++i) {
      var to = this._eventMap[inputs[i]]
      var props = {}
      //props['label'] = to.durations.length
      g.addEdge(nodes[inputs[i]], nodes[k], props)
    }
  }

  return g
}
fs.readFile("all_data.json", function (err, data) {
  var nodes = [],links = [];
  var modules = JSON.parse(data);



  var g = graphviz.digraph("G");

  var allModules = _.keys(modules);
  var nodeModuleMap ={};
  _.each(allModules, function (module) {
    var n1 = g.addNode(module,{"color" : "blue"});
    n1.set( "style", "filled" );
    nodeModuleMap[module] = n1;
  });
  _.each(allModules, function  (module) {
    var deps = modules[module];
    
    _.each(deps, function  (dep) {
      g.addEdge(nodeModuleMap[module], dep).set( "color", "red" );
    });
  });

  console.log(g.to_dot());
  g.setGraphVizPath( "/opt/local/bin/" );
  // Generate a PNG output
  g.output( "png", "viz.png" );
  process.exit(0);
});
Ejemplo n.º 3
0
Archivo: cfg.js Proyecto: gdhuang/atg
function dump(tree) {
    var graph = graphviz.digraph(path.basename(tree.filename, '.js')),
        nodeLabel = function(node) {           
            if(node === null)
                return null;
            else
                return util.format('%d_%s', node.loc.start.line, node.type);
        };
        
    visitor.traverse(tree, function (node, path) {  
        if(node.type === esprima.Syntax.ForStatement ||
          node.type === esprima.Syntax.WhileStatement ||
          node.type === esprima.Syntax.DoWhileStatement ||
          node.type === esprima.Syntax.ForInStatement) {
          
          if(node.body.body.length > 0)
              graph.from(nodeLabel(node)).to(nodeLabel(node.body.body[0]));
          else
              graph.from(nodeLabel(node)).to(nodeLabel(node));
        }
            
        if(!node.succs)
            return;
        
        node.succs.forEach(function(succ) {
            if(!succ)
                return;

            graph.from(nodeLabel(node)).to(nodeLabel(succ));
        });
    });

    graph.render('png', graph.id+'.png');
    return graph.to_dot();
}
Ejemplo n.º 4
0
function buildUml(modules, outputFilename, dependenciesOnly) {
    var g = graphviz.digraph("G");
    var FontSizeKey = "fontsize";
    var FontSize = 12;
    var FontNameKey = "fontname";
    var FontName = "Verdana";
    g.set(FontSizeKey, FontSize);
    g.set(FontNameKey, FontName);
    g.setEdgeAttribut(FontSizeKey, FontSize);
    g.setEdgeAttribut(FontNameKey, FontName);
    g.setNodeAttribut(FontSizeKey, FontSize);
    g.setNodeAttribut(FontNameKey, FontName);
    g.setNodeAttribut("shape", "record");
    modules.forEach(function (module) {
        buildModule(module, g, "", 0, dependenciesOnly);
    });
    if (process.platform === "win32") {
        var pathVariable = process.env["PATH"];
        if (pathVariable.indexOf("Graphviz") === -1) {
            console.warn("Could not find Graphviz in PATH.");
        }
    }
    else {
        g.setGraphVizPath("/usr/local/bin");
    }
    g.output("png", outputFilename);
}
Ejemplo n.º 5
0
Archivo: dot.js Proyecto: vesln/depviz
Dot.prototype.render = function(name) {
  var g = graphviz.digraph('G');

  Object.keys(this.deps).forEach(function(dep) {
    if (!g.getNode(dep)) g.addNode(dep);
    this.deps[dep].forEach(function(child) {
      g.addNode(child);
      g.addEdge(dep, child);
    });
  }, this);

  g.output('png', name + '.png');
};
Ejemplo n.º 6
0
		client.on('graph', function (data) {
			if (app.get('disable_graphviz_tidy')) {
				emitData(id, 'graph', {});
			} else {
				var g = graphviz.digraph("G");
				var options = {
					type: "dot",
					G: {
						splines: false,
						rankdir: "BT",
						nodesep: "0.2"
					}
				};

				// this creates the initial dot file to be rendered
				for (var prop in data.nodes) {
					if (data.nodes.hasOwnProperty(prop)) {
						g.addNode(prop);
						if (data.nodes[prop]) {
							for (var i = 0; i < data.nodes[prop].length; i+=1) {
								g.addEdge(prop, data.nodes[prop][i]);
							}                   
						}                   
					}
				}

				// this takes the dote graph generated above and creates a dot file with all the postions
				g.output(options, function (out) { 
					var dot = out.toString('utf-8');
					var regex = /(q\d+)\s\[pos="(\d+),(\d+)",/gmi;
					var graph = {};
					var match;

					while ((match = regex.exec(dot)) !== null) {
						graph[match[1].toString()] = {
							x: parseInt(match[2],10),
							y: parseInt(match[3],10)
						};
					}

					emitData(id, 'graph', graph);               
				});
			}
		});
Ejemplo n.º 7
0
function createGraphForCfg(cfg, options) {
	const graph = graphviz.digraph("cfg");
	const nodeCache = new Map();

	plotNodes();
	plotEdges();

	return graph;

	function plotNodes () {
		for (const node of sortNodes(cfg.getNodes())) {
			const label = createLabelForNode(node.value);
			const graphvizNode = graph.addNode(nodeCache.size.toString(), {label: label});
			nodeCache.set(node, graphvizNode);
		}
	}

	function plotEdges() {
		for (const edge of sortEdges(cfg.getEdges())) {
			const predecessorNode = nodeCache.get(edge.src);
			const successorNode = nodeCache.get(edge.to);
			// console.log(`${edge.src.value.loc.start.line} -> ${edge.to.value.loc.start.line}`);
			graph.addEdge(predecessorNode, successorNode, { label: edge.branch });
		}
	}

	function sortNodes (nodes) {
		if (options.stable) {
			return Array.from(nodes).sort(stableNodeComparator);
		}

		return nodes;
	}

	function sortEdges (edges) {
		if (options.stable) {
			return Array.from(edges).sort(stableEdgeComparator);
		}

		return edges;
	}
}
Ejemplo n.º 8
0
'use strict';

/**
 * Module dependencies
 */
var exec = require('child_process').exec,
	graphviz = require('graphviz'),
	g = graphviz.digraph('G');

/**
 * Set color on a node
 *
 * @param  {Object} node
 * @param  {String} color
 */
function nodeColor(node, color) {
	node.set('color', color);
	node.set('fontcolor', color);
}

/**
 * Set color for nodes without dependencies
 *
 * @param  {Object} node
 * @param  {String} [color]
 */
function noDependencyNode(node, color) {
	nodeColor(node, color || '#cfffac');
}

/**
var util = require('util'),
  graphviz = require('graphviz');

// Create digraph G
var g = graphviz.digraph("G");

// Add node (ID: Animal)
var n1 = g.addNode( "Animal", {"color" : "blue"} );
n1.set( "style", "filled" );

// Add node (ID: Mammal)
g.addNode( "Mammal" );
g.addNode( "Reptile");
g.addNode( "Bird");
g.addNode( "Fish" );
g.addNode("Insect");

// Add edge between the two nodes
var m = g.addEdge( "Mammal", n1 );
m.set( "color", "red" );

var r = g.addEdge( "Reptile", n1 );
r.set( "color", "red" );

var b = g.addEdge( "Bird", n1 );
b.set( "color", "red" );

var f = g.addEdge( "Fish", n1 );
f.set( "color", "red" );

var i = g.addEdge( "Insect", n1 );
Ejemplo n.º 10
0
Dynapack.prototype.bundle = function(opts) {
  var pack = this;
  var roots = {};
  var bundle;
  var bundles;
  var index = 0;
  var cwd = process.cwd();

  // Graph metadata all in one place.
  var graph = {
    modules: {}, // maps source ids to input ids (i.e. filenames)
    bundles: {}, // maps bundle ids to module id arrays.
    entries: {}  // maps entry ids to bundle id arrays.
  };

    // Consistent id'ing of modules uses its relative path. Watch out
    // for dependencies that go outside project directory.

  var basePath = commondir(
    Object.keys(pack.modules)
  );

  if (cwd.indexOf(basePath) === 0 && cwd.length > basePath.length) {
    // basePath is a parent directory of cwd
    console.warn(
      'The directory common to all modules in the dependency',
      'graph is', basePath, ', but the current working directory',
      'is', cwd + '.', 'If you are working from the root of your',
      'project directory, this means your bundle names may vary',
      'depending on your development machine, which is bad. Maybe',
      'a global module is being required somehow?'
    );
  }

  pack.traverse(function(visited) {
    var module = last(visited);
    var root;
    var parent;

    if (module.index === undefined) {
      module.index = index++;
    }

    // Find closest ancestor that is a root.
    for (var len = visited.length, i = len - 1; i > 0; i--) {
      parent = visited[i - 1];

      if (visited[i].isDynamicDependencyOf(parent)) {
        root = visited[i];
        break;
      }
    }

    root = root || visited[0];
    module.roots = union([root.path], module.roots);

    if (root.path === module.path) {
      roots[module.path] = 1;
    }
  });

  roots = pack.roots = Object.keys(roots).sort();
  bundles = pack.bundles = {};
  ids = pack.ids = {};

  /**
   *  Form the bundles. Shorten the module ids.
   */

  forEach(pack.modules, function(module) {
    var bundle;
    var bundleId;
    var relPath = module.path.slice(basePath.length + 1); // remove leading slash.

    module.relPath = relPath;

    // Consistent id'ing of modules uses its relative path.

    ids[module.path] = pack.opts.debug ? relPath : md5(relPath);
    graph.modules[ids[module.path]] = module.path;

    // Push module into a bundle based on its roots.

    bundleId = (
      pack.opts.debug ?
      ids[module.path] :
      (
        md5(
          module.roots.sort().join('')
        ) +
        '.js'
      )
    );

    bundle = bundles[bundleId] || {id: bundleId, modules: []};
    bundle.modules.push(module.path);

    if (!module.bundled) {
      bundle.render = true;
      module.bundled = true;
    }

    bundles[bundleId] = bundle;
  });

  /**
   *  Sort modules in all bundles and name the bundle by its contents
   *  before rendering.
   */

  forEach(bundles, function(bundle) {
    bundle.modules.sort();
    bundle.name = md5(bundle.modules.join(''), 8) + '.js';
    graph.bundles[bundle.id] = bundle.modules.concat();
  });


  /**
   *  Output the graph if we have graphviz.
   */

  try {
    var graphviz = require('graphviz');
    var g = graphviz.digraph('app');
    var bundleColors = {};
    var currentColor = 0;
    var graphOpts = pack.opts.graph || {};
    var colorscheme = graphOpts.colorscheme || 'brbg11';

    forEach(pack.bundles, function(bundle) {
      var color = ((currentColor++ % 11) + 1).toString();
      var cluster = g.addCluster('"cluster-' + bundle.name + '"');

      forEach(bundle.modules, function(path) {
        var module = pack.modules[path];
        var n = cluster.addNode(module.relPath, {
          //group: bundle.id,
          colorscheme: colorscheme,
          color: color,
          style: 'filled'
        });
      });
    });

    forEach(pack.modules, function(module) {
      module.deps.static.forEach(function(depPath) {
        var dep = pack.modules[depPath];
        var edge = g.addEdge(module.relPath, dep.relPath);

        edge.set('style', 'solid');
      });

      module.deps.dynamic.forEach(function(depPath) {
        var dep = pack.modules[depPath];
        var edge = g.addEdge(module.relPath, dep.relPath);

        edge.set('style', 'dashed');
      });
    });

    pack.emit('graph', g);
  }
  catch (e) {
    console.log(e.message);
  }


  /**
   *  Push only the bundles that need to be rendered.
   */

  forEach(bundles, function(bundle) {
    if (bundle.render) {
      pack.push(
        new File({
          path: path.join(process.cwd(), bundle.name),
          base: process.cwd(),
          modules: bundle.modules,
          contents: new Buffer(
            pack.renderBundle(bundle)
          )
        })
      );
    }
  });

  /**
   *  Push only the entries that depend on bundles that have been
   *  rerendered or rendered for the first time.
   */

  //pack.entryPaths.forEach(function(entryPath, index) {
  //  var name = pack.entryNames[index];
  //  var entryBundles = pack.requiredBundles(entryPath);
  //  var filename = name + '.entry.js';
  //  var render;

  //  graph.entries[name] = [filename].concat(entryBundles);

  //  entryBundles.forEach(function(bundleId) {
  //    if (bundles[bundleId].render) {
  //      render = true;
  //    }
  //  });

  //  if (render) {
  //    pack.push(
  //      new File({
  //        path: path.join(process.cwd(), filename),
  //        base: process.cwd(),
  //        contents: new Buffer(
  //          pack.renderEntry(entryPath, entryBundles)
  //        )
  //      })
  //    );
  //  }
  //});

  pack.emit('bundled', graph);
};
Ejemplo n.º 11
0
Archivo: cli.js Proyecto: jryans/npmdep
            Traverse(tree).forEach(function (node) {
                for (var i = 0; i < this.level; i++) print('--')
                if (this.isRoot) {
                    console.log(start)
                }
                else {
                    console.log(' ' + this.key)
                }
            })
        }
    });
}
else if (cmd === 'graph' && process.argv[3]) {
    var outfile = process.argv[3];
    var graphviz = require('graphviz');
    var g = graphviz.digraph('npm');
    g.use = process.argv[4] || 'fdp'; // also twopi looks pretty good
    
    npmdep.load(function (err, pkgs) {
        if (err) cb(err)
        else {
            Hash(pkgs).forEach(function (pkg, name) {
                var mag = 255 - Math.floor((Hash(pkgs).filter(function (p) {
                    return p.dependencies[name]
                }).length || 0) / 50 * 255);
                
                var fhex = mag.toString(16);
                if (fhex.length == 1) fhex = '0' + fhex;
                
                var node = g.addNode(name, {
                    style : 'filled',