ruby生成C++头文件引用关系图

首先生成graphviz的dot格式文件

require 'find'
class RefNode
	attr_accessor :name,:reference
end
include Find
if __FILE__ == $0
	name = "name"
	dot = []
	h = Hash.new
	puts ["digraph #{name}{","overlap = false","spline = true","ranksep=1.5"].join("\n")
	Find.find('XX/dir1','XX/dir2') do |path|
			path = path.downcase
			if (path.end_with?(".h") && !path.end_with?("stdafx.h"))
	    		headers = []
	        File.readlines(path).each do |line|
	        	line = line
	        	begin
	        	m = /^\s*#include\s+"(.*?)"\s*/.match(line)
	        	rescue
	        	begin
	        	m = /^\s*#include\s+"(.*?)"\s*/u.match(line)
	        	rescue
	        	end
	        	end
	        	if (m)
	        		headers<<File.basename(m[1]).downcase
	        	end
	        end
          headers.each do |header|
          	if h.key?(header)
          		h[header]<<File.basename(path);
          	else
          		h[header] = []
          	end
          end
	    end
	end
	h.keys.each do |key|
		if (h[key].size > 3)
			src = key
			#sprintf("%d %s",h[key].size,key)
			color = sprintf("%.4f,%.4f,%.4f",1 - h[key].size/150.0,1 - h[key].size/150.0,1 - h[key].size/150.0)
	  	dot << sprintf("\nnode[color=\"%s\"]\nedge[color=\"%s\"]\n\"%s\"",color,color,src)
    	h[key].each do |header|
    		dot << sprintf("\t\"%s\"->\"%s\"",header,src)
    	end
  	end
	end
	puts dot.join("\n") 
  puts "}\n"

end

  生成格式大概是这样的

node[color="0.9733,0.9733,0.9733"]
edge[color="0.9733,0.9733,0.9733"]
"tagnode.h"
"tagdocument.h"->"tagnode.h"
"tagelement.h"->"tagnode.h"
"tagnodecollection.h"->"tagnode.h"

然后调用graphviz 的命令行 fdp -Tpng XX.dot -o XX.png这样调用关系就生成了


原文地址:https://www.cnblogs.com/marryZhan/p/2215148.html