Graphviz 14.0.0~dev.20250918.1035
Loading...
Searching...
No Matches
graphml2gv.c
Go to the documentation of this file.
1
6/*************************************************************************
7 * Copyright (c) 2011 AT&T Intellectual Property
8 * All rights reserved. This program and the accompanying materials
9 * are made available under the terms of the Eclipse Public License v1.0
10 * which accompanies this distribution, and is available at
11 * https://www.eclipse.org/legal/epl-v10.html
12 *
13 * Contributors: Details at https://graphviz.org
14 *************************************************************************/
15
16
17#include "convert.h"
18#include <assert.h>
19#include <getopt.h>
20#include <limits.h>
21#include <stdbool.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include "openFile.h"
26#include <util/agxbuf.h>
27#include <util/alloc.h>
28#include <util/debug.h>
29#include <util/exit.h>
30#include <util/gv_ctype.h>
31#include <util/list.h>
32#include <util/unreachable.h>
33#ifdef HAVE_EXPAT
34#include <expat.h>
35
36#ifndef XML_STATUS_ERROR
37#define XML_STATUS_ERROR 0
38#endif
39
40#define NAMEBUF 100
41
42#define GRAPHML_ID "_graphml_id"
43
44#define TAG_NONE -1
45#define TAG_GRAPH 0
46#define TAG_NODE 1
47#define TAG_EDGE 2
48
49static FILE *outFile;
50static char *CmdName;
51static char **Files;
52static int Verbose;
53static char* gname = "";
54
55typedef LIST(char *) strs_t;
56
57static void pushString(strs_t *stk, const char *s) {
58
59 // duplicate the string we will push
60 char *copy = gv_strdup(s);
61
62 // push this onto the stack
63 LIST_PUSH_BACK(stk, copy);
64}
65
66static void popString(strs_t *stk) {
67
68 if (LIST_IS_EMPTY(stk)) {
69 fprintf(stderr, "PANIC: graphml2gv: empty element stack\n");
70 graphviz_exit(EXIT_FAILURE);
71 }
72
73 LIST_DROP_BACK(stk);
74}
75
76static char *topString(strs_t *stk) {
77
78 if (LIST_IS_EMPTY(stk)) {
79 fprintf(stderr, "PANIC: graphml2gv: empty element stack\n");
80 graphviz_exit(EXIT_FAILURE);
81 }
82
83 return *LIST_BACK(stk);
84}
85
86static void freeString(strs_t *stk) {
87 LIST_FREE(stk);
88}
89
90typedef struct {
91 char* gname;
92 strs_t elements;
93 int closedElementType;
94 bool edgeinverted;
95} userdata_t;
96
97static Agraph_t *root; /* root graph */
98static Agraph_t *G; /* Current graph */
99static Agedge_t *E; // current edge
100
101static LIST(Agraph_t *) Gstack;
102
103static userdata_t genUserdata(char *dfltname) {
104 userdata_t user = {0};
105 user.elements = (strs_t){.dtor = LIST_DTOR_FREE};
106 user.closedElementType = TAG_NONE;
107 user.edgeinverted = false;
108 user.gname = dfltname;
109 return user;
110}
111
112static void freeUserdata(userdata_t ud) {
113 freeString(&ud.elements);
114}
115
116static int isAnonGraph(const char *name) {
117 if (*name++ != '%')
118 return 0;
119 while (gv_isdigit(*name))
120 name++; /* skip over digits */
121 return (*name == '\0');
122}
123
124static void push_subg(Agraph_t * g)
125{
126 // save the root if this is the first graph
127 if (LIST_IS_EMPTY(&Gstack)) {
128 root = g;
129 }
130
131 // insert the new graph
132 LIST_PUSH_BACK(&Gstack, g);
133
134 // update the top graph
135 G = g;
136}
137
138static Agraph_t *pop_subg(void)
139{
140 if (LIST_IS_EMPTY(&Gstack)) {
141 fprintf(stderr, "graphml2gv: Gstack underflow in graph parser\n");
142 graphviz_exit(EXIT_FAILURE);
143 }
144
145 // pop the top graph
146 Agraph_t *g = LIST_POP_BACK(&Gstack);
147
148 // update the top graph
149 if (!LIST_IS_EMPTY(&Gstack)) {
150 G = *LIST_BACK(&Gstack);
151 }
152
153 return g;
154}
155
156static Agnode_t *bind_node(const char *name)
157{
158 return agnode(G, (char *)name, 1);
159}
160
161static Agedge_t *bind_edge(const char *tail, const char *head)
162{
163 Agnode_t *tailNode, *headNode;
164 char *key = 0;
165
166 tailNode = agnode(G, (char *) tail, 1);
167 headNode = agnode(G, (char *) head, 1);
168 E = agedge(G, tailNode, headNode, key, 1);
169 return E;
170}
171
172static int get_xml_attr(char *attrname, const char **atts)
173{
174 int count = 0;
175 while (atts[count] != NULL) {
176 if (strcmp(attrname, atts[count]) == 0) {
177 return count + 1;
178 }
179 count += 2;
180 }
181 return -1;
182}
183
184static char *defval = "";
185
186static void setEdgeAttr(Agedge_t *ep, char *name, const char *value,
187 userdata_t *ud) {
188 if (strcmp(name, "headport") == 0) {
189 char *const attrname = ud->edgeinverted ? "tailport" : "headport";
190 Agsym_t *ap = agattr_text(root, AGEDGE, attrname, 0);
191 if (!ap)
192 ap = agattr_text(root, AGEDGE, attrname, defval);
193 agxset(ep, ap, value);
194 } else if (strcmp(name, "tailport") == 0) {
195 char *const attrname = ud->edgeinverted ? "headport" : "tailport";
196 Agsym_t *ap = agattr_text(root, AGEDGE, attrname, 0);
197 if (!ap)
198 ap = agattr_text(root, AGEDGE, attrname, defval);
199 agxset(ep, ap, value);
200 } else {
201 Agsym_t *ap = agattr_text(root, AGEDGE, name, 0);
202 if (!ap)
203 ap = agattr_text(root, AGEDGE, name, defval);
204 agxset(ep, ap, value);
205 }
206}
207
208/*------------- expat handlers ----------------------------------*/
209
210static void
211startElementHandler(void *userData, const char *name, const char **atts)
212{
213 int pos;
214 userdata_t *ud = userData;
215 Agraph_t *g = NULL;
216
217 if (strcmp(name, "graphml") == 0) {
218 /* do nothing */
219 } else if (strcmp(name, "graph") == 0) {
220 const char *edgeMode = "";
221 const char *id;
222 Agdesc_t dir;
223 char buf[NAMEBUF]; /* holds % + number */
224
225 if (ud->closedElementType == TAG_GRAPH) {
226 fprintf(stderr,
227 "Warning: Node contains more than one graph.\n");
228 }
229 pos = get_xml_attr("id", atts);
230 if (pos > 0) {
231 id = atts[pos];
232 }
233 else
234 id = ud->gname;
235 pos = get_xml_attr("edgedefault", atts);
236 if (pos > 0) {
237 edgeMode = atts[pos];
238 }
239
240 if (LIST_IS_EMPTY(&Gstack)) {
241 if (strcmp(edgeMode, "directed") == 0) {
242 dir = Agdirected;
243 } else if (strcmp(edgeMode, "undirected") == 0) {
244 dir = Agundirected;
245 } else {
246 GV_INFO("Warning: graph has no edgedefault attribute - assume directed");
247 dir = Agdirected;
248 }
249 g = agopen((char *) id, dir, &AgDefaultDisc);
250 push_subg(g);
251 } else {
252 Agraph_t *subg;
253 if (isAnonGraph(id)) {
254 static int anon_id = 1;
255 snprintf(buf, sizeof(buf), "%%%d", anon_id++);
256 id = buf;
257 }
258 subg = agsubg(G, (char *) id, 1);
259 push_subg(subg);
260 }
261
262 pushString(&ud->elements, id);
263 } else if (strcmp(name, "node") == 0) {
264 pos = get_xml_attr("id", atts);
265 if (pos > 0) {
266 const char *attrname;
267 attrname = atts[pos];
268 if (G == 0)
269 fprintf(stderr,"node %s outside graph, ignored\n",attrname);
270 else
271 bind_node(attrname);
272
273 pushString(&ud->elements, attrname);
274 }
275
276 } else if (strcmp(name, "edge") == 0) {
277 const char *head = "", *tail = "";
278 char *tname;
279 Agnode_t *t;
280
281 pos = get_xml_attr("source", atts);
282 if (pos > 0)
283 tail = atts[pos];
284 pos = get_xml_attr("target", atts);
285 if (pos > 0)
286 head = atts[pos];
287
288 if (G == 0)
289 fprintf(stderr,"edge source %s target %s outside graph, ignored\n",tail,head);
290 else {
291 bind_edge(tail, head);
292
293 t = AGTAIL(E);
294 tname = agnameof(t);
295
296 if (strcmp(tname, tail) == 0) {
297 ud->edgeinverted = false;
298 } else if (strcmp(tname, head) == 0) {
299 ud->edgeinverted = true;
300 }
301
302 pos = get_xml_attr("id", atts);
303 if (pos > 0) {
304 setEdgeAttr(E, GRAPHML_ID, atts[pos], ud);
305 }
306 }
307 } else {
308 /* must be some extension */
309 fprintf(stderr,
310 "Unknown node %s - ignoring.\n",
311 name);
312 }
313}
314
315static void endElementHandler(void *userData, const char *name)
316{
317 userdata_t *ud = userData;
318
319 if (strcmp(name, "graph") == 0) {
320 pop_subg();
321 popString(&ud->elements);
322 ud->closedElementType = TAG_GRAPH;
323 } else if (strcmp(name, "node") == 0) {
324 char *ele_name = topString(&ud->elements);
325 if (ud->closedElementType == TAG_GRAPH) {
326 Agnode_t *node = agnode(root, ele_name, 0);
327 if (node) agdelete(root, node);
328 }
329 popString(&ud->elements);
330 ud->closedElementType = TAG_NODE;
331 } else if (strcmp(name, "edge") == 0) {
332 E = 0;
333 ud->closedElementType = TAG_EDGE;
334 ud->edgeinverted = false;
335 }
336}
337
338static Agraph_t *graphml_to_gv(char *graphname, FILE *graphmlFile, int *rv) {
339 char buf[BUFSIZ];
340 int done;
341 userdata_t udata = genUserdata(graphname);
342 XML_Parser parser = XML_ParserCreate(NULL);
343
344 *rv = 0;
345 XML_SetUserData(parser, &udata);
346 XML_SetElementHandler(parser, startElementHandler, endElementHandler);
347
348 root = 0;
349 do {
350 size_t len = fread(buf, 1, sizeof(buf), graphmlFile);
351 if (len == 0)
352 break;
353 done = len < sizeof(buf);
354 assert(len <= INT_MAX);
355 if (XML_Parse(parser, buf, (int)len, done) == XML_STATUS_ERROR) {
356 fprintf(stderr,
357 "%s at line %lu\n",
358 XML_ErrorString(XML_GetErrorCode(parser)),
359 XML_GetCurrentLineNumber(parser));
360 *rv = 1;
361 break;
362 }
363 } while (!done);
364 XML_ParserFree(parser);
365 freeUserdata(udata);
366
367 return root;
368}
369
370static FILE *getFile(void)
371{
372 FILE *rv = NULL;
373 static FILE *savef = NULL;
374 static int cnt = 0;
375
376 if (Files == NULL) {
377 if (cnt++ == 0) {
378 rv = stdin;
379 }
380 } else {
381 if (savef)
382 fclose(savef);
383 while (Files[cnt]) {
384 if ((rv = fopen(Files[cnt++], "r")) != 0)
385 break;
386 else
387 fprintf(stderr, "Can't open %s\n", Files[cnt - 1]);
388 }
389 }
390 savef = rv;
391 return rv;
392}
393
394static const char *use = "Usage: %s [-gd?] [-o<file>] [<graphs>]\n\
395 -g<name> : use <name> as template for graph names\n\
396 -o<file> : output to <file> (stdout)\n\
397 -v : verbose mode\n\
398 -? : usage\n";
399
400static void usage(int v)
401{
402 fprintf(stderr, use, CmdName);
403 graphviz_exit(v);
404}
405
406static char *cmdName(char *path)
407{
408 char *sp;
409
410 sp = strrchr(path, '/');
411 if (sp)
412 sp++;
413 else
414 sp = path;
415 return sp;
416}
417
418static void initargs(int argc, char **argv)
419{
420 int c;
421
422 CmdName = cmdName(argv[0]);
423 opterr = 0;
424 while ((c = getopt(argc, argv, ":vg:o:")) != -1) {
425 switch (c) {
426 case 'g':
427 gname = optarg;
428 break;
429 case 'v':
430 Verbose = 1;
431 break;
432 case 'o':
433 if (outFile != NULL)
434 fclose(outFile);
435 outFile = openFile(CmdName, optarg, "w");
436 break;
437 case ':':
438 fprintf(stderr, "%s: option -%c missing argument\n", CmdName, optopt);
439 usage(1);
440 break;
441 case '?':
442 if (optopt == '?')
443 usage(0);
444 else {
445 fprintf(stderr, "%s: option -%c unrecognized\n", CmdName,
446 optopt);
447 usage(1);
448 }
449 break;
450 default:
451 UNREACHABLE();
452 }
453 }
454
455 argv += optind;
456 argc -= optind;
457
458 if (argc)
459 Files = argv;
460 if (!outFile)
461 outFile = stdout;
462}
463
464static char *nameOf(agxbuf *buf, char *name, int cnt) {
465 if (*name == '\0')
466 return name;
467 if (cnt) {
468 agxbprint(buf, "%s%d", name, cnt);
469 return agxbuse(buf);
470 }
471 else
472 return name;
473}
474
475#endif
476
477int main(int argc, char **argv)
478{
480 Agraph_t *prev = 0;
481 FILE *inFile;
482 int rv = 0, gcnt = 0;
483
484#ifdef HAVE_EXPAT
485 agxbuf buf = {0};
486 initargs(argc, argv);
487 while ((inFile = getFile())) {
488 while ((graph = graphml_to_gv(nameOf(&buf, gname, gcnt), inFile, &rv))) {
489 gcnt++;
490 if (prev)
491 agclose(prev);
492 prev = graph;
493 GV_INFO("%s: %d nodes %d edges", agnameof(graph), agnnodes(graph),
494 agnedges(graph));
496 fflush(outFile);
497 }
498 }
499
500 LIST_FREE(&Gstack);
501
502 agxbfree(&buf);
503 graphviz_exit(rv);
504#else
505 fputs("graphml2gv: not configured for conversion from GXL to GV\n", stderr);
506 graphviz_exit(1);
507#endif
508}
Agobj_t * copy(Agraph_t *g, Agobj_t *obj)
Definition actions.c:145
static void agxbfree(agxbuf *xb)
free any malloced resources
Definition agxbuf.h:77
static int agxbprint(agxbuf *xb, const char *fmt,...)
Printf-style output to an agxbuf.
Definition agxbuf.h:233
static WUR char * agxbuse(agxbuf *xb)
Definition agxbuf.h:306
Memory allocation wrappers that exit on failure.
static char * gv_strdup(const char *original)
Definition alloc.h:101
static FILE * inFile
Definition acyclic.c:36
DOT-GXL converter API for gxl2gv.c and gv2gxl.c.
static const char * use
Definition cvtgxl.c:66
static FILE * outFile
Definition cvtgxl.c:35
static void initargs(int argc, char **argv)
Definition cvtgxl.c:130
static char * cmdName(char *path)
Definition cvtgxl.c:78
static char * CmdName
Definition cvtgxl.c:36
helpers for verbose/debug printing
#define GV_INFO(...)
Definition debug.h:15
#define head
Definition dthdr.h:15
static char ** Files
static NORETURN void graphviz_exit(int status)
Definition exit.h:23
#define E
Definition gdefs.h:6
#define G
Definition gdefs.h:7
static double len(glCompPoint p)
Definition glutils.c:136
static FILE * getFile(void)
Definition gml2gv.c:30
static char * gname
Definition gml2gv.c:25
static bool Verbose
Definition gml2gv.c:24
static char * nameOf(agxbuf *buf, char *name, int cnt)
Definition gml2gv.c:120
node NULL
Definition grammar.y:181
static int cnt(Dict_t *d, Dtlink_t **set)
Definition graph.c:196
int agnedges(Agraph_t *g)
Definition graph.c:161
int agnnodes(Agraph_t *g)
Definition graph.c:155
Agsym_t * agattr_text(Agraph_t *g, int kind, char *name, const char *value)
creates or looks up text attributes of a graph
Definition attr.c:334
int agxset(void *obj, Agsym_t *sym, const char *value)
Definition attr.c:522
Agdisc_t AgDefaultDisc
Definition graph.c:275
Agedge_t * agedge(Agraph_t *g, Agnode_t *t, Agnode_t *h, char *name, int createflag)
Definition edge.c:253
#define AGTAIL(e)
Definition cgraph.h:973
Agdesc_t Agundirected
undirected
Definition graph.c:272
int agclose(Agraph_t *g)
deletes a graph, freeing its associated storage
Definition graph.c:95
Agraph_t * agopen(char *name, Agdesc_t desc, Agdisc_t *disc)
creates a new graph with the given name and kind
Definition graph.c:42
int agwrite(Agraph_t *g, void *chan)
Return 0 on success, EOF on failure.
Definition write.c:669
Agdesc_t Agdirected
directed
Definition graph.c:270
Agnode_t * agnode(Agraph_t *g, char *name, int createflag)
Definition node.c:141
char * agnameof(void *)
returns a string descriptor for the object.
Definition id.c:143
int agdelete(Agraph_t *g, void *obj)
deletes object. Equivalent to agclose, agdelnode, and agdeledge for obj being a graph,...
Definition obj.c:20
@ AGEDGE
Definition cgraph.h:207
Agraph_t * agsubg(Agraph_t *g, char *name, int cflag)
Definition subg.c:53
static uint64_t id
Definition gv2gml.c:40
Agraph_t * graph(char *name)
Definition gv.cpp:30
replacements for ctype.h functions
static bool gv_isdigit(int c)
Definition gv_ctype.h:41
static const char * usage
Definition gvpr.c:51
#define XML_STATUS_ERROR
Definition htmllex.c:41
$2 prev
Definition htmlparse.y:291
type-generic dynamically expanding list
#define LIST_DTOR_FREE
Definition list.h:70
#define LIST(type)
Definition list.h:55
#define LIST_BACK(list)
Definition list.h:201
#define LIST_DROP_BACK(list)
Definition list.h:431
#define LIST_FREE(list)
Definition list.h:379
#define LIST_POP_BACK(list)
Definition list.h:416
#define LIST_IS_EMPTY(list)
Definition list.h:90
#define LIST_PUSH_BACK(list, item)
Definition list.h:393
static FILE * openFile(const char *argv0, const char *name, const char *mode)
Definition openFile.h:8
graph descriptor
Definition cgraph.h:284
graph or subgraph
Definition cgraph.h:424
string attribute descriptor symbol in Agattr_s.dict
Definition cgraph.h:640
Definition types.h:81
int main()
Definition grammar.c:90
#define UNREACHABLE()
Definition unreachable.h:30